For loop in CS Circles section 7C coding exercise: One Triangle - python

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)

Related

Why am I not getting desired output in this code

I want to write a code for this question:
write a code which creates a new number 'n2' which consists reverse order of digits of a number 'n' which divides it without any remainder for example if input is 122
it will print 221 because 1,2,2 can divide 122 without any remainder another example is 172336 here 1,2,3,3,6 can divide it without any remainder so the output should be 63321(reverse order).
my code is:
n = str(input())
x = ""
z = 0
for z in range(len(n)):
if int(n)%int(n[z])==0:
x = n[z] + ""
else:
n.replace(n[z],"")
z = z+1
print(x[::-2])
if I input the number 122 here i get the output 2 but i should be getiing output of 221 why.
The reason why you are not getting the desired output in this code is because of several logical and syntactical errors in your code. Here are some of them:
You are using x = n[z] + "" to append the digits that divide n without any remainder, but this will overwrite the previous value of x every time. You should use x = x + n[z] instead.
You are using n.replace(n[z],"") to remove the digits that do not divide n without any remainder, but this will not modify the original value of n, since strings are immutable in Python. You should assign the result of n.replace(n[z],"") to a new variable, or use a different approach to filter out the unwanted digits.
You are using z = z+1 to increment the loop variable, but this is unnecessary and redundant, since the for loop already does that for you. You can remove this line.
You are using print(x[::-2]) to print the reversed value of x, but this will skip every other digit, since the negative step of -2 means you are slicing the string from the end to the beginning with a step of 2. You should use print(x[::-1]) instead, which will reverse the whole string. A possible corrected version of your code is:
python
n = str(input())
x = ""
for z in range(len(n)):
if int(n)%int(n[z])==0:
x = x + n[z]
print(x[::-1])
This code will print the reversed order of the digits of n that divide it without any remainder, as expected. For example, if the input is 122, the output will be 221.
The code works by iterating over each digit of the input number n, which is converted to a string for convenience. For each digit, it checks if it divides n without any remainder, using the modulo operator %. If it does, it appends the digit to the end of the string x, using the + operator. If it does not, it ignores the digit. After the loop, it prints the reversed value of x, using the slicing notation [::-1], which means start from the end and go backwards until the beginning.
This should do the Trick
num = input()
new_num = ""
for i in num:
if int(num)%int(i) == 0:
new_num += i
print(new_num[::-1])

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)

How to print the value of number during a "x" number of loops?

basically, Im trying to use a while loop to make an arithmetic sequence of numbers the code i made being rather simple:
x=2
while True:
x=x+3
print(x)
but a problem with this code of course is that there is no way i can find the value of x during a certain number of loops and rather this code prints every possible value in the sequence.
Does anyone know how i can make the code in a way that i can choose to print the value of x after a certain number of loops?
The easiest for a known nuber of iterations is a for-loop:
x = 2
iterations = 5
for _ in range(iterations):
x = x + 3
print(x)
This of course can be shortened in this particular example:
x = x + 3 * iterations

Putting integers in tabular form without whitespace in Python

Sorry that I ask this here, because this seems really elementary and is most likely asked before. However, I have been searching and trying for hours and I couldn't find anything that helped me out. I want to write a program that asks for an upper bound and returns a table with pairs of numbers (m,n) such that the sum of of divisors of n (excluding n) equals m, and vice versa.
Now I wrote the following
bound = int(input('upper bound = '))
l = len(str(bound))
for x in range(1,l):
print(' ', end='')
print('m', end=' ')
for y in range(1,l):
print(' ', end='')
print('n', end='')
for i in range(1,bound):
for j in range (1, bound):
if j == i:
break
som_i = 0
som_j = 0
for k in range(1,i):
if i % k == 0:
som_i += k
for l in range(1,j):
if j % l == 0:
som_j += l
if som_i == j and som_j == i:
print('{:{prec}d}'.format(j, prec = l).rstrip(''), end="")
print('{:{prec}d}'.format(i, prec = l+2).lstrip(''), end="")
The problem is that I want the pair to be displayed in tabular form side to side and with the right indentation, depending on the length of the number. Whatever I tried (I read so many treads with similar questions already) Python keeps adding a whitespace.
Can anyone help me out on this? I am really new to Python and I cannot figure this out myself. If relevant, I am using version 3.6.
EDIT:
For example, when I run the program I get:
upper bound = 300
m n
220
284
while I would like to get
upper bound = 300
m n
220 284
And similar for larger inputs.
EDIT2 My question is not a duplicate, since i already tried adding
end=""
which did not work.
The first problem is that you're not using end='' after printing the j value, but you apparently already know about that. You also are using it after printing the n header, which you don't want.
Your edited version fixes the missing end='' after the j print, but then adds one after the i print, which, again, you don't want.
I'm not sure you understand what end='' means, so you're just putting it into your code randomly. That isn't going to get you very far. You can read the docs for print, but the short version is: use end='' when you're printing something that isn't supposed to be the end of a line, like that m header and j value, but don't use it when you're printing something that is supposed to be the end of a line, like that n header and i value.
The second problem is that l is just way too big. After for l in range(1,j):, it's going to be the same value as j, which means it's going to be 219, so you're going to print that 220 filled out to 219 characters, and that 284 filled out to 221 characters. So, unless your terminal is more than 446 characters wide, it's going to scroll across multiple lines and look like a mess. I think what you may want here is to use 3 and 5.
Or, maybe, you have some other variable that's supposed to be 3, and you want to use (let's call that variable x) x and x+2 instead of l and l+2. But I don't see any obvious candidates in your code.
So:
# ... unchanged lines
print('n') # no end='' here
# ... more unchanged lines
# using 3 and 5 instead of l and l+2, and adding end=''
print(('{:{prec}d}'.format(j, prec = 3)).rstrip(''), end='')
print(('{:{prec}d}'.format(i, prec = 5)).lstrip(''))
And now, the output is:
upper bound = 300
m n
220 284

Print cubes of the numbers 1 through 10 only if the cube is evenly divisible by four

Is everything right with code_cademy here ?
cubes_by_four = [x*x*x for x in range(1,10) if (x*x*x) % 4 == 0]
for x in cubes_by_four:
print x
They are asking me to print each cube which is evenly divisible by four for numbers between 1 to 10. What am I doing wrong here ?
Also is this notation x^3 allowed to get the cube of x ? if yes then why does is it results in wrong output ?
Finally print that list to the console
>>> cubes_by_four = [x**3 for x in range(1,11) if x**3 % 4 == 0]
>>> print(cubes_by_four)
[8, 64, 216, 512, 1000]
It says print the list, not print each item in the list to console
When you write range(1,10), you include 1 but exclude 10.
So correct code is:
cubes_by_four = [x*x*x for x in range(1,11) if (x*x*x) % 4 == 0]
print cubes_by_four:
It will be a good practice to use x**3 for cubes.
cubes_by_four = [x**3 for x in range(1,11) if (x**3) % 4 == 0]
Your range is off. You need range(1, 11), because the second argument of range() is the first value to exclude. range(1, 10) only gives you number 1 through 9.
If you want to include the value 10 you must change the range to range(1, 11), since the range does not include the second parameter.
In regular Python, x^3 does not mean exponentiation but rather the binary operation "bitwise exclusive or". That is exponentiation in SageMath (which is based on Python) but not in regular Python, which uses x**3, or as in your code, x*x*x.
Since you want to print out the list all in one line, including the surrounding brackets, just print using print x. Use that instead of your last two lines of code.
The second argument to range is not included in the range.
Is it between 1 and 10? or is it 1 through 10?
between 1 and 10 is range(2,10)
1 through 10 is range(1,11)
Okay , a couple of things to keep in mind :-
1) if you want numbers 1-10 , do range(1,11) , since the last number is excluded, while the first number is (obviously) , included.
2) instead of (x*x*x) , you can something better like :- pow(x,3) , which essentially means x to the power 3,or x cubed.
So,your final code becomes :-
cubes = [pow(x,3) for x in range(1,11) if pow(x,3) % 4 == 0]
I hope this helps you , keep learning , getting stuck is a part of the wonderful journey in the world of programming . Cheers ! :)
There are two separate problems with the code you showed here:
First, change range(1,10) to range(1,11) because Python doesn't include the second parameter (10), and 10^3 is evenly divided by 4 (1000/4 = 250).
And finally, the tutorial wants you to print the numbers all in a single line, so just use print cubes_by_four instead of the for loop that you used to print each number in a different line.
script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10
for x in range(1,11):
print(x*x*x)
The thing that helped me, was realizing that the range excludes 1, i.e.: range(0,9) will only do 0-8, the right way to do it unless you want 0-8 is 0-10.
Taken from Codecademy:
Use a list comprehension to create a list, cubes_by_four.
The comprehension should consist of the cubes of the numbers 1 through
10 only if the cube is evenly divisible by four.
Finally, print that list to the console.
Note that in this case, the cubed number should be evenly divisible by
4, not the original number.
cubes_by_four = [x ** 3 for x in range(1,11) if (x ** 3) % 4 == 0]
print cubes_by_four
Result:[8, 64, 216, 512, 1000] ie: Range of 5 cubed numbers (evenly divisible by 4)
for x in range(1,11):
print(x*x*x)

Categories

Resources