I'm having trouble displaying my list in a money format ($0000.00)
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
priceList[i] = random.uniform(1,1000)
print (priceList)
If I try
print ('%.02d' %(priceList))
Python returns
TypeError: %d format: a number is required, not list
You cannot print a list this way, you need to print each list item. A list comprehension works well here:
[print('%.02f' % i) for i in priceList]
You need to put the printing inside your for loop:
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range(10):
priceList[i] = random.uniform(1,1000)
print("${:07.02f}".format(priceList[i]))
In 07.02f, 07 says to make sure that the string is at least 7 characters long. The 0 is there because if the string is less than 7 characters, that is the character to be used to make it 7 characters. 02 before the f means that there should be at least two characters after the decimal point. The 0 is there so that if there are fewer than two characters, it will be used to fill it in.
Because you are trying to do that operation over a list. You need to do it on each element in your list. Try this:
Also, I think you want to use %.02f and not %.02d
print(' '.join('%.02f' % (x) for x in priceList))
Output:
728.08 289.73 117.96 29.70 562.40 255.97 213.55 235.08 436.10 654.54
If you want it just as a list, you can simply do this only:
print(['%.02f' % x for x in priceList])
You should be using proper Python 3 format strings. You can do something like this:
import random
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
priceList[i] = random.uniform(1,1000)
moneyList = list(map(lambda x: "${:07.02f}".format(x), priceList))
print(moneyList) # => output:
"""
['$294.90', '$121.71', '$590.29', '$45.52', '$319.40', '$189.03', '$594.63', '$135.24', '$645.56', '$954.57']
"""
Related
Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2
My code:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = input().split()
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
However, whenever my input consists of a 2 digit number, the logic fails.
Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.
This work perfectly for single digit numbers. Can someone help me out with this?
You only need a slight modification. You are comparing strings instead of numbers, so try this instead:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = map(int, input().split())
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
If you want, you can also do:
numbers = (int(x) for x in input().split())
You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.
testcases = int(input())
for _ in range(testcases):
print(' '.join(sorted(set(input().split()), key=int)))
You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.
Try this:
x_numbers = input().split()
numbers = [int(x) for x in x_numbers]
Try it now:
testcase = int(input())
n=list(str(testcase))
results = map(int, n)
numbers= sorted(set(results))
print(numbers)
code here:https://repl.it/repls/SeriousRosybrownApplicationprogrammer
We can keep it simple like this. This is a reference
input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted
print(lsintegers)`
I am trying to create a loop where I can generate string using loop. What I am trying to achieve is that I want to create a small collection of strings starting from 1 character to up to 5 characters.
So, starting from sting 1, I want to go to 55555 but this is number so it seems easy if I just add them, but when it comes to alpha numeric, it gets tricky.
Here is explanation,
I have collection of alpha-numeric chars as string s = "123ABC" and what I want to do is that I want to create all possible 1 character string out of it, so I will have 1,2,3,A,B,C and after that I want to add one more digit in length of string so I can get 11, 12, 13 and so on until I get all possible combination out of it up to CA, CB, CC and I want to get it up to CCCCCC. I am confused in loop because I can get it to generate a temp sting but looping inside to rotate characters is tricky,
this is what I have done so far,
i = 0
strr = "123ABC"
while i < len(strr):
t = strr[0] * (i+1)
for q in range(0, len(t)):
# Here I need help to rotate more
pass
i += 1
Can anyone explain me or point me to resource where I can find solution for it?
You may want to use itertools.permutations function:
import itertools
chars = '123ABC'
for i in xrange(1, len(chars)+1):
print list(itertools.permutations(chars, i))
EDIT:
To get a list of strings, try this:
import itertools
chars = '123ABC'
strings = []
for i in xrange(1, len(chars)+1):
strings.extend(''.join(x) for x in itertools.permutations(chars, i))
This is a nested loop. Different depths of recursion produce all possible combinations.
strr = "123ABC"
def prod(items, level):
if level == 0:
yield []
else:
for first in items:
for rest in prod(items, level-1):
yield [first] + rest
for ln in range(1, len(strr)+1):
print("length:", ln)
for s in prod(strr, ln):
print(''.join(s))
It is also called cartesian product and there is a corresponding function in itertools.
So this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
Is giving me the TypeError: 'int' object has no attribute 'getitem'.
But if I change the 3rd line from n into i then this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(i[0])
list = lst
print list
print first_n
Gives me the list and the last number on that list. I need the first number not the last.
It gives me the first if instead I replace n in range (500): with n = raw input()
n = raw_input()
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
But this is single number and need to have run thousands of numbers. (As you can see I change the i on the 3rd line back into n)
Please can you help?
Your issue lies with the raw_input. In python 2, it returns a string, not an integer. What you need is input(), which just returns an integer:
n = input()
lst = [int(i) for i in str(n)]
first_n = int(lst[0]) #also, need lst here, not n, as it is now an integer
list = lst
print list
print first_n
Probably an easier solution here is to instead convert it to a string:
>>> str(123)[0] # Convert to string and take 1st character
'1'
If you need it as a number, you can int it back. This feels inefficient, but you're trying to solve a problem strongly related to the written representation of a number, so strings feel like the appropriate solution. You can however use solutions related to taking the place value. If you are looking for the number of hundreds in the above, for example, you could % 100. This requires a little more work to make general, though.
I am fairly new to programming and have been learning some of the material through HackerRank. However, there is this one objective or challenge that I am currently stuck on. I've tried several things but still cannot figure out what exactly I am doing wrong.
Objective: Read N and output the numbers between 0 and N without any white spaces or using a string method.
N = int(input())
listofnum = []
for i in range(1, N +1):
listofnum.append(i)
print (*(listofnum))
Output :
1 2 3
N = int(input())
answer = ''
for i in range(1, N + 1):
answer += str(i)
print(answer)
This is the closest I can think of to 'not using any string methods', although technically it is using str.__new__/__init__/__add__ in the background or some equivalent. I certainly think it fits the requirements of the question better than using ''.join.
Without using any string method, just using integer division and list to reverse the digits, print them using sys.stdout.write:
import sys
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
sys.stdout.write(chr(c+48))
Or as tdelaney suggested, an even more hard-code method:
import os,sys,struct
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
os.write(sys.stdout.fileno(), struct.pack('b', c+48))
All of this is great fun, but the best way, though, would be with a one-liner with a generator comprehension to do that, using str.join() and str construction:
"".join(str(x) for x in range(1,N+1))
Each number is converted into string, and the join operator just concatenates all the digits with empty separator.
You can print numbers inside the loop. Just use end keyword in print:
print(i, end="")
Try ''.join([str(i) for i in range(N)])
One way to accomplish this is to append the numbers to a blank string.
out = ''
for i in range(N):
out += str(i)
print(out)
You can make use of print()'s sep argument to "bind" each number together from a list comprehension:
>>> print(*[el for el in range(0, int(input())+1)], sep="")
10
012345678910
>>>
You have to do a simple math to do this. What they expect to do is multiply each of your list elements by powers of ten and add them up on each other. As an example let's say you have an array;
a = [2,3,5]
and you need to output;
235
Then you multiply each of loop elements starting from right to left by 10^0, 10^1 and 10^2. You this code after you make the string list.
a = map(int,a)
for i in range(len(a)):
sum += (10**i)*a[-i]
print sum
You are done!
Given List:
l = [1,32,523,336,13525]
I am having a number 23 as an output of some particular function.
Now,
I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.
Output should be:[1]
I want to write some cool one liner code.
Please help!
My approach was :
1.) Convert list of int into list of string.
2.) then use for loop to check for either character 2 or character 3 like this:
A=[x for x in l if "2" not in x] (not sure for how to include 3 also in this line)
3.) Convert A list into integer list using :
B= [int(numeric_string) for numeric_string in A]
This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.
You could convert the numbers to sets of characters:
>>> values = [1, 32, 523, 336, 13525]
>>> number = 23
>>> [value for value in values
... if set(str(number)).isdisjoint(set(str(value)))]
[1]
You're looking for the filter function. Say you have a list of ints and you want the odd ones only:
def is_odd(val):
return val % 2 == 1
filter(is_odd, range(100))
or a list comprehension
[x for x in range(100) if x % 2 == 1]
The list comprehension in particular is perfectly Pythonic. All you need now is a function that returns a boolean for your particular needs.