-1

this is what needs to be done

below is a few values from list data.txt

79012400

adfadfaf

54523

29813360

30489059

30350069wqer

30530679

28863496

8787390

ValueError: Invailid literal for int() with base 10: '29933900jhgd'

def FileOpen(studentNumbers):
        count=0
        INFILE=open("data.txt","r")
        for line in INFILE:
            studentNumbers.append(line.rstrip())
            count+=1
        INFILE.close()
        return count


def AnalyseStudents(rawList,ValidNumbers,InvalidNumbers):
    num_sum=0
    for b in range(8,0,-1):
        num_sum += int(rawList[len(rawList)-7])**b


    result = num_sum%11

    if result == 0:
        VailidNumbers.append(rawList)
    else:
        InvalidNumbers.append(rawList)

def Write(outlist):
    OUTFILE=open("output.txt","W")
    for number in outlist:
        OUTFILE.write(number+"\n")
    OUTFILE.close()




inputList = []
outputList=[]
print(FileOpen(inputList),"number of lines read from file")
print("Analysing file")
AnalyseStudents(inputList,outputList,outputList)
print("Writing result to file..")
WriteFile(outputList)
print("Done.Please cheack the output file.")
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • You mistakenly added `jhgd` in your input – Devesh Kumar Singh May 22 '19 at 15:21
  • @devesh the list that I'm reading from has it like that some of the int are even like "ahkdlim" i need to work around it and just add it to the new list "invalidnumbers" – Anton Buitendag May 22 '19 at 15:26
  • you mean `rawList = 'ahkdlim'` sometimes? – Devesh Kumar Singh May 22 '19 at 15:27
  • Please show a full [mcve] including _how you call_ your function and _demodata_. To avoid ValueErrors you need a try: except: around your `int(.....)` line. See the accepted answer to [asking user for input until valid](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) fro how to do that – Patrick Artner May 22 '19 at 15:30
  • yes the following are some of them 28698118adfs - abcdagsa - 2432142341432134 - 30048117 some are wrong and some are correct i need to differentiate and then add all the correct ones to one list and the incorrect ones to another – Anton Buitendag May 22 '19 at 15:31
  • [edit] your post - do not use comments for important information – Patrick Artner May 22 '19 at 15:32
  • Check if rawlist is 'int' by 'int(rawlist)' inside 'try' and 'exception' block – Piotr Kurowski May 22 '19 at 15:32
  • @PatrickArtner this is my whole code for the program do you perhaps see a problem elsewhere which can cause an issue. – Anton Buitendag May 22 '19 at 16:11
  • `AnalyseStudents(inputList,outputList,outputList)` .-.. why provide the same list twice? `int(rawList[len(rawList)-7])**b` this will _always_ be the same number (the `rawList[len(rawList)-7]-th in rawlist`) summed as `n**8+n**7+n**6...etc` ... that code makes no sense to me, sorry. If it is not a number but has text in it the `int` conversion will throw an value error and your program crashes. – Patrick Artner May 22 '19 at 16:18
  • @PatrickArtner they said i don't have enough list thus i added another one for output seeing that I"m creating 2 lists at the end and for the middle def the whole point of that is the following Studentenommer: 20570856 sum = (2*8)+(0*7)+(5*6)+(7*5)+(0*4)+(8*3)+(5*2)+(6*1) result = sum%11 – Anton Buitendag May 22 '19 at 16:26

2 Answers2

0

Going by the comments you added, it looks like you only want the first 8 characters:

rawList = ['28698118adfs', 'abcdagsa', '2432142341432134', '30048117']
VailidNumbers = []
InvalidNumbers = []
length = 8
for rawString in rawList:
    if(rawString[0:length].isdigit()):
        num_sum = 0
        for b in range(length,0,-1):
            num_sum += int(rawString[length-b])**b
        print(num_sum)
        result = num_sum%11

        if result == 0:
            VailidNumbers.append(rawString)
        else:
            InvalidNumbers.append(rawString)
    else:
        InvalidNumbers.append(rawString)
print(InvalidNumbers)
print(VailidNumbers)

In your example of 30048117, this expands to (3^8 + 4^5 + 8^4 + 1^3 + 1^2 + 7^1)%11 = 8, which is not equal to zero, so it will be added to InvalidNumbers.

If your code is correct however, this is the fix:

rawList = ['28698118adfs', 'abcdagsa', '2432142341432134', '30048117']
VailidNumbers = []
InvalidNumbers = []
length = 8
for rawString in rawList:
    if(rawString[0:length].isdigit()):
        num_sum = 0
        number = rawString[0:length]
        for b in range(length,0,-1):
            num_sum += int(number[len(number) - 7]) ** b
        print(num_sum)
        result = num_sum%11

        if result == 0:
            VailidNumbers.append(rawString)
        else:
            InvalidNumbers.append(rawString)
    else:
        InvalidNumbers.append(rawString)
print(InvalidNumbers)
print(VailidNumbers)
blackdrumb
  • 310
  • 1
  • 8
  • i only need to use the first 8 digits but they have to get separated and raised to the power of 8 deciding by one each time . You can see that on my profile from my first question. – Anton Buitendag May 22 '19 at 16:16
  • @AntonBuitendag I updated the post. It seems that in your example you are not iterating through the digits and adding them after raising them to a power. You are just raising the 7th character from the end of rawList to the 8th power then the same 7th character to the 7th power and so on. – blackdrumb May 22 '19 at 16:59
  • @AntonBuitendag I added the code that you requested – blackdrumb May 22 '19 at 17:32
  • i would like to apologize i have not stated my question like i should have . i have updated it if you would like to have a look to what i actually need sorry for the inconvenience – Anton Buitendag May 22 '19 at 17:44
0

None of your given data samples survive your logic - they are either invalid due to ValueError or due to number % 11 != 0

Write demo data:

with open("studs.txt","w") as f:
    f.write("""79012400 
adfadfaf
20570856 
54523 
29813360 
30489059 
30350069wqer 
30530679 
28863496 
8787390 """)

Use this to analyze:

def AnalyseStudents(rawList):
    bad = []
    good = []
    for student in rawList:
        try:
            number = int(student[:8])
        except ValueError:  # not 8 numbers
            bad.append(student)
            continue        # next student

        v = 0
        for idx,n in enumerate(str(number)): # enumerate starts at idx 0 to 7
            n = int(n)
            idx = 8-idx  
            # detail printing # print(f"v ({v:>10}) += {n}*{idx} => {v+n*idx}")
            v += n*idx

        print(f"v ({v:>10}) % 11 = {v%11}")
        if v%11 == 0:
            good.append(student)
        else:
            # verification mishap
            bad.append(student)
    return good,bad  # return a tuple of 2 lists

Process the file of demo data:

with open("studs.txt") as f:
    students = [line.strip() for line in f if line.strip()]

print(f"{len(students)} lines read from file")
good, bad = AnalyseStudents(students)

with open("output.txt","w") as f:
    f.write( "\n".join(good))

if good:
    with open("output.txt","w") as f:
        f.write( "\n".join(good))
else:
    print("No good ones")

print(good)
print(bad)

Output:

10 lines read from file
v (       144) % 11 = 1
v (       121) % 11 = 0
v (       120) % 11 = 10
v (       165) % 11 = 0
v (       143) % 11 = 0
v (        88) % 11 = 0
v (       110) % 11 = 0
v (       198) % 11 = 0
v (       235) % 11 = 4
# good
['20570856', '29813360', '30489059', '30350069wqer', '30530679', '28863496']
# bad
['79012400', 'adfadfaf', '54523', '8787390']
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • May i ask for your email adress then i can send you that text file and a better explanation of what i need to do if i have die email address you can just delete the comment – Anton Buitendag May 22 '19 at 17:05
  • @an Whatfor - you can simply post some lines inside your questions ([edit] it) and format the filecontent as code block to keep it aligned. – Patrick Artner May 22 '19 at 17:17
  • @anton btw. if you add `20570856` as seperate line into the file I use to demo my code - it will pass into the good list using my code... – Patrick Artner May 22 '19 at 17:19
  • did you view the image on top of my question Click on the words "this is what needs to be done" it shows what i need to do and who we get the values == 0 So that some of them go to the valid list and the other to the invalid list. – Anton Buitendag May 22 '19 at 18:05
  • @Anton Why did you use the POWER `**` function in your code if you need multiplication `*` ? - Fixed. – Patrick Artner May 22 '19 at 18:10
  • Thank you for that i had know idea i added an extra *@patrick – Anton Buitendag May 22 '19 at 18:16