Write the digits of a number into an array - python

I want to calculate with seperated digits of a very long number. How can I do this in Python2.7? I thought about somehow write the digits in an array so that I can access the digits with array(x):
number = 123456789123456789
array = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]
The problem is, that the number has so many digits, that it would take very long to do that manually. So how can I do this automatically?

You can use map, int and str functions like this
print map(int, str(number))
str function converts the number to a string.
map function applies the int function to each and every element of stringifed number, to convert the string to an integer.
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you are doing this again and again, like in a loop, then list comprehension will be faster than the map approach
number = 123456789123456789
from timeit import timeit
print timeit("map(int, str(number))", "from __main__ import number")
print timeit("[int(dig) for dig in str(number)]", "from __main__ import number")
Output on my machine
12.8388962786
10.7739010307

You can also use a list comprehension link this.
array = [int(x) for x in str(number)]

As an alternative, the purely mathematical solution is below. By repeatedly dividing by 10 and taking the remainder you can extract each digit.
n = 123456789123456789
result = []
while n != 0:
n, d = divmod(n, 10)
result.append(int(d))
result.reverse()
print result # [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can simply iterate over each digit in number and push into an array. Try this
result = []
for d in str(number):
result.append (int(d))
print result

Related

Write a function that will take as input a string that includes both letters and numbers

The function should first remove all of the letters, and then convert each digit to a single-digit integer. Finally, it should return a list with each of the integers sorted from lowest to highest.
("a2fei34bfij1") should return [1, 2, 3, 4]
("owifjaoei3oij444kfj2fij") should return [2, 3, 4, 4, 4]
("987321a") should return [1, 2, 3, 7, 8, 9]
One of the several ways is using regex, see if this helps
import re
regex="(?P<numbers>\d)"
def filter_digits(words):
num=[]
if words:
m = re.findall(regex,words)
num=sorted([int(i) for i in m])
return num
print(filter_digits("a2fei34bfij1"))
print(filter_digits("owifjaoei3oij444kfj2fij"))
print(filter_digits("987321a"))
print(filter_digits(None))
print(filter_digits("abcd"))
Reference: https://docs.python.org/3/library/re.html
Use regex and a sort:
import re
def clean_up(input_string):
return sorted(re.findall("[0-9]", input_string))
Here is my solution
import re
def intList(text):
# use regex to find every single digit in the string
numRe = re.compile(r'\d')
# use list comprehension to transform every found digit (which is string at first) to integer and make a list
mo = [int(i) for i in numRe.findall(str(text))]
# return sorted list of integers
return sorted(mo)
print(intList("a2fei34bfij1")) # prints [1, 2, 3, 4]
print(intList("owifjaoei3oij444kfj2fij")) # prints [2, 3, 4, 4, 4]
print(intList("987321a")) # prints [1, 2, 3, 7, 8, 9]

Is there a way to use setdiff1d on 2D arrays?

I have an assignment to code kfold(n, n_folds) function, which is supposed to work exactly like sklearn.model_selection.KFold: divide list of integers from 1 to n into n % k_folds groups of n // k_folds + 1 elements and n - n % k groups of n // k_folds elements (this part works well & optimized), then for each group get tuple (all integers from 1 to n not being part of the group, the group) My own realization of this last step just hits TL verdict hard (yet outputs correct answers).
def kfold(n, n_folds):
elements = np.arange(0, n)
slices = np.array(np.array_split(elements, n_folds))
ans = []
for slice in slices:
ans.append((np.setdiff1d(elements, slice), slice))
return ans
kfold(10, 3) as example returns:
[([5, 6, 7, 8, 9, 10], [1, 2, 3, 4]), ([1, 2, 3, 4, 8, 9, 10], [5, 6, 7]), ([1, 2, 3, 4, 5, 6, 7], [8, 9, 10])]
I believe the problem is my code is not fully vectorized, employing one cycle instead of numpy methods. I've read documentation of setdiff1d, setxor1d and likewise functions. While they work well dividing a single slice, I cannot see a way to make them execute all the n_folds slices simultaneously. Is there a way to make this functions work? If there is a nice alternative solution, I'd like to hear about it too

How to insert 1 interval numbers between given irregular numbers in python

I've generated index number list what I do find data using for-loop.
That numbers are as follows.
I want to generate 1 interval index numbers between each given numbers
Int64Index([ 2343, 2913, 5466, 8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700],dtype='int64')
for e.g) 2343,2344,2345,2346 ......,2911,2912,2913,2914....5464,5465,5466 some thing like that.
Is there any method that i generate 1 interval numbers do not use for-loop?
Try using the builtin range() function.
First you need to determine start and end number using the min() and max() functions.
start_num = min(listr)
end_num = max(listr)
Then we use range() to create our new list
new_listr = list(range(start_num, end_num+1))
The complete sample code:
listr = [2343, 2913, 5466, 8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700]
start_num = min(listr)
end_num = max(listr)
new_listr = list(range(start_num, end_num+1))
Did you try:
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,1)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
>>> range(1,10,3)
[1, 4, 7]
>>> help(range)
Help on built-in function range in module __builtin__:
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.
(END)

Trying to produce a Random list of single digit integers which are not repeated. Getting only 5 instead of 9 [duplicate]

This question already has answers here:
Random number generator, how to get random numbers that are not the same
(2 answers)
Closed 6 years ago.
Here is my code
from random import randint
SudList = []
numbers = [1,2,3,4,5,6,7,8,9]
for i in numbers:
SudList.append(numbers[randint(0,len(numbers)-1)])
print("Sudlist-" + str(SudList))
numbers.remove(SudList[-1])
print("numbers-" + str(numbers))
print(SudList)
I expected this code to return something like this- (the final SudList)
[9,7,2,8,6,4,5,3,1]
But Instead it Returns something like this -
[9,4,6,7,2]
Here is the whole output-
Sudlist-[5]
numbers-[1, 2, 3, 4, 6, 7, 8, 9]
Sudlist-[5, 1]
numbers-[2, 3, 4, 6, 7, 8, 9]
Sudlist-[5, 1, 9]
numbers-[2, 3, 4, 6, 7, 8]
Sudlist-[5, 1, 9, 3]
numbers-[2, 4, 6, 7, 8]
Sudlist-[5, 1, 9, 3, 4]
numbers-[2, 6, 7, 8]
[5, 1, 9, 3, 4]
Press any key to quit
How do i correct my code?
You can use shuffle. It's will meet your needs.
import random
random.shuffle(numbers)
output
[7, 4, 3, 2, 1, 8, 6, 5, 9]
If you wish to stick with this piece of code, simply use i in range len(numbers) instead of i in numbers. Your remove statement is reducing the length of numbers and thus, the number of numbers printed is always (len(numbers)+1)/2
from random import randint
SudList = []
numbers = [1,2,3,4,5,6,7,8,9]
for i in range(len(numbers)):
SudList.append(numbers[randint(0,len(numbers)-1)])
print("Sudlist-" + str(SudList))
numbers.remove(SudList[-1])
print("numbers-" + str(numbers))
print(SudList)
If you want to stay with your implementation just change:
for i in numbers:
To:
for i in range(len(numbers)):
So you don't iterate over the list that changes
As has been mentioned, shuffle is the quickest and most readable solution.
import random
numbers = [1,2,3,4,5,6,7,8,9]
random.shuffle(numbers)
print(numbers)
However, it looks like you're wanting to see the state of each list at every step, so if you're looking for a custom implementation, you could also try the following:
from random import randint
Sudlist = []
numbers = [1,2,3,4,5,6,7,8,9]
while len(numbers) > 0:
index = randint(0, len(numbers) - 1)
Sudlist.append(numbers.pop(index))
print('Sudlist-' + str(Sudlist))
print('numbers-' + str(numbers))
print(Sudlist)

Check what numbers in a list are divisible by certain numbers?

Write a function that receives a list of numbers
and a list of terms and returns only the elements that are divisible
by all of those terms. You must use two nested list comprehensions to solve it.
divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) # returns [12, 6]
def divisible_numbers(a_list, a_list_of_terms):
I have a vague pseudo code so far, that consists of check list, check if divisible if it is append to a new list, check new list check if divisible by next term and repeat until, you have gone through all terms, I don't want anyone to do this for me but maybe a hint in the correct direction?
The inner expression should check if for a particular number, that number is evenly divisible by all of the terms in the second list
all(i%j==0 for j in a_list_of_terms)
Then an outer list comprehension to iterate through the items of the first list
[i for i in a_list if all(i%j==0 for j in a_list_of_terms)]
All together
def divisible_numbers(a_list, a_list_of_terms):
return [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]
Testing
>>> divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3])
[12, 6]
if you want to get input from the user using this type of way.
enter code hereprint("numbers which are divisible by 5")
user_input=eval(input("enter the value in list type [1,2,3]: "))**
print(type(user_input)) if type(user_input)==list: for i in
user_input: if(i%5==0): print(i,end=",") else:
print("none")
OUTPUT:
numbers that are divisible by 5 enter the value in list type [1,2,3]:
[15,10,20,45,69] <class 'list'> 15,10,20,45,

Categories

Resources