Switching positions of two strings within a list - python-3.x

I have another question that I'd like input on, of course no direct answers just something to point me in the right direction!
I have a string of numbers ex. 1234567890 and I want 1 & 0 to change places (0 and 9) and for '2345' & '6789' to change places. For a final result of '0678923451'.
First things I did was convert the string into a list with:
ex. original = '1234567890'
original = list(original)
original = ['0', '1', '2' etc....]
Now, I get you need to pull the first and last out, so I assigned
x = original[0]
and
y = original[9]
So: x, y = y, x (which gets me the result I'm looking for)
But how do I input that back into the original list?
Thanks!

The fact that you 'pulled' the data from the list in variables x and y doesn't help at all, since those variables have no connection anymore with the items from the list. But why don't you swap them directly:
original[0], original[9] = original[9], original[0]
You can use the slicing operator in a similar manner to swap the inner parts of the list.
But, there is no need to create a list from the original string. Instead, you can use the slicing operator to achieve the result you want. Note that you cannot swap the string elements as you did with lists, since in Python strings are immutable. However, you can do the following:
>>> a = "1234567890"
>>> a[9] + a[5:9] + a[1:5] + a[0]
'0678923451'
>>>

Related

How to Change position of elements in python list

I have a python list like
the_list= ['john',"nick","edward","mood","enp","wick"]
i always want the mood and enp to be in the 0th and 1st index of list rest order can be anything.
so the output will be
op_list= ["mood","enp",........rest..]
The following will work:
op_list = ["mood", "enp"] + [x for x in the_list if x not in ("mood", "enp")]
This assumes the two special elements are always present.

Python 3: Add string to OBJECTS within a list

I am sure it is a very trivial question but I can not seem to find anything online, perhaps because I am not using the right terminology..
I have a list that looks like so:
list = ["abc",
"ded"]
I know how to append elements to this list, how to add elements to the beginning, etc.
What I need to do is to add a string (more specifically an asterisk (*)) before and after each object in this list. So it should look like:
list = ["*abc*",
"*ded*"]
I have tried:
asterisk = '*'
list = [asterisk] + list[0]
list = asterisk + List[0]
list = ['*'] + list[0]
list = * + list[0]
asterisk = list(asterisk)
list = [asterisk] + list[0]
and I always get:
TypeError: can only concatenate list (not "str") to list
Then of course there is the problem with adding it before and after each of the objects in the list.
Any help will be appreciated.
Just string interpolate it in as follows:
[f'*{s}*' for s in ["abc","ded"]]
Output
['*abc*', '*ded*']
Note this is for Python 3.6+ only.
For your list you use this beautiful syntax, called "list comprehension":
lst = ['abc', 'ded']
lst = ['*'+s+'*' for s in lst]
print(lst)
This would get you:
['*abc*', '*ded*']
Have you tried using a list comprehension to adjust
[('*'+i) for i in asterix]
you can give it a name just for good measure so that you can call it later
You can join the asterisks with each word
asterisked = [w.join('**') for w in lst]
The trick here is to remember that strings are iterables, so you can pass a string that contains two asterisks to the word's join method to let it prepend the word with the first asterisk and append the second one

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

accessing specific intervals in list

I have a list containing the system time from a machine. Since the list contains only the milliseconds part, the values donĀ“t go beyond 1000.
For better viewing I want to add i*1000 to certain intervals in this list for each time the list skips 1000. For better understanding i will give my input list and what my output list should look like:
inputlist = [300,600,900,200,500,800,100,400]
etc, the output list should look like this:
outputlist = [300,600,900,1200,1500,1800,2100,2400]
since I want the list to start with zero i subtracted the first element of the list from each element giving me a new inputlist:
inputlist_new = [0,300,600,-100,200,500,-200,100]
which should give me a new outputlist like:
outputlist_new = [0,300,600,900,1200,1500,1800,2100]
I tried creating a list containing the indices of each element < 0 to cut the list into intervals, to multiply the thousands on each interval but I am not able to do so. My code for this index list is this:
list_index = [i for i, j in enumerate(inputlist_new) if j < 0]
I actually found a solution myself: i copied the list i want to change into a new one, just for the sake of maybe using it later (so this is not necessary for the solution) and then used 2 for loops:
inputlist_new = [0,300,600,-100,200,500,-200,100]
inputlist2 = inputlist_new.copy()
for x in range(len(list_index)):
for y in range(list_index[x],len(inputlist2)):
inputlist2[y] = inputliste2[y]+1000
this gave me the wanted output

Get value from query string in Python 3 without the [' '] showing up in the value

I have the following code in a Python 3 http server parse out a URL and then parse out a query string:
parsedURL = urlparse(self.path)
parsed = parse_qs(parsedURL.query)
say that parsedURL.query in this case turns about to be x=7&=3.I want to get the 7 and the 3 out and set them equal to variables x and y. I've tried both
x = parsed['x']
y = parsed['y']
and
x = parsed.get('x')
y = parsed.get('y')
both of these solutions come up with x = ['7'] and y = ['3'] but I don't want the brackets and single quotes, I want just the values 7 and 3, and I want them to be integers. How do I get the values out and get rid of the brackets/quotes?
Would simply:
x = int(parsed['x'][0])
y = int(parsed['y'][0])
or
x = int(parsed.get('x')[0])
y = int(parsed.get('y')[0])
serve your purpose? You should of course have suitable validation checks, but all you want to do is convert the first element of the returned array to an int, so this code will do the business.
This is because the get() returns an array of values (I presume!) so if you try parsing url?x=1&x=2&x=foo you would get back a list like ['1', '2', 'foo']. Normally there is only one (or zero, of course) instance of each variable in a query string, so we just grab the first entry with [0].
Note the documentation for parse_qs() says:
Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

Resources