How to compute the average of a string of floats - python-3.x

temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
I am stuck in this assignment and unable to find a relevant answer to help.
I’ve used .split(",") and float()
and I am still stuck here.

temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
li = temp.split(",")
def avr(li):
av = 0
for i in li:
av += float(i)
return av/len(li)
print(avr(li))

You can use sum() to add the elements of a tuple of floats:
temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
def average (s_vals):
vals = tuple ( float(v) for v in s_vals.split(",") )
return sum(vals) / len(vals)
print (average(temp))

Admittedly similar to the answer by #emacsdrivesmenuts (GMTA).
However, opting to use the efficient map function which should scale nicely for larger strings. This approach removes the for loop and explicit float() conversion of each value, and passes these operations to the lower-level (highly optimised) C implementation.
For example:
def mean(s):
vals = tuple(map(float, s.split(',')))
return sum(vals) / len(vals)
Example use:
temp = '75.1,77.7,83.2,82.5,81.0,79.5,85.7'
mean(temp)
>>> 80.67142857142858

Related

How to generate list of string with Random Characters using python3

I tried with the below code but it seems not to give the intended output.
ran = ''.join(random.choice(string.ascii_uppercase+string.digits) for x in range(10))
So the above code gives '6U1S75' but I want output like
['6U1S75', '4Z4UKK', '9111K4',....]
Please help.
I thought this is elegant :
from string import digits, ascii_letters
from random import choices
def rand_list_of_strings(list_size, word_size, pool=ascii_letters + digits):
return ["".join(choices(pool, k=word_size)) for _ in range(list_size)]
I used ascii_letters instead of ascii_uppercase to have both upper and lower case values, you can edit it to your suiting.
Example use of the above function :
>>> rand_list_of_strings(4, 5)
['wBSbH', 'rJoH8', '9Gx4q', '8Epus']
>>> rand_list_of_strings(4, 10)
['UWyRglswlN', 'w0Yr7xlU5L', 'p0e6rghGMS', 'Z8zX2Vqyve']
>>>
The first argument is the list size, and the second argument is how large each consequent string should be, and the function invocation returns a list instance. Do not that this should not be used for cryptographic purposes.
Take a look at this.
list_size = 10
word_size = 4
ran = []
for i in range(list_size):
rans = ''
for j in range(word_size):
rans += random.choice(string.ascii_uppercase + string.digits)
ran.append(rans)
Though the above solution is clearer and should be preferred, if you absolutely want to do this with list comprehension...
list_size = 10
word_size = 4
ran = [
''.join([
random.choice(string.ascii_uppercase + string.digits)
for j in range(word_size)
])
for i in range(list_size)
]

Can we change for loop result into list with index?

I am currently learning python, I just have one little question over here.
I used for loop and getting a result below.
Here is my code:
def psuedo_random(multiplier, modulus, X_0, x_try):
for i in range(x_try):
place_holder = []
count = []
next_x = multiplier * X_0 % modulus
place_holder.append(next_x)
X_0 = next_x
for j in place_holder:
j = j/modulus
count.append(j)
print(count)
Result:
[0.22021484375]
[0.75439453125]
[0.54443359375]
[0.47705078125]
Can we somehow change it into something like this?
[0.22021484375, 0.75439453125, 0.54443359375, 0.47705078125]
After you initialized a list, you can use append function in the loop.
initialize a list where you want to list these numbers
mylist = []
use this function in your for loop
for i in .....:
mylist.append(i)
It's simple. Do not initialize your list inside the loop. Just place it outside.

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))

2-opt algorithm using generators instead for nested for loop

I am using an opt-2 approach on the TSP problem and have adapted some code I found on-line. I pass in a list road_map which is a list of tuples that contains a region (string), city (string), latitude (float) and longitude (float) like the following (lats and longs made up here)
[('South England' 'London', '32.361538', '-86.279118'),
('Yorkshire', 'Manchester', 35,6656, '-86.4543')]
I want to use this 2-opt algorithm to reorder the map and return a new map/route that contains a shorter distance than the previous one, this will be the best_map.
Below are my two functions I am using but it seems messy with the while nested fors and if statements. I think there must be a much cleaner way of doing this with generator functions, but I am unable to think how. Any ideas?
def opt2(best_map, i, j):
new_map = best_map[:]
new_map[i:j] = best_map[j:i:-1]
return new_map
def start_opt2(road_map):
best_map = road_map[:]
best_distance = compute_total_distance(best_map)
for i in range(len(best_map) + 1):
for j in range(i+1, len(best_map)):
new_map = opt2(best_map, i, j)
new_distance = compute_total_distance(new_map)
if new_distance < best_distance:
best_distance= new_distance
best_map = new_map
break
return best_map

Creating a function that returns index of minimum value in a list?

def minimum_index(xs):
minimum_index=xs[0]
for i in range(len(xs)):
if xs[i]<xs[i+1]:
min_i=i
elif xs[i]>xs[i+1]:
min_i=i+1
continue
return minimum_index
This looks correct to me, but for some reason, I keep trying to change things around and I either get an incorrect return value or no return value.
Simplify the function
def minimum_index(xs):
ans = 0
for i in range(1, len(xs)):
if xs[i] < xs[ans]:
ans = i
return ans
or in a more pythonic way
minimum_index = lambda xs: xs.index(min(xs))
Your code has at least two issues: You seem to have two variables that stand for the minimal index, and you mix them up. Also, it is not enough to compare subsequent elements, you will have to compare to the minimal value. Try this:
def minimum_index(xs):
minx = xs[0]
mini = 0
for i in range(1,len(xs)):
if xs[i]<minx:
mini = i
minx = xs[i]
return mini
If you are using numpy, then you can simply use their numpy.argmin(xs).

Resources