问题
Just a forewarning: I just recently started programming and Python is my first language and only language so far.
Is there a builtin that works in the opposite way of .index()
? I'm looking for this because I made a bool function where I have a list of ints and I want to return True
if the given list of ints is a list of powers of some int x of the form [x^0, x^1, x^2, x^3, ...]
and `False' otherwise.
What I want to say in code is along the lines of:
n >= 1
while the position(n+1) = position(1)*position(n)
for the length of the list
return True
otherwise
False.
Is there a builtin I could use to input the position and return the item in the list?
list = [1,2,4,8,16]
position(4)
returns the int 16.
EDIT: sorry I don't know how to format on here ok ill show what I mean:
def powers(base):
''' (list of str) -> bool
Return True if the given list of ints is a list of powers of
some int x of the form [x^0, x^1, x^2, x^3, ...] and False
otherwise.
>>> powers([1, 2, 4, 8])
True
>>> powers([1, 5, 25, 75])
False
'''
FINAL EDIT:
I just went through all of the available list methods from here (https://docs.python.org/2/tutorial/datastructures.html) and read the descriptions. What I'm asking for, isn't available as a list method :(
sorry for any inconvenience.
回答1:
As an answer to:
Is there a builtin I could use to input the position and return the item in the list?
You just need to access the list
with it's index as:
>>> my_list = [1,2,4,8,16]
>>> my_list[4]
16 # returns element at 4th index
And, this property is independent of language. All the languages supports this.
Based on your edit in the question, you may write your function as:
def check_value(my_list):
# if len is less than 2
if len(my_list) < 2:
if my_list and my_list[0] == 1:
return True
else:
return False
base_val = my_list[1] # as per the logic, it should be original number i.e num**1
for p, item in enumerate(my_list):
if item != base_val ** p:
return False
else:
return True
Sample run:
>>> check_value([1, 2, 4, 8])
True
>>> check_value([1, 2, 4, 9])
False
>>> check_value([1, 5, 25, 75])
False
回答2:
def powers(n):
for i in itertools.count(0):
yield n**i
def is_powers(li):
if li[0] == 1:
if len(li) > 1:
return all(x==y for x,y in zip(li,powers(li[1])))
return True
return False
is_powers([1, 2, 4, 8])
is_powers([1, 5, 25, 75])
maybe ... its really not clear what you are asking... this assumes that it always must start with a 1 if it is valid...
来源:https://stackoverflow.com/questions/40390902/python-is-there-a-builtin-that-works-similar-but-opposite-to-index