I'm new to programming and have been experimenting with for loops to try and figure out how to make different shapes however I have encountered a problem that I cannot solve.
So far I have been able to create a rectangle of 1's as shown below in a 5X5
for i in range(0, 5):
X = 0
for j in range(0, 5):
X = (X*10)+1
print(X)
I would like to be able to modify this code using a for loop to be able to create a triangle like so...
1 1 1
1 1
1
How would I go about doing this? Is there also a way that I could input n and dependant on whatever number is input the program creates a triangle of that size? for example I input a 5 and it creates a triangle like...
11111
1111
111
11
1
Ive tried various different things but i'm unable to figure it out.
def triangle(c, n):
for i in xrange(n, 0, -1):
print c * i
triangle("X", 5)
prints:
XXXXX
XXXX
XXX
XX
X
don't try to modify it.
make a new one
def generateLine(size):
line = ""
for i in range(0, size):
line = line+"1"
return line
for i in range(6, 0):
print generateLine(i)
Related
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)
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.
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.
Here is an example of a for loop inside another for loop.
Example
This code prints a 5×5 square of ones.
Note: when we multiply a number X by ten and add one, we're essentially putting an extra 1 digit at the end of X. For example, (1867*10)+1=18671.
for i in range(0, 5):
X = 0
for j in range(0, 5):
X = (X*10)+1
print(X)
Modify the previous program in two ways. First, instead of a square, make it draw a triangle shaped like this: ◤. Second, instead of always having 5 lines, it should take the desired size as input from input(). For example, if the input is 3, then the output should be
111
11
1
So far the code that I have got is:
X=input()
for i in range(0, 3):
X = 0
for j in range(0, 3):
X = (X*10)+1
print(X)
However this code outputs:
1
11
111
When the expected output should be:
111
11
1
I can't seem to figure out how to change my code that I have so far to get the expected output?
This can solve the problem for you:
def test(X,_range):
x = X
for j in range(0, _range):
print int(str((x*10) +1) + ("1"*(_range-1-j)))
test(0,3)
>>>
111
11
1
>>>
In every loop step the number starts with (X*10)+1
In the next step X has changed and you add the digit 1 to the right side
If want to reverse it, you need to use ("1"*(_range-1-j))
The for iterator changes the X content every step. (he don't use i and j, "For" only for step derivation )
Here's the solution:
n=int(input())
for i in range(0, n):
X = 0
for j in range(0, n-i):
X = (X*10)+1
print(X)
As you said, 10*X + 1 means putting extra 1 at the end of X. You need an inverse operation: how to remove the last digit of a number. Hint: integer division. Google "python integer division" to get to pages such as Python integer division yields float.
So, then all you've to do is construct 111...11 of the right length, and then iteratively print and remove digits one by one.
This block is very confusing, here's what happens:
X=input()
Get value of X from input.
for i in range(0, 3):
X = 0
Now set the value of X to 0 three times (overwriting your input)
for j in range(0, 3):
X = (X*10)+1
print(X)
Now X is being set to 1, then 11 and then 111.
Even if you meant to nest the for loops, this wont behave right. Instead, you want to get the i value to loop backwards, using the slice operator [::-1]. You should then make j's range be zero to i.
You'll also need to compensate by increasing the value of both numbers in i's range (otherwise the last line will be a zero) but this will work:
for i in range(1, 6)[::-1]:
X = 0
for j in range(0, i):
X = (X*10)+1
print(X)
Note that I moved the print out of the j loop, as that wasn't how the original code was (and generated the wrong output), pay attention to whitespace. Using 4 spaces is preferable to just 2 for reasons like this.
If you are doing CS Circles than these other answers probably contain code you still haven't come in contact with, at least I haven't, so I'll try to explain it with the knowledge I've gathered so far (couple weeks doing CS Circles).
You are ignoring the first loop and it is where your answer lies. Notice that if you put the print command outside of the loop body it would just output:
111
That it because your second loop is not in the body of the first, so python just loops the first one 3x and than moves to the second loop. Instead it should be:
for i in range(0, 3):
X = 0
for j in range (0, 3):
X = (X*10)+1
print(X)
Now the program outputs:
111
111
111
But you want one less digit each time print is called again. This is achieved by subtracting the value of "i" (since it neatly goes from 0 to 2) from second loop's range tail value. So now you have :
for i in range(0, 3):
X = 0
for j in range(0, 3-i):
X = (X*10)+1)
print(X)
Finally the output is:
111
11
1
Protip: use the visualizer in CS Circles, it helps you better understand the way code is executed in python, and can provide insight to your problems. Best of luck!
The easiest way is to use the following code;
p = int(input())
for i in range(0,p):
x = 0
for j in range(i,p):
x = (x*10)+1
print(x)
I have one array 'barray' of size 'bsize' and another 'carray' of size 'csize'.
The i loop is for barray and j loop is for carray.
I get an error that i is not defined. I want the loops to go from 0 to bsize - 2 in steps of 3, and 0 to csize - 2 in single steps.
How should I relate the size and array to the for loop?
bsize = 960
csize = 960
barray = bytearray(fi.read())
carray= bytearray(f1.read())
for i in range (bsize-2,i+3):
for j in range (csize-2,j+1):
for i in range (0, bsize - 2, 3): #possibly bsize - 1?
for j in range (csize - 2): # possibly csize - 1?
#do your thing
That will loop through the first one incrementing i by 3 every time, and j by 1.
Look at this tutorial or these docs to learn range, it's really useful!
I'm not sure if you want to go through bsize - 2 or just up to it. If through, use size - 1 to get size - 2.
The reason you're getting an error is that you haven't defined the i you're using in the step. As you can see, python's range isn't like a lot of other languages' for constructs. Once you get used to it, though, it's really flexible and easy to use.
Some examples using simple range:
>>> for i in range(0, 14, 3):
... print i
...
0
3
6
9
12
>>> for i in range(1, 5):
... print i
...
1
2
3
4
>>> for i in range(5):
... print i
...
0
1
2
3
4