get variables outside the for loop in python - python

I am trying to print all the values of x not just 9 outside the for loop. What change do I need to make to my code?
for x in range(10):
x
print x

in:
vars = []
for i in range(10):
vars.append(i)
for i in vars:
print i
out:
0
1
2
3
4
5
6
7
8
9

It would be easier just to do print(range(10)), but you could also do:
aux = []
for x in range(10):
aux.append(x)
print(aux)

Use this
for x in range(10):
print(x+"\n")
the output will be
0
1
...
9
or
for x in range(10):
print(x+end=' ')
out
0 1 2 3 4 5 6 7 8 9
:)

Related

Python string length generate output

I am trying to create ruler by print, it should look like this for input value 5:
Im trying to change in my code numbers to symbols, my code is:
length = str(input("Enter the ruler length = "))
def ruler(string):
top = []
top_out = []
bottom = []
for i in range(length):
top.append((i+1)//10)
bottom.append((i+1)%10)
for i in range(length):
if ((i+1)//10) == 0:
top_out.append(" ")
elif (((i+1)//10) in list(sorted(set(top)))) and (((i+1)//10) not in top_out):
top_out.append(((i+1)//10))
else:
top_out.append(" ")
print (''.join(list(map(str, top_out))))
print (''.join(list(map(str,bottom))))
print (string)
How to correct it to get appropriate output format of a ruler?
Ruler printing can be down by pretty small function like this,
def print_ruler(n):
print('|....'*(n)+'|')
print(''.join(f'{i:<5}' for i in range(n+1)))
Execution:
In [1]: print_ruler(5)
|....|....|....|....|....|
0 1 2 3 4 5
In [2]: print_ruler(10)
|....|....|....|....|....|....|....|....|....|....|
0 1 2 3 4 5 6 7 8 9 10
In [3]: print_ruler(15)
|....|....|....|....|....|....|....|....|....|....|....|....|....|....|....|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
For double-digit numbers, It doesn't come to the center.
For ex: For 12, | align with number 1 or 2 it can't not make into the center of 12

Multiplication Tables in Python

this is my code right now:
loop_count = 1
for i in range(mystery_int):
for x in range(1,mystery_int):
print(x*loop_count, end=" ")
print (loop_count)
loop_count+=1
this is what it is supposed to print:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
But it prints:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
5 10 15 20 5
You need to range till mystery_int + 1 because in range, second argument is exclusive. So, for example, range(1,6) gives numbers from 1 to 5.
Also, I added an empty print() which basically adds a newline to match with desired output.
Using end='\t' further aligns output properly.
loop_count = 1
mystery_int = 5
for i in range(mystery_int):
for x in range(1, mystery_int + 1):
print(x * loop_count, end='\t')
print()
loop_count += 1
the range for x should be range(1,mystery_int+1), and you also incorrectly print loop_count at the end of each line (which I replaced with the empty string, just to produce a newline).
loop_count = 1
for i in range(mystery_int):
for x in range(1,mystery_int+1):
print(x*loop_count, end=" ")
print('')
loop_count+=1
Note that the loop_count variable is not really needed. You could write the program as:
for i in range(1,mystery_int+1):
for x in range(1,mystery_int+1):
print(x*i, end=" ")
print('')
or even better as:
for i in range(1,mystery_int+1):
print(*[x*i for x in range(1,mystery_int+1)], sep=" ")
you are running on two for loops in addition to using another counter, i would recommend sticking only to the loops:
for i in range(1,mystery_int+1):
for x in range(1,mystery_int+1):
print(i*x, end=" ")
print("") # new line

python Multiprocess with two list compare

I have the question on multiprocess in python3.5.
If i have two list like:
xlist = [1,2,3]
ylist = [4,5,6]
and I want to do :
for i in xlist:
for j in ylist:
print (i*j)
the output is
4
5
6
8
10
12
12
15
18
I try to do that like this with Multiprocess:
import multiprocessing
global xlist
xlist = [1,2,3]
ylist = [4,5,6]
def product(ylist):
for x in xlist:
for y in ylist:
print (x,y)
return 'OK'
if __name__ == "__main__":
pool = multiprocessing.Pool()
results = []
for i in range(0, len(ylist)):
result = pool.apply_async(job, args=(ylist,))
results.append(result)
# print (result.get())
pool.close()
pool.join()
for result in results:
print(result.get())
But I can not got the output show above. My output will be
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
1 4
1 5
...
with the code.
Are there any ways to achieve the goal (must use multiprocess)?
I think you want to try a simple example before using it on a very big set of numbers, and with a more complex function.
Here is one program that prints what you want, uses multiprocessing, and should scale for larger lists and more complex functions.
import multiprocessing
xlist=[1,2,3]
ylist=[4,5,6]
def enum_tasks():
for x in xlist:
for y in ylist:
yield (x,y)
def product(xy):
x,y = xy
return x * y
if __name__ == '__main__':
CHUNK_SIZE = multiprocessing.cpu_count()
pool = multiprocessing.Pool()
for result in pool.imap(product, enum_tasks(), CHUNK_SIZE):
print result

Keeping Python from spacing after breaking a line when printing a List

(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)
I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."
e.g
2 4 as entrance
1 2
3 4
e.g 2 6
1 2
3 4
5 6
Okay... So, I thought on doing this:
line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1
if i != final:
List = list(range(1, final + 1, 1))
i += 1
while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')
print(*List)
Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)
So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:
2 10 as entrance
1 2
3 4
5 6
7 8
9 10
And, using the code I just posted, I get this as a result:
1 2
3 4
5 6
7 8
9 10
Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)
Well, I've tried pretty much anything. Hope anyone can help me.
Thanks in advance :)
You have built a list that includes each necessary character, including the linefeed. Therefore, you have a list like this:
[1, 2, '\n', 3, 4, '\n'...]
When you unpack arguments to print(), it puts a separator between each argument, defaulting to a space. So, it prints 1, then a space, then 2, then a space, then a linefeed, then a space... And that is why you have a space at the beginning of each line.
Instead of inserting linefeeds into a list, chunk that list with iter and next:
>>> def chunks(x, y):
... i = iter(range(1, y+1))
... for row in range(y//x):
... print(*(next(i) for _ in range(x)))
... t = tuple(i)
... if t:
... print(*t)
...
>>> chunks(2, 6)
1 2
3 4
5 6
>>> chunks(2, 7)
1 2
3 4
5 6
7
The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.
Try this approach: (EDITED)
x, y = input().split()
x, y = int(x), int(y)
for i in range(1, y+1):
if i % x == 0 or i == y:
print(i)
else:
print(i, end=" ")
Output for 3 11
1 2 3
4 5 6
7 8 9
10 11
Output for 2 10
1 2
3 4
5 6
7 8
9 10
Use itertools to take from an iterable in chunks:
>>> import itertools
>>> def print_stuff(x,y):
... it = iter(range(1, y + 1))
... chunk = list(itertools.islice(it,X))
... while chunk:
... print(*chunk)
... chunk = list(itertools.islice(it,X))
...
>>> print_stuff(2,4)
1 2
3 4
>>>
And here:
>>> print_stuff(2,10)
1 2
3 4
5 6
7 8
9 10
>>>
I split user input into two string then convert them into int and comapre if y greater than x by 2 because this is minimum for drawing your sequence
Then i make a list from 1 to y
And iterate over it 2 element for each iteration printing them
x,y=input().split()
if int(y)>int(x)+2:
s=range(1,int(y)+1)
for i in range(0,len(s),2):
print(' '.join(str(d) for d in s[i:i+2]))
result:
1 2
3 4
5 6
7 8
9 10

Python Help finding value of i

What is the value of i at the end of the loop body when a is 6?
def loopIdentification():
i=0
for a in range(2,8):
i=i+a-3
return i
5
>>> def loopIdentification():
i=0
for a in range(2,8):
i=i+a-3
print a, i
return i
>>> loopIdentification()
2 -1
3 -1
4 0
5 2
6 5
7 9
9

Categories