How to get compare variables of a list individually? - python

So I have this code below that I'm trying to make, to where it will sort any list I give it so the lowest variable will be at the beginning, in position [0]. The problem I think is when the while loop comes in it compares uList[y] to the sum of uList[z:p] but, I was hoping it would compare it to each of the numbers individually so that if uList[y] is greater than ANY variable in uList[z:p] it would step into the loop how ever it does not. How would I go about making it compare the variables individually rather to the sum of them all, if that is whats happening.
Code:
import random
import sys
import os
import time
clear = lambda: os.system('cls')
clear()
y = 0
z = 1
x = 0
nNum = 1
uList = []
sList = []
listL = int(raw_input("How many elements would you like to be in your list?"))
clear()
while x < listL:
uList.append(int(raw_input("Num %s:" %(nNum))))
x = x + 1
nNum = nNum + 1
p = len(uList) - 1
clear()
print("Your list was %s!" %(uList))
while z <= p:
while uList[y] > uList[z]:
j = uList[y]
del uList[y]
uList.append(j)
print(uList)
P.S. Any other tips or advice on anything about my code would be greatly appreciated as I am very obviously knew to python and coding in general lol, thank you so much!

The comments under your answer suggest that you have already solved your problem but because you asked for some Python advice: the 'pythonic' way to iterate is by using a for loop with a range instead of a while loop.
i = 0
while i < 10:
i += 1
Becomes:
for i in range(10):
pass
If you want to get the indices of the sequence you are iterating over you can use enumerate.
my_list = [*range(10)] # this is basically a for loop creating a list
for index, element in enumerate(my_list):
print(index, element)
This gives you:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
One last thing though. I am not sure if you are using Python 2 or 3 because you are using raw_input (Python 2) and print() (Python 2 or 3). If you are learning Python or programming in general I would recommend you go with Python 3 because it is easier to learn in some aspects and offers various improvements in efficiency and effectiveness.

Related

When I run my code, I keep getting an error saying perhaps I forgot a comma. Where would this be an issue within the code?

n= int(input())
a= list(range(1,"x",n+1)
print(a)
b=1:
for b in a
if num % 2 != 0:
b= b*num
print(b)
This is for my into to python class and this is the question for context.
"Taking an integer value n from the user with input(). Your program will calculate the
product of all odd numbers from 1 through the given n. For example: the user gave
n=20. You python code will calculate the following value:
1 x 3 x 5 x 7 x 9 x 11 x 13 x 15 x 17 x 19
Your program will print out 654729075.0 back to the user.
Please calculate the value for n=23 using your program?"
When I run my code, I keep getting an error saying perhaps I forgot a comma. Where would this be an issue within the code? The r in range keeps getting highlighted.
Noticed a few issues here. First, you don’t need list() in your definition of a. You also don’t need a var named a at all.
Also, the syntax for range is range(start, stop, step). You want to start at 1, stop at n+1 (because range is exclusive), and move forward 2 each time. Therefore, it’s range(1, n+1, 2). The code will look like this:
n = int(input())
b = 1
for num in range(1, n+1, 2):
b *= num
print(b)
try this: You are adding unnecessary "x" in code range should (start, end, [Step])
n= int(input())
a= list( range(1,n+1) )
print(a)
ans=1
for i in range(len(a)):
if a[i] % 2 != 0:
ans*=a[i]
else:
continue
print(float(ans)
Read:
Try to go through built in functions
https://docs.python.org/3/library/functions.html
Range- https://docs.python.org/3/library/functions.html#func-range
List - https://docs.python.org/3/library/functions.html#func-list
The code has several flaws. The expert comments are already indicating that. here is one possible version of executable code that can do what you want.
n= int(input())
a=list(range(1,n+1,2))
print(a)
b = 1
for num in a:
b *= num
print(b)

Modify range() during for loop [duplicate]

This question already has answers here:
Changing the number of iterations in a for loop
(8 answers)
Closed 1 year ago.
can I modify range() during for loop?
for i in range(10):
if something:
pass
# change range
print(i)
An example:
Let method something be i == 5 and the body will decrease range by one.
Expected output:
0
1
2
3
4
5
5
6
7
8
9
I have a little more complex range() like range(0, len(data), 1024).
Thanks for any help!
You cannot modify the generator used in the for loop during the iteration process. Instead, you could refactor your code using a while loop. For example, if your range is range(start, stop, step) (using the notation similar to that used in the Python documentation), you can write the loop as follows:
i = start
while i < stop:
# do stuff
i += step
This allows you to modify i however you'd like inside the while loop.
Try the following:
i = 0
while i <= 5:
print(i)
i = i + 1
i = i - 1
while i <= 10:
print(i)
i = i + 1
As others have said, it is probably best to use a while loop in this scenario and manually increase your value every time the loop is performed, rather than using a for loop.
You can kind of modify it within the for loop using break keyword.
start_val = 0
stop_val = 10
for i in range(start_val ,stop_val):
if i==5:
start_val = 5
print(i)
for i in range(start_val ,stop_val):
print(i)
break
print(i)
This gives expected output:
0
1
2
3
4
5
5
6
7
8
9

I am having trouble fixing my code which tries to generate a random sudoku board using python 3x

This code is able to generate some rows but suddenly it goes into a infinite loop i suppose. please somebody fix this code.
import numpy as np
import random
soduku = np.zeros(shape=(9,9))
for i in range(0,9,1):
for j in range(0,9,1):
while True:
x = random.randint(1,9)
if x not in soduku[i,:] and x not in soduku[:,j]:
soduku[i,j] = x
if j == 8: print(soduku[i,:])
break
Your logic is faulty in that you have no provision for backtracking. Look at your inner loop:
# i and j are "given" at this point.
while True:
x = random.randint(1,9) # grab a random number
# Is it legal to put the number in this square? If not, keep looping
if x not in soduku[i,:] and x not in soduku[:,j]:
soduku[i,j] = x
if j == 8: print(soduku[i,:])
break
Now let's look at a simple situation, a partial fill, at the end of the second row:
1 2 3 4 5 6 7 8 9
4 5 6 7 8 1 2 3 _
We want to fill the last spot in the second row. However, no matter what number you pick in the range 1-9, the number already exists in either that row, or in the last column.
Your program has no way to back up and try again: it simply keeps choosing a random number and trying to put it there.
You need to research Sudoku filling algorithms. These are readily available on Stack Overflow and elsewhere on line.

Three values for a for loop

I would like to have three values increment at different speeds. My overall goal is to emulate this pattern:
0,0, 0
0,1, 1
0,2, 2
1,0, 3
1,1, 4
1,2, 5
2,0, 6
2,1, 7
2,2, 8
The first two numbers are easy. I would solve it like this:
for x in range(3):
for y in range(3):
print(x, y)
>>> 0 0
>>> 0 1
>>> 0 2
>>> 1 0
>>> 1 1
>>> 1 2
>>> 2 0
>>> 2 1
>>> 2 2
This is the pattern that I want.
The question is how do I increment the third number by one each time, while still having the first two numbers increment in the way that they are?
Basically, how can I make the third number increment by one each time the for loop goes?
Since we have all these answers, I will post the most straightforward one
count = 0
for x in range(3):
for y in range(3):
print(x, y, count)
count += 1
You don't need nested loops for this. You can use itertools.product to get your first two numbers, and enumerate to get your last one.
from itertools import product
for i, (u, v) in enumerate(product(range(3), repeat=2)):
print(u, v, i)
output
0 0 0
0 1 1
0 2 2
1 0 3
1 1 4
1 2 5
2 0 6
2 1 7
2 2 8
itertools.product is a very handy function. It basically performs nested loops efficiently, but its main benefit is that they don't look nested, so you don't end up with massively indented code. However, its real strength comes when you don't know how many nested loops you need until runtime.
enumerate is probably even more useful: it lets you iterate over a sequence or any iterable and returns the iterable's items as well as an index number. So whenever you need to loop over a list but you need the list items and their indices as well, it's more efficient to use enumerate to get them both at once, rather than having a loop that uses range to produce the index and then using the index to fetch the list item.
The third number counts how many total iterations you had so far. For each increment in X it gains the total size of Y's loop, and to that you need to add the value of Y:
X_SIZE = 3
Y_SIZE = 3
for x in range(X_SIZE):
for y in range(Y_SIZE):
print(x, y, x * Y_SIZE + y)
single variable. single loop.
for i in range(9):
print(i // 3, i % 3, i)
// is floor division and % is modulus (the remainder, in most cases)
Personally, I like this solution because it plainly explains the underlying pattern, and can therefore be easily altered or extended to other patterns.
Try this:
for x in range(3):
for y in range(3):
print(x, y, x * 3 + y) # Python 3.x
print x, y, x * 3 + y # Python 2.x
Hope this helps.
You can use simply a count variable for this
count = 0
for x in range(3):
for y in range(3):
print(x, y, ' ' ,count) # use ' ' for making exact look what OP asked..lol
count = count + 1
This looks more natural to me :)
x_range = 3
y_range = 3
for x in range( x_range*y_range ):
print(x // x_range, x % x_range, x)
Similar to what cwharris wrote.

Python find max number of combinations in binary

Hi I'm trying to figure out a function where given a length n of a list [x1, x2... xn], how many digits would be needed for a base 2 number system to assign a unique code to each value in the list.
For example, one digit can hold two unique values:
x1 0
x2 1
two digits can hold four:
x1 00
x2 01
x3 10
x4 11
etc. I'm trying to write a python function calcBitDigits(myListLength) that takes this list length and returns the number of digits needed. calcBitDigits(2) = 1, calcBitDigits(4) = 2, calcBitDigits(3) = 2, etc.
>>> for i in range(10):
... print i, i.bit_length()
0 0
1 1
2 2
3 2
4 3
5 3
6 3
7 3
8 4
9 4
I'm not clear on exactly what it is you want, but it appears you want to subtract 1 from what bit_length() returns - or maybe not ;-)
On third thought ;-), maybe you really want this:
def calcBitDigits(n):
return (n-1).bit_length()
At least that gives the result you said you wanted in each of the examples you gave.
Note: for an integer n > 0, n.bit_length() is the number of bits needed to represent n in binary. (n-1).bit_length() is really a faster way of computing int(math.ceil(math.log(n, 2))).
Clarification: I understand the original question now ;-) Here's how to think about the answer: if you have n items, then you can assign them unique codes using the n integers in 0 through n-1 inclusive. How many bits does that take? The number of bits needed to express n-1 (the largest of the codes) in binary. I hope that makes the answer obvious instead of mysterious ;-)
As comments pointed out, the argument gets strained for n=1. It's a quirk then that (0).bit_length() == 0. So watch out for that one!
Use the following -
import math
int(math.ceil(math.log(x,2)))
where x is the list length.
Edit:
For x = 1, we need to have a separate case that would return 1. Thanks #thefourtheye for pointing this out.
I am not comfortable with the other answers, since most of them fail at the corner case (when n == 1). So, I wrote this based on Tim's answer.
def calcBitDigits(n):
if n <= 0: return 0
elif n <= 2: return 1
return (n-1).bit_length()
for i in range(10):
print i, calcBitDigits(i)
Output
0 0
1 1
2 1
3 2
4 2
5 3
6 3
7 3
8 3
9 4
x = int(log(n,2))+1
x will be the number of bits required to store the integer value n.
If for some reason you don't want to use .bit_length, here's another way to find it.
from itertools import count
def calcBitDigits(n):
return next(i for i in count() if 1<<i >= n)

Categories

Resources