Home > Software engineering >  Need help in iterating and changing index using dictionary?
Need help in iterating and changing index using dictionary?

Time:06-12

So basically what i am trying to achieve is get my program to perform a n number of iterations on one input variable(i use a for loop for this). After the for loop ends the program asks the user if they want to continue, for yes the program then asks the user for another n number of iterations to perform on the same input variable. The program then has to start the operation from where it left from the previous value, i used a dictionary for this but cant find it working. Would be great if i can get some help. my code is pasted below:

def function(x,i):
    return x**i
num_dic = {}
j = 1

while True:
if j == 1:
    start = 1
    n = int(input("number of iterations: "))
    x = int(input("Number to perform operation: "))
    for i in range(start, n   1):
        total = function(x, i)
        print(f"{x}", "**", i, "=", total)
        num_dic[f"{i}"] = total

elif j > 1:
    start = int(sorted(num_dic.keys())[-1])   1
    x = sorted(num_dic.values())[-1]
    n = int(input("number of iterations: "))
    for i in range(start, n   1):
        total = function(x, i)
        print(f"{x}", "**", i, "=", total)
        num_dic[f"{i}"] = total
j  = 1
while True:  # while loop for repeating program
    ask = input("Do you want to continue?(Y to continue/ N to exit): ")
    if ask.upper() == 'Y':
        break

    if ask.upper() == 'N':
        break
    else:
        print("Please enter a correct operation (Y/N) ")
        continue
if ask.upper() == 'Y':
    continue
else:
    break

current output i am getting:

number of iterations: 5
Number to perform operation: 2
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
Do you want to continue?(Y to continue/ N to exit): y
number of iterations: 5

after this part it just doesn't do anything.

the desired output should look like:

number of iterations: 5
Number to perform operation: 2
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
Do you want to continue?(Y to continue/ N to exit): y
number of iterations: 5
2 ** 6 = 64
2 ** 7 = 128
2 ** 8 = 256
2 ** 9 = 512
2 ** 10 = 1024

CodePudding user response:

You don't need a dictionary for this operation. You just need a clean and proper while-loop that can keep track of your variables, specifically the exponent (variable j in your original code) and your number of iterations, n.

base doesn't change, so it should be left outside the while-loop, as advised by the @Blckknght's answer to this question.

exponent = 1
base = int(input("Number to perform operation: "))
n = None  # initialize n to None

while True:
    # logic to keep track of n in the previous loop, if there is one.
    if n:
        n  = int(input("number of iterations: "))  # cumulatively increment n if user wishes to continue.
    else:
        n = int(input("number of iterations: "))

    # while-loop that prints the output for a single set of x and n values
    while n >= j:
        print(f"{base} ** {exponent} = {base ** exponent}")
        exponent  = 1

    # get user input for continuation
    ask = input("Do you want to continue?(Y/ N): ")

    # while loop to handle user input values
    while ask.upper() not in ["Y", "N"]:
        ask = input("Please enter a correct operation (Y/N).")
    
    if ask.upper() == 'Y':
        continue  # loop back to the outer while-loop and ask for another set of user input
    elif ask.upper() == 'N':
        break  # break if user says no

CodePudding user response:

Since you only need to keep track of where you left off, there's no need to store many values in a dictionary. Just remembering the base and the last exponent used is enough. And conveniently, the variables x and i that you're using won't automatically get reset between iterations, so you can just start the next iteration from i 1:

elif j > 1:
    n = int(input("number of iterations: "))
    for i in range(i 1, i   n   1):
        total = function(x, i)
        print(f"{x}", "**", i, "=", total)

Indeed, you could probably simplify things so that you don't need a special case for the first iteration. Just ask for the base before the loop starts! Here's how I'd do it (using more descriptive variable names too):

base = int(input("Number to perform operation: "))
start_from = 1
while True:
    n = int(input("number of iterations: "))
    for exponent in range(start_from, start_from   n):
        print(f'{base} ** {exponent} = {function(base, exponent)}')
    start_from = start_from   n

    # ask about continuing down here, optionally break out

If you really want to prompt for the number of iterations first, before asking for the base, you could probably make that work by using a sentinel value like None to indicate when it hasn't been set yet, so that you only prompt for it the first iteration (without explicitly counting):

base = None
start_from = 0
while True:
    n = int(input("number of iterations: "))
    if base is None:
        base = int(input("Number to perform operation: "))
    # ...
  • Related