How can I find the alphabetic position of the letters in a word and then add the numbers up? - python-3.x

I wrote some of the code which gives me the total of the word with the position of the English alphabet but I am looking for something that prints the line like this:
book: 2 + 15 + 15 + 11 = 43
def convert(string):
sum = 0
for c in string:
code_point = ord(c)
location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
sum += location + 1
return sum
print(convert('book'))

def convert(string):
parts = []
sum = 0
for c in string:
code_point = ord(c)
location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
sum += location + 1
parts.append(str(location + 1))
return "{0}: {1} = {2}".format(string, " + ".join(parts), sum)
print(convert('book'))
Heres the output:
book: 2 + 15 + 15 + 11 = 43
More info on string.format and string.join.

Related

Parse Basic Programming

Receiving this error when trying to compile code on replit. I have already tried to declare two arrays, you need to use separate DIM statements for each array:
as 20 DIM W$(10)
30 DIM G$(26)
Error: ParseError: Parse error on line 20: Unexpected token DIM
Any suggestions on how to resolve this issue
10 REM Hangman game
20 REM Set up variables
30 DIM W$(10), G$(26)
40 LET C = 0
50 LET I = 0
60 LET J = 0
70 REM Set up word list
80 W$(1) = "HANGMAN"
90 W$(2) = "BASIC"
100 W$(3) = "COMPUTER"
110 W$(4) = "PROGRAM"
120 W$(5) = "VINTAGE"
130 REM Select a random word
140 LET R = INT(RND(1) * 5) + 1
150 LET W = W$(R)
160 REM Set up guess string
170 FOR I = 1 TO LEN(W)
180 G$(I) = "-"
190 NEXT I
200 REM Main game loop
210 DO
220 CLS
230 PRINT "Hangman"
240 PRINT
250 PRINT "Word: ";
260 FOR I = 1 TO LEN(W)
270 PRINT G$(I);
280 NEXT I
290 PRINT
300 PRINT "Guesses: ";
310 FOR I = 1 TO 26
320 IF G$(I) <> "-" THEN PRINT G$(I);
330 NEXT I
340 PRINT
350 INPUT "Enter a letter: ", L$
360 IF LEN(L$) > 1 THEN 400
370 IF L$ < "A" OR L$ > "Z" THEN 400
380 LET L = ASC(L$) - 64
390 GOTO 420
400 PRINT "Invalid input. Please enter a single letter."
410 GOTO 350
420 REM Check if letter is in word
430 LET F = 0
440 FOR I = 1 TO LEN(W)
450 IF MID$(W, I, 1) = L$ THEN G$(I) = L$: F = 1
460 NEXT I
470 IF F = 0 THEN C = C + 1
480 IF C = 6 THEN 600
490 REM Check for win
500 LET WN = 1
510 FOR I = 1 TO LEN(W)
520 IF G$(I) = "-" THEN WN = 0
530 NEXT I
540 IF WN THEN PRINT "You win!": GOTO 650
550 REM Check for loss
560 IF C = 6 THEN PRINT "You lose. The word was "; W: GOTO 650
570 LOOP
600 REM Draw hangman
610 PRINT " _____"
620 PRINT " | |"
630 IF C > 1 THEN PRINT " O |" ELSE PRINT " |"
640 IF C > 2 THEN PRINT "/|\ |" ELSE PRINT " |"
650 END
/////
I tried declaring separate arrays. I also tried running it on a vintage basic terminal, and received an error with line 150 "type mismatch"

Displaying element in my text file when it is lesser than the range?

I am trying to create a Top 5 leaderboard for my game in Python 3.
Here's what I have
Top_Score = open("highscore.txt", "r+")
score_list = []
print(" Top 5")
print("==========")
for line in Top_Score.readlines(): # Read lines
score_list.append(line)
score_list.sort()
for i in range(5):
print("Pos", str(i + 1), ":", score_list[i])
print("==========")
Top_Score.close()
highscore.txt
50
18
20
40
50
60
70
Output
Top 5
==========
Pos 1 : 18
Pos 2 : 20
Pos 3 : 40
Pos 4 : 50
Pos 5 : 50
==========
But how can I display element in my text file if it is lesser than the range(5) without any errors? Any help would be appreciated
Example highscore.txt
50
18
20
Example Output
Top 5
==========
Pos 1 : 18
Pos 2 : 20
Pos 3 : 50
==========
In the print loop, you need to check if the size of the list is smaller than 5. If so, only loop until the size.
So, something like this:
loop_range = 5
if len(score_list) < loop_range:
loop_range = len(score_list)
for i in range(loop_range):
print("Pos", str(i + 1), ":", score_list[i])
This can be rewritten using the min function to select the smaller of the two numbers, 5 or the size:
loop_range = min(5, len(score_list))
for i in range(loop_range):
print("Pos", str(i + 1), ":", score_list[i])

Code fails on Test case. (InterQuartile Range)

This is a challenge from 10 Day statistics on Hackerrank.(https://www.hackerrank.com/challenges/s10-interquartile-range/problem?h_r=next-challenge&h_v=zen)
Task :
Task
The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3 - Q1).
Given an array,X, of n integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each xi occurs at frequency fi. Then calculate and print S's interquartile range, rounded to a scale of 1 decimal place (i.e., 12.3 format).
Following is my code.
n = int(input())
x = list(map(int, input().split()))
f = list(map(int, input().split()))
s = []
for i in range(len(x)):
j = f[i]
for k in range(j):
s.append(x[i])
n = len(s)
s.sort()
if n%2 == 0:
Q21 = s[n//2]
Q22 = s[n//2 - 1]
Q2 = (Q21 + Q22) / 2
else:
Q2 = s[n//2]
LH = s[:n//2]
if n%2==0:
UH = s[n//2:]
else:
UH = s[n//2+1:]
Q1_len = len(LH)
Q3_len = len(UH)
if Q1_len%2 == 0:
Q11 = LH[Q1_len//2]
Q12 = LH[Q1_len//2 - 1]
Q1 = (Q11 + Q12) / 2
else:
Q1 = LH[Q1_len//2]
if Q3_len%2 == 0:
Q31 = UH[Q3_len//2]
Q32 = UH[Q3_len//2 - 1]
Q3 = (Q31 + Q32) / 2
else:
Q3 = UH[Q3_len//2]
print(round(Q3 - Q1,1))
# print(int(Q2))
# print(int(Q3))
Here is the test case: with std input.
5
10 40 30 50 20
1 2 3 4 5
Expected output:
30.0
My code output:
30.0 # I get this output on my code editor but not on Hackerrank
Can someone help me on this where I am wrong ?
I get the output what is expected but it shows as failed.
print(float(Q3 - Q1))
Basically is the answer.

To Print each stage of Bubble sort in Python3.6

Sort the given set of numbers using Bubble Sort. The first line of the input contains the number of elements, the second line of the input contains the numbers to be sorted. In the output print the status of the array at the 3rd iteration and the final sorted array in the given format
alist=[]
def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return
n=int(input())
for i in range(n):
alist.append(int(input()))
alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted array: ', end='\n')
for i in alist:
print(i,end=" ")
Test Case 1
7
64
34
25
12
22
11
90
Expected Output:
It should print the following 3 lines
12 22 11 25 34 64 90
Sorted array:
11 12 22 25 34 64 90
Test Case 2
8
14
83
25
47
9
77
1
0
Expected Output:
It should print the 3 following lines
14 9 25 1 0 47 77 83
Sorted array:
0 1 9 14 25 47 77 83
Just add in your for loop a print when you reach the third iteration
alist=[]
def bubble_sort(alist):
number_of_iterations = 0
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if i == len(alist) - 3:
print(*alist) # Using the unpacking operator for pretty print, if you are in python2 you can print it this way : " ".join(map(str, alist))
if no_swap:
return
n=5
alist = [7, 64, 34, 25, 12, 22, 11, 90]
bubble_sort(alist)
print('Sorted array: ', end='\n')
for i in alist:
print(i,end=" ")

Number to text decoding

Can anybody help me come up with an algorithm or way to decode a number to 3 characters when they are encoded in the following manner:
Each element represents 3 alphabetic characters as in the following examples:
DOG -> (3 * 26^2) + (14 * 26) + 6 = 2398
CAT -> (2 * 26^2) + (0 * 26) + 19 = 1371
ZZZ -> (25 * 26^2) + (25 * 26) + 25 = 17575
So say I have 7446 or 3290 how would I go about converting them to text?
Try this to extract the letters in reverse order:
7446 % 26 = 10
(7446 / 26) % 26 = 0
(7446 / 26 / 26) % 26 = 11
For example:
1371 % 26 = 19 (T)
(1371 / 26) % 26 = 0 (A)
(1371 / 26 / 26) % 26 = 2 (C)
CAT
The % refers to the modulo operation. x % y gives you the remainder of the division x / y.
Modulo
input = 2398
iteration = 1
while input > 0
character = input % 26
input = input - character
input = input / 26
print character

Resources