lists functions- len ,cal - python

I'm thinking about making a small program that calculates a mathematical base.
I need to know the length of a list and I want to store in a variable its value!
I also want to add all the lists elements "they are numbers" and store there value all together in a variable.
Note: the list is really long, so I want an easy way. I know other long ways!
numbers=[1,2,3,4,5,6]
x=len(numbers)
print(x)
Now how to all them all?

Just use sum()
numbers=[1,2,3,4,5,6]
x=sum(numbers)
print(x)
>>prints 21

Related

Limiting user input to number of variables when using split() to prevent 'ValueError: too many values to unpack'?

a,b = map(int, input().split())
In the above code or anything similar, we use split to separate multiple inputs on a single line, typically separated with a space, and assign the results to the variables.
This is very convenient feature, however I am facing a problem:
Say I want to populate a list A with n integers inside of it, It is relatively easy to ask for n to get the list size and populate it using split, BUT! what if the user wrote too many values?
Say I have 3 variables to fill but the user inputted 4, I get the ValueError: too many values to unpack.
Is there any way to limit the user input to n space separated variables that they would write on a single line? i.e: after writing n space separated variables, stop listening for inputs or don't let them type anything more or just disregard whatever comes after that.
Does split have any functionality like that?
I am newly learning python and as I write this, it comes to my mind to try and take whatever the user inputs, put it in a list, slice off whatever elements beyond n, our list size, and assign the remaining values to A, our list. But that sounds like scratching my left ear with my right hand (like the needlessly long way) and it feels, to me at least, that something like that should be included in split or in python somewhere.
I'm a beginner so please keep your answer relatively beginner-friendly/easy to tell what is going on.
Thank you,
Fuzzy.
Note: I am aware that I can take each input on a line and use a for loop in range(n), yes. But the aim here is to use input().split().
You can catch any additional unwanted values with an asterisk (an underscore typically represents an unused variable):
a, b, *_ = map(int, input().split())
This will place any additional inputs into a list called _. Note that this method requires at least two input values separated by a space.
Your idea of "slicing off" additional inputs can actually be done pretty concisely like this:
a,b = map(int, input().split()[:2])
...of course, there remains the possibility of the user giving a list of inputs that is too short.

trying add two numbers ,by reading them from list and print their index no. from their actual list

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
,in each input would have not use the same element twice.
class solution():
def __init__(self,array_num,target_num):
self.array_num=array_num
self.target_num=target_num
for t in self.array_num:
for b in self.array_num:
e=t+b
w=self.array_num.index(t),self.array_num.index(b)
y=list(w)
if e==self.target_num:
if y==[0,0]:
break
else:
print(y)
p=[3,3]
so=solution(p,6)
output
[] or nothing
expected output
[0,1]
The problem is that you are asking the list to give you the index if a number like this:
self.array_num.index(t)
This will always give you the first occurrence, which is 0 here, although the loop is actually at the second position with index 1.
To avoid that, reverse the logic: create the loop for the index (use len() and range()), then get the number at that position.
As this question sounds like homework or school assignment, I'll not post a full solution. It should be possible to solve the problem now.
More hints to make your teacher happy:
[0, 0] is not the only solution that results in 6. You want to exclude other invalid combinations as well. Pro tip: there's a nice solution that doesn't require any check and will run faster. It's easy to find once you switched the logic.
Currently you do all work in the constructor of the object. Maybe you want a method that does the actual calculation.
Your variable names are not self-explaining. Don't use so many single letter variables.

Assign a Range of Numbers to a Single Key with Dictionaries

I was working on a dictionary, but I came up with an issue. And the issue is, I want to be able to use more than 1 number in order to reference a key in a dictionary.
For example, I want the range of numbers between 1 and 5 to be all assigned to, let's say, "apple". So I came up with this:
my_dict['apple'] = range(1,5)
At the program's current state, its far from being able to run, so testing is an issue, but I do not receive any issues from my editor. I was just wondering, is this the correct way to go about this? Or is there a better way?
Thanks.
EDIT:
A little more info: I want to make a random integer with the randint function. Then, after Python has generated that number, I want to use it to call for the key assigned to the value of the random integer. Thing is, I want to make some things more common than others, so I want to make the range of numbers I can call it with larger so the chance of the key coming up becomes likelier. Sorry if it doesn't make much sense, but at the current state, I really don't even have code to show what I'm trying to accomplish.
You have the dictionary backwards. If you want to be able to recall, e.g., 'apple' with any of the numbers 1-5, you'd need the numbers to be the keys, not the values.
for i in range(1,6): # range(a,b) gives [a,b)
my_dict[i] = 'apple'
etc. Then, my_dict[4] == 'apple' and the same is true for the other values in the range.
This can create very large dictionaries with many copies of the same value.
Alternately, you can use range objects as dictionary keys, but the testing will be a bit more cumbersome unless you create your own class.
my_dict[range(1,6)] = 'apple'
n = random.randint(1, 5)
for key in my_dict:
if n in key:
print(my_dict[key])
...prints apple.
The value in a dictionary can be any arbitrary object. Whether it makes sense to use a given type or structure as a value only makes sense in the context of the complete script, so it is impossible to tell you whether it is the correct solution with the given information.

Difficulty with writing a merge function with conditions

Im trying to write a function but simply cant get it right. This is supposed to be a merge function the merges as follows: the function recieves as an input a list of lists(m lists, all ints). The function creates a list that contains the indexes of the minimun values in each list of the input(each list of the list of lists, overall m indexes). example:
lst_of_lsts= [[3,4,5],[2,0,7]]
min_lst= [0,1]
At each stage, the function chooses the minimum value from that list and adds it to a new list called merged. Then, it erases it from the list of indexes(min_lst) and adds the next index which is now the new minimum.
At the end it returns merged which is an organized list from small ints to big ints. example:
merged= [0,2,3,4,5,7]
Another thing is that Im not allowed to change the original input.
def min_index(lst):
return min(range(len(lst)), key=lambda n: lst[n])
def min_lists(lstlst):
return [min_index(lst) for lst in lstlst]
then
min_lists([[3,4,5],[2,0,7]]) # => [0, 1]
Edit:
This site doesn't exist to solve your homework for you. If you work at it and your solution doesn't do what you expect, show us what you've done and we'll try to point out your mistake.
I figure my solution is OK because it's correct, but in such a way that your teacher will never believe you wrote it; however if you can understand this solution it should help you solve it yourself, and along the way teach you some Python-fu.

How can I run a loop against 2 random elements from a list at a time?

Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string?
What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for them to not be chosen?
you need to look into random module. It has for example a random.choice function that lets you select a random element from a sequence or a random.sample that selects given number of samples, it's easy to account for different weights too.
explain better your problem, what operations and what elements you're focusing?
regarding the problem with the elements beeing chosen more often, give each string an "chance multiplier", each comparison you multiply a number between 1 and 10 and the chance multiplyer of the string, if the result is higher than X (say... 5), so it select the string, if not, it searches for another string. this way, strings with higher multipliers will have more chance to be selected

Categories

Resources