Python Basics: create a range that includes all numbers - python

I am trying to create a function and I keep on getting the same error message. And this is something that I have had a problem with for a while. The (key) input is supposed to be an integer. The same integer that's (x). Like input 200 for key/x and the output would be '11001000'. The error message I keep getting is:
"TypeError: 'int' object is not iterable"
I am trying to make it so that all of the numbers are integers. I am trying to make a function that executes the same thing that "{0:b}".format(200) would deliver. So the code that I have come up with is:
def createBinKeyFromKey(key):
for x in key:
return "{o:b}".format(x)
I have also tried to use while loop to execute it correctly and not get an error message, but that hasn't worked so far.
I would like to call an integer. As in the place where it says (key), the input there would be an integer. And then it would return the binary string of the integer. For example I would input createBinKeyFromKey(200) in python shell and it would return '11001000'

You can't iterate over an integer, to get a range of numbers use range() or xrange().
range() creates a whole list first, while xrange() returns an iterator(memory efficient)
here:
def createBinKeyFromKey(key):
for x in range(key):
yield "{0:b}".format(x) #use yield as return will end the loop after first iteration
Using yield makes it a generator function.
demo:
>>> list(createBinKeyFromKey(10))
['0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
>>> for x in createBinKeyFromKey(5):
... print x
0
1
10
11
100
help on range:
>>> range?
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

Related

Converting Strings to int in List [duplicate]

This question already has answers here:
Convert all strings in a list to int
(10 answers)
Closed last month.
have a list with numeric strings, like so:
numbers = ['1', '5', '10', '8'];
I would like to convert every list element to integer, so it would look like this:
numbers = [1, 5, 10, 8];
The natural Python way of doing this is using list comprehensions:
intlist = [int(element) for element in stringlist]
This syntax is peculiar to the Python language and is a way to perform a "map" with an optional filtering step for all elements of a sequnce.
An alterantive way, which will be more familiar for programmers that know other languages is to use the map built-in: in it, a function is passed as the first parameter, and the sequence to be processed as the second parameter. The object returned by map is an iterator, that will only perform the calculations on each item as it is requested. If you want an output list, you should build a list out of the object returned by map:
numbers = list(map(int, stringlist))
You can use a simple function called map:
numbers = ['1', '5', '10', '8']
numbers = list(map(int, numbers))
print(numbers)
This will map the function int to each element in the iterable. Note that the first argument the map is a function.
you can use generator objects
[int(i) for i in numbers]
Sometimes int() gives convertion error if the input it's not a valid variable. In that case must create a code that wraps all convertion error.
numbers = []
not_converted = []
for element in string_numbers:
try:
number = int(element)
if isinstance(number, int):
numbers.append(number)
else:
not_converted.append(element)
except:
not_converted.append(element)
If you expect that the input it's aways a string int you can simply convert like:
numbers = [int(element) for element in string_numbers]
You can use the below example:-
numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)

How to perform operation on specific elements of a list? [duplicate]

This question already has answers here:
modify list elements on a condition
(3 answers)
Closed last year.
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want
i=['0','7','2','3','4']
o=['0','14','2,'6','4']
here's the code I tried:
list=["1","3","7"]
for num in list:
if num%2!=0:
num*2
print(list)
here's the error I get:
PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
if num%2!=0:
TypeError: not all arguments converted during string formatting
ls = ['1', '2', '3']
for i, el in enumerate(ls):
if int(el) % 2:
ls[i] = str(int(el)*2)
print(ls)
# prints ['2', '2', '6']
If you intend to not mutate the input list and create a new list for the results:
ls = ['1', '2', '3']
res = []
for el in ls:
if int(el) % 2:
res.append(str(int(el)*2))
else:
res.append(el)
print(res)
# prints ['2', '2', '6']
If the input list were only integers you wouldn't need to convert the elements to integers and back to strings, of course:
ls = [1, 2, 3]
for i, el in enumerate(ls):
if el % 2:
ls[i] = el*2
print(ls)
# prints [2, 2, 6]
Please avoid naming your lists list. This shadows the list type of python and can create a lot of confusion and subtle bugs later on.
Your error comes from the comparison if num%2!=0: where num is a str-type and 0 is an integer. To check this you can use the type function, returning what type your variable num is;
list=["1","3","7"]
for num in list:
print(type(num))
if num%2!=0:
num*2
print(list)
instead of looping through the list and saving each element as a variable, you want to iterate through a range with the length of your list. By doing so you can use the number in the range to access the index of each element of the list instead and updating the lists element if your criteria is met;
list = ['0','7','2','3','4']
# wanted output ['0','14','2','6','4']
for i in range(len(list)):
num = int(list[i])
if num%2 != 0:
list[i] = num*2
print(list)
Read some about loops and lists to get the syntax right for next try :)
w3school Python - Loop Lists
The below approach uses a list comprehension to achieve the desired list. Here, if we consider in_list as input list then no. inside list is stored as a string so while iterating over the list to check whether no. is odd or even first no. needs to be converted to int and then it is checked with % operator if it is even then it's multiplied with 2 and then result is converted back to string as the output requirement is a list of numbers stored as a string
in_list=['0','7','2','3','4']
output = [i if (int(i)%2)==0 else str(int(i)*2) for i in in_list ]
print(output)
Example is a little misleading here. If we consider odd indices then
o=[int(i[x])*2 if x%2==1 else int(i[x]) for x in range(len(i))]
If we consider numbers themselves
o= [str(int(x)*2) if int(x)%2!=0 else x for x in i]

why sort in python is not working?

code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?
when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in
I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']
You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list
Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())
I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

python sets with integers is splitting integers greater than 10 into two digits

I'm trying to initialize a list of sets in python. Each set initially contains a single integer representing a numbered vertex in a graph.
for x in graph:
setList.append(set(x))
print setList
If the graph has 10 vertices it will print out the following:
[set(['0']), set(['1']), set(['2']), set(['3']), set(['4']), set(['5']), set(['6']), set(['7']), set(['8']), set(['9']), set(['1', '0'])]
Why is 10 getting split into 1, 0 ?
set(['1', '0'])
Those are strings, not integers, and strings are sequences. That means calling set() on them creates a set of each element in the sequence - which in the case of strings are the individual characters. This ought to fix your problem:
for x in graph:
setList.append(set([x]))
print setList
Or if you want integers instead:
for x in graph:
setList.append(set([int(x)]))
print setList
These work because now that x has been wrapped in a list, Python iterates over that list to populate the set, rather than attempting to iterate over x itself (which would have raised a TypeError if x had actually been an integer, because integers aren't iterable).
You can do
setList.append({x})
example:
>>> set('10')
{'1', '0'}
>>> a={'10'}
>>> a
{'10'}

How to "unzip" then slice and find max for elements in a list of lists in Python

I have a list of lists and need to find a way to find the max of the numerical portion of element [0] of each list. I know it'll involve slicing and finding max and think it'll involve the zip(*L) function but don't really know how to get there. For example, what I have is a list of lists that looks like this:
L = [['ALU-001', 'Aluminum', 50], ['LVM-002', 'Livermorium', 20], ['ZIN-003', 'Zinc', 30]]
and need to find the largest numerical portion (ex. 001) of the first elements.
You can do unzip using zip(*L), and since the numerical comparison is same as comparing alphabetically, so you don't have to convert the numerical part to int if the number have a fixed width.
>>> max([i.split('-')[1] for i in zip(*L)[0]])
'003'
zip is its own complement!
L = [['ALU-001', 'Aluminum', 50], ['LVM-002', 'Livermorium', 20], ['ZIN-003', 'Zinc', 30]]
zip(*L)[0]
#=> ('ALU-001', 'LVM-002', 'ZIN-003')
However, it's unnecessary to zip here. Instead, most python sort/max/etc. functions take a key argument:
max(L,key=lambda (a,b,c):int(a.split('-')[1]))
#=> ['ZIN-003', 'Zinc', 30]
The max function considers the value generated by applying key to each element of L.
max(int(subl[0].rsplit('-',1)[1]) for subl in L)
This will return 3. If you want to print '003', then you can do this:
print "%03d" %max(int(subl[0].rsplit('-',1)[1]) for subl in L)
Explanation:
As you seem to already know, max takes a list of numbers and returns the largest one. This is almost correct: max takes any interable and returns the largest element. A generator is an iterable and takes O(1) space as opposed to a list, which takes O(n) space.
You can also use a list comprehension to create a generator (called a generator comprehension), which is what I have done.
(int(subl[0].rsplit('-',1)[1]) for subl in L)
is the same as:
def myGen():
for subl in L:
elem = subl[0]
myNum = elem.rsplit('-', 1)
myNum = int(myNum)
yield myNum
max(myGen)
The subl iteration iterates over the sublists of L. subl[0] gets the 0th element of each sublist. We then call rsplit('-' ,1), which splits the string into two parts, at the occurrence of the first - from the end of the string; the splits are presented in a list. The 0th index of this list is what was on the left of the - and the 1th index is what was to the right. Since the number was on the right, we take subl[0].rsplit('-',1)[1].
At this point, we only have the string '003', which we want to turn into an int for the purposes of maxing. So we call int(subl[0].rsplit('-',1)[1]). And that's how this generates all the required numbers, which max then pulls the biggest one out of

Categories