I'm new to this enumerate command and I'm not sure if I'm supposed to use it like this, what I want to do is to enumerate the ASCII characters from 0 - 129, and what I get is '1' before each character.
for x in range(129):
xxx = chr(x)
z = list(xxx)
for i, a in enumerate(z, 1):
print(i, a)
random text output:
1 .
1 /
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
You are looping over a list with a single character in it:
>>> xxx = chr(65)
>>> xxx
'A'
>>> list(xxx)
['A']
>>> len(list(xxx))
1
You then loop over the enumerate() result for that single character, so yes, you only get 1.
You repeat that inner loop for each value of x, so you do get it 129 times. It is your outer for x in range(129) loop that makes the 1s repeat.
You'd use enumerate() for the outer loop, and there's no point in turning your single character into a list each time:
for i, x in enumerate(range(129)):
xxx = chr(x)
print(i, xxx)
Note that x is already an increasing integer number however. enumerate() is really just overkill here. Just print x + 1 for the same number:
for x in range(129):
xxx = chr(x)
print(x + 1, xxx)
Related
I am really struggling with this program. I would appreciate any kind of help.
For a natural number we say that it is strange if it is completely composed of digits 2 and 3. The user enters a natural number. The program prints the n-th strange number.
Numbers that are considered strange are 2, 3, 22, 23, 33...
n = int(input())
current_number = 1
counter_strange = 0
counter = 0
while counter_strange < n:
x = current_number
while x < n:
k = x % 10
if k != 2 or k != 3:
counter += 1
else:
break
if counter >= 1:
counter_strange += 1
current_number += 1
print(current_number-1)
Strange numbers come in blocks. A block of 2 1-digit numbers, followed by a block of 4 2-digit numbers, then 8 3-digit numbers. You can do the math and determine which block of k-digit numbers a given index n is, and how far into that block it lies. Convert that distance into a base-2 number, zero-filled to k digits, then replace 0 by 2 and 1 by 3. Convert the result back to an int:
from math import log2, ceil
def strange(n):
"""returns the nth strange number"""
#first determine number of digits:
k = ceil(log2(n+2)) - 1
#determine how far is in the block of strange k-digit numbers
d = n - (2**k - 1)
#convert to base 2, zfilling to k digits:
s = bin(d)[2:].zfill(k)
#swap 2,3 for 0,1:
s = s.replace('0','2').replace('1','3')
#finally:
return int(s)
for n in range(1,10): print(n,strange(n))
Output:
1 2
2 3
3 22
4 23
5 32
6 33
7 222
8 223
9 232
You can use a while loop with itertools.product in a generator function. Using a generator will allow you to create a stream from which you can access strange numbers on the fly:
import itertools
def strange():
c = 0
while True:
yield from map(''.join, itertools.product(*([['2', '3']]*(c:=c+1))))
s = strange()
for _ in range(10):
print(int(next(s)))
Output:
2
3
22
23
32
33
222
223
232
233
i can't understand this convention range in python, range(len(s) -1) for representing all elements including the last one. For me makes no sense like when I print all elements the last one is not included in the list. Someone could help me understand this logic?
this>
s = "abccdeffggh"
for i in range(len(s) -1):
print(i)
result this
0
1
2
3
4
5
6
7
8
9
you are trying to print range to compiler you saying like this print numbers greter than 1 and below than 10 to the output not include 1 and 10 compiler only print 2,3,4,5,6,7,8,9 in your case
s = "abccdeffggh"
this s string length must be 11 if you print like this
s = "abccdeffggh"
for i in range(len(s)):
print(i)
you get output as 1,2,3,4,5,6,7,8,9,10 that is the numbers between 0 and 11
but in your code you have subtract -1 from the length then your range is become -1 and 10 then compiler print all numbers between the -1 and 10 it not include -1 and 10
try this code
s = "abccdeffggh"
print(len(s))
print(len(s)-1)
for i in range(len(s)):
print(i)
while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
I got two strings, called string1 and string2. Both consists of 6 different numbers.
What i would like to do in Python is to substract the values in string1 from the values in string2. How do I do this? I Guess this involves a for loop, since I only want to substract the first value in string1 from the first value in string2. And substract the second value from string1 from the second value in string2 etc.
So if string 1 got the numbers
2 5 8 9 6 3
and string 2 got the numbers
2 3 5 9 3 2
I want to take "string1" minus "string2" to get
0 2 3 0 3 1
Any suggestions?
You can achieve this with split(), zip(), and join():
" ".join([str(int(a) - int(b)) for a, b in zip(s1.split(), s2.split())])
Building on #pault answer, you can have the following variation (removed the calls to split(), added a conditional):
"".join([str(int(a) - int(b)) if a != ' ' else ' ' for a, b in zip(s1, s2)])
which is simply fancier way of doing:
" ".join([str(int(a) - int(b)) for a, b in zip(s1.replace(' ', ''), s2.replace(' ', ''))])
The latter might be more readable.
You can use regular expressions:
import re
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
new_string = ' '.join(str(a-b) for a, b in zip(map(int, re.findall('\d+', s1)), map(int, re.findall('\d+', s2))))
Output:
'0 2 3 0 3 1'
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
l1 = [int(x) for x in s1.split()]
l2 = [int(x) for x in s2.split()]
r1 = [v1 - v2 for v1, v2 in zip(l1, l2)]
.split() splits your string into a list based on where whitespace occurs (although you could provide it an argument to tell it to split on something else).
[int(x) for x in s1.split()] is a list comprehension. It's a one-line loop that does stuff for each value in a list (the split string). We need to convert the values in the split string into ints.
zip(l1, l2) takes the values in two lists and pairs them up. You'd need the lists to have the same number of elements for this to work (we do). From here, we use another list comprehension to pull out pairs of values and then take the difference.
edit (ty danihp): if you need the results to be a string, you can join the values in the list with ' '.join([str(x) for x in r1]) (this uses a space to separate elements in the list).
Step for step:
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
s3 = [int(x) for x in s1.split()] # split and convert to int
s4 = [int(x) for x in s2.split()] # split and convert to int
s5 = [] # result
for idx in range(0,len(s3)): # length are equal so this is ok
s5.append(s3[idx]-s4[idx]) # put into result
rv = " ".join([str(x) for x in s5]) # join result to string
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(rv)
Output:
2 5 8 9 6 3
2 3 5 9 3 2
[2, 5, 8, 9, 6, 3]
[2, 3, 5, 9, 3, 2]
[0, 2, 3, 0, 3, 1]
0 2 3 0 3 1
Since python is typed, you cannot subtact the strings: you have to convert each string to a list of integers and then subtract each one of the elements.
You can do this with only one loop:
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
list_diff = [int(x2) - int(x1) for x1, x2 in zip(s1.split(), s2.split())]
# or if you want the result as a string:
list_diff = [str(int(x1) - int(x2)) for x1, x2 in zip(s1.split(), s2.split())]
result = " ".join(list_diff)
I have
for i in range(0, 11): print i, "\n", i
I'd like my python program to print this way for each for loop
1st loop:
1
1
2nd loop:
1
2
2
1
3rd loop:
1
2
3
3
2
1
I've tried using \r\n or \033[1A but they just overwrite the previous line. Is there a way I can "push" the outputted line down so I don't overwrite it?
One way to do this,
def foo(x, limit):
if x < limit :
print x
foo(x + 1, limit)
print x
foo(1, 11)
It's not possible to do it in 1 for loop as you're currently trying.
As I suggested, you can do it like this by using lists
>>> l1 = []
>>> l2 = []
>>> for i in range(0, 11):
... l1.append(i)
... l2 = [i] + l2
>>> l1.extend(l2)
>>> for i in l1:
... print i
0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
Concatenation of two list generators.
>>> ladder = [x for x in range(5)] + [x for x in range(5,-1,-1)]
>>> ladder
[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
>>> for x in ladder:
... print x
...
0
1
2
3
4
5
4
3
2
1
0
>>>
one of ways to solve this
def two_side_print(start, end):
text = [str(i) for i in range(start,end)]
print '\n'.join(text), '\n', '\n'.join(reversed(text))
two_side_print(1, 11)
Another option is to save the printed values in a list and print that list in reverse order in each loop iteration.
My suggestion:
l = []
for i in range(1, 5):
print 'Loop '+str(i) # This is to ease seeing the printing results
for val in l:
print val
print i
l.insert(len(l),i)
for val in reversed(l):
print val
The output for a loop iterating from 0 to 5:
Loop 1
1
1
Loop 2
1
2
2
1
Loop 3
1
2
3
3
2
1
Loop 4
1
2
3
4
4
3
2
1
I hope this is what you are looking for.
You can use a recursive function to help here:
def print_both_ways(start, end):
print(start)
if start != end:
print_both_ways(start+1, end)
print(start)
Usage:
print_both_ways(1,3) # prints 1,2,3,3,2,1 on separate lines