Home > Software engineering >  Python nested loops with list
Python nested loops with list

Time:06-24

Given a list

my_numbers = [1, 3, 5, 3, 7, 8, 12, 4]

The number K is given (must be entered from the console). Print K-th powers of numbers from the given set: (A1)K, (A2)K, ..., (AN)K Do not use the ready-made arithmetic exponentiation (**).

Input: k = 2
Output: 1 9 25 9 49 64 144 16

My attempt: But I don't know what to write next

my_numbers = [1, 3, 5, 3, 7, 8, 12, 4]
k = int(input("k = ")) 
i = 0
value = i
for i in range(len(my_numbers)):
    value = i

CodePudding user response:

Use this:

my_numbers = [1, 3, 5, 3, 7, 8, 12, 4]
k = int(input("k = "))

for i in my_numbers:    # Iterate through my_numbers
    x = 1               # Result variable
    for j in range(k):  # Repeatedly multiply by i,
        x *= i          # k number of times, then
    print(x)            # Output result

Output:

k = 2
1
9
25
9
49
64
144
16


For the second problem ("Output the following numbers: A1, (A2)2, ..., (AN−1)N−1, (AN)N.")

my_numbers = [1, 3, 5, 3, 7, 8, 12, 4]

n = len(my_numbers)         # Length of my_numbers, to be used later
for i in range(n):          # Iterate through indexes 0 to n
    x = 1                   # Result variable
    for j in range(i   1):  # Repeatedly multiply by my_numbers[i],
        x *= my_numbers[i]  # (i   1) times, then
    print(x)                # Output result

Output:

1
9
125
81
16807
262144
35831808
65536
  • Related