lundi 13 janvier 2020

Split numbers into smaller pieces according to condition

i am new to python and trying to make a program that divides a number into pieces (pieces will be random) with 2 conditions.

I have manage to make a program to do so but as soon as i make changes to demo data my program doesn't work as expected.

What i want to to is to get 2 number from the list with same indexes amd then multiply their value (ie. 100 * 10) then checks for if the result is greater then max value (1000 in this case). Of it is greater then max value then it should divide the number of qtl list (qtl[index]) into smaller pieces. After that i want to store them into pieces list.

Here is the code


import random

qtl = [100, 200 , 500]
prices = [10 , 20, 5]
total = qtl[0] * prices[0]
pieces = []
prices_for_pieces = []
max = 1000

for index in range(3):
    total = qtl[index] * prices[index]
    print(f' now {qtl[index]}')
    if  total  > max:
            number_of_piece = int((total/max) +1)
            temp_qtl = qtl[index]
            if temp_qtl > 0:
                counter = 1
                for i in range(number_of_piece):

                    if counter == number_of_piece:
                        #runs at last range to add remaining piece to the list
                        price = int(random.uniform((prices[index] / 1.05) , (prices[index] / 1.1)))
                        prices_for_pieces.append(price)
                        pieces.append(temp_qtl)
                    else:
                        #to make piece and add them to pieces
                        counter = counter + 1
                        new_qtl = int(random.uniform((qtl[index]/(number_of_piece * 2)),(qtl[index]/number_of_piece)))
                        temp_qtl = temp_qtl - new_qtl
                        print(new_qtl)
                        print(f' remain {temp_qtl} out of {qtl[index]}')
                        price = random.uniform((prices[index] / 1.05) , (prices[index] / 1.1))
                        prices_for_pieces.append(price)
                        pieces.append(new_qtl) 
    else:
        price = random.uniform((prices[index] / 1.05) , (prices[index] / 1.1))
        prices_for_pieces.append(price)
        pieces.append(qtl[index])   


# stats 
print(pieces)
print(len(pieces))
print(prices_for_pieces)
print(len(prices_for_pieces))
last = len(pieces)

# making sure if  it follows 'max' condition
for i in range(last):
    print(f'{pieces[i]} X {prices_for_pieces[i]} = {pieces[i] * prices_for_pieces[i]}')

Problem Every thing works fine as long as i keep using same data. But If i do

 qtl = [450, 20, 150]
 prices = [100, 12000, 400]
max = 5000

It doesn't work with my if condition, it doesn't go for last 2 for loops ( do for loop only 4 or 5out 6)




Aucun commentaire:

Enregistrer un commentaire