question regarding while loops and variable indexing - python

I am new to coding, so forgive me if this is answered elsewhere. I am not sure what to search for to find a relevant answer. I also am not sure if my title is even correct. I want to print out each value in C_numbers that is associated with the same index in barcode_names. I want to separate these numbers each time the value in barcode_names changes. So I am using a third list unique_barcodes to compare to.
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
unique_barcodes = [1111,2222,3333]
x = 0
y = 0
for z in barcode_names:
if barcode_names[x] == unique_barcodes[y]:
print(C_numbers[x])
x = x+1
else:
y = y+1
print('next page')
result:
12
5
7
next page
28
32
13
next page
For some reason, it doesn't print the last two values 2 and 9. How do I get it to continue looping until it finishes printing all the values?

You're looping over barcode_names, so the most iterations that loop can make is eight. Increasing y while printing next page counts as one of those iterations. This prevents you from doing the last two things you wanted to do, as then you'd need a total of ten iterations. To fix this, you need to keep looping as long as x is a valid index in barcode_names. Change for z in barcode_names: to while x < len(barcode_names):.

Using x and y was throwing off your loop and is why it didn't complete.
Maybe something like this is more simple?
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
last_name = barcode_names[0]
for i in range(len(barcode_names)):
barcode_name = barcode_names[i]
if not barcode_name == last_name:
last_name = barcode_name
print('next page')
print(C_numbers[i])
result:
12
5
7
next page
28
32
13
next page
2
9

The loop control variable z is not stopping itself from being incremented when y index value is incrementing. Hence, before your desired print, the loop gets terminated.
I found this by adding the following line to your code inside the loop at the beginning
print('z value: ', z)
i.e. complete program becomes:
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
unique_barcodes = [1111,2222,3333]
x = 0
y = 0
for z in barcode_names:
print('z value: ', z)
if barcode_names[x] == unique_barcodes[y]:
print(C_numbers[x])
x = x+1
else:
y = y+1
print('next page')
Output:
z value: 1111
12
z value: 1111
5
z value: 1111
7
z value: 2222
next page
z value: 2222
28
z value: 2222
32
z value: 3333
13
z value: 3333
next page
>
Try this instead:
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
unique_barcodes = [1111,2222,3333]
x = 0
y = 0
for z in barcode_names:
# print('z value: ', z)
if barcode_names[x] != unique_barcodes[y]:
y = y+1
print('next page')
print(C_numbers[x])
x = x+1
Output:
12
5
7
next page
28
32
13
next page
2
9
>

Related

Working with document, MAX, MIN values and list

I have a document in which a first number is a number of racers, the second is time in the first lap and the third is time in the second lap.
I want to count how many people were DNF in the first round, How many in the second, the Best time in the first round, the second round, and what was the best time.
r.n. 1. 2.
329 56 47
129 55 0
78 0 0
pretek = open ("26-pretek.txt", "r")
riadok = pretek.readline ()
preteky = []
x=0
y=0
while riadok != "" :
a = riadok.strip().split()
preteky.append (a)
riadok = pretek.readline ()
print(preteky)
if "0" in preteky[1]:
x+=1
print(x)
if "0" in preteky[2]:
y+=1
print(y)
naj1=min(preteky[2])
naj2=max(preteky[2])
print(naj1)
print(naj2)

Python convert String to Variable in the loop

I would like to do something like this:
x = 0
y = 3
TEST0 = 10
TEST1 = 20
TEST2 = 30
while x < y:
result = exec('TEST{}'.format(x))
print(result)
x += 1
And have the output:
10
20
30
Somehow convert TEST{variable} to the actual variable, or what is the way to do it?
Currently, I have result as:
None
None
None
Welcome to Python! What you need is a list:
x = 0
y = 3
TEST = [10, 20, 30]
while x < y:
result = TEST[x]
print(result)
x += 1
A list is created by putting the values between []. You access a particular element in the list by writing the name of the variable, followed by the index enclosed in []. Read more about lists here in the official tutorial.
Instead of the while loop with explicit indexing, it's nicer to use a for loop instead:
TEST = [10, 20, 30]
for element in TEST:
result = element
print(result)
I would recommend using a dictionary in most cases, however if you don't want to use a dictionary you can always use globals() or vars(). They work as follows:
global_var = 5
>> 5
print(globals()["global_var"])
>> 5
vars() works in the same way but at module scope.
In your case, do the following:
x = 0
y = 3
TEST0 = 10
TEST1 = 20
TEST2 = 30
while x < y:
result = globals()['TEST{}'.format(x)]
print(result)
x += 1

how to print true or false depending on addition in python?

I am a bit confused on how to get this to print either true or false, for example, you have 4 of Xobject which have a value of 2 each and you have 5 of Yobject which have a value of 5 each.
you have to see if 3 xobject and 2 yobject fit into 15. this should print false as you are not able to break the objects in half or count all of them together.
as in you can not do 3(2) + 2(5) = 16, which is larger than 15 but involves you adding the objects together which is not allowed as they are meant to be two completely different things
ok so here's one way of doing it:
x = 2 #value of each x object
y = 5 #value of each y object
xObjects = int(input('How many x objects:'))
yObjects = int(input('How many y objects:'))
if ((xObjects * x) + (yObjects * y)) == 15:
print("True")
else:
print("False")

seven (7) boom game in one line code python

I need to create a game that every number that divides in 7 or has the digit 7 should be printed as boom:
[1 2 3 4 5 6 boom 8 ... 13 boom 15 16 boom ...]
my line get invalid text. I think its because of the mix of int and str. not shore what to do to fix the code.
boom7 = [x = "boom" if 7 in x else x*1 for x in range(1,99)]
print(boom7)
almost, this should do it
[ "boom" if "7" in str(x) or x%7==0 else x for x in range(1,99)]
let me know if you need explaining
def seven_boom(end_number):
for x in range(0,end_number+1):
str_first = str(x)
replace_first_num = str_first.replace(str_first[0],"boom")
if "7" in str_first or x%7 ==0:
new_seven_boom = str_first.replace(str_first,"boom")
print(new_seven_boom)
else:
print(x)
replace_last_num = str_first.replace(str_first[-1],"boom")
seven_boom(27)

A simple prog in Python. Involves digits of numbers

So basically, this prog reads 5 numbers:
X, Y, startFrom, jump, until
with space separating each number. an example:
3 4 1 1 14
X = 3
Y = 4
1 = startFrom
jump = 1
until = 14
In order to do that, I used:
#get X, Y, startFrom, jump, until
parameters = raw_input()
parametersList = parameters.split()
X = int(parametersList[0])
Y = int(parametersList[1])
#start from startFrom
startFrom = int(parametersList[2])
#jumps of <jump>
jump = int(parametersList[3])
#until (and including) <until>
until = int(parametersList[4])
The program outputs a chain (or however you would like to call it) of, let's call it BOOZ and BANG, when BOOZ is X if exists in the number (i.e X is 2 and we are at 23, so it's a BOOZ) . in order to check that (I used: map(int, str(currentPos)) when my currentPos (our number) at first is basically startFrom, and as we progress (add jump every time), it gets closer and closer to until), or if X divides the currentPos (X%num == 0. i.e: X is 2 and we are at 34, it's also a BOOZ).
BANG is the same, but with Y. If currentPos is both BOOZ & BANG, the output is BOOZ-BANG.
startFrom, startFrom+ jump, startFrom+2*jump, startFrom+3*jump, ..., until
We know the numbers read are int type, but we need to make sure they are valid for the game.
X and Y must be between 1 and 9 included. otherwise, we print (fter all 5 numbers have been read): X and Y must be between 1 and 9 and exit the prog.
In addition, jump can't be 0. if it is, we print jump can't be 0 and exit the prog. Else, if we can't reachuntil using jump jumps (if startFrom+ n * jump == until when n is an int number) so we need to print can't jump from <startFrom> to <until> and exit the prog.
My algorithm got too messy there with alot of ifs and what not, so I'd like an assistance with that as well)
so for our first example (3 4 1 1 14) the output should be:
1,2,BOOZ,BANG,5,BOOZ,7,BANG,BOOZ,10,11,BOOZ-BANG,BOOZ,BANG
another example:
-4 -3 4 0 19
OUTPUT:
X and Y must be between 1 and 9
juump can't be 0
another:
5 3 670 7 691
OUTPUT:
BOOZ,677,BANG,691
another:
0 3 4 -5 24
OUTPUT:
X and Y must be between 1 and 9
can't jump from 4 to 24
another:
3 4 34 3 64
OUTPUT:
BOOZ-BANG,BOOZ,BANG,BOOZ-BANG,BANG,BANG,BANG,55,58,61,BANG
my prog is toooo messy ( I did a while loop with ALOT of ifs.. including if currentPos==until so in that cause it won't print the comma (,) for the last item printed etc.. but like I said, all of it is so messy, and the ifs conditions came out so long and messy that I just removed it all and decided to ask here for a nicer solution.
Thanks guys
I hope it was clear enough
My version has no if :)
parameters = raw_input()
sx, sy, sstartfrom, sjump, suntil = parameters.split()
x = "0123456789".index(sx)
y = "0123456789".index(sy)
startfrom = int(sstartfrom)
jump = int(sjump)
until = int(suntil)
for i in range(startfrom, until+jump, jump):
si = str(i)
booz = sx in si or i%x == 0
bang = sy in si or i%y == 0
print [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang]
Easiest way to get the commas is to move the loop into a generator
def generator():
for i in range(startfrom, until+jump, jump):
si = str(i)
booz = sx in str(i) or i%x == 0
bang = sy in str(i) or i%y == 0
yield [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang]
print ",".join(generator())
Sample output
$ echo 3 4 1 1 14 | python2 boozbang.py
1,2,BOOZ,BANG,5,BOOZ,7,BANG,BOOZ,10,11,BOOZ-BANG,BOOZ,BANG
$ echo 5 3 670 7 691 | python2 boozbang.py
BOOZ,677,BANG,691
$ echo 3 4 34 3 64 | python2 boozbang.py
BOOZ-BANG,BOOZ,BANG,BOOZ-BANG,BANG,BANG,BANG,55,58,61,BANG
def CheckCondition(number, xOrY):
return (xOrY in str(number)) or not (number % xOrY)
def SomeMethod(X, Y, start, jump, end):
for i in range(start, end, jump):
isPassX = CheckCondition(i, X)
isPassY = CheckCondition(i, Y)
if isPassX and isPassY:
print "BOOZ-BANG"
elif isPassX:
print "BOOZ"
elif isPassY:
print "BANG"
else:
print i
def YourMethod():
(X, Y, start, jump, end) = (3, 4, 1, 1, 14)
if (X not in range(1, 10) or Y not in range(1, 10)):
print "X and Y must be between 1 and 9"
if jump <= 0:
print "juump can't be less than 0"
SomeMethod(X, Y, start, jump, end)

Categories