How to insert 1 interval numbers between given irregular numbers in python - 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)

Related

Mapping a function each list in a list of lists

I've been given a homework task that asks me to find in a list of data the greatest continuous increase. i.e [1,2,3,4,5,3,1,2,3] the greatest static increase here is 4.
I've written a function that takes a single list and spits out a list of sublists like this.
def group_data(lst):
sublist= [[lst[0]]]
for i in range(1, len(lst)):
if lst[i-1] < lst[i]:
sublist[-1].append(lst[i])
else:
sublist.append([lst[i]])
return(sublist)
Which does what it's supposed to
group_data([1,2,3,4,5,6,7,8,9,10,1,2,3,5,4,7,8])
Out[3]: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 5], [4, 7, 8]]
And I now want to subtract the last element of each individual list from the first to find their differences. But I'm having difficulty figuring out how to map the function to each list rather than each element of the list. Any help would be greatly appreciated.
you can do it using map function where arr is your grouped list
list(map(lambda x: x[-1]-x[0], arr ))
For this problem I think itertools.groupby would be a good choice. Since your final goal is to find the difference of longest consecutive numbers:
from itertools import groupby
max_l = max([len(list(g)) - 1 for k, g in groupby(enumerate([1,2,3,4,5,6,7,8,9,10,1,2,3,5,4,7,8]), key=lambda x: x[0] - x[1])])
print(max_l)
#it will print 9
Explanation:
First groupby the numbers with the difference between index and number value. For example [0, 1, 2, 4] will create [0, 0, 0, 1] as the index of 0 is 0, so 0-0=0, for the second one 1-1=0. Then take the maximum length of the grouped list. Since you want difference, I used len(list(g)) - 1

Python Powers and Exponents

What would be the best implementation for multiplying a list of numbers raised to a defined number of exponents.
Currently I have a list of 8 numbers that would be needed to be raised to a power. Every list will always contain 8 numbers and the numbers in the list will always have the exponent of which their index value is.
For example:
List = [1,2,3,4,5,6,7,8]
Power(1,0) + Power(2,1) + Power(3,2) +.... Power(8,7)
However, the issue is what if the list has a none value, how can you carry the exponential increased value without affecting the total sum.
Example:
List = [1,None,3,4,5,6,7,8]
Power(1,0) + (none) + Power(3,2) +.... Power(8,7)
Any ideas of implementation would help.
Maybe something like this could get you started?
import numpy as np
l = [1, None, 3, 4, 5, 6, 7, 8]
# If you need to define the powers
# powers = [0, 1, 2, 3, 4, 5, 6, 7]
powers = np.arange(len(l)) # If powers are always indices
arr = np.array([x if x is not None else 0 for x in l])
arr**powers
# array([ 1, 0, 9, 64, 625, 7776, 117649, 2097152]
(arr**powers).sum()
# 2223276
On second thought, the above would have a problem if you had [None, 1, 2, 3] since 0**0=1. So we should probably go with something like
l = [1, None, 3, 4, 5, 6, 7, 8]
numbers = np.array([x for x in l if x is not None])
powers = np.array([i for i in range(len(l)) if l[i] is not None])
(numbers**powers).sum()
List = [1,None,3,4,5,6,7,8]
result = sum([pow(List[i],i) for i in range(len(List)) if str(List[i]).isdigit()])
Well, you can use list comprehension to only pow numeric values:
index_list = range(len(list))
sum([pow(list[i], i) for i in index_list if str(list[i]).isdigit()])
#Output: 2223276
In here, we sum a list that contains all values powered by an exponent. It will only sum numeric values!

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,

Write the digits of a number into an array

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

Shuffle a list within a specific range python

I'm very new to Python, so bear with me. I would like to run a program that will shuffle a string of integers in a specific range, but without having to input each integer within that range. I.e., I want to randomize the list of integers from 1 to 100 without typing out (1, 2, 3...100).
Yes, I've looked at other answers to similar questions, but all are asking for one integer within a specific range, or are not answered for Python, or are asking for something way more complex. Thanks
You can use range() along with list() to generate a list of integers, and then apply random.shuffle() on that list.
>>> lst = list(range(1,11))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> random.shuffle(lst)
>>> lst
[4, 5, 3, 9, 2, 10, 7, 1, 6, 8]
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
In case you want the entire population within a given range, As #Ashwini proposed you can use random.shuffle
In Case you are interested in a subset of the population, you can look forward to use random.sample
>>> random.sample(range(1,10),5)
[3, 5, 2, 6, 7]
You may also use this to simulate random.shuffle
>>> random.sample(range(1,10),(10 - 1))
[4, 5, 9, 3, 2, 8, 6, 1, 7]
Note, The advantage of using random.sample over random.shuffle, is , it can work on iterators, so in
Python 3.X you don;t need to convert range() to list
In Python 2,X, you can use xrange
Same Code can work in Python 2.X and 3.X

Categories

Resources