how to change a variable name in a while loop? - python-2.7

I have a question. I want to use a while loop and in the while loop I have to assign a view lists, but they shouldn't be assigned to the same variable over and over again. but I don't know how much lists I have to assign.
K = 2
D = 2
while( K <= 2 or K >= 20):
K = int(raw_input("Give the number of candidates running for speaker. "))
if(K <= 2 or K >= 20):
print("Sorry, wrong input.")
while(D <= 2 or D >= 1000):
D = int(raw_input("Give the number of people who take part in the meeting. "))
if(D <= 2 or D >= 1000):
print("Sorry, wrong input.")
row = 1
vlist = [[]*D]
while(D > row):
while(K < len(vlist[row-1])):
number = int(raw_input("Give a number of a person you want to win: "))
if(0 < number < K and number not in vlist[row-1]):
vlist[row-1].append(number)
else:
print("Sorry, wrong input, try again.")
row += 1
this is what I have now, but it throws the following error: List index out of range. I don't get why...

First item of list is empty: len(vlist[0])
returns 0, so list[row-1] is trying to acces element of -1 index.

Related

Appropriate logic for this pattern

How do I print a pattern with number of rows is equal to number of stars such that if 1 star then 1 row of 1 star, 2 star then 2 rows of 2 stars and so on, provided with good logic?
Here's the output for the logic mentioned above
*
**
**
***
***
***
using mod operator you can get proper output.Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or remainder operator. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1. You can use % just as you might use any other more common operator like + or -.
I write code in java.
Execution Steps:-
for loop for declare i value to 1.loop start with value 1 and last value 5.
for loop for declare i value to 1.in this we gave condition for j is i*i.
if j value is 1 then it print star.
if j value is not 1 then it goes to else part.
in this there are again if and else part in if part we use mod operator and if its value gives 0 value then print star otherwise goto else condition.
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i * i; j++) {
if(j == 1) {
System.out.println();
System.out.print("*");
} else if(j % i == 0) {
System.out.print("*");
System.out.println();
} else {
System.out.print("*");
}
}
}

Program determines how many numbers are positive, negative, or zeros

(Edit: Using python 2.7) I’m trying to get the user to input 10 numbers and the program needs to count and determine how many are negative, positive, or zeros.
However, everytime I run the program, it doesn’t give me the right number of negative or positive (or zero) numbers
i =[]
for i in range(10)
i = input('Enter Next Number: ')
n = 0
p = 0
z = 0
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
elif (i == 0):
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
As Johnny Mopp suggested in his comment, you need to declare your counters outside of the loop. If you declare them inside, they are reset at every iteration and you are only counting the last number input by the user
n = 0
p = 0
z = 0
for i in range(10):
i = input('Enter Next Number:')
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
else:
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
You will also want to convert the inputs to integers. If you really wish to add them to the list you will then need to iterate through the list after gathering all of the inputs. If retaining the values in a list is not needed #Bentaye answer will work just fine.
i =[]
n = 0
p = 0
z = 0
for num in range(10):
x = int(input('Enter Next Number: '))
i.append(x)
for y in range(len(i)):
if (i[y] > 0):
p = p+1
elif (i[y] < 0):
n = n+1
elif (i[y] == 0):
z = z+1
print ("The number of negative numbers is",n)
print ("The number of positive numbers is",p)
print ("The number of zeros is",z)

List manipulation to extract values greater than current and remaining index values

I have following list:
elev = [0.0, 632.8, 629.9, 626.5, 623.7, 620.7, 620.7, 607.4, 603.2, 602.0, 606.6, 613.2, 608.4, 599.7, 583.6]
Ideally it should be in descending order but 602.0 is smaller than next 3 values (606.6,613.2,608.4) and I need a count of those values each time this issue arises. I am trying nested for loops to count those values with following:
l = len(et)
for i in xrange(1,l-1,1):
for j in xrange(1,l-1,1):
if (et[i] < et[j]):
print et[i]
But instead I get all values greater than 602.0. How do I restrict loop to only count those 3 values? Appreciate any suggestions.
I guess this will solve your problem:
l = len(et)
for i in xrange(1,l-1,1):
if et[i] < et[i+1]:
for j in xrange(i,l-1,1):
if (et[i] < et[j]):
print et[j]
It will print the values greater than your number, not all but only the ones which came after the number.
This is what I've got from my terminal:
>>> for i in xrange(1,l-1,1):
... if et[i] < et[i+1]:
... print "for",et[i]
... for j in xrange(i,l-1,1):
... if (et[i] < et[j]):
... print et[j]
...
for 602.0
606.6
613.2
608.4
for 606.6
613.2
608.4
l_elev = len(elev)
gt_cnt = 0
eq_cnt = 0
slp_idx = []
for i in xrange(1,l_elev-3,1):
# following will take care of greater than current value inversion
if elev[i+gt_cnt] < elev[i+1+gt_cnt]:
lnew = elev[i+gt_cnt:]
gt_inv = [y for y in lnew if y >= elev[i+gt_cnt]]
gt_cnt += 1
for x in xrange(i,i+len(gt_inv),1):
slp_idx.append(x)
# following will take care of adjacent equal values
if (elev[i+eq_cnt] - elev[i+eq_cnt+1]) == 0:
cnew = elev[i:]
eq_inv = [y for y in cnew if y == elev[i+eq_cnt]]
eq_cnt+=1
for y in xrange(i,i+len(eq_inv),1):
slp_idx.append(y)
# break loop to avoid out of index error
if i+gt_cnt > l_elev:
break

Prime number checkers

I have a problem with my code that my teacher ask my to check the prime numbers but he does not allow me to use If-Else function . Here is my code:
def is_prime(n):
i = 2
while (i % n != 0):
while (n % i == 0) and ( n != i):
print("False")
break
i += 1
while (i == n):
print("True")
break
number = int(input("Please enter a certain number: "))
print(is_prime(number))
But the problem is when i print out the result, it's a little bit weird with the numbers which are not a prime number:
Please enter a certain number: 10
False
False
True
None
How would i solve this problem? I just need one answer: True or False. Thank you for your helps!!!
To be short: let your function to return a value, not to print it.
def is_prime(n):
i = 2
while (i % n != 0):
while (n % i == 0) and ( n != i):
return False
i += 1
return True
number = int(input("Please enter a certain number: "))
print(is_prime(number))
Explanation:
As soon as you find out that n is not prime (line while (n % i == 0) and ( n != i):) you return False. The function is left at this moment so you do not need break. If n is not found to be divisible by any i you return True.
The True or False is now the result of the function and you can print it or assign to a variable and use somewhere else. E.g.
x = is_prime(12) // x is False now

List index out of range (Python 2.7)

I feel like I am constantly having this problem when I am writing a program, what I want to do is iterate over every value in my nested list and say that if it's not a zero, make it one.
Here is the error I am getting:
Traceback (most recent call last):
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 65, in <module>
resetBoard()
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 49, in resetBoard
if board[i][j] != 0:
IndexError: list index out of range
Here is my full code:
import random
grid = [100,100]
board = [[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,5,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
playerX = None
playerY = None
randX = 0
randY = 0
def getRandomGridPos():
global randX, randY
randX = int(random.uniform(0, grid[0]))
randY = int(random.uniform(0, grid[1]))
def main():
pass
def printBoard():
print str(board[0]).replace(',', '')
print str(board[1]).replace(',', '')
print str(board[2]).replace(',', '')
print str(board[3]).replace(',', '')
print str(board[4]).replace(',', '')
print str(board[5]).replace(',', '')
print str(board[6]).replace(',', '')
print str(board[7]).replace(',', '')
print str(board[8]).replace(',', '')
print str(board[9]).replace(',', '')
def resetBoard():
i = 0
j = 0
while i < 10:
if board[i][j] != 0:
board[i][j] = 0
j += 1
print "Looping"
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
print "I == 10"
else:
j += 1
resetBoard()
Can someone help me find a solution and also help me not get this error anymore (explain why it happens)?
You've already gotten several pointers to the cause of your error, but I just wanted to point out a clearer pattern to iterate multi-dimensional arrays:
for x in range(0, 10):
for y in range(0, 10):
# you will now have all values for a 10x10 array in x & y
if board[x][y] != 0:
board[x][y] = 0
If you really just want to make sure all board fields (10 x 10) are zeros, the following is even more consice:
# zero out a 10 x 10 multi-dimensional array
board = [[0] * 10] * 10
Your for reset board doesn't work for the following reasons:
"if i == 10" ,i never actually reaches 10, since it is in a while loop which states "while i < 10". The loop would exit before i actually reaches 10
no nested while loop. You need two while loops to reset the board.
When j reaches 10 this line raises an index error: if board[i][j] != 0: , because j equals 10, and the maximum index you can take of a 10 element list is 9(since index starts at 0)
I recommend reading the following
http://introtopython.org/lists_tuples.html
I would add that one of the best ways to achieve what you want in python with loops is:
for row in board: # runs the following once for every item in board
for item in row: # runs the following for every item in row.
# A second for statement is required because
# multidimensional lists are lists of lists.
if(item != 0)
item = 0 #sets items to 0 if the item isn't equal to 0
UPDATE:
Sorry but I also encoutered another problem, my bad for not checking the code:
The final code should be:
while i < 10:
if j == 10:
j = 0
i += 1
print ("J == 10")
elif board[i][j] != 0:
board[i][j] = 0
j += 1
print ("Looping")
else:
j += 1
The problem I missed was that you should have checked the j boundary before trying to access the array, only then you should start the loop again.
The problem is in this part:
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
if i = 9, j= 10 then we enter into the first if which changes i,j to be 10,10
Then the code continues and we enter the second if, thus reseting i and j making the loop go again and again...
Solve it by deleting the second if part, since the while condition will make sure we will never go to that case in the first place.