I am currently learning to use ord() and chr() but the having difficulties with the following code.
b = '1101'
i = 0
while b != ' ' :
i = i*2 + ( ord(b[0]) + ord('0') )
b = b[1:]
Traceback (most recent call last):
File "<pyshell#86>", line 2, in <module>
i = i*2 + ( ord(b[0]) + ord('0') )
IndexError: string index out of range
Why does my string go out of range and throw the error instead of exiting the loop as I expect?
Your while condition never becomes true. ' ' doesn't mean Nothing, it means an empty space. Unless your original string contains a space at the end, it will never be true.
It should work if you make it '' instead of ' '.
Also, since variables evaluate to True when they hold a value and False when are reduced to None type, you can write the same thing as while b: . This will be true as long as b holds a value, but as soon as it's empty, it'll stop looping.
Related
lines = [[str(i * j) for i in xrange(1, 13)] for j in xrange(1, 13)]
for line in lines:
for num in line:
if line.index(num):
print ' ' * (3 - len(num)) + num,
else:
print ' ' * (2 - len(num)) + num,
print
I am trying to understand why the else statement pertains to the first line
and the line.index(num) pertains to remaining lines.
As your if statement is not comparing the return of line.index(num) against anything, returning any non zero value will satisfy the condition and returning a value of 0 will result in the else statement.
line.index(num) returns 0 if num is the first entry in line and so only acts on the first entry from each line in lines.
You are given an integer NN on one line. The next line contains NN space separated integers. Create a tuple of those NN integers. Let's call it TT.
Compute hash(T) and print it.
Note: Here, hash() is one of the functions in the __builtins__ module.
Input Format
The first line contains NN. The next line contains NN space separated integers.
Output Format
Print the computed value.
Sample Input
2
1 2
Sample Output
3713081631934410656
My code
a=int(raw_input())
b=()
i=0
for i in range (0,a):
x=int(raw_input())
c = b + (x,)
i=i+1
hash(b)
Error:
invalid literal for int() with base 10: '1 2'
There are three errors that I can spot:
First, your for-loop is not indented.
Second, you should not be adding 1 to i - the for-loop does this automatically.
Thirds - and this is where the error is thrown - is that raw_input reads the entire line. If you are reading the line '1 2', you cannot convert this to an int.
To fix this problem, I suggest doing:
line = tuple(map(int,raw_input().split(' ')))
This takes the raw input, splits it into an list, makes this list into ints, then turns this list into a tuple.
In fact, you can scrap the entire for loop. You could answer this problem in two lines of code:
raw_input()#To get rid of the first line, which we do not need
print hash(tuple(map(int,raw_input().split(' '))))
The input format
next line contains NN space separated integers
eg: 1 2 3, is not an integer (because of the spaces), that is why when you try int(raw_input()) your code throws an error. You should use split(' ') as the other answer has suggested, to separate each integer. This will remove the error.
Also, there is no need to use i=i+1 as the loop will take care of it
Try the below code:
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
t = tuple(integer_list)
print(hash(t))
Try This code for Python-3
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
input_list = [int(x) for x in integer_list]
t = tuple(input_list)``
print(hash(t))
I have a problem which is giving me a headache. I really thought someone would have asked this already, but days of reading and testing has been fruitless.
I have a text file which starts:
"Determining profile based on KDBG search...
Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)"
(The blank line between the two is not an error and neither are the spaces before 'Suggested')
I need to read the line starting 'Suggested...' only and extract every unique word starting 'Win' and populate a combobox with them. (i.e. 'WinXPSP2x86' and 'WinXPSP3x86')
I know i need to use the 'StreamReader' class and probably get a Regex going on, but, as a beginner, connecting it all together is beyond my knowledge at the moment.
Can anyone help? It would be much appreciated.
Imports System.IO
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
' BASIC is case sensitive and e is parameter so we will start
' new variables with the letter f.
' Read all lines of file into string array F.
Dim F As String() = File.ReadAllLines("H:\Projects\35021241\Input.txt")
' F() is a 0 based array. Assign 3 line of file to G.
Dim G As String = F(2)
' On line 3 of file find starting position of the word 'win' and assign to H.
' TODO: If it is not found H will be -1 and we should quit.
Dim H As Integer = G.IndexOf("Win")
' Assign everything beginning at 'win' on line 3 to variable I.
Dim I As String = G.Substring(H)
' The value placed in delimiter will separate remaining values in I.
' Place C after ending quote to represent a single character as opposed to a string.
Dim Delimiter As Char = ","C
' J array will contain values left in line 3.
Dim J As String() = I.Split(Delimiter)
' Loop through J array removing anything in parenthesis.
For L = J.GetLowerBound(0) to J.GetUpperBound(0)
' Get location of open parenthesis.
Dim ParenBegin As Integer = J(L).IndexOf("(")
' If no open parenthesis found continue.
If ParenBegin <> -1 then
' Open parenthesis found. Find closing parenthesis location
' starting relative to first parenthesis.
Dim Temp As String = J(L).Substring(ParenBegin+1)
' Get location of ending parenthesis.
Dim ParenEnd As Integer = Temp.IndexOf(")")
' TODO: Likely an exception will be thrown if no ending parenthesis.
J(L) = J(L).Substring(0,ParenBegin) & J(L).Substring(ParenBegin + ParenEnd +2)
' Change to include text up to open parenthesis and after closing parenthesis.
End If
Next L
' UnwantedChars contains a list of characters that will be removed.
Dim UnwantedChars As String = ",()"""
' Check each value in J() for presence of each unwanted character.
For K As Integer = 0 to (UnwantedChars.Length-1)
For L = J.GetLowerBound(0) To J.GetUpperBound(0)
' Declare M here so scope will be valid at loop statement.
Dim M As Integer = 0
Do
' Assign M the location of the unwanted character or -1 if not found.
M= J(L).IndexOf(UnwantedChars.Substring(K,1))
' Was this unwanted character found in this value?
If M<>-1 Then
' Yes - where was it found in the value?
Select Case M
Case 0 ' Beginning of value
J(L) = J(L).Substring(1)
Case J(L).Length ' End of value.
J(L) = J(L).Substring(0,(M-1))
Case Else ' Somewhere in-between.
J(L) = J(L).Substring(0,M) & J(L).Substring(M+1)
End Select
Else
' No the unwanted character was not found in this value.
End If
Loop Until M=-1 ' Go see if there are more of this unwanted character in the value.
Next L ' Next value.
Next K ' Next unwanted character.
' Loop through all the values and trip spaces from beginning and end of each.
For L As Integer = J.GetLowerBound(0) To J.GetUpperBound(0)
J(L) = J(L).Trim
Next L
' Assign the J array to the combobox.
ComboBox1.DataSource = J
End Sub
End Class
As some have already suggested:
Use System.IO.File.ReadAllLines, if the file is not too big
Iterate through the array of lines
For each line, use the Split method to split on space
Check the first three characters of each word
This works but does of course need some error checking etc:
Dim lines() As String = System.IO.File.ReadAllLines("c:\temp\example.txt")
Dim lineWords() As String
For Each line As String In lines
lineWords = line.Split(New Char() {" "}, System.StringSplitOptions.RemoveEmptyEntries)
For Each word As String In lineWords
If word.Length > 3 Then
If word.Substring(0, 3).ToUpper = "WIN" Then
cmbWords.Items.Add(word)
End If
End If
Next
Next
I am beginner for real programming and have the ff problem
I want to read many instances stored in a file/csv/txt/excel
like the folloing
find<S>ing<G>s<p>
Then when I read this file it goes through each character and start from the six position and continue until the 11 position-the max size of a single row is 12
-,-,-,-,-,f,i,n,d,i,n,0
-,-,-,-,f,i,n,d,i,n,g,0
-,-,-,f,i,n,d,i,n,g,s,0
-,-,f,i,n,d,i,n,g,s,-,S//there is an S value next to the letter d
-,f,i,n,d,i,n,g,s,-,-,0
f,i,n,d,i,n,g,s,-,-,-,0
i,n,d,i,n,g,s,-,-,-,-,G // there is a G value here at th end of g
n,d,i,n,g,s,-,-,-,-,-,P */// there is a P value here at th end of s
Here is the code that I tried in python. but can be possible in c++, java, dotNet.
import sys
import os
f = open('/home/mm/exprimentdata/sample3.csv')// can be txt file
string = f.read()
a = []
b = []
i = 0
while (i < len(string)):
if (string[i] != '\n '):
n = string[i]
if (string[i] == ""):
print ' = '
if (string[i] = upper | numeric)
print rep(char).rjust(12),delimiter=','
a.append(n)
i = (i+1)
print (len(a))
print a
my question is how can I compare each string and assign a single char at the rightmost part (position 12 like above G,P,S)
how can I push one step back after aligning the first row?
how can i fix the length
please anyone see fragment and adjust to solve the above case
I don't understand your question.
But some advice:
Firstly, you should be closing the file after you open it.
f = open('/home/mm/exprimentdata/sample3.csv')// can be txt file
string = f.read()
**f.close()**
Secondly, your indentation is problematic. Whitespace matters in Python. (Maybe your real code is indented properly and it's just a StackOverflow thing.)
Thirdly, instead of using a while loop and incrementing, you should be writing:
for i range(len(string)):
# loop code
Fourthly, this line will never evaluate to True:
if (string[i] == ""):
string[i] will always be some character (or cause an out of bounds error).
I advise you read a Python tutorial before you try and write this program.
I wrote the following two codes
FCTRL2.py
import sys;
def fact(x):
res = 1
for i in range (1,x+1):
res=res*i
return res;
t = int(raw_input());
for i in range (0,t):
print fact(int(raw_input()));
and
AP2.py
import sys;
t = int(raw_input());
for i in range (0,t):
x,y,z = map(int,sys.stdin.readline().split())
n = (2*z)/(x+y)
d = (y-x)/(n-5)
a = x-(2*d)
print n
for j in range(0,n):
sys.stdout.write(a+j*d)
sys.stdout.write(' ')
print' '
FCTRL2.py is accepted on spoj whereas AP2.py gives NZEC error. Both work fine on my machine and i do not find much difference with regard to returning values from both. Please explain what is the difference in both and how do i avoid NZEC error for AP2.py
There may be extra white spaces in the input. A good problem setter would ensure that the input satisfies the specified format. But since spoj allows almost anyone to add problems, issues like this sometimes arise. One way to mitigate white space issues is to read the input at once, and then tokenize it.
import sys; # Why use ';'? It's so non-pythonic.
inp = sys.stdin.read().split() # Take whitespaces as delimiter
t = int(inp[0])
readAt = 1
for i in range (0,t):
x,y,z = map(int,inp[readAt:readAt+3]) # Read the next three elements
n = (2*z)/(x+y)
d = (y-x)/(n-5)
a = x-(2*d)
print n
#for j in range(0,n):
# sys.stdout.write(a+j*d)
# sys.stdout.write(' ')
#print ' '
print ' '.join([str(a+ti*d) for ti in xrange(n)]) # More compact and faster
readAt += 3 # Increment the index from which to start the next read
The n in line 10 can be a float, the range function expects an integer. Hence the program exits with an exception.
I tested this on Windows with values:
>ap2.py
23
4 7 9
1.6363636363636365
Traceback (most recent call last):
File "C:\martin\ap2.py", line 10, in <module>
for j in range(0,n):
TypeError: 'float' object cannot be interpreted as an integer