Python splitting an int based on the char length - python

I’m new to python and would like to do a simple function. I’d like to read the input array and if the value is more than 4 digits, to then split it then print the first value then the second value.
I’m having issues splitting the number and getting rid of 0’s inbetween; so for example 1006, would become 1, 6.
Input array:
a = [ 1002, 2, 3, 7 ,9, 15, 5992]
Desired output in console:
1, 2
2
3
7
9
15
59,92

You can abstract the splitting into a function and then use a list comprehension to map that function over the list. The following can be tweaked (it matches more of what you had before one of your edits). It can be tweaked of course:
def split_num(n):
s = str(n)
if len(s) < 4:
return 0, n
else:
a,b = s[:2], s[2:]
if a[1] == '0': a = a[0]
return int(a), int(b)
nums = [1002, 2, 3, 7 ,9, 15, 5992]
result = [split_num(n) for n in nums]
for a,b in result:
print(a,b)
Output:
1 2
0 2
0 3
0 7
0 9
0 15
59 92

If you just want a list of the non-zero digits in the original list, you can use this:
a = [ 1002, 2, 3, 7 ,9, 15, 5992]
strings = [str(el) for el in a]
str_digits = [char for el in strings for char in el if char != '0']
and if you want the digits as ints, you can do:
int_digits = [int(el) for el in str_digits]
or go straight to
int_digits = [int(char) for el in strings for char in el if char != '0']
I'm not sure what the logic is behind your desired output is, though, so if this isn't helpful I'm sorry.

Related

IndexError: list index out of range in Reversal of arrays

I am trying to reverse arrays in groups. I have wasted more than half an hour finding the problem but not able to figure out how is index is out of range.
Here is my code:
def rev(A,S,N):
start=S
end=N
while start<end:
A[start],A[end]=A[end],A[start] #error here
start+=1
end-=1
return A
def reverseInGroups(A,N,K):
#Your code here
rev(A,0,K)
rev(A,K,N) #error here
return A
Here is the error I am getting
Sample Input 1 : N=5 K=3 A= [1,2,3,4,5]
Sample Output 1 : 3 2 1 5 4
Sample Output 2 N= 8 K=3 A=[1,2,3,4,5,6,7,8]
Sample Output 2 : 3 2 1 6 5 4 8 7
For more information please visit this link
How about
def rev(a,start,end, middle):
assert 0 <= start <= middle <= end < len(a)
a[start:middle] = reversed(a[start:middle])
a[middle:end] = reversed(a[middle:end])
return a
There is no need to use / iterate positions at all - this avoids your error because slicing can handle oversized slices: [1,2,3,4][2:99] works w/o error.
def rev(data, start, end):
"""Reverses the range start:end (end exclusive) of the given list.
No safeguards whatsoever so only use with correct data. Out of bounds
is irrelevant due to slices used to reverse."""
data[start:end] = data[start:end][::-1] # you need end+1 if you want inclusive
return data
def reverseInGroups(A,N,K):
rev(A,0,K)
rev(A,K,N)
return A
l = list(range(11))
print ( reverseInGroups(l , 8, 3)) # why N (the bigger number) first?
to get
[2, 1, 0, 7, 6, 5, 4, 3, 8, 9, 10]
#0 1 2 3 4 5 6 7 8 9 10 # 0-3(exclusive) and 3-8(exclusive) reversed
To revere all K sized groups do
def reverseInGroups(A,K):
pos_at = 0
while pos_at < len(A):
rev(A, pos_at, pos_at+K)
pos_at += K
return A

Check pandas column for successive row values

I have:
hi
0 1
1 2
2 4
3 8
4 3
5 3
6 2
7 8
8 3
9 5
10 4
I have a list of lists and single integers like this:
[[2,8,3], 2, [2,8]]
For each item in the main list, I want to find out the index of when it appears in the column for the first time.
So for the single integers (i.e 2) I want to know the first time this appears in the hi column (index 1, but I am not interested when it appears again i.e index 6)
For the lists within the list, I want to know the last index of when the list appears in order in that column.
So for [2,8,3] that appears in order at indexes 6, 7 and 8, so I want 8 to be returned. Note that it appears before this too, but is interjected by a 4, so I am not interested in it.
I have so far used:
for c in chunks:
# different method if single note chunk vs. multi
if type(c) is int:
# give first occurence of correct single notes
single_notes = df1[df1['user_entry_note'] == c]
single_notes_list.append(single_notes)
# for multi chunks
else:
multi_chunk = df1['user_entry_note'].isin(c)
multi_chunk_list.append(multi_chunk)
You can do it with np.logical_and.reduce + shift. But there are a lot of edge cases to deal with:
import numpy as np
def find_idx(seq, df, col):
if type(seq) != list: # if not list
s = df[col].eq(seq)
if s.sum() >= 1: # if something matched
idx = s.idxmax().item()
else:
idx = np.NaN
elif seq: # if a list that isn't empty
seq = seq[::-1] # to get last index
m = np.logical_and.reduce([df[col].shift(i).eq(seq[i]) for i in range(len(seq))])
s = df.loc[m]
if not s.empty: # if something matched
idx = s.index[0]
else:
idx = np.NaN
else: # empty list
idx = np.NaN
return idx
l = [[2,8,3], 2, [2,8]]
[find_idx(seq, df, col='hi') for seq in l]
#[8, 1, 7]
l = [[2,8,3], 2, [2,8], [], ['foo'], 'foo', [1,2,4,8,3,3]]
[find_idx(seq, df, col='hi') for seq in l]
#[8, 1, 7, nan, nan, nan, 5]

Looking for the biggest number before and after 'i' in list

I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3
I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?
'a' is the list in my code
a = [1, 3, 2, 4, 3]
for i in a:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
Try:
for i in range(len(a)):
print(max(a[:i+1]))
print(max(a[i:]))
You are not iterating over the indices in your original code; and thus the partition does not make sense.
The only mistake in your code is the for i in a loop, which loops throgh i = 1,3,2,4,3 and not i=0,1,2,3,4
The following piece of code works
a=[1,3,2,4,3]
for i in range(len(a)) :
print max(i,max(a[:i+1]))
print max(i,max(a[i:]))
this may work... not fully tested but it looks correct
a = [1, 3, 2, 4, 3]
for i in a[:-1]:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
num = a[-1]
west = a[0:-1]
if max(west) > num:
print(max(west))
else:
print(str(a[-1]))
print(str(a[-1]))
Output: 1 4 3 4 4 4 4 3

Python - string to matrix representation

I have a string a="1 2 3; 4 5 6". How do i express this as a matrix [1 2 3; 4 5 6] in Python?
I want to then use another such string b, convert to a matrix and find a x b.
You can use the numpy module to create a matrix directly from a string in matlab type format
>>> import numpy as np
>>> a="1 2 3; 4 5 6"
>>> np.matrix(a)
matrix([[1, 2, 3],
[4, 5, 6]])
You can use the same library to do matrix multiplication
>>> A = np.matrix("1 2 3; 4 5 6")
>>> B = np.matrix("2 3; 4 5; 6 7")
>>> A * B
matrix([[28, 34],
[64, 79]])
Go read up on the numpy library, it is a very powerful module to do all of the type of work that you are referring to.
This is one way to do it, split the string at ;, then go through each string, split at ' ' and then go through that, convert it to an int and append to a sublist, then append that sublist to another list:
a = "1 2 3; 4 5 6"
aSplit = a.split('; ')
l = []
for item in aSplit:
subl = []
for num in item.split(' '):
subl.append(int(num))
l.append(subl)
print l

for loop conversion from C to Python

How can I write the for loop in Python as I write it in C:
for(i=0;i<10;)
{
if(i%2==0)
i=i+3;
else
i++;
printf("%d\n",i);
}
Can anyone tell me about this? I searched a lot but couldn't find it. I wrote it like this in Python:
for i in range(0,10):
if (i%2==0):
i+=3
else:
i+=1
print i
Output:
3
2
5
4
7
6
9
8
11
10
Expected output:
3
4
7
8
11
Can anyone also explain the reason of this output?
To write the same loop in Python:
i = 0
while i < 10:
if i % 2 == 0:
i += 3
else:
i += 1
print i
Which gives:
3
4
7
8
11
Note that, per the tutorial:
The for statement in Python differs a bit from what you may be used to
in C or Pascal. Rather than always iterating over an arithmetic
progression of numbers (like in Pascal), or giving the user the
ability to define both the iteration step and halting condition (as
C), Python’s for statement iterates over the items of any sequence (a
list or a string), in the order that they appear in the sequence.
In a Python for loop, any changes to the loop variable (i, in this case) that occur during the loop are ignored when the loop repeats, and the next value from the object being iterated over is used. In this case, the object is a list of numbers:
>>> range(10) # note that a 0 start is the default
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Some languages call this a for each loop. See also the language reference for more details.
range(0, 10) function returns list of values from 0 to 9:
range(0, 10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Then for body is executed for each element in this list.
If You have 0, the 0 % 2 == 0 so it prints 0 + 3 etc.
In C You changed i value so You jumped to other value in set. Using python's for You will get through all elements. You should use
i = 0
while i < 10:
if (i % 2 == 0):
i += 3
else:
i += 1
print i
To have same results as in C
try this
for i in range(10):
if i%2 == 0:
i = i+3
else:
i = i + 1
print i
it gives the same output u asked for...hope this helps

Categories

Resources