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
Related
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))
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='')
I'm trying to get a python script to print '#' symbols, in relation the the value held in a list. For example, if the list as [1,2,3] - the script would print:
1 #
2 ##
3 ###
With the following code:
myList = [0,1,2,3,4,5,6]
x = 1
While x < range(len(myList)):
print (x, end ='')
for frequency in myList[x]:
print ('#')
print ('\n')
x = x + 1
So far I get this error "TypeError: unorderable types: int() < range()". I think I'm getting this because it can't compare a single number to a range of numbers.
But when I try to just use:
len(myList)
I get: "TypeError: 'int' object is not iterable".
Not sure what to do!
As the error says, this is comparing the value in x to the value range(...):
while x < range(len(myList)):
print (x, end ='')
That's not what you want. Instead, you want to loop across those values:
for x in range(len(myList)):
...
Similarly, your second loop isn't going to work:
for frequency in myList[x]:
print ('#')
Since myList[x] is an int, that translates as "for every value frequency in the the number myList[x]..." which doesn't really make sense. You really mean:
for frequency in range(myList[x]):
print ('#')
Please throw your code in the dustbin and look for a better approach
You'd better do this:
for number in yourList:
if number <= 0:
print("Cannot use negative numbers or zero here!")
else:
print ("{} {}".format(number, "#" * number))
Don't forget that you can get N copies of a string by simply multiplying this string by N, where N is a positive non-zero number.
You're getting the error because you are actually comparing an int to a range object on this line:
while x < range(len(myList)):
To get the output you desire, it would be much easier to just multiply strings:
for i in range(7):
print(i, i * '#')
Adjust the call to range if you want to omit the zero row.
You can use a for loop to do this:
>>> myList = [0,1,2,3,4,5,6]
>>> for item in myList:
... if item > 0:
... print(item, '#' * item)
...
1 #
2 ##
3 ###
4 ####
5 #####
6 ######
In python you can use the '*' operator to print strings multiple times, like a kind of multiplication.
If you want output a zero but no '#' when the item is zero, remove the if item > 0: and dedent the line that follows it.
The code I'm working on takes an input, and is meant to return a "staircase" of hashes and spaces. For instance, if the input was 5, the result should be:
#
##
###
####
#####
I've turned the input into a list of spaces and hashes, and then converted that to a string form, in order to insert \n in every space corresponding to the length of the input (e.g. every 5 characters above). However, my code prints the result in one line. Where am I going wrong??
x = input()
list = []
a = x-1
while a > -1:
for i in range(0, a):
list.append(" ")
for i in range(0, (x-a)):
list.append("#")
a = a - 1
continue
z = str("".join(list))
t = 0
while t<x:
z = z[t:] + "\n" + z[:t]
t = t + x
continue
print str(z)
Start with pseudocode, carefully laying out in clear English what you want the program to do.
Get a number from the user.
Go through each number from 1 until the user's number, inclusive.
On each line, print a certain number of spaces, starting from one fewer than the user's number and going down to zero, inclusive.
On each line, also print a certain number of hash symbols, starting from one and going up to the user's number, inclusive.
Now you can turn that into Python.
First, get a number from the user. It looks like you're using Python 2, so you could use input() or try the safer raw_input() and cast that to int().
num = input()
Going through each number from one until the user's number, inclusive, means a for loop over a range. On Python 2, using xrange() is better practice.
for i in xrange(1, num+1):
This next part will combine steps 3 and 4, using string multiplication and concatenation. For the spaces, we need a number equal to the max number of lines minus the current line number. For the hash symbols, we just need the current line number. You can multiply a string to repeat it, such as 'hi' * 2 for 'hihi'. Finally, the newline is taken care of automatically as the default end character in a Python 2 print statement.
print ' ' * (num-i) + '#' * i
Put it all together and it looks like this:
num = input()
for i in xrange(1, num+1):
print ' ' * (num-i) + '#' * i
As you discovered, achieving the same effect with an intricate structure of counters, nested loops, list operations, and slicing is more difficult to debug. The problems don't stop when you get it working properly, either - such code is difficult to maintain as well, which is a pain if you ever want to modify the program. Take a look at the official Python tutorial for some great examples of clear, concise Python code.
Try this
x = input()
list1 = []
a = x-1
while a > -1:
for i in range(0, a):
list1.append(" ")
for i in range(0, (x-a)):
list1.append("#")
a = a - 1
list1.append("\n")
continue
z = str("".join(list1))
print z
Please help me understand why my Python code to solve the 13th Project Euler problem is incorrect. I believe that I understand the task correctly and I think my code is correct, but it is obviously not.
number = '5000 digit number - see in the problem decription at the provided link'
list1 = [number[i:i+100] for i in range(0, len(number), 100)]
temp = []
for i in range(0, len(list1)):
y = int(list1[i])
temp.append(y)
print sum(temp)
First, the numbers are 50 digits long, not 100. Change this:
list1 = [number[i:i+100] for i in range(0,len(number),100)]
To this:
list1 = [number[i:i+50] for i in range(0,len(number),50)]
Second, you're printing the entire sum, rather than just the first ten digits. Try:
print str(sum(temp))[:10]
Much simpler:
s = 'copied and pasted from the page'
result = sum(map(int, s.splitlines()))[:10]
Only the 11 first digits need to be summed,
somme11=sum(int(number2[i:i+11]) for i in range(100))
print(somme11)
print( 'the ten first digits are' , somme11//1000)
Because the carry can't exceed 99.
4893024188690
the ten first digits are 4893024188
An alternative is to load the numbers into a file and then just add them up, unless I too have completely misunderstood the question.
with open("sum.nums","r") as f:
data = f.readlines()
total = 0
for i in data:
total += int(i)
print "1st 10 digits ", str(total)[:10], "of total", total
1st 10 digits 5537376230 of total 5537376230390876637302048746832985971773659831892672
It's pretty simple
def e13():
f=open("100x50digits.txt")
summ=0
for line in f:
summ+=int(line[:11])
print(int(summ/1000))
f.close()
e13()
number = '''The 100 lines of 50 characters'''
numbers = number.splitlines() #Devide the string into a list of strings.
numbers = [int(i) for i in numbers] #Convert all elements into integers.
totalSum = str(sum(numbers)) #Add everything and convert to a string.
print(totalSum[:10]) #Print the first 10 digits of the result.
The correct answer is 5537376230, checked with P.E.
The real challenge here is to deal with the really long string
Use StringIO to take number as a input string and iterate trough elements by converting each one to a integer value
from io import StringIO
number = StringIO(""" # Paste one-hundred 50 numbers """)
print(str(sum(map(lambda x: int(x), number)))[:10])
>>> '5537376230'