Magic numbers in python

Magic Number in Python

A number is said to be magic when its digits are added recursive till we get a single digit which is equal to 1, this approach uses brute force, which keeps on adding the digit until a single digit is obtained.

For example: 1234 = 1 + 2 + 3 + 4 = 10
1 + 0 = 1
Therefore, 1234 is a magic number.

Magic Number Program in Python

Now, let us code to find the magic number in python, for this, we use a while loop to iterate and find the sum of the digits until it becomes a single digit. We have defined a function “Magic” to find the magic number.

Program description:- Write a program to check whether the number is a magic number or not in python

def Magic(n): sum = 0 while (n > 0 or sum > 9): if (n == 0): n = sum sum = 0 sum = sum + n % 10 n = int(n / 10) return True if (sum == 1) else False n = 1234 if (Magic(n)): print("The given number is Magic Number.") else: print("The given is not a Magic Number.")

The given number is Magic Number.

Now, for the same, we will try in a different way that is shortcut way by using if loop.

n = 1234 if (n % 9 == 1): print("The given number is Magic Number.") else: print("The given number is not a Magic Number.")

The given number is Magic Number.

Python Program to Find All Magic Numbers in the Interval

Here, we find magic numbers between the given interval of numbers, the program takes two inputs from the user and then finds the magic number between that numbers.

print("Enter a range") i1 = int(input("Start: ")) i2 = int(input("Last: ")) print("Magic numbers between ",i1," and ",i2," are: ") for i in range(i1,i2+1): if (i % 9 == 1): print(i)

Enter a range
Start: 1
Last: 100
Magic numbers between 1 and 100 are:
1
10
19
28
37
46
55
64
73
82
91
100

Python Program to Find Magic Number in List

Now, we find the magic number in a list of elements, that is we iterate and check over all the list elements to find whether it is a magic number or not. The program prints the magic number if it is present in the list.

n = [1234, 345, 343] for i in n: if (i % 9 == 1): print(i)

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Читайте также:  Java bean to csv

Источник

Python what is the magic numbers

However, they are considered reserved for internal Python machinery, so you shouldn’t add your own; per the language reference on «reserved classes of identifiers»: That said, there are a couple in common use that I don’t think are actually specified anywhere in the official docs, like and ; see e.g. what is the common header format of python files? Solution: You cannot cross-compile for other Python versions, no. Just install Python 2.6 next to Python 2.7 and use with that to produce your bytecode files instead.

Pythonic way to describe «magic objects» (in the sense of «magic numbers»)

I have objects of class Node , they get compared by an id. Now I also have nodes with a special meaning, SpecialNodeA and SpecialNodeB . They do not have any properties, they just transport their special meaning by being that type/that object. It would call them «magic objects» since they have a similiar function as «magic numbers».

As was said in a comment below: I’m looking for something like a singleton that is only equal to itself. It will be compared to other types and should not throw an Exception, just give false.

I currently do it the following way:

class Node: def __eq_(self, other) return (self.id == other.id) class SpecialNodeA: pass; class SpecialNodeB: pass; spNoA = SpecialNodeA() # spNoB = SpecialNodeB() n1 = Node(id = 1) specialNodeA1 = spNoA specialNodeA2 = spNoA specialNodeB1 = spNoB specialNodeB2 = spNoB print(n1 == specialNode1) # should return false print(specialNodeA1 == specialNodeA2) # should return true print(specialNodeA1 == specialNodeB2) # should return false 

It works fine, but is there a «more pythonic» way to implement such «magic objects»?

I would probably use an enum:

from enum import Enum class SpecialNodes(Enum): A = 1 B = 2 

Or if you want actual nodes:

class SpecialNodes(Enum): A = Node() B = Node() 
>>> class Node: . pass . >>> class SpecialNodes(Enum): . B=Node() . A=Node() . >>> A1 = SpecialNodes.A >>> A2 = SpecialNodes.A >>> B1 = SpecialNodes.B >>> A1 == A2 True >>> A1 == B1 False 

Python — Determining magic number without imp.get, A «word» in this context is fixed-length (notionally the size of an integer). Python’s magic numbers are four bytes long. I believe Jython compiles to java bytecode (which is then run by the java VM), rather than python bytecode. Share answered Mar 9, 2012 at 20:50 alexis 46.6k 14 98 154 1

Is there a way to avoid «Magic Number» issues when I know the destination plateform?

I built a tool in python 2.7.5 and I compiled it with python -m compileall

When I tried to use it on the destination plateforme (python 2.6.6) I got that annoying «Magic Number» error.

I already read a bunch of things about that error and I think I understand whats happening.

Then my question is : Is there a way to specify the «target platform» when I compile the .py files or should I downgrade my current version of python to match the «production» one ?

Just install Python 2.6 next to Python 2.7 and use compileall with that to produce your bytecode files instead. You can install multiple versions of Python quite painlessly.

Magic number game in Python, There are 6 variable sets of numbers, someone picks a number between 1-63, if their number is in a set, you add the first number of the list to the magic number Stack Exchange Network Stack Exchange network consists of 180 Q&A communities including Stack Overflow , the largest, most trusted online …

Читайте также:  Selenium использование прокси python

Is there a comprehensive table of Python’s «magic constants»?

Where are __file__ , __main__ , etc. defined, and what are they officially called? __eq__ and __ge__ are «magic methods», so right now I’m just referring to them as «magic constants» but I don’t even know if that’s right.

Google search really isn’t turning up anything and even Python’s own documentation doesn’t seem to have a comprehensive list of them after scanning through the layers of pages.

Short answer: no . For the longer answer, which got badly out of hand, keep reading.

There is no comprehensive table of those __dunder_names__ (also not their official title!), as far as I’m aware. There are a couple of sources:

  • The only real «magic constant» is __debug__ : it’s a SyntaxError to attempt to assign to this name. It’s covered in the list of constants and mentioned in the context of the assert statement.
  • Another module-level name with specific use by a statement is __all__ , which is documented alongside the import statement.
  • There are two special modules, documented in the library reference, which have their own pages:
    • __main__ is the top-level environment in which a script is executed.
    • __future__ is for accessing language features that aren’t yet mandatory (e.g. print_function to replace the print statement in Python 2).

    There are also many related to objects. The basic methods for implementing built-in behaviour (like __eq__ and __ge__ , as you mention) are listed in the data model documentation. But plenty of other, more specific names exist; for example, there are several related specifically to exceptions, like __cause__ and __traceback__ , in the exceptions documentation.

    Note that there is nothing particularly «magic» about most of these, they are just regular attributes and can be assigned to as you see fit. However, they are considered reserved for internal Python machinery, so you shouldn’t add your own; per the language reference on «reserved classes of identifiers»:

    Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

    That said, there are a couple in common use that I don’t think are actually specified anywhere in the official docs, like __author__ and __version__ ; see e.g. what is the common header format of python files? and What is the origin of __author__? A few have semi-official status via PEP-8, but that’s about it.

    A few others have trodden this path, by the looks of it:

    Hex header of file, magic numbers, python, In Python 3 you’ll get bytes from a binary read, rather than a string. No need to convert it to a string by str. Print will try to convert bytes to something human readable. If you don’t want that, convert your bytes to e.g. hex representations of the integer values of the bytes by: Code samplewith open (from_folder+»/»+i, «rb») as myfile:header=myfile.read(24)header = str(binascii.hexlify(header))[2:-1]Feedback

    Источник

    Binary Study

    In the program example below, we display magic numbers between 1 and 200.

    Example 1 (Easy Approach)

    # Python program to print Magic numbers between 1 and 200.
    start = 1
    end = 200
    list_magic = []
    for numb in range(start,end+1):
    if numb % 9 == 1:
    list_magic.append(numb)
    print("Magic numbers between 1 and 200: \n",list_magic)

    Output:

    Magic numbers between 1 and 200: [1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 100, 109, 118, 127, 136, 145, 154, 163, 172, 181, 190, 199]

    Example 2

    # Python program to print Magic numbers between 1 and 200.
    start = 1
    end = 200
    list_magic = []
    # define a function to calculate the sum of digits in a number
    def sum_digit(x):
    dig_sum = 0
    num = x
    while num > 0:
    dig_sum +=num%10
    num = num//10
    return dig_sum

    # iterate from 1 to 200 and check if a number is magic number
    # if number is magic number append the list_magic
    for numb in range(start,end+1):
    digSum = sum_digit(numb)
    while digSum > 9:
    digSum = sum_digit(digSum)
    if digSum == 1:
    list_magic.append(numb)
    print("Magic numbers between 1 and 200: \n",list_magic)

    Output:

    Magic numbers between 1 and 200: [1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 100, 109, 118, 127, 136, 145, 154, 163, 172, 181, 190, 199]

    Источник

    Python Program for Magic Number

    A magic number is that number whose repeated sum of its digits till we get a single digit is equal to 1.

    Magic number in python

    Steps to Check Magic Number in Python

    1. Take a number as input (num).
    2. Calculate the sum of digits of the input number.
    3. Repeat step 2 until we get a single digit.
    4. If resultant sum is equal to 1 then it is a Magic number else not.

    We will calculate the sum of the digits until we get a single-digit number as the sum. To count the number of digits we will use math.log10()+1.

    Check Whether a number is a Magic Number in Python

    import math num = int(input("Enter a Number \n")) digitCount = int(math.log10(num))+1 sumOfDigits = 0 temp = num #copying num #calculating sum of digits of temp(i.e num) until #sumOfDigits is a single digit while( digitCount > 1): sumOfDigits = 0 while(temp > 0): sumOfDigits += temp%10 temp = temp//10 temp = sumOfDigits #count the digits of sumOfDigits digitCount = int(math.log10(sumOfDigits))+1 #check whether sumOfDigits == 1 if(sumOfDigits == 1): print("Magic number") else: print("Not a magic number")
    Enter a Number 65 Not a magic number Enter a Number 1729 Magic number

    Find all the Magic Numbers in the interval in Python

    import math def magic_number(num): digitCount = int(math.log10(num))+1 sumOfDigits = 0 temp = num #copying num #calculating sum of digits of temp(i.e num) until #sumOfDigits is a single digit while( digitCount > 1): sumOfDigits = 0 while(temp > 0): sumOfDigits += temp%10 temp = temp//10 temp = sumOfDigits #count the digits of sumOfDigits digitCount = int(math.log10(sumOfDigits))+1 #check for sumOfDigits == 1 if(sumOfDigits == 1): print(num) low = int(input("Enter lower interval value \n")) up = int(input("Enter upper interval value \n")) print("Magic numbers between and are".format(x=low,y=up)) for num in range(low,up+1): magic_number(num)
    Enter lower interval value 1 Enter upper interval value 100 Magic numbers between 1 and 100 are 10 19 28 37 46 55 64 73 82 91 100

    Any doubts then comment below.

    Источник

Оцените статью