Why does len(point_str) return 1? - python-3.x

import sys
string_input = "6\n212 132322\n212 21\n65 56\n32 3\n3232 32\n313 13\n0"
# a two dimensional array to store points
points = []
for line in string_input.split("\n"):
# split the inputed line using space to divide x and y coordinate
points_str = line.split(" ")
point_coordinate = []
if len(points_str) != 1:
for val in points_str:
point_coordinate.append(int(val))
points.append(point_coordinate)
print(str(points))
print(len(points_str))
Why does the len(points_str) return 1? I am also very confused why 1 != 1 continues to perform the rest of the code.

First your loop run through all iterations, then you print out len(points_str). Now points_str gets a new value in each iteration, but since you only print at the end, you get the length of the last value that points_str was assigned. This is the last element of string_input.split("\n"), which is '0'. The length of '0' is indeed 1.
Try moving the line
print(len(points_str))
inside of the loop (that is, just add four spaces) and check the output. You should also try to print out points_str, not just its length.

Well, because it's of length 1. At least in your first iteration.
Your first line is "6", so points_str is ["6"], which has a length of 1.
You should really use a debugger.

Related

I need the code to stop after break and it should not print max(b)

Rahul was learning about numbers in list. He came across one word ground of a number.
A ground of a number is defined as the number which is just smaller or equal to the number given to you.Hence he started solving some assignments related to it. He got struck in some questions. Your task is to help him.
O(n) time complexity
O(n) Auxilary space
Input Description:
First line contains two numbers ‘n’ denoting number of integers and ‘k’ whose ground is to be check. Next line contains n space separated numbers.
Output Description:
Print the index of val.Print -1 if equal or near exqual number
Sample Input :
7 3
1 2 3 4 5 6 7
Sample Output :
2
`
n,k = 7,3
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
print(max(b))
`
I've found a solution, you can pour in if you've any different views
n,k = 7,12
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
else:
print(max(b))
From what I understand, these are the conditions to your question,
If can find number, print the number and break
If cannot find number, get the last index IF it's less than value k
Firstly, it's unsafe to manually input the length of iteration for your list, do it like this:
k = 3
a= [1,7,2,2,5,1,7]
finalindex = 0
for i, val in enumerate(a):
if val==k:
finalindex = i #+1 to index because loop will end prematurely
break
elif val>=k:
continue
finalindex = i #skip this if value not more or equal to k
print(finalindex) #this will either be the index of value found OR if not found,
#it will be the latest index which value lesser than k
Basically, you don't need to print twice. because it's mutually exclusive. Either you find the value, print the index or if you don't find it you print the latest index that is lesser than K. You don't need max() because the index only increases, and the latest index would already be your max value.
Another thing that I notice, if you use your else statement like in your answer, if you have two elements in your list that are larger than value K, you will be printing max() twice. It's redundant
else:
print(max(b))

Apply edit to strings

I have an practice that gives input and wants to get the 'hello'by deleting letters and if it get print 'YES' and if not print 'NO'.python 3
i write this but i do not know why it is not work sometime
def edit(x):
for h in x:
if h in ('a','q','z','w','s','x','d','c','r','f','v','t','g','b','y','n','u','j','m','i','k','p'):
y = x.replace(h,'')
return y
x =input()
x1='a'.join(x)
y = edit(x1)
if y==('hello'):
print('YES')
elif y.count('l')>=2 and y.count('h')>=1 and y.count('e')>=1 and y.count('o')>=1:
if y.startswith('h') and y.endswith('o'):
y1=y.replace('h','')
if y1.startswith('e'):
y2=y1.replace('e','')
if y2.startswith('l') and y2.endswith('o'):
print('YES')
else:
print('NO')
for example
aahhelllo
YES
asdxhhhellooooo
Process finished with exit code 0
The error is in your edit(x) function. It iterates through characters of the string in the x variable and checks if the character is in the list of 22; if so, it removes all instances of a chosen character from the string and stores a result in the y variable.
Note: on every iteration it takes the x variable; it does not take y, which is a result of the previous modification, but it takes an original input parameter again and again. Finaly, you get y from the last modification performed.
In "aahhelllo" there is only one character to remove: 'a', so only one substitution is done and its result is "hhello", as expected.
OTOH, in "aasdxhhhellooooo" there are four characters to be removed, so:
in the first iteration y is assigned a value of "aasdxhhhellooooo".replace('a','') which is "sdxhhhellooooo";
in the second iteration you remove 'a' again (because it was not deleted from x);
in the third you assign y="aasdxhhhellooooo".replace('s','') which is "aadxhhhellooooo";
and so on, until the last modification done for h=='x', which makes y="aasdxhhhellooooo".replace('x',''), which is "aasdhhhellooooo".
And that is the result returned from edit(x) in the second case.

Unable to Reverse the text using 'for' Loop Function

I want to reverse the string using the Loop & Function. But when I use the following code, it is output the exact same string again. But it suppose to reverse the string. I can't figure out why.
def reversed_word(word):
x=''
for i in range(len(word)):
x+=word[i-len(word)]
print(i-len(word))
return x
a=reversed_word('APPLE')
print(a)
If you look at the output of your debug statement (the print in the function), you'll see you're using the indexes -5 through -1.
Since negative indexes specify the distance from the end of the string, -5 is the A, -4 is the first P, and so on. And, since you're appending these in turn to an originally empty string, you're just adding the letters in the same order they appear in the original.
To add them in the other order, you can simply use len(word) - i - 1 as the index, giving the sequence (len-1) .. 0 (rather than -len .. -1, which equates to 0 .. (len-1)):
def reversed_word(word):
result = ""
for i in range(len(word)):
result += word[len(word) - i - 1]
return result
Another alternative is to realise you don't need to use an index at all since iterating over a string gives it to you one character at a time. However, since it gives you those characters in order, you need to adjust how you build the reversed string, by prefixing each character rather than appending:
def reverse_string(word):
result = ""
for char in word:
result = char + result
return result
This builds up the reversed string (from APPLE) as A, PA, PPA, LPPA and ELPPA.
Of course, you could also go fully Pythonic:
def reverse_string(word):
return "".join([word[i] for i in range(len(word), -1, -1)])
This uses list comprehension to create a list of characters in the original string (in reverse order) then just joins that list into a single string (with an empty separator).
Probably not something I'd hand in for classwork (unless I wanted to annoy the marker) but you should be aware that that's how professional Pythonistas usually tackle the problem.
Let's say your word is python.
You loop will then iterate over the values 0 through 5, since len(word) == 6.
When i is 0, i-len(word) is -6 (note carefully that this value is negative). You'll note that word[-6] is the character six places to the left from the end of the string, which is p.
Similarly, when i is 1, i-len(word) is -5, and word[i-len(word)] is y.
This pattern continues for each iteration of your loop.
It looks like you intend to use positive indices to step backward through the string with each iteration. To obtain this behavior, try using the expression len(word)-i-1 to index your string.
def reversed_word(word):
reversed = ''
for i in range(len(word)-1, -1, -1):
reversed += word[i]
return reversed
print(reversed_word("apple"))

Length of list within list (jagged list) becomes zero after leaving loop

All -
For a Selenium webscraper using Python 3.x - I am trying to get a printout that depends upon the length of each 1d index in a jagged list, in this case only 2d. The list is named masterViewsList, and the lists it contains are versions of a list named viewsList. Below see how my list masterViewsList of viewsList's is constructed:
from selenium import webdriver
import os
masterLinkArray = []
masterViewsList = []
# a bunch of code here that I cut out for simplicity's sake
for y in range(0, len(masterLinkArray)):
browser = webdriver.Chrome(chromePath)
viewsList = []
browser.get(masterLinkArray[y])
productViews = browser.find_elements_by_xpath("// *[ # id = 'lightSlider'] / li / img")
counter = - 1
for a in productViews:
counter = counter + 1
viewsList.append(a.get_attribute('src'))
print(viewsList[counter])
print(len(viewsList))
masterViewsList.append(viewsList)
if y == 10:
print(masterViewsList[y])
print(len(masterViewsList[y]))
del viewsList[:]
print(len(masterLinkArray))
print(len(masterViewsList))
print(len(masterViewsList[0]))
print(len(masterViewsList[1]))
print(len(masterViewsList[10]))
The printout is this:
["https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM2_Front%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Side%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Interior%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Other%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Other%20view2.jpg?wid=140&hei=140"]
5
79
79
0
0
0
As you can see, neither the masterLinkArray, nor the masterViewsList are empty - they're 79 long. Also, print(masterViewsList[y]) prints out an actual non-empty list, one with a recognized length of 5. Oddly, once I leave the for y loop, len(masterViewsList[*any integer*]) prints out to "0". These similar questions:
Find the dimensions of a multidimensional Python array,
Find length of 2D array Python,
both indicate that len(array[*integer*]) is the proper way to get the length of a list within a list, but in my case this appears not to be working consistently.
The masterViewlist is empty a the point where you call the len method on it. That's why all the results of the len method will be zero.
In the first short version of your code this is not clear because the following line of code is missing in that version:
del viewsList[:]
After appending the viewList to masterViewList, this line of code causes the masterViewlist being empty again. This is because the del command deletes all references to this viewList including the one in the masterViewlist. You can remove this del of the viewList because you starts with a new viewList every time you are back in the beginning of the outer for loop.

Return False if the same input is given more than once

I want to return False if the same input is given:
first_answer = input("select square number 1: ")
second_answer = input("select square number 2: ")
third_answer = input("select square number 3: ")
if first_answer == second_answer or first_answer == third_answer or
second_answer == first_answer or second_answer == third_answer or
third_answer == first_answer or third_answer == second_answer:
print("don\'t repeat squares")
Is there an easier way?
Do you like this:
set_answers = set()
set_answers.add(input("select square number 1: "))
set_answers.add(input("select square number 2: "))
set_answers.add(input("select square number 3: "))
if len(set_answers) < 3:
print("don\'t repeat squares")
?
The TRICK: set() stores only unique elements, so adding same value again to a set doesn't change the number of its elements.
Try this.
count = 3
answers = []
for i in range(0, count):
answers[i] = input("select square number " + str(i+1) + ": "
for i in range(0, count-1):
for j in range(i+1, count):
if answers[i] == answers[j]:
print("don\'t repeat squares")
It is (almost) always easier to abstract this kind of thing by using loops and arrays (or sets, or tuples) than to program each variable by hand.
answers is a list here, and the first loop inputs the data into the array. Note that you can easily change the amount of data you want simply by modifying the initial value of count -- this will change everything else as well (including the input messages!).
The second loop is actually a nested pair of for loops in order to generate all of the (relevant) pairs of data items to compare. Note that the first loop stops one short of the last element and that the second loop starts one after whatever the value of the first loop is. This is in order to avoid incorrectly comparing an element with itself.
CLARIFICATION:
[] is an empty list. A list in Python is just an ordered list of elements that can be accessed by their position (index) in the list. Indexes start from 0. (there are good reasons for this)
In general, the range function returns all the integers in the given range that includes the lower bound (the left argument) and does not include the upper bound (the right argument). (there are good reasons for this too)

Resources