Python range - Print from desired number till desired number - python-3.x

Python range () seems to be weird. I want to print the number from 1 to 9, for that I have typed the following code
for i in range(1,10):
print i
Is there a way of mentioning the start and end numbers in range(). Should I use any other function that can do this for me. Any help would be appreciated.

You are making an assumption that range(1,10) means that
10 is for printing 10th number starting from 0.
in the comments. This isn't how range() works.
range() takes three arguments, 2 required and 1 optional:
range(start, stop, step). (further reading)
start should be the number you want to start with
stop is the number you want to stop before
step is the increment range you would like to walk between start and stop
For instance range(1,10) will contain all the numbers from 1-9 (note: not including 10): [1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0,10) would include 0 to above, while range(1,11) would include 10.
range(1,10,2) would render [1, 3, 5, 7, 9]
As for your desire for a "cleaner" solution; that is a subjective question. A list comprehension like [i for i in range(1,10)], or even your nested code in the question is pretty clean by most people's standards.

Related

"IndexError: list index out of range" in very simple 3 lines of Python code

I am a newbie to the programming and trying to understand how things work.
I couldn't get my program to iterate through numpy.array normally, so I decided to try one level simple iteration through list. But still it wouldn't work!
The code is as follows:
my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
print(my_list[i])
The output is:
So it doesn't take the my_list[0] index of some reason and comes out of range.
Could you please help me to understand why?
It's not clear what exactly you're trying to do. When you iterate over an iterable like a list with
for i in my_list:
each i is each member of the list, not the index of the member of the list. So, in your case, if you want to print each member of the list, use
for i in my_list:
print(i)
Think about it: what if the 3rd member of the list was 9, for example? Your code would be trying to print my_list[9], which doesn't exist.
As pointed out that's not how you should iterate over the elements of the list.
But if you persist, your loop be should over the range(my_list), at the moment you're indexing by the values of the list, and since the length is 7, the last valid index is 6, not 7.
You get an IndexError, because you are looping through the values, which means, that your first value for i is 1 and the last one is 7. Because 7 is an invalid Index for this list you get an IndexError. A suitable code would be:
my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
print(i)

How to add numbers within a list

the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
print(len(the_list))
So in this list there are 15 cans of food. how do I make a function that counts and returns the total amount of cans in the list.
Create a dictionary then sum the values in your dictionary:
the_list = {'diced tomatoes': 3, 'olives': 2, 'tomato soup': 3, 'tuna': 7}
sum(the_list.values())
Here you go
total_cans = 0
for food in the_list:
if (isinstance(food,int)): total_cans += food
print(total_cans)
With O(n) performance, goes through the list once.
Hi and welcome to StackOverFlow! As a general tip, it would be a lot more helpful for us to answer your question if you added what you've done so far like #Victor Wilson said, but nonetheless, we will try to help.
Think about what you may need to "increment" a "counter" variable (major hint here!). Since you are working with a list, you know that it is an iterable so you know you can use iterative processes like for-loops/while-loops and range() function to help you.
Once you find the "number of cans" (hint: type int), then you can increment that with your counter variable (hint: addition here).
Knowing what data types you're working with and what built-in methods that can be used with those types can be extremely helpful when learning to debug your own code.
And... by the time I finished my post, #bashBedlam seems to have answered you with a full program already ;). Hope this helps!
If you want to add only the numbers in a list, you can extract numbers from that list and then sum that sublist. That would mean something like,
def get_number(whatever):
try:
return float(whatever)
except ValueError:
return 0
your_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
total = sum([get_number(i) for i in your_list])
However, if you tell us your actual problem statement, I feel we can tackle the problem more efficiently. You should more likely use a different data structure. Use a hash-map/dictionary if you know that the items (condiments) in your list are unique or maybe use tuple/namedtuple to provide a structure to your input data - name-of-item: count-of-item. And then you can use more efficient techniques to extract your desired data.
I feel like this is some homework problem, and I am not quite sure about the policy of SO regarding that. Regardless of that, I would suggest focusing on the ideas provided by the answers here and apply yourself instead of copy-pasting the (pseudo-)solutions.
Yes you can use range function with loop to count numbers. Range function return sequence of numbers and takes 3 parameters
Syntax
range(start, stop, step).
start and step are optional.
To learn about range function, visit
https://www.w3schools.com/python/ref_func_range.asp
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
count=0
for i in range(1,len(the_list)+1,2):
count+=int(the_list[i])
return count
Pick out the numbers and then add them up.
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans (list) :
sum = 0
for element in list :
if type (element) == int :
sum += element
return sum
print (count_cans (the_list))
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
sum([the_list[i] for i in range(1,len(the_list),2)])
It works by :
creating a new list using a comprehension of the_list index by a range
starting with 1 and iterating every other value
then passing that to the sum() function

Is there a way to sort an unsorted list with some repeated elements?

I am trying to sort an unsorted list [4, 5, 9, 9, 0, 1, 8]
The list has two repeated elements. I have tried to approach the question by having a loop that goes through each element comparing each element with the next in the list and then placing the smaller element at the start of the list.
def sort(ls:
ls[x]
x = [4, 5, 9, 9, 0, 1, 8]
while len(x) > 0:
for i in the range(0, len(x)):
lowest = x[i]
ls.append(lowest)
Please, could someone explain where I am going wrong and how the code should work?
It may be that I have incorrectly thought about the problem and my reasoning for how the code should work is not right
I do not know, if this is exactly what you are looking for but try: sorted(ListObject).
sorted() returns the elements of the list from the smallest to the biggest. If one element is repeated, the repeated element is right after the original element. Hope that helped.
Yes, you can try x.sort() or sorted(x). Check this out https://www.programiz.com/python-programming/methods/built-in/sorted. Also, in your program I don't see you making any comparisons, for example, if x[i] <= x[i+1] then ...
This block of code is just gonna append all the elements in the same order, till n*n times.
Also check this https://en.wikipedia.org/wiki/Insertion_sort
For a built-in Python function to sort, let y be your original list, you can use either sorted(y) or y.sort().Keep in mind that sorted(y) will return a new list so you would need to assign it to a variable such as x=sorted(y); whereas if you use x.sort() it will mutate the original list in-place, so you would just call it as is.
If you're looking to actually implement a sorting function, you can try Merge Sort or Quick Sort which run in O (n log n) in which will handle elements with the same value. You can check this out if you want -> https://www.geeksforgeeks.org/python-program-for-merge-sort/ . For an easier to understand sorting algorithm, Insertion or Bubble sort also handle duplicate as well but have a longer runtime O (n^2) -> https://www.geeksforgeeks.org/python-program-for-bubble-sort/ .
But yea, I agree with Nameet, what you've currently posted looks like it would just append in the same order.
Try one of the above suggestions and hopefully this helps point you in the right direction to if you're looking for a built-in function or to implement a sort, which can be done in multiple ways with different adv and disadv to each one. Hope this helps and good luck!
There are several popular ways for sorting. take bubble sort as an example,
def bubbleSort(array):
x = len(array)
while(x > 1): # the code below make sense only there are at least 2 elements in the list
for i in range(x-1): # maximum of i is x-2, the last element in arr is arr[x-1]
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
x -= 1
return array
x = [4, 5, 9, 9, 0, 1, 8]
bubbleSort(x)
your code has the same logic as below
def sorts(x):
ls = []
while len(x) > 0:
lowest = min(x)
ls.append(lowest)
x.remove(lowest)
return ls
x = [4, 5, 9, 9, 0, 1, 8]
sorts(x)
#output is [0, 1, 4, 5, 8, 9, 9]

Remove number from list in which difference between two number are less then specific number

a = [2, 5, 6, 12, 21, 25, 32, 41]
This is my list and I want to remove all the numbers which are not in difference of 7.
Before diving into the answers, let's go over what we're dealing with.
You got a list 'A', which you need to loop through to get a list of numbers that are greater than the previous value + 7
If you boil down the question, you get left with two main goals
We need a loop
and we have a list with the final answer
There are two generic ways of approaching this question. In a loop, we populate a new list. The second way is to manipulate the original list.
Although the First approach requires additional memory, I'll be using the First approach for simplicity.
a = [2, 5, 6, 12, 21, 25, 32, 41] # your original list
b = [] # Empty list that will contain final product
for i in range(len(a)):
if len(b) == 0: # if the list is empty, we add first item from 'a' (In our example, it'll be 2)
b.append(a[i])
else:
if a[i] > b[len(b)-1]+7 or a[i] < b[len(b)-1]-7: # for every value of a, we compare the last digit from list b
b.append(a[i])
As far as I have understood your question, in your output list, only those elements should be there whose sum is 7. So that can be achieved by
i=1;
while i<len(a):
if(a[i]-a[i-1] < 7):
a.remove(a[i])
else:
i+=1
print(a)

Reverse exercise (Python Codecademy course, part "Practice makes perfect" 15/15)

the task runs as follows:
Define a function called reverse that takes a string textand returns that string in reverse.You may not use reversed or [::-1] to help you with this.
My code works all right but I want to understand one detail. Tks to all.
def reverse (text):
result = ''
for i in range (len(text)-1,-1,-1):
result += text[i]
return result
The point is that originally I wrote in the 3rd line for i in range (len(text)-1,0,-1):But the program returned '!nohty' instead of '!nohtyP'. So I changed to (len(text)-1,-1,-1) ant it's ok.
BUT WHY?!
The end point is omitted from the range.
>>> range(2,5)
[2, 3, 4]
To get the zeroth element, you need -1.
Because the text (Python!) is of 7 length and lists are zero based (starting from 0) and the for loop is decreasing, you need to have -1.
The string "Python!" is 7 characters. Range is exclusive with the final number, thus the range is accounting for 6, 5, 4, 3, 2, 1, 0.
The length - 1 = 6, range of 6 to -1, where -1 is exclusive accounts for numbers 0 - 6. Because lists are 0 based, it accounts for all. With zero as the range's second argument, you only get the numbers 6, 5, 4, 3, 2, 1, which doesn't account for the whole word.
For example:
The word "Stack" has 5 letters.
Once it is a list, it occupies the indices 0, 1, 2, 3, 4.
You are looping through the whole word, thus you need to access the 0th element. To do that, the range must go to -1 exclusive.
For your loop:
>>> range(6, -1, -1)
[6, 5, 4, 3, 2, 1, 0]
Then, when you access it by doing:
text = "Python!"
for i in range(len(text)-1, -1, -1):
print(text[i])
text[i] accesses all the individual characters and prints them, backwards.

Resources