I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that:
when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
The most Pythonic way of doing this is to use list comprehension and join:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...) joins whatever iterable is passed in using the string (in this case ','). If you want to have spaces between your numbers, you can use ', '.join(...).
[str(x) for x in range(n)] is a list comprehension. Basically, for every x in range(n), str(x) is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print (expanded with *) seperated by ',' and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')
Related
L=input().split(' ')
for i in L:
c=float(i)
print(int(c), sep=",")
A sequence of numbers separated by space is to be accepted from user, the numbers are converted to the greatest integer less than or equal to the number and then printed.
I wanted to print the output on same line, but my code doesn't work
Thanks in advance....
You are looping through the list, change to float and put it into variable c. That loop is essentially meaningless. After that loop c contains the last value in the iteration. Just print the result at once:
L=input().split(' ')
all_ints = map(int, L)
print(*all_ints, sep=',')
Or using str.join:
print(','.join(map(str, all_ints)))
Or using a loop:
for i in all_ints:
print(i, end=',')
To get them all as floats you can use map as well:
all_floats = list(map(float, L))
I think this should work for you:
L = input().split(' ')
for i in L:
c = float(i)
print(int(c), end=" ")
I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))
Trying to create an integer that starts at 0000 and increments by +1 (0001 etc) and then adds it to a string until the number reaches 9999. How could i do this?
for x in range(10000):
print(str(x).rjust(4, '0'))
You stated that you want to add them to a URL so the way to do it would be:
url = "thisisanamazingurl{0:0>4}" # insert your URL instead of thisisanamazingurl
for i in range(10000):
tempurl = url.format(i)
print(tempurl) # instead of print you should do whatever you need to do with it
This works because :0>4 fills the "input string" with leading zeros if it's shorter than 4 characters.
For example with range(10) this prints:
thisisanamazingurl0000
thisisanamazingurl0001
thisisanamazingurl0002
thisisanamazingurl0003
thisisanamazingurl0004
thisisanamazingurl0005
thisisanamazingurl0006
thisisanamazingurl0007
thisisanamazingurl0008
thisisanamazingurl0009
or if you want to store them as a list:
lst = [url.format(i) for i in range(10000)]
num = ""
for number in range(10000):
num = num + str('%04d' % number)
print num
This will iterate through every number between 0 and 9999 and append it to the num string. The '%04d' bit forces it to use 4 numeric places with the leading zeros.
(As an aside, you can change the ending number by changing the value of the number in the range function.)
Since you want to add it to a string, I am going to assume you want the type of the 4 digit number as string .
So you can do(python3.x) :
string=''
for x in range(10000):
digit= '0'*(4- len(str(x)) + str(x)
string+=digit
When I am printing the list, there is a comma and quotations in the letter X, how do I remove it?
#asks user input
m = int(input("Enter number of boxes horizontally and vertically: "))
n = int(input("Enter number of mines: "))
a=[]
for i in range(m):
a.append([])
for k in range(m):
a[i].append("X")
i=1
#prints the generated cells
for i in range(m):
print a[i]
i=i+1
You are looking to use join to make your list in to a string. You want to make your string space separated, so you will want to use ' '.join():
Change this:
print a[i]
to this:
print(' '.join(a[i]))
Or, if you are mixing types, you should do:
' '.join(str(x) for x in a)
you can also use this:
print ' '.join(map(str, a[i]))
my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:
def main(L,n):
i=0
while i<(len(L)):
if L[i]>n:
L.pop(i)
else:
i=i+1
return L
#MAIN PROGRAM
L = ["bob", "dave", "buddy", "tujour"]
n = int (input("enter an integer value)
main(L,n)
So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.
Thanks a million!
Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.
def main(L,n):
return([x for x in L if len(x) <= n])
Just use the built-in filter method, where n is the cut off length:
newList = filter(lambda i:len(i) <= n, oldList)
You should not remove elements from a list you are iterating over, you need to copy or use reversed:
L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))
for name in reversed(L):
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
Making a copy using [:] syntax:
for name in l[:]:
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
This is a simple solution where you can print L after calling the main function. Hope this helps.
def main(L,n):
l=len(L)
x=0
while x<l:
#if length is greater than n, remove the element and decrease the list size by 1
if len(L[x])>n:
L.remove(L[x])
l=l-1
#else move to the next element in the list
else:
x=x+1