I have written this code for finding the numerological value of a name. Is there any way in which i can shorten the code, or nest one loop inside the other?
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
word =input("your numerology score is :") #since i am using python 3 to code this
def digit_sum(n):
#prepare a list of numbers in n convert to string and reconvert
numbers=[]
for digit in str(n):
numbers.append(int(digit))
# add up the total of numbers
total=0
for number in numbers:
total += number
return total
def numerology(word):
total = 0
for letter in word.upper():
total += alphabets[letter]
total = digit_sum(total)
return total
print (numerology(word))
To understand what is meant by numerological value, please see https://en.wikipedia.org/wiki/Numerology#Latin_alphabet_systems.
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
name = "this is a sample name"
digits = str(sum([alphabets[l] for l in name.upper() if l in alphabets.keys()]))
numerological_value = int(digits) % 9
if numerological_value == 0:
numerological_value = 9
print(numerological_value)
Comprehensions allow you to have a short hand for creating various data types.
In this case you want to build generators.
This is as you don't need to build every number before reducing the list, to a single number.
Wrapping one in sum can allow you to significantly shorten digit_sum. Which can become:
def digit_sum(n):
return sum(int(digit) for digit in str(n))
You can also change numerology to be a little shorter, if you combine the addition and assignment.
def numerology(word):
total = 0
for letter in word.upper():
total = digit_sum(total + alphabets[letter])
return total
If you want, you can use functools.reduce to make this span a total of six lines.
def numerology(word):
return functools.reduce(
lambda a, b: sum(int(digit) for digit in str(a + b)),
(alphabets[letter] for letter in word.upper()),
0
)
One-liner for laughs.
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
print("Your numerology score is "+ str((int(sum([alphabets[l] for l in input("Type your name:").upper() if l in alphabets.keys()])) % 9) or 9))
this one !!!
a= input()
b= 0
c= len(a)
d= {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10, "k":11, "l":12, "m":13, "n":14, "o":15, "p":16, "q":17, "r":18, "s":19, "t":20, "u":21, "v":22, "w":23, "x":24, "y":25, "z":26, " ":0}
for i in range(c):
b= b+d[a[i]]
print(b)
gematria
i'm sure you can chain the reducer functions a bit better but...
const charMap = {A:1, J:1, S:1, B:2, K:2, T:2, C:3, L:3, U:3, D:4,
M:4, V:4, E:5, N:5, W:5, F:6, O:6, X:6, G:7, P:7, Y:7, H:8,
Q:8, Z:8, I:9, R:9};
let name = prompt ("Type your name in CAPS"); //for example: TOM
let wordScore = Array.from(name).reduce((nameScore, element) => {
let curValue = charMap[element]
return (nameScore + curValue)
},0)
let finalScore = Array.from(String(wordScore), Number).reduce((score, element) => {
return score > 10 ? score + element : score
})
alert(finalScore)
Related
i have to create a lucky name number programme in python but i keep coming across many errors.
if you don't know what a lucky name number is, it is basically where each letter of the alphabet has a value and you add the values toether in your first name and second name so for example
john doe
165 465
1+6+5 = 12
4+6+5 = 15
15 + 12 = 27
2+7 = 8
then 8 = has diplomatic skills
Here is what i have done so far:
#this will go all the way to z
charDict = { 'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4}
# example names - while loop will go here
firstName = 'AAB'
lastName = 'DCDD'
# split the strings into a list of chars
firstNameChars = list(firstName)
lastNameChars = list(lastName)
# sum up values
firstNameSum = 0
lastNameSum = 0
for chr in firstNameChars:
firstNameSum += charDict[chr]
for chr in lastNameChars:
lastNameSum += charDict[chr]
# cast sums to strings. In this example, this would be '2024'
combinedNames = str(firstNameSum) + str(lastNameSum)
# split the string into a list of chars
combinedNameDigits = list(combinedNames)
# sum them up
finalSum = 0
for dgt in combinedNames:
finalSum += int(dgt)
# print the lucky number
print finalSum
So my question is, is where do i go from here, as the numbers don't add up correctly and the values of the letters aren't correct, so basically how do i do the calculations correctly
I really don't undersand how: john doe gives 165 465 and how: AAB DCDD gives 2024.
However, the standard way to convert letters in numbers and to sum the digits of a number is the following:
def letters_to_numbers(name):
sum_ = 0
for letter in name:
sum_ += ord(letter.upper())-64 #ord("A")=65 minus 64 -> 1
return sum_
def sum_digits(number):
sum_ = 0
while number:
sum_ += number%10
number //=10
return sum_
sum_digits(
sum_digits(letters_to_numbers("john"))
+sum_digits(letters_to_numbers("doe")))
This works considering you always split your numbers to the digit level, I let you wrap it in a function and modify the dictionary to add other letters
first = 'aaa'
last = 'bbb'
name = first + last
dicti = {'a':1, 'b':2, '1':1, '2':2 , '3':3 , '4':4 , '5':5 , '6':6 ,
'7':7 , '8':8 , '9':9 , '0':0}
while len(name) >1:
sum = 0
for letter in name:
sum = sum + dicti[letter]
name = str(sum)
final_sum = int(name)
I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades.
I'm pretty much stuck. Right now I´ve only got:
for c in range (0,50):
grade = ("What is the grade?")
Also, how could I print the count of grades that are below 50?
Any help is appreciated.
If you don't mind using numpy this is ridiculously easy:
import numpy as np
print np.mean(grades)
Or if you'd rather not import anything,
print float(sum(grades))/len(grades)
To get the number of grades below 50, assuming you have them all in a list, you could do:
grades2 = [x for x in grades if x < 50]
print len(grades2)
Assuming you have a list with all the grades.
avg = sum(gradeList)/len(gradeList)
This is actually faster than numpy.mean().
To find the number of grades less than 50 you can put it in a loop with a conditional statement.
numPoorGrades = 0
for g in grades:
if g < 50:
numPoorGrades += 1
You could also write this a little more compactly using a list comprehension.
numPoorGrades = len([g for g in grades if g < 50])
First of all, assuming grades is a list containing the grades, you would want to iterate over the grades list, and not iterate over range(0,50).
Second, in every iteration you can use a variable to count how many grades you have seen so far, and another variable that sums all the grades so far. Something like that:
num_grades = 0
sum_grades = 0
for grade in grades:
num_grades += 1 # this is the same as writing num_grades = num_grades + 1
sum_grades += sum # same as writing sum_grades = sum_grades + sum
Now all you need to do is to divide sum_grades by num_grades to get the result.
average = float(sum_grade)s / max(num_grades,1)
I used the max function that returns the maximum number between num_grades and 1 - in case the list of grades is empty, num_grades will be 0 and division by 0 is undefined.
I used float to get a fraction.
To count the number of grades lower than 50, you can add another variable num_failed and initialize him to 0 just like num_counts, add an if that check if grade is lower than 50 and if so increase num_failed by 1.
Try the following. Function isNumber tries to convert the input, which is read as a string, to a float, which I believe convers the integer range too and is the floating-point type in Python 3, which is the version I'm using. The try...except block is similar in a way to the try...catch statement found in other programming languages.
#Checks whether the value is a valid number:
def isNumber( value ):
try:
float( value )
return True
except:
return False
#Variables initialization:
numberOfGradesBelow50 = 0
sumOfAllGrades = 0
#Input:
for c in range( 0, 5 ):
currentGradeAsString = input( "What is the grade? " )
while not isNumber( currentGradeAsString ):
currentGradeAsString = input( "Invalid value. What is the grade? " )
currentGradeAsFloat = float( currentGradeAsString )
sumOfAllGrades += currentGradeAsFloat
if currentGradeAsFloat < 50.0:
numberOfGradesBelow50 += 1
#Displays results:
print( "The average is " + str( sumOfAllGrades / 5 ) + "." )
print( "You entered " + str( numberOfGradesBelow50 ) + " grades below 50." )
6174 is known as Kaprekar's constant[1][2][3] after the Indian mathematician D. R. Kaprekar. This number is notable for the following property:
Take any four-digit number, using at least two different digits. (Leading zeros are allowed.)
Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
Subtract the smaller number from the bigger number.
Go back to step 2.
Dattaraya Ramchandra Kaprekar
number="0011"
print(" helo world, lets do this: " , number)
i = 0
while number != "6174":
sortedS = sorted(number)
String[] sortedString = array[4] av strangen number
reversed = sorted(number, reverse=True)
sortedIntMin = int(sortedS[0]+sortedS[1]+sortedS[2]+sortedS[3])
reversedIntMax = int(reversed[0]+reversed[1]+reversed[2]+reversed[3])
i += 1
number = str(reversedIntMax - sortedIntMin)
reversedIntMax - sortedIntMin
print("det behovdes " , i , "iterationer for processen")
This is my unsuccessful attempt
def Kaprekar(number, i):
if number == 6174:
return
elif number != 6174:
sortedString = sorted(number)
reversedString = sorted(number, reverse=True)
sortedIntMin = int(sortedString[0]+sortedString[1]+sortedString[2]+sortedString[3])
reversedIntMax = int(reversedString[0]+reversedString[1]+reversedString[2]+reversedString[3])
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num), i)
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547", 0) , "iterationer for processen")
there are three things that are wrong: -
You don't need i. remove it from function definition.
The variable you are passing is a string and you are comparing it with an integer, convert it to a string while comparing.
You need to return 1 when number='6174', while you are returning None.
Also, it can be done a bit clearer if list is joined after sorted and it can be directly converted to integer, (thanks endzior for the edit)
try this : -
def Kaprekar(number):
if number == '6174':
return 1
elif number != '6174':
sortedString = ''.join(sorted(number))
reversedString = ''.join(sorted(number, reverse=True))
sortedIntMin = int(sortedString)
reversedIntMax = int(reversedString)
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num))
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547") , "iterationer for processen")
number is a string, so in the first 2 if statements :
if number == '6174':
return 1
else:
And as in another answer i variable is not needed here.
I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Something like this?
>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'
best way is
x=12345
a=str(x)[::-1]\\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \\ Here i have converted string a in integer
or
one line code is
a=int(str(x)[::-1]))
def reverse(x):
re = 0
negative = x < 0
MAX_BIG = 2 ** 31 -1
MIN_BIG = -2 ** 31
x = abs(x)
while x != 0:
a = int(x % 10)
re = re * 10 + a
x = int(x // 10)
reverse = -1 * re if negative else re
return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse
this is for 32 - bit integer ( -2^31 ; 2^31-1 )
def reverse_number(n):
r = 0
while n > 0:
r = (r*10) + (n % 10)
print(r)
r *=10
n //= 10
return r
print(reverse_number(123))
You can cast an integer to string with str(i) and then use your reverse function.
The following line should do what you are looking for:
def line(b, ending):
print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Original number is taken in a
a = 123
We convert the int to string ,then reverse it and again convert in int and store reversed number in b
b = int("".join(reversed(str(a))))
Print the values of a and b
print(a,b)
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
This code will not work if the number ends with zeros, example 100 and 1000 return 1
def reverse(num):
rev = 0
while(num != 0):
reminder = num % 10
rev = (rev * 10 ) + reminder
num = num // 10
print ("Reverse number is : " , rev )
num=input("enter number : ")
reverse(int(num))
#/ always results into float
#// division that results into whole number adjusted to the left in the number line
I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.
n = input() # input is always taken as a string
rev = int(str(n)[::-1])
If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer
import math
def Function(inputt):
a = 1
input2 = inputt
while(input2 > 9):
input2 = input2/10
a = a + 1
print("There are ", a, " numbers ")
N = 10
m = 1
print(" THe reverse numbers are: ")
for i in range(a):
l = (inputt%N)/m
print(math.floor(l), end = '')
N = N*10
m = m*10
print(" \n")
return 0
enter = int(input("Enter the number: "))
print(Function(enter))
More robust solution to handle negative numbers:
def reverse_integer(num):
sign = [1,-1][num < 0]
output = sign * int(str(abs(num))[::-1])
An easy and fast way to do it is as follows:
def reverse(x: int|str) -> int:
reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
if '-' in num:
reverse_x = -reverse_x'
return reverse_x
First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ''.join() method.
Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.
Easily you can write this class:
class reverse_number:
def __init__(self,rvs_num):
self.rvs_num = rvs_num
rvs_ed = int(str(rvs_num)[::-1])
print(rvs_ed)
You can use it by writing:
reverse_number(your number)
I have written it in a different way, but it works
def isPalindrome(x: int) -> bool:
if x<0:
return False
elif x<10:
return True
else:
rev=0
rem = x%10
quot = x//10
rev = rev*10+rem
while (quot>=10):
rem = quot%10
quot = quot//10
rev = rev*10+rem
rev = rev*10+quot
if rev==x:
return True
else:
return False
res=isPalindrome(1221)
I am trying to write a function that return the biggest number formed by the digits from an input integer number.
So if the input = 123584
output should be = 854321
My code is -
def maxNumber(inputNumber):
x = len(str(inputNumber))
max_number = []
result= []
while(x>0):
max_number.append(inputNumber%10)
inputNumber = inputNumber/10
x -= 1
while(x<(len(str(max_number)))):
result.append(max(max_number))
x += 1
return result
print maxNumber(1238675)
and off-course the output is not as I want. Please help. I am eager to learn all possible way to do it.
def maxNumber(inputNumber):
return int(''.join(sorted(str(inputNumber), reverse=True)))
The biggest number is formed by sorting the digits in descending order. This can be achived using the rverse=True parameter to sorted():
def max_digit_permutation(n):
return int("".join(sorted(str(n), reverse=True)))
This is more reliable than most answers given so far ;-)
def max_number(n):
s = str(n)
digits = sorted(s, reverse=n>0)
return int(''.join(digits))
print max_number(231)
print max_number(-231)
print max_number(+231)
And good point - I missed the option of doing it with number alone - here it is for completeness. :)
from math import *
def max_number(n):
digit_count = int(log(abs(n+1),10)) + 1
digits = sorted([(n / 10 ** (x - 1) % 10) for x in range(digit_count,0,-1) ], reverse=True)
return reduce(lambda x, y:10*x + y, digits)
print max_number(1000)
print max_number(999)
print max_number(2345128)
print max_number(231)
sort the string of number, reverse it, join it and convert to int
>>> x=123584
>>> int(''.join(sorted(str(x))[::-1]))
854321
You could just treat the number as a list of single digits and then sort the list in decreasing order.
What about something like this:
num = str(123584)
int(''.join(sorted(num, reverse=True)))