Function returns incorrect False (only at higher values)

Simon Ungar

At higher input values my checkInputFile() function will return false, even when the input is a legal value. This only really becomes a problem with values greater than 400, but I want to be able to use numbers up to 10,000.

I've attached the a module used for getting user input, as well as the text files used to generate the insults.

import random
from getNum import *

def main() :
    random.seed()
    allWords = loadInsults()
    print("One insult: ", end="")
    print(generateInsult(allWords))
    insults = generateInsults(allWords)
    displaySomeInsults(insults)
    saveInsults(insults)
    if checkInsultsFile() :
        print("\n1000 insults properly saved. They are unique and in order.")
    else :
        print("\nThe insults are not properly generated or saved!")

# Using all possible arguments and prompting the user for the number of insults.
    allWords = loadInsults("word1.txt", "word2.txt", "word3.txt")
    numInsults = getNumInsults()
    insults = generateInsults(allWords, numInsults)
    displaySomeInsults(insults)
    saveInsults(insults, "Insults.txt")
    if checkInsultsFile(numInsults, "Insults.txt") :
        print("\n" + str(numInsults) + " insults properly saved. They are unique and in order.")
    else :
        print("\nThe insults are not properly generated or saved!")

# Write your functions here:

def readFiles(fileName):
    inFile = open(fileName, "r")
    fileContentsList = []
    for line in inFile:
        fileContentsList.append(line.rstrip())
    inFile.close()
    return fileContentsList

def loadInsults(word1="word1.txt", word2="word2.txt", word3="word3.txt"):
    return readFiles(word1), readFiles(word2), readFiles(word3)

def generateInsult(allWords):
    return "thou " + random.choice(allWords[0]) + " " + random.choice(allWords[1]) \
           + " " + random.choice(allWords[2]) + "!"

def generateInsults(allWords, numInsults=100):
    insultList = []
    while len(insultList) < numInsults:

        insultList.append(generateInsult(allWords))
    insults = list(set(insultList))
    return insults

def displaySomeInsults(insults):
    insults.sort()
    print("Some insults:")
    for i in insults[0 : 10]:
        print(i)
    print(". \n<snip>\n.")
    for i in insults[-11 : -1]:
        print(i)

def saveInsults(insults, filename="Insults.txt"):
    if 100 <= len(insults) <= 10000:
        outFile = open(filename, "w")
        for line in insults:
            outFile.write(line + "\n")
        outFile.close()

def checkInsultsFile(numInsults=100, filename="Insults.txt"):
        inFile = open(filename, "r")
        newList = []
        for line in inFile:
            newList.append(line.rstrip())
        inFile.close()
        for i in range(1, len(newList)):
            if newList[i] < newList[i-1]:
                print("Not all insults are in order")
                return False
            elif newList[i] == newList[i-1]:
                print("Not all insults are unique")
                return False
        if len(newList) != numInsults:
            print("Wrong number of insults.")
            return False
        return True

def getNumInsults():
    numInsults = getNum("\nEnter a number between 100 and 10,000: ", 100, 10000)
    return numInsults

main()
Aaron

I think I may know what is happening, you are creating a set of insults out of your list which will remove any duplicates. The more insults you generate, the more likely there will be a duplicate which will cause your set of insults to be smaller than numInsults.

This line will remove duplicates: insults = list(set(insultList))

Causing the length of the insults list to be smaller than numInsults.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Type hint for a function that returns only a specific set of values

Higher order function returns pure function

numpy.vectorize returns incorrect values

EWS FindItem call returns incorrect EffectiveRights values

Dictionary of Objects returns incorrect values

MACD Function Returning Incorrect Values

Android MediaPlayer.getCurrentPosition() returns incorrect values

Why is this function producing incorrect values?

checkPrime function returns incorrect values

Matlab returns the function only

eigen eulerAngles() returns incorrect values

function replace substring returns incorrect answer

The function returns invalid values

Function that only returns false returns nothing

OpenGL - glReadPixels returns incorrect values

Len function returns incorrect results

Run Javascript function only if 'beforeunload' function returns false

Use only the 5 higher values in amCharts pie?

Trying to set ProcessStrictHandleCheckPolicy returns 87 - Incorrect Function

PL/pgSQL function returns incorrect bitwise result

Applying custom function to data.table by row returns incorrect amount of values

Python function returns incorrect value

Is it possible to find COUNT function and then to show only certain values that are higher than 10

How to get my function to take higher values

Function returns json instead of only values

Javascript date calculation returns incorrect values

Recursive Function Always Returns False

Syntax Error: Unexpected Identifier - Higher Order Function that Returns a Function in JavaScript

Give lower values a higher weight in a `randint()` function

TOP Ranking

  1. 1

    What exactly is memory mapped io and port based io

  2. 2

    How i extract text from a model dialog in selenium?

  3. 3

    pump.io port in URL

  4. 4

    Selenium browsing with headless isn't working?

  5. 5

    change TabView indicator SwiftUI

  6. 6

    python requests How to send data to a website

  7. 7

    Kubernetes pods not starting, running behind a proxy

  8. 8

    Scaffold-DbContext returns System.ArgumentNullException: Parameter name: proposedIdentifier in EFCore 2.0 when trying to pluralize

  9. 9

    Java POI: How to find an Excel cell with a string value and get its position (row) to use that position to find another cell

  10. 10

    Creating interaction sessions based on timestamps in pandas

  11. 11

    Maven annotation processing processor not found

  12. 12

    Missing field when deserializing using Jackson (Polymorphic)

  13. 13

    Spring Data JPA repository methods don't recognize property names with underscores

  14. 14

    Get all Woocommerce products from current product category term Id in a WP_Query

  15. 15

    How to update if key exists - sequelize

  16. 16

    I got message for error_log file "The stream or file ".../laravel.log" could not be opened: failed to open stream: Permission denied"

  17. 17

    Servlet: HTTP Status 404 - Not Found

  18. 18

    Type 'Moment' is not assignable to type 'Date'. Property 'toDateString' is missing in type 'Moment'

  19. 19

    what is key in CTTelephonyNetworkInfo().serviceSubscriberCellularProviders and CTTelephonyNetworkInfo().serviceCurrentRadioAccessTechnology

  20. 20

    Laravel(ajax) 404 not found

  21. 21

    Error: Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters

HotTag

Archive