Convert a number to a list of integers [duplicate] - python

This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
Closed 4 months ago.
How do I write the magic function below?
>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>

You mean this?
num = 1234
lst = [int(i) for i in str(num)]

a = 123456
b = str(a)
c = []
for digit in b:
c.append (int(digit))
print c

You could do this:
>>> num = 123
>>> lst = map(int, str(num))
>>> lst, type(lst)
([1, 2, 3], <type 'list'>)

magic = lambda num: map(int, str(num))
then just do
magic(12345)
or
magic(someInt) #or whatever

>>> from collections import deque
>>> def magic(num):
digits = deque()
while True:
num,r = divmod(num,10)
digits.appendleft(r)
if num == 0:
break
return list(digits)
>>> magic(123)
[1, 2, 3]
According to my timings, this solution is considerably faster than the string method (magic2), even for smaller examples.
>>> def magic2(num):
return [int(i) for i in str(num)]
Timings:
magic
>>> timeit.timeit(setup='from __main__ import magic', stmt='magic(123)')
1.3874572762508706
>>> timeit.timeit(setup='from __main__ import magic', stmt='magic(999999999)')
3.2624468999981673
magic2
>>> timeit.timeit(setup='from __main__ import magic2', stmt='magic2(123)')
3.693756106896217
>>> timeit.timeit(setup='from __main__ import magic2', stmt='magic2(999999999)')
10.485281719412114

Don't use the word list as variable name! It is a name of python built in data type.
Also, please clarify your question. If you are looking for a way to create a one-member list, do the following:
a = 123
my_list = [a]
and "pythonizing" Cannonade's answer:
a = 123
my_list = [int(d) for d in str(a)]

num = map(int, list(str(num)))

If it is named as magic, why not just use magic:
def magic(x):
if x < 10:
return [x]
else:
return magic(x//10) + [x%10]

for python 3.x:
num = 1234
lst = list(map(int, str(num)))

You can try this:
def convert_to_list(number):
return list(map(lambda x: int(x), str(number)))
convert_to_list(1245)

Just use :
a= str (num)
lst = list(a)

Related

python:loop vs comprehension [duplicate]

This question already has answers here:
Are list-comprehensions and functional functions faster than "for loops"?
(8 answers)
Closed 7 years ago.
I was trying to do some simple procedures using lists.
From the book learning python I saw the method of using a comprehension.
Well I also knew that a loop could replace it.
Now I really want to know that which is faster, loop or comprehension.
These are my programs.
a = []
for x in range(1, 101):
a.append(x)
This would set a as [1, 2, 3, ......, 99, 100]
Now this is what I have done with the comprehension.
[x ** 2 for x in a]
This is what I did with the loop.
c = []
for x in a:
b=[x**2]
c+=b
Could any one say a way to find which of the above is faster.Please also try to explain that how comprehensions differ from loops.
Any help is appreciated.
You can use the timeit library, or just use time.time() to time it yourself:
>>> from time import time
>>> def first():
... ftime = time()
... _foo = [x ** 2 for x in range(1, 101)]
... print "First", time()-ftime
...
>>> def second():
... ftime = time()
... _foo = []
... for x in range(1, 101):
... _b=[x**2]
... _foo+=_b
... print "Second", time()-ftime
...
>>> first()
First 5.60283660889e-05
>>> second()
Second 8.79764556885e-05
>>> first()
First 4.88758087158e-05
>>> second()
Second 8.39233398438e-05
>>> first()
First 2.8133392334e-05
>>> second()
Second 7.29560852051e-05
>>>
Evidently, the list comprehension runs faster, by a factor of around 2 to 3.

Python: select digits from NoneType object

I have a 'NoneType' object like:
A='ABC:123'
I would like to get an object keeping only the digits:
A2=digitsof(A)='123'
Split at the colon:
>>> A='ABC:123'
>>> numA = int(A.split(':')[1])
123
How about:
>>> import re
>>> def digitsof(a):
... return [int(x) for x in re.findall('\d+', a) ]
...
>>> digitsof('ABC:123')
[123]
>>> digitsof('ABC:123,123')
[123, 123]
>>>
Regular Expressions?
>>> from re import sub
>>> A = 'ABC:123'
>>> sub(r'\D', '', A)
123
A simple filter function
A='ABC:123'
filter(lambda s: s.isdigit(), A)

Python why would you use [:] over =

I am just learning python and I am going though the tutorials on https://developers.google.com/edu/python/strings
Under the String Slices section
s[:] is 'Hello' -- omitting both always gives us a copy of the whole
thing (this is the pythonic way to copy a sequence like a string or
list)
Out of curiosity why wouldn't you just use an = operator?
s = 'hello';
bar = s[:]
foo = s
As far as I can tell both bar and foo have the same value.
= makes a reference, by using [:] you create a copy. For strings, which are immutable, this doesn't really matter, but for lists etc. it is crucial.
>>> s = 'hello'
>>> t1 = s
>>> t2 = s[:]
>>> print s, t1, t2
hello hello hello
>>> s = 'good bye'
>>> print s, t1, t2
good bye hello hello
but:
>>> li1 = [1,2]
>>> li = [1,2]
>>> li1 = li
>>> li2 = li[:]
>>> print li, li1, li2
[1, 2] [1, 2] [1, 2]
>>> li[0] = 0
>>> print li, li1, li2
[0, 2] [0, 2] [1, 2]
So why use it when dealing with strings? The built-in strings are immutable, but whenever you write a library function expecting a string, a user might give you something that "looks like a string" and "behaves like a string", but is a custom type. This type might be mutable, so it's better to take care of that.
Such a type might look like:
class MutableString(object):
def __init__(self, s):
self._characters = [c for c in s]
def __str__(self):
return "".join(self._characters)
def __repr__(self):
return "MutableString(\"%s\")" % str(self)
def __getattr__(self, name):
return str(self).__getattribute__(name)
def __len__(self):
return len(self._characters)
def __getitem__(self, index):
return self._characters[index]
def __setitem__(self, index, value):
self._characters[index] = value
def __getslice__(self, start, end=-1, stride=1):
return str(self)[start:end:stride]
if __name__ == "__main__":
m = MutableString("Hello")
print m
print len(m)
print m.find("o")
print m.find("x")
print m.replace("e", "a") #translate to german ;-)
print m
print m[3]
m[1] = "a"
print m
print m[:]
copy1 = m
copy2 = m[:]
print m, copy1, copy2
m[1] = "X"
print m, copy1, copy2
Disclaimer: This is just a sample to show how it could work and to motivate the use of [:]. It is untested, incomplete and probably horribly performant
They have the same value, but there is a fundamental difference when dealing with mutable objects.
Say foo = [1, 2, 3]. You assign bar = foo, and baz = foo[:]. Now let's say you want to change bar - bar.append(4). You check the value of foo, and...
print foo
# [1, 2, 3, 4]
Now where did that extra 4 come from? It's because you assigned bar to the identity of foo, so when you change one you change the other. You change baz - baz.append(5), but nothing has happened to the other two - that's because you assigned a copy of foo to baz.
Note however that because strings are immutable, it doesn't matter.
If you have a list the result is different:
l = [1,2,3]
l1 = l
l2 = l[:]
l2 is a copy of l (different object) while l1 is an alias of l which means that l1[0]=7 will modify also l, while l2[1]=7 will not modify l.
While referencing an object and referencing the object's copy doesn't differ for an immutable object like string, they do for mutable objects (and mutable methods), for instance list.
Same thing on mutable objects:
a = [1,2,3,4]
b = a
c = a[:]
a[0] = -1
print a # will print [1,2,3,4]
print b # will print [-1,2,3,4]
print c # will print [1,2,3,4]
A visualization on pythontutor of the above example - http://goo.gl/Aswnl.

Python list.append as an argument

Why does the following code give 'None'? How can I resolve this?
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
What also doesn't work:
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
In general, Python methods that mutate an object (such as list.append, list.extend, or list.sort) return None.
If you wish to print out the new list:
def f1(list1):
list1.append(2)
f2(list1)
It depends on what you want to do. If you want list1 to have changed after a call to f1, use
def f1(list1):
list1.append(2)
f2(list1)
See what happens:
>>> l = [1]
>>> f1(l) # Modifies l in-place!
[1, 2]
>>> l
[1, 2]
If you don't want list1 to be changed:
def f1(list1):
f2(list1 + [2])
Now see this:
>>> l = [1]
>>> f1(l) # Leaves l alone!
[1, 2]
>>> l
[1]

shuffle string in python

I am looking for a function or short program that receives a string (up to 10 letters) and shuffles it.
>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'
There is a function shuffle in the random module. Note that it shuffles in-place so you first have to convert your string to a list of characters, shuffle it, then join the result again.
import random
l = list(s)
random.shuffle(l)
result = ''.join(l)
Python Provides the various solutions to shuffle the string:
1. External library: python-string-utils
first install the python-string-utils library
pip install python_string_utils
use string_utils.shuffle() function to shuffle string
please use the below snippet for it
Code Snippet
import string_utils
print string_utils.shuffle("random_string")
Output:
drorntmi_asng
2. Builtins Method: random.shuffle
Please find the code below to shuffle the string. The code will take the string and convert that string to list. Then shuffle the string contents and will print the string.
import random
str_var = list("shuffle_this_string")
random.shuffle(str_var)
print ''.join(str_var)
Output:
t_suesnhgslfhitrfi_
3. External Library: Numpy
import numpy
str_var = list("shuffle_this_string")
numpy.random.shuffle(str_var)
print ''.join(str_var)
Output:
nfehirgsu_slftt_his
you can use more_itertools.random_permutation
from more_itertools import random_permutation
s = 'ABCDEFGHIJ'
''.join(random_permutation(s))
output:
'DFJIEABGCH'
Here is a helper that uses random to non-destructively shuffle, string, list or tuple:
def shuffle_any(o):
is_l=is_t=False
if isinstance(o, str):
l = list(o)
elif isinstance(o, list):
l = o[:]
is_l = True
elif isinstance(o, tuple):
is_t = True
l = list(o)
else:
raise Exception("o is None!" if o is None \
else f"Unexpected type: {o.__class__.__name__}")
random.shuffle(l)
return l if is_l else tuple(l) if is_t else ''.join(l)
Usage:
print(f"shuffle_any('abcdefg'): {shuffle_any('abcdefg')}")
print(f"shuffle_any([1,2,3,4,5]): {shuffle_any([1,2,3,4,5])}")
print(f"shuffle_any((1,2,3,4,5)): {shuffle_any((1,2,3,4,5))}")
Output:
shuffle_any('abcdefg'): dfceabg
shuffle_any([1,2,3,4,5]): [5, 2, 3, 4, 1]
shuffle_any((1,2,3,4,5)): (4, 3, 2, 5, 1)

Categories