How do I get the last number from the range() function? - python

Is there a way to get the last number from the range() function?
I need to get the last number in a Fibonacci sequence for first 20 terms or should I use a list instead of range()?

Not quite sure what you are after here but here goes:
rangeList = range(0,21)
lastNumber = rangeList[len(rangeList)-1:][0]
or:
lastNumber = rangeList[-1]

by in a range, do you mean last value provided by a generator? If so, you can do something like this:
def fibonacci(iterations):
# generate your fibonacci numbers here...
[x for x in fibonacci(20)][-1]
That would get you the last generated value.

I don't think anyone considered that you need fibonacci numbers. No, you'll have to store each number to build the fibonacci sequence recursively, but there is a formula to get the nth term of the fibonacci sequence.
Binet's Formula
If you need the last number of a list, use myList[-1].

Is this what you're after?
somerange = range(0,20)
print len(somerange) # if you want 20
print len(somerange)-1 # if you want 19
now if you want the number or item contained in a list...
x = [1,2,3,4]
print x[len(x)-1]
# OR
print x[-1] # go back 1 element from current index 0, takes you to list end

Related

Kaprekar's constant (sorted(numbers) [duplicate]

This question already has answers here:
How to sort digits in a number?
(5 answers)
Closed 10 months ago.
Okay I've broken down step by step what the function needs to do.
create random number, sort ascending and descending(needs both), subtract, sort the new number ascending and descending and repeat this until the number you get from subtraction is 6174 (preferably I'd like it to loop a time or two after as it should stay at 6174 "which is why it's called Kaprekar's constant".
What I currently have is a random number between 1000,9999. I kept getting (TypeError: 'int' object is not iterable) so I created a list and appended the random number to the list. I'm having issue with sorting the number ascending/descending.
import random
numbers = []
n = random.randint(1000,9999)
print(n)
numbers.append(n)
sorted(numbers)
print(numbers)
So I create a blank list, random number is generated and then printed, the number is then .append to the list and should sort and print the list.
The current output I get is
6988
[6988]
The expected output of what is written is
6988
[6889]
I attempted to use
print(numbers.sort(reverse=True))
this gave "None"
I was expecting it to give [9886]
The only reason this is happening is that it wants to sort multiple items in the list opposed to sorting the numbers in the single item. I'm just not sure how to resolve it.
I'm not quite following you but I think you would like to have the individual digits of the randomly generated number as a list.
If so try doing:
my_str = str(n)
for my_char in my_str:
numbers.append(int(my_char))
instead of:
numbers.append(n)
The first problem is a list.sort method returns None.
import random
numbers = []
n = random.randint(1000,9999)
numbers.append(n)
numbers.sort(reverse=True)
print(numbers)
Also reverse=True does not reverse the element but it reverses the list.
You can check this by this
import random
numbers = []
n = random.randint(1000,9999)
numbers.append(n)
numbers.append(10)
print(sorted(numbers))
print(sorted(numbers,reverse=True))
If you want to reverse element then use this one
import random
lst = []
num = random.randint(1000,9999)
print(num)
lst.append(num)
func = lambda e:int(str(e)[::-1]) # lambda function
lst = list(map(func,sorted(lst)))
print(lst)
NOTE:
1000 after reversing become 1 'cause int('0001') is 1.
4590 after reversing become 954 'cause int('0954') is 954.

How to get items from a list > than X

I have a function called "first_funtion()" that returns a list of 100 instances of a class.
Then I want to define a second function that is going to create a new list with random instances taken from the output list of first_function(), something like:
first_funtion()
def second_function(list2, N):
list2 = list2(random.choice(first_function()))
The thing is that I want list2 to be always greater than N, so if N = 5 I want the random list2 to be more than 5 instances. If N = 10 then I want the list to be more that 10 instances.
How can I do that?
You can first create the list using first_function, then draw a random integer in the range between N and the length of the list and then draw a random sample from the list.
import random
def second_function(list2, N):
len_list = len(list2)
length = random.randint(N, len_list)
return random.sample(list2, length)
You can do it by using two random function;
Use first one to choose a value of N from the range excluding N to including lenght of list1, i.e, (N, len(list1)]
x = random.randint(N+1, len(list1)
And use second one to choose x number of values from list_1;
random.choices(list1, k=x)
So, the code will look something like this:
import random
def second_function(list1, N):
x = random.randint(N+1, len(list1))
y = random.choices(list1, k=x)
print(y)
Here randint(start, stop) includes both start and stop numbers while generating random integer. It will generate a random number from the inclusive range.
Andrandom.choices () function returns total k number of random items from any list.
Note: You may get repeated values if you're using random.choices (). So, use random.sample() function when you want to choose multiple random items from a list without repetition or duplicates.
You can visit on this link and explore more related to this.
As the random.choice() function always picks one element from the list, so you can iterate through the list more than N number of times and use random.choice() each time. And you can also use random.randint() to get a random number above N, to be used in the range function for the for loop.
import random
def second_function(list2, N):
for i in range(N,random.randint(N,len( first function() ))) :
list2.append(random.choice(first_function()))
return list2

Problems in create function

That's my first question, I'm new at programming, sorry about any inconvinience !
I need to finish an exercise that consists in create a fuction to find the higher number and another function to find the lower number on a List, but when I print the results, it keeps giving me a wrong answer.
Here is my code:
lista_numeros = [1593, 200, 72, 8, 423, 2, 39, 293, 20120]
def menor_numero(arg1):
colector1 = arg1[0]
print(coletor1) # - Checking value added to COLECTOR1
for a in range(len(arg1)):
print(arg1[a]) # - Checking if the A argument is running through the list.
if colector1 < arg1[a]:
colector1 = arg1[a]
return colector1
resultado2 = menor_numero(lista_numeros)
print("menor ", str(resultado2)) # Result is the last position of the list, must be the 6th position.
Thank you very much.
Fist of all indentation is very important in python to tell it the order to execute your code and also to define where code sits within a loop etc.
Now you say you want to make a function that finds the smallest and largest number from the output of another function, for this I will assume this output is a list.
Please see code below with comments.
Mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] #assume this is output from other funtion
def func(alist): #define function
collector1 = 100 #keeping your collector idea
for i in alist: #iterate through input
if i < collector1: #check if the item you are currently looking at is smaller than the item currently stored in collector
collector1 = i #if is smaller overwitre colletor with new item
print(collector1) #after iterating through all items in input print final value of colletor
func(Mylist) #call function with input
This outputs,
1
Simply change this,
if i > collector1:
And it will now find the largest in input, so output is now.
9
Edit: if you are looking for the smallest number start collector1 at a large number, if you are looking for the largest start collector1 at = 1.
assuming your input is a list and not a string or some sort you can just use the min()/max() methods:
myList = [1,2,3,4,5]
print(max(myList)) >> 5
print(min(myList)) >> 1
you can find more info here :
https://www.tutorialspoint.com/python3/list_max.htm
https://www.tutorialspoint.com/python3/list_min.htm
Your function is finding the maximum instead of the minimum value. Changing the < to > should do what you want.
Python also has builtin methods min() and max() which should do what you want.
#! python3
import random
numbers = []
max = 1000
min = 0
for i in range(40):
numbers.append(random.randint(min,max))
maxNum = min
minNum = max
for num in numbers:
if num > maxNum:
maxNum = num
elif num < minNum:
minNum = num
print(maxNum, minNum)
This is my code, I use the random library in python to generate a random list of numbers, then I set max to equal the maximum number in that list.
The following for loop generates 40 random numbers and appends them to my list.
I then set maxNum to equal zero, so everything will be greater than it, thereby the initial value will not influence the outcome, and then I set minNum to equal max, so every number will be less than it.
The last block of code loops through the numbers list, and compares every number with the current maxNum and minNum variables to see whether that number is greater than the max or less than the min. If it is, the maxNum (or minNum) number will be updated and the code will move on to the next number.
The last statement prints or minimum and maximum values.
I don't know what course you are taking, but I would advise you to familiarize yourself with this code and understand what it is doing, as it's pretty basic and the stuff you encounter in the future will be much harder.

Find middle of a list

How would I find the exact middle of a python list?
aList = [1,2,3,4,5]
middle = findMiddle(aList)
print middle
This is just an example of a function that would be able to find the middle of any list, is this something you can do using list comprehension?
Edit: This is different than taking out the middle point because I would like to just print out the middle value, if the list is odd I would like to return both the middle values like the accepted answer. Not getting the median like the other question has asked and getting the average of the two values.
Something like this would do:
aList = [1,2,3,4,5]
#minus 1 because the first element is index 0
middleIndex = (len(aList) - 1)/2
print middleIndex
print aList[middleIndex]
Why would you use a list comprehension? A list comprehension only knows about any one member of a list at a time, so that would be an odd approach. Instead:
def findMiddle(input_list):
middle = float(len(input_list))/2
if middle % 2 != 0:
return input_list[int(middle - .5)]
else:
return (input_list[int(middle)], input_list[int(middle-1)])
This one should return the middle item in the list if it's an odd number list, or a tuple containing the middle two items if it's an even numbered list.
Edit:
Thinking some more about how one could do this with a list comprehension, just for fun. Came up with this:
[lis[i] for i in
range((len(lis)/2) - (1 if float(len(lis)) % 2 == 0 else 0), len(lis)/2+1)]
read as:
"Return an array containing the ith digit(s) of array lis, where i is/are the members of a range, which starts at the length of lis, divided by 2, from which we then subtract either 1 if the length of the list is even, or 0 if it is odd, and which ends at the length of lis, divided by 2, to which we add 1."
The start/end of range correspond to the index(es) we want to extract from lis, keeping in mind which arguments are inclusive/exclusive from the range() function in python.
If you know it's going to be an odd length list every time, you can tack on a [0] to the end there to get the actual single value (instead of an array containing a single value), but if it can or will be an even length list, and you want to return an array containing the two middle values OR an array of the single value, leave as is. :)
Take the length of the list, cut that in half and access whatever the list at that index point.
Are you expecting something like
def findMiddle(list):
l = len(list)
if l/2:
return (list[l/2-1]+list[l/2])/2.0
else:
return list[(l/2-1)/2]

Using Operations on a List in Python and Aggregating Results in New List

I have a list of numbers, all of which need to be divided by the same number. I can do this, no problem, but how do I create a new list featuring these new quotients?
I have tried:
for n in numbers:
newnumbers = []
newnumbers.append(n/649.00)
but it only gives me one number, the quotient of the last number in the list, back.
Instead of a loop you can also use a list comprehension (see https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
newnumbers = [n/649.00 for n in numbers]
It's executing your code literally.
for each element in numbers:
set newnumbers equal to an empty list
add a value to newnumbers
So yes, of course you'll end up with a list with only one value in it. What you want to do is move the list initialization out of the loop.
newnumbers = []
for n in numbers:
newnumbers.append(n/649.00)

Categories