Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

built in - Python: Is There a builtin that works similar but opposite to .index()?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...