What happens if I write this FizzBuzz code in Ruby in Python?

Asked 2 years ago, Updated 2 years ago, 41 views

I usually use Ruby. I started studying Python, but I was having a hard time, so please let me know.

class FizzBuzz
  def self.fizz?(i)
    i>0&(i%3) == 0
  end

  def self.buzz?(i)
    i>0&(i%5) == 0
  end

  def self.fizz_buzz?(i)
    fizz?(i)&buzz?(i)
  end

  def self.to_p(i)
    case
    When fizz?(i)&&! fizz_buzz?(i)
      "Fizz".
    When Buzz?(i)&&!fizz_buzz?(i)
      "Buzz".
    When fizz_buzz?(i)
      "FizzBuzz".
    else
      i
    end
  end
end

1.upto(100)do|i|
  puts FizzBuzz.to_p(i)
end

I'm trying to write this in Python, but I don't know how to write it.
Below is the Python code I wrote.(Cannot run)
"I would appreciate it if you could give me advice such as ""This is the best way to write like Python."""

class FizzBuzz:
    @classmethod
    defis_fizz(i):
        return(i>0 and(i%3) == 0)

    @classmethod
    defis_buzz(i):
        return(i>0 and(i%5) == 0)

    @classmethod
    defis_fizz_buzz(i):
        return(self.is_fizz(i) and self.is_buzz(i))

    @classmethod
    def to_print(i):
        if self.is_fizz(i) and not self.is_fizz_buzz(i):
            return 'Fizz'
        elif self.is_buzz(i) and not self.fizz_buzz(i):
            return 'Buzz'
        elifself.fizz_buzz(i):
            return 'FizzBuzz'
        else:
            returni

for i in range (1,101):
    print FizzBuzz.to_print(i)

ruby python

2022-09-30 10:55

2 Answers

I think the above is good for class study, but it will be easier if you use a function.
(By the way, I don't see many methods like .to_print() in python, so I feel like I'm writing ruby-pocket python here.)

def fizzbuzz(n):
    if n%3 == 0 and n%5 == 0:
        return 'FizzBuzz'
    elif n%3 == 0:
        return 'Fizz'
    elif n%5 == 0:
        return 'Buzz'
    else:
        return str(n)

for i in range (1,101):
    print(fizzbuzz(i))


2022-09-30 10:55

If you want to modify it to move at least, it looks like this.

class FizzBuzz:

    @staticmethod
    defis_fizz(i):
        return i>0 and(i%3) == 0

    @staticmethod
    defis_buzz(i):
        return i>0 and(i%5) == 0

    @classmethod
    defis_fizz_buzz(cls, i):
        return cls.is_fizz(i) and cls.is_buzz(i)

    @classmethod
    def to_print(cls, i):
        if cls.is_fizz(i) and not cls.is_fizz_buzz(i):
            return 'Fizz'
        elif cls.is_buzz(i) and not cls.is_fizz_buzz(i):
            return 'Buzz'
        elif cls.is_fizz_buzz(i):
            return 'FizzBuzz'
        else:
            returni

for i in range (1,101):
    print FizzBuzz.to_print(i)


2022-09-30 10:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.