Checking if all the values I want are in my table - python

I want to do a function that takes in a 2D table, which represents a magic square, and check if all numbers between 1 and size*size are in the table.
Any ideas for an effective way to write my function?

Assuming your 'tab' variable is a list, something like this should work:
for x in range(1, size*size+1):
if x not in tab:
print(f"{x} not in list")
break
If you want it to tell you every missing number, remove the break. The break makes it more efficient if you just want to check whether it is a valid list or not, so it will only tell you the first missing number.

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.

The reason of using ''temp'' variables?

The question I'm asking is why do we use temporary variables after taking an input? For example: In the code down below, we've requested a 'num' from the customer. Then we've changed into it a 'temp'. Why don't we simply continue with 'num'? I can't see any aim into changing it a different variable. Why don't the code work if we don't make this swap? Thanks.
It is beacause in the while cycle in the last row you change the value of temp so if instead of temp you use num you will change its value and in the if else statement you can't compare the sum with the input number.

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.

Python 2.7.5 how to accumulate and declare values in an array/ list from user input?

My apologizes for the basic question, I'm working through a programming book discussing arrays, Using python 2.7.5 I want to ask the user for input and store the numbers in an array, I can assign a value in the array to a string but don't want to do that, instead of doing:
emp_name[0] = raw_input("please enter employee name")
I want to add values to the array emp_name, and recall something like: emp_name[1] and have the 2nd name entered displayed for the user. I apologize for the novice question but I'm still wrapping my head around arrays.
I think I have to use a for numbers in range loop, or a while loop? Please assist
give this a shot
emp_names = []
num_to_enter = 10
while num_to_enter > 0:
emp_names.append(raw_input("enter name"))
num_to_enter -= 1
print emp_names[0]
#do what you need to do
The data structure you are looking for is dictionary, not array. Although, you can make array in that way which can be highly inefficient for searching, particularly when it involves large amount of data. If you want to stick with array, consider tuple rather than array.
Storing in dictionary can be done as key/value pair like you want.
my_store=dict()
or
my_store={}
and after that, you can store the data like you wanted as:
my_store[0]="emp_name_1"
My answer is based on the fact that you want to identify your data using some key, not just index like 1. If index is all you want to refer to your data, array is not a problem. But I think I hastened to answer you without looking and asking you properly if you just are looking to use index or other strings to fetch the stored data.
If array is all your are looking you can do as simple as:
emp_names = []
while True:
inp=raw_input("enter_name or nothing but enter to exit")
if inp='':
break
else:
emp_names.append(inp)
And you can use index 0 referring to the first element and so on to fetch the data.

Categories

Resources