bw61293
bw61293

Reputation: 91

Finding smallest number in a for loop with a range using Python

First off, I am using python. Ok, so I need to print the smallest float found after iterating through this for loop. I have tried using min() and I get an error saying that the 'float' object is not iterable. I cannot figure out another way to print out the smallest number or for it to accept all the floats so I can use the min() function. Any help would be appreciated. Here is my code:

def decryption():
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]    
    phrase=input('What would you like decrypted?')
    number=0
    for number in range(0,26):
        e=0+number
        t=0+number
        o=0+number
        a=0+number
        i=0+number
        n=0+number
        for letter in phrase:
            if letter== 'e':
                e+=1 
            if letter== 't':
                t+=1
            if letter== 'o':
                o+=1
            if letter== 'a':
                a+=1
            if letter== 'i':
                i+=1
            if letter== 'n':
                n+=1        
        e_freq= .1119-e/10
        e_ans= e_freq*e_freq

        t_freq= .0928-t/10
        t_ans= t_freq*t_freq

        o_freq= .0819-o/10
        o_ans= o_freq*o_freq

        a_freq= .0754-a/10
        a_ans= a_freq*a_freq

        i_freq= .0710-i/10
        i_ans= i_freq*i_freq

        n_freq= .0643-n/10
        n_ans= n_freq*n_freq

        square_sum= e_ans+t_ans+o_ans+a_ans+i_ans+n_ans

Upvotes: 0

Views: 2512

Answers (1)

Alpaca
Alpaca

Reputation: 707

The min function takes as its argument a list of numbers. So you would need to create an array of all the numbers you want to search through, and then you could use min. (Actually, as the error says, it takes an iterable, which is more generic than a list)

Another way to do this is to keep track of smallest one you have seen so far, and do a check at the end of each iteration.

if smallest_seen > square_sum:
    smallest_seen = square_sum

Then, at the end of your loop, smallest_seen will be the minimum value out of all the calculated square_sum values.

Here is a more complete example.

import sys                                                              
import random                                                           

smallest_seen = sys.float_info.max                                      

for i in range(26):                                                     
    some_num = random.random()                                          
    if smallest_seen > some_num:                                        
        smallest_seen = some_num                                        

print(smallest_seen)  

Upvotes: 1

Related Questions