Python - Circular Shift Lists (but not the whole index) - python

so basically i want to make list shift left but only 1 digit from every index.
for example:
if i have this list [123,45678,90] i want to get this [234,56789,1]
another example just to make sure from this [12,34,56] i want to get this [23,45,61]
what ive done so far is
def main():
lst_lenght = int(input("Enter the lenght of the list:")) #amount of indexes
lst_elements = create_list(lst_lenght)
print(lst_elements)
def create_list(y):
lst = []
for i in range(y):
x = int(input('Enter the list elements:'))
lst.append(x)
return lst
then ive tried to do function that i will get the first digit of number(in every index)
after this i was just thinking removing the digit and placing it in the end of the index before it exept the first index which will go to the last one.
unfortunately i wasnt able to do it ive got stuck on this part, would love ur help, Thank you very much!!

You could do this with a list comprehension. Each element in the new list is defined by taking item[1:] (everything after the first digit in that item) plus next_item[0] (the first digit of the next item).
To do this, it's easier if you operate on it as a list of strings, and then convert back to integers to return.
def shifted_list(lst):
str_lst = [str(x) for x in lst]
str_lst_shifted_by_one = str_lst[1:] + [str_lst[0]]
shifted_str_lst = [item[1:] + next_item[0] for item, next_item in zip(str_lst, str_lst_shifted_by_one)]
return [int(x) for x in shifted_str_lst]
print(shifted_list([123,45678,90])) # [234, 56789, 1]

Related

Adding string values together that are elements in a list

How would I go about doing the following? I need to add the number in the various elements together and assign the total to a new variable. I have been trying for days without much luck. I'm not sure if the numbers have to be split from the letters first?
list = ['2H','4B']
any help would be GREATLY appreciated.
edit:
Thanks for the replies eveyrone. I dont know why I cant get this right it seems like it should be so simple.
I will give you guys some more infomration.
the list below represents to playing cards, the first number or letter is the face value ie: 2 or 3 but can be a 'K' as well which stands for king and the value for that will be ten. the second part is the card suit ie. C for Clubs or H for hearts. I need to add the face value for these two cards together and get the hand total. a More accurate list might look like this.
list1 = ['KH', '10C']
Is this helping. it will help regardless of the number position in them element.
list1 = ['2H','4B']
list1=[word for x in list1 for word in x] #== Split the elements
print(list1)
new_var=0
for value in list1:
try:
value=int(value) #=== Convert to int
new_var+=value #== Add value
except ValueError:
pass
print(new_var)
One approach, using a list comprehension along with re.findall to extract the leading digits from each list entry:
list = ['2H','4B']
nums = [int(re.findall(r'^\d+', x)[0]) for x in list] # [2, 4]
output = sum(nums) # 6
You should avoid using function names as variable names i.e. list =
There are a few ways to do this and I suggest you review the Python documentation on slicing and indexing strings.
l = ['2H','4B']
result = sum(int(x[0]) for x in l)
print(result)
result equals sum of first char of each element of the list. I have converted each indexed element zero to integer to allow addition.
You can also do it the following way:
result = 0
for x in l:
result += int(x[0])
print(result)
You can extract numbers from each string then add them
You can use
total = 0
list = ['2H','4B']
for element in list:
res = [int(i) for i in element.split() if i.isdigit()]
total += sum(res)
print(total)

Finding nth digit of a number in a list

Say you have some nested list
[[4,682,31249,81,523],[321741245,7],[349,25,5]]
where each element can be of any length and the length of each number can vary also. How can one check each individual number for what the first digit from the left contains? As well as continuing through the number to find the 2nd, 3rd, etc digit.
For simplicity, the program just needs to return one digit at a time, i.e. returns 4, then 6 when called again.
Expected output:
4,6,3,8,5,3,7,3,2,5
8,1,1,2,2,4,5
2,2,3,1,9
x=[[4,682,31249,81,523],[321741245,7],[349,25,5]]
x=[item for sublist in x for item in sublist]
max_len=len(str(max(x)))
x=[str(y) for y in x]
def digits(x,index):
digit_list=[]
for num in x:
try:
digit_list.append(num[index])
except:
pass
return digit_list
for index in range(0,max_len):
print(digits(x,index))
Explanation:
1.Intialize x
2.Flat x i.e convert nested list to list
3.Calculate the length of highest number. You can take 'n' on your choice as well. I took it as length of highest number
4.Convert all numbers as string
5.define function digits(). It initializes a list & append single digits according the index called
6.By looping over range(0,max_len/n), call digits() for each index:0-->n
Assuming you are using python do it as:
nestedArr = [[4,682,31249,81,523],[321741245,7],[349,25,5]]
for arr in nestedArr:
firstNums = [str(x)[0] for x in arr]
print(", ".join(firstNums))

Comparing adjacent elements together without using zip method

How would you go about comparing two adjacent elements in a list in python? How would save or store the value of that item while going through a for loop? I'm trying not to use the zip method and just using an ordinary for loop.
comparing_two_elements = ['Hi','Hello','Goodbye','Does it really work finding longest length of string','Jet','Yes it really does work']
longer_string = ''
for i in range(len(comparing_two_elements)-1):
if len(prior_string) < len(comparing_two_elements[i + 1]):
longer_string = comparing_two_elements[i+1]
print(longer_string)
The below works simply by 'saving' the first element of your list as the longest element, as it will be the first time you loop over your list, and then on subsequent iterations it will compare the length of that item to the length of the next item in the list.
longest_element = None
for element in comparing_two_elements:
if not longest_element:
longest_element = element
continue
if len(longest_element) < len(element):
longest_element = element
If you want to go the "interesting" route, you could do it with combination of other functions, for eg
length_map = map(len, comparing_two_elements)
longest_index = length_map.index(max(length_map))
longest_element = comparing_two_elements[longest_index]
Use the third, optional step argument to range - and don't subtract 1 from len(...) ! Your logic is incomplete: what if the first of a pair of strings is longer? you don't do anything in that case.
It's not clear what you're trying to do. This for loop runs through i = 0, 2, 4, ... up to but excluding len(comparing_two_elements) (assumed to be even!), and prints the longer of each adjacent pair:
for i in range(0, len(comparing_two_elements), 2):
if len(comparing_two_elements[i]) < len(comparing_two_elements[i + 1]):
idx = i
else:
idx = i + 1
print(comparing_two_elements[idx])
This may not do exactly what you want, but as several people have observed, it's unclear just what that is. At least it's something you can reason about and adapt.
If you just want the longest string in a sequence seq, the whole adjacent pairs rigamarole is pointless; simply use:
longest_string = max(seq, key=len)

Simple selection sort with repeated elements?

Given a list x, I want to sort it with selection sort, and then count the number of swaps made within the sort. So I came out with something like this:
count=0
a=0
n=len(x)
while (n-a)>0:
#please recommend a better way to swap.
i = (min(x[a:n]))
x[i], x[a] = x[a], x[i]
a += 1
#the count must still be there
count+=1
print (x)
Could you help me to find a way to manage this better? It doesn't work that well.
The problem is NOT about repeated elements. Your code doesn't work for lists with all elements distinct, either. Try x = [2,6,4,5].
i = (min(x[a:n]))
min() here gets the value of the minimum element in the slice, and then you use it as an index, that doesn't make sense.
You are confusing the value of an element, with its location. You must use the index to identify the location.
seq = [2,1,0,0]
beg = 0
n = len(seq)
while (n - beg) > 0:
jdx = seq[beg:n].index((min(seq[beg:n]))) # use the remaining unsorted right
seq[jdx + beg], seq[beg] = seq[beg], seq[jdx + beg] # swap the minimum with the first unsorted element.
beg += 1
print(seq)
print('-->', seq)
As the sorting progresses, the left of the list [0:beg] is sorted, and the right side [beg:] is being sorted, until completion.
jdx is the location (the index) of the minimum of the remaining of the list (finding the min must happen on the unsorted right part of the list --> [beg:])

(Python) Checking the 3x3 in a Sudoku, are there better ways to do this?

My partner in a summative for HS gave me this algorithm, I was hoping somebody could tell me if there is a more eloquent way of coding this..
CB is current board position(global), its a list of lists.
for a in xrange(0, 3):
for b in xrange(0, 3):
for j in xrange(1, 4):
for k in xrange(1, 4):
boxsum += CB[3a + j][3b + k]
if not(boxsum == 45):
return False
boxsum = 0
First, the following code is not indented correctly:
if not(boxsum == 45):
return False
boxsum = 0
(with the current indentation it will always fail on the first time this code is executed)
Second, in the following line:
boxsum += CB[3a + j][3b + k]
you probably meant to do:
boxsum += CB[3*a + j][3*b + k]
And last, in order to check a 3x3 part of sudoku game it is not enough to check the sum - you should also check that every number between 1-9 is present (or in other words, that all the numbers are in the range 1-9 and there is no number that appears more than once).
There are dozens of "cleaner" ways to do so.
First of all, why not use numpy for matrices, where you are obviously working with a matrix? I am assuming your numeration (which is a bit odd, why you start numerating from "1"?)
import numpy as np
CB = np.array(CB)
def constraint3x3check(CB):
return np.all(np.sum( CB[3*a+1:3*a+3, 3*b+1:3*b+3)==45 for a in range(3) for b in range(3))
Given the sum of the box equals 45, that doesn't mean there are all 1-9 numbers present.
You could for example add your numbers to set and check if the length of the set is always 9.
Since the sum 45 does not mean the answer is correct, necessarily, a different way is needed. Personally, I would join the rows into a single list and compare them to the list (1,2,...9), e.g.
#assuming this is your format...
box = [[4,2,3],[1,5,9],[8,7,6]]
def valid_box(box):
check_list = []
for row in box:
check_list += row
return list(range(1,10)) == sorted(check_list)
Although the code creating the list could also be done with list comprehension (I have no idea which one is more efficient, processor-wise)
def valid_box2(box):
return list(range(1,10)) == sorted( [item for row in box for item in row ] )
Merge list code taken from Making a flat list out of list of lists in Python

Categories

Resources