私信  •  关注

Green Cloak Guy

Green Cloak Guy 最近创建的主题
Green Cloak Guy 最近回复了
3 年前
回复了 Green Cloak Guy 创建的主题 » Python类属性错误,尽管存在?

编写类方法更惯用的方法是

class Dice:
    ...

    @classmethod
    def roll(cls):
        ...

注意,该参数通常被调用 cls self .怎么了 @classmethod 方法是这样的,当你调用 Dice.roll() ,传递给方法的“实例”就是对象 Dice -确切地说,是拥有该方法的类(而不是该类的任何特定实例)。这通常与继承和多态性结合使用。

现在,自从 __init__() 从来没有被要求 掷骰子 类本身(只有在 例子 关于 掷骰子 类),则 掷骰子 类从来没有名为 sides 附属于它。


在你的情况下,你可能想要 roll() 要成为实例方法,并将新实例保存到变量中,请执行以下操作:

class Dice:
    def __init__(self, sides):
        self.sides = sides

    def roll(self):
        return self.sides + 2

die = Dice(int(input('How many sides are on the dice? ')))
print(die.roll())

# alternatively

sides = int(input('How many sides are on the dice? '))
print(Dice(sides).roll())
5 年前
回复了 Green Cloak Guy 创建的主题 » 在python3中,向查询字符串传递多个字符串变量的最佳方式是什么

使用f字串。

query = f"insert into case({description}, {comment}) value({description}, {comment})"

不要使用任何类型的字符串格式来执行实际的数据库查询-这会导致出现SQL注入问题。使用数据库库来正确地清理数据。

% 其他语言倾向于使用的格式(在技术上,python仍然可以通过 "some_string %s %s %s" % (str1, str2, str3)" )

6 年前
回复了 Green Cloak Guy 创建的主题 » Python函数通过引用、值或对象调用

Python通过引用传递。如果将对象传递给函数,然后修改该对象,则当函数结束时,该对象将保持修改状态。例如:

def f(a):
    a[1] = 'b'

x = [1, 2, 3]
f(x)
print(x)
# [1, 'b', 3]

不要 修改对象。例如,字符串几乎是完全不可变的-可以对字符串执行的大多数操作,以及可以执行的大多数函数 在字符串上,返回一个新的(修改的)字符串而不更改原始字符串。这包括连接、反转和切片。

my_list[1] = 'b' )或者用类似的方法 .append() .extend() . 但是,作为一个整体,iterables的许多共同点并不会改变列表本身。这包括连接、反转和切片。

赋值运算符 = 不会修改左侧的对象;相反,它 取代 它。

所以你不能得到相同输出的原因是这一行:

matrix = matrix[::-1]

matrix -相反,它通过切片创建一个新列表 矩阵 矩阵 . 当你在函数之外运行代码时,只有一个 命名空间中的引用,该引用将被替换,因此您永远看不到差异。然而 矩阵

# global scope
# matrix --> some object with address 0x001
def rotate(matrix):
    # local scope
    # matrix --> 0x001  (the reference that was passed in)
    matrix = matrix[::-1]  # the slice creates a new object 0x002
    # matrix --> 0x002
    ...

然后继续修改 矩阵 0x002 . 一切都很好,但这些变化并没有影响 0x001

有一些方法可以解决这个问题-例如,就地反转,而不是使用切片来获取原始列表的反转版本:

def reverse_in_place(lst):
    for i in range(len(lst) // 2):
        lst[i], lst[-i-1] = lst[-i-1], lst[i]

但正如@Jmonsky在他们的回答中指出的,更传统的做法是 返回修改后的值 比去 ,但有几个特殊的例外。

6 年前
回复了 Green Cloak Guy 创建的主题 » 有没有一个快速的Python函数可以将数字转换成不同的基数?

我认为在标准库中没有一个函数可以做到这一点。但正在努力 a different project 对于我自己的一门课,我必须解决这类问题,我的解决方案如下:

def _base(decimal, base):
    """
    Converts a number to the given base, returning a string.
    Taken from https://stackoverflow.com/a/26188870/2648811
    :param decimal: an integer
    :param base: The base to which to convert that integer
    :return: A string containing the base-base representation of the given number
    """
    li = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    other_base = ""
    while decimal != 0:
        other_base = li[decimal % base] + other_base
        decimal = decimal // base
    if other_base == "":
        other_base = "0"
    return other_base

def palindromes(num, bases=range(2, 11)):
    """
    Checks if the given number is a palindrome in every given base, in order. 
    Returns the sublist of bases for which the given number is a palindrome, 
    or an empty list if it is not a palindrome in any base checked.
    :param num: an integer to be converted to various bases
    :param bases: an iterable containing ints representing bases
    """
    return [i for i in bases if _base(num, i) == _base(num, i)[::-1]]

(上一个语句的一个不那么简洁的版本(扩展 for 循环)如下所示:

r = []
for i in bases:
    b = _base(num, i)
    if b == b[::-1]:
        r.append(i)
return r

在您的例子中,如果您只需要一个以各种基表示整数的列表,那么代码将更加简单:

reps = {b: _base(num, b) for base in range(2, 11)}

将产生 base : representation in that base . 例如,如果 num = 23

{2: '10111',
 3: '212',
 4: '113',
 5: '43',
 6: '35',
 7: '32',
 8: '27',
 9: '25',
 10: '23'}

即使我们已经移动了C从0开始的数组推理(即数组索引是内存地址偏移的直接抽象),在0开始数组/列表索引仍然简化了许多不同的索引相关的数学东西。 Here's a Quora post on the subject . 这些东西是 许多的 比反向列表索引更常见的用例,所以从设计的角度来看,它们将被优先考虑。

0 -0 某物 相反,和 -1

某些编程语言 1索引,包括(但不限于)MATLAB、Mathematica、Lua、APL,甚至grandaddy FORTRAN。在这里,您将注意到这些语言设计用来做什么的一个主题—它们都不是面向通用软件开发或 计算机 数学的 任务,面向用例和功能,其中1-索引更方便或更有意义。Python有不同的优先级。


如果你需要在抽象中总结你的脑袋,你可以考虑我们如何用其他语言来做索引。

boolean isPalindrome(List x) {
    for(int i = 0; i < x.size() / 2; i++)
        if(x.get(i) != x.get(x.size() - i - 1))
            return false;
    return true;
}

请注意 i - 1

5 年前
回复了 Green Cloak Guy 创建的主题 » 获取所有元素的python列表的增量计数

你可以用字典和 for 循环以完成此操作:

counts = {}
a = ['bike','bike','jeep','horse','horse','horse','flight','flight','cycle']
z = []
for i in a:
    if i in counts:
        counts[i] += 1
    else:
        counts[i] = 1
    z.append(counts[i])

print(z)
# [1, 2, 1, 1, 2, 3, 1, 2, 1]

您还可以使用列表理解来完成这项有趣的工作,它利用了元组的求值顺序,并且基本上与上面一样 对于 循环但浓缩成一行:

counts = {}
z = [(counts.__setitem__(i, counts[i] + 1 if i in counts else 1), counts[i])[1] for i in a]
print(z)
# [1, 2, 1, 1, 2, 3, 1, 2, 1]
5 年前
回复了 Green Cloak Guy 创建的主题 » 在Python中如何使用Unix套接字?

同一个系统上的两个Python程序之间的对话

不要使用插座。使用管道。

在网络中,套接字本质上是应用层和传输层之间的链接。这就是为什么你需要提供一个IP和端口号-这些是重要的地址信息任何人看你的电脑外部。这也是为什么你有数据报对流-TCP和UDP是两个主要的传输层协议,当建立到传输层的链接时,你需要指定你想使用的协议。插座用于通信 使用网络 -在同一个系统上的两个进程之间有替代的、更有效和更简单的通信方式。

管道更像是专门用于进程间通信的文件描述符。基本上有两种使用管道的方法-命名管道和匿名管道。如果您的“两个python程序”是使用类似于 multiprocessing ,则可以使用匿名管道 os.pipe() 来设置它。否则,您需要为您的管道找出一个两个程序都知道的一致名称和位置,并在一端使用 os.mkfifo() 然后在另一端像普通文件一样打开它。此功能似乎仅在Unix上可用,因此如果您在Windows上,则可能必须 investigate other solutions .

5 年前
回复了 Green Cloak Guy 创建的主题 » 在python中使用getattr

getattr() 转到 __getattribute__() 首先,与点运算符相同:

>>> class A:
...     def __getattr__(self, obj):
...         print("Called __getattr__")
...         return None
...     def __getattribute__(self, obj):
...         print("Called __getattribute__")
...         return None
...     def __get__(self, obj):
...         print("Called __get__")
...         return None
... 
>>> a = A()
>>> a.foobar
Called __getattribute__
>>> getattr(a, 'foobar')
Called __getattribute__

惯例是使用 获取属性() 只有在编译时不知道属性名应该是什么的时候。如果你这样做了,那么使用点运算符(“显式优于隐式”…)。

正如@klaus d.在评论中提到的, the python Data Model documentation 更详细地说明 .__getattribute__() .__getattr__() 互动。可以说,在高水平上,后者是一种退却的选择,因为如果前者失败了。请注意 .\uu getattr_uuu() 以及内置的 获取属性() 不是直接相关的-iirc这是一个命名的怪癖,起源于早期版本的python,并被赋予到python 3中。

6 年前
回复了 Green Cloak Guy 创建的主题 » 在python中读取文本的用途和目的

您所看到的不是有效的python代码,除非 read_text() 是在看不见的地方定义的。函数 读文本() 在标准python中不存在;相反,内置函数 input() 而是为了这个目的。您提供的图像的正确实现是:

def read_float(prompt):                  # prompt is a string, e.g. "Enter a float"
    while True:                          # this is to continue trying if not-a-float is entered
        try:
            number_text = input(prompt)  # this prompts the user for input, and returns a string
            result = float(number_text)  # this tries to convert the string to a float
            break                        # exit this loop to return the float
        except ValueError:               # this is thrown by the previous line if number_text isn't able to be converted to a float
            print('Enter a Number')      # ask the user to try again
    return result

在python控制台中运行此函数的结果:

>>> read_float("Enter a float, please: ")
Enter a float, please: float
Enter a Number
Enter a float, please: 7.5
7.5
6 年前
回复了 Green Cloak Guy 创建的主题 » 使用python识别直线、齐平和其他类别(从扑克中)

直牌的条件是你的五张牌有相邻的等级,这样没有两张牌有相同的等级。您可以使用两种不同的检查来确认这一点:

  1. 直牌中没有两张牌具有相同的等级(因此,根据鸽子洞原则,必须存在最小和最大之间的所有等级

def hasStraight(hand):
    # account for both low-ace and high-ace
    ranks_low = sorted([card._rank for card in hand])
    ranks_high = sorted([(14 if card._rank == 1 else card._rank) for card in hand])

    return (
        (
            ranks_low[-1] - (len(hand) - 1) == ranks_low[0]
            or ranks_high[-1] - (len(hand) - 1) == ranks_high[0]
        )                                                        # condition 1
        and len(set(hand)) == len(hand)                          # condition 2
    )


冲洗的条件是所有卡片都是同一套。这很容易验证,只需 set true

def hasFlush(hand):
    suits_set = set(*[card._suit for card in hand])
    return len(suits_set) == 1

def hasStraightFlush(hand):
    return hasStraight(hand) and hasFlush(hand)

def hasRoyalFlush(hand):
    ranks = sorted([14 if card._rank == 1 else card._rank for card in hand])
    return (
        hasStraightFlush(hand)
        and ranks[0] == 10 and ranks[-1] == 14
    ) # royal flush starts at 10, ends at high-ace