Python 'float' 对象不能被解释为 int,但转换为 int 不会产生任何输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19507185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:55:16  来源:igfitidea点击:

'float' object can't be interpreted as int, but converting to int yields no output

pythonfor-loopint

提问by Cortney Reagle

So I'm trying to test if something is a palindrome. Here is my code:

所以我试图测试某些东西是否是回文。这是我的代码:

This function returns a string of the first half of a larger string. ("TEST" returns "TE", "HELLO" returns "HE")

此函数返回较大字符串前半部分的字符串。(“TEST”返回“TE”,“HELLO”返回“HE”)

def takeStart(s):
    start = ""

    # The following determines the final index of the first half

    if len(s)%2==0:  
        a = (len(s)/2)-1
    else:
        a = ((len(s)-1)/2)-1

    for i in range(a):
        start+=s[i]
    return start

This function returns a string of the second half of a larger string. ("TEST" returns "ST", "HELLO" returns "LO")

此函数返回一个较大字符串的后半部分的字符串。(“TEST”返回“ST”,“HELLO”返回“LO”)

def takeEnd(s):  
    end = ""

    # The following determines the beginning index of the second half

    if len(s)%2==0:
        a = (len(s)/2)
    else:
        a = ((len(s)-1)/2)

    for i in range(a,len(s)):
        end+=s[i]
    return end

This function flips a string. ("TEST" returns "TSET", "HELLO" returns "OLLEH")

这个函数翻转一个字符串。(“TEST”返回“TSET”,“HELLO”返回“OLLEH”)

def flip(s):
    flipped = ""
    for i in range(1,len(s)):
        flipped+=s[len(s)-i]
    flipped+=s[0]
    return flipped

This code takes every product of two 3-digit numbers, and checks if it's a palindrome

此代码取两个 3 位数字的每个乘积,并检查它是否是回文

for i in range(100,1000):
    for q in range(100,1000):
        a = i*q
        if takeStart(str(a)) == flip(takeEnd(str(a))):
            print(str(a))

When this code is run, it outputs:

运行此代码时,它输出:

Traceback (most recent call last):
  File "[redacted]", line 39, in <module>
    if takeStart(str(a)) == flip(takeEnd(str(a))):
  File "[redacted]", line 14, in takeStart
    for i in range(a):
TypeError: 'float' object cannot be interpreted as an integer

Alright, I thought I just convert a to an integer and all should be swell.

好吧,我以为我只是将 a 转换为整数,并且一切都应该膨胀。

Doing that appears to remove all errors, but there is NO output whatsoever. (There are new lines every once and a while which makes me think it's working but not outputing any data)

这样做似乎消除了所有错误,但没有任何输出。(每隔一段时间就会有新行,这让我认为它正在工作但不输出任何数据)

Any ideas on why this is happening?

关于为什么会发生这种情况的任何想法?

UPDATE: my code now:

更新:我现在的代码:

def takeStart(s):
    start = ""
    if len(s)%2==0:
        a = (len(s)//2)
    else:
        a = (len(s)-1)//2
    return start[0:a]

def takeEnd(s):  
    end = ""
    if len(s)%2==0:
        a = (len(s)//2)
    else:
        a = ((len(s)-1)//2)

    return end[int(a):len(s)]

def flip(s):
    return s[::-1]

for i in range(100,1000):
    for q in range(100,1000):
        a = i*q
        if takeStart(str(a)) == flip(takeEnd(str(a))):
            print(str(a))

This is just outputting every single number. I tested each method and they're returning empty strings. (I'm assuming), which is why every number is passing the palindrome check and printing.

这只是输出每个数字。我测试了每种方法,它们都返回空字符串。(我假设),这就是为什么每个数字都通过回文检查和打印的原因。

采纳答案by abarnert

First, using range(int(a))and range(int(a), len(s))will solve your error. As Jon Clements points out, you can solve that more easily by just using //instead of /to get integers in the first place. But either way, it's not causing any problems.

首先,使用range(int(a))range(int(a), len(s))将解决您的错误。正如 Jon Clements 指出的那样,您可以通过首先使用//而不是/获取整数来更轻松地解决该问题。但无论哪种方式,它都不会造成任何问题。

Your problem is that ranges, and just about everything related in Python, are half-open. So, your takeStartfunction is returning all the values up to, but not including, the half-way point—that is, it gives you Hfor HELLO, Tfor TEST, BIGGfor BIGGERTEST.

你的问题是ranges 和 Python 中几乎所有相关的东西都是半开放的。因此,您的takeStart函数将返回所有值,但不包括中间点——也就是说,它为您提供Hfor HELLOTfor TESTBIGGfor BIGGERTEST

Just get rid of the -1on your a = …lines, and that will solve that problem.

只要摆脱-1你的a = …线路,这将解决这个问题。

And then it prints out a whole bunch of output lines, all palindromes, which I assume is what you were intending to do.

然后它打印出一大堆输出行,所有回文,我认为这是你打算做的。

However, you're still not going to get any odd-length palindromes. For example, with 'MADAM', even when you get the functions right, takeStart(s)is MA, takeEnd(s)is DAM, flip(takeEnd(s))is MAD, and that's not the same as MAD. Even though your functions are working right, they're not solving the problem. So there's a bug in your design as well as your implementation. If you think about it for a while, you should figure out how to make this work.

但是,您仍然不会得到任何奇数长度的回文。例如,对于 'MADAM',即使您正确使用了函数takeStart(s)is MAtakeEnd(s)is DAMflip(takeEnd(s))is MAD,这与MAD. 即使您的功能正常工作,它们也不能解决问题。因此,您的设计和实现中都存在错误。如果您考虑一段时间,您应该弄清楚如何使这项工作发挥作用。

And, once you do, you should realize that takeStartand takeEndcan be simplified a lot. (Hint: In which cases do you really need to treat odd and even lengths differently?)

而且,一旦你这样做了,你应该意识到这一点takeStart并且takeEnd可以简化很多。(提示:在哪些情况下,您真的需要区别对待奇数和偶数长度?)



While we're at it, this:

当我们在做的时候,这个:

foo = ""
for i in range(x, y):
    foo += s[i]
return foo

…?is just a verbose, slow, and easy-to-get-wrong way of writing this:

...? 只是一种冗长、缓慢且容易出错的写法:

return foo[x:y]

And, likewise, your whole flippedfunction is just:

而且,同样,您的整个flipped功能只是:

return s[::-1]

回答by mrk

Pythons range()function does not support floats but numpys arange()function does

Pythonsrange()函数不支持浮点数,但 numpysarange()函数支持

To use arange()function, you need to install and import the numpypackage. We'll here use the arange()function for generating a range of float numbers. The arange()has the same signature as the built-in range()method. But we can pass float type arguments as parameters to this function.

要使用arange()功能,您需要安装并导入numpy包。我们将在这里使用该arange()函数来生成一系列浮点数。在arange()具有相同签名的内置range()方法。但是我们可以将浮点型参数作为参数传递给这个函数。

import numpy
arange (start, stop, step)

In a full code example this looks as follows:

在完整的代码示例中,如下所示:

from numpy import arange

print("Float range using NumPy arange():")

print("\nTest 1:")
for i in arange(0.0, 1.0, 0.1):
    print(i, end=', ')