├── README.md ├── chocobars.py ├── lonely_integer.py ├── binary_reversal.py ├── scope.py ├── pick_numbers.py ├── maximiz_xors.py ├── permutation.py ├── min_abs.py ├── pairs.py ├── find_intersection.py ├── two_strings.py ├── angry_professor.py ├── unfairness.py ├── longest_word.py ├── ice_cream_parlour.py ├── kangaroo.py ├── jim_orders.py ├── beaut_pairs.py ├── cut_the_sticks.py ├── strong_psw.py ├── making_anagrams.py ├── funny_strings.py ├── guess_number.py ├── Jclouds_rev.py ├── missing_numbers.py ├── scissors_rock_paper.py ├── greedy_florist.py ├── password_generator.py └── hangman.py /README.md: -------------------------------------------------------------------------------- 1 | # Coding challenges 2 | 3 | 4 | The scripts in this repo show the solution of some coding challenges proposed on Hackerrank and Coderbyte. 5 | -------------------------------------------------------------------------------- /chocobars.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/the-birthday-bar/problem 4 | 5 | import math 6 | import random 7 | import sys 8 | 9 | 10 | def birthday(s, d, m): 11 | 12 | return len([1 for i in range(len(s)-m+1) if sum(s[i:i+m])==d]) 13 | 14 | 15 | if __name__ == '__main__': 16 | 17 | n = int(input().strip()) 18 | 19 | s = list(map(int, input().rstrip().split())) 20 | 21 | dm = input().rstrip().split() 22 | 23 | d = int(dm[0]) 24 | 25 | m = int(dm[1]) 26 | 27 | print(birthday(s, d, m)) 28 | 29 | -------------------------------------------------------------------------------- /lonely_integer.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/angry-professor/problem 3 | 4 | 5 | import math 6 | import random 7 | import re 8 | import sys 9 | 10 | # To solve the challenge, we can return that item whose number of occurences across a is equal to 1 11 | 12 | 13 | def lonelyinteger(a): 14 | 15 | for item in a: 16 | if a.count(item) == 1: 17 | return item 18 | 19 | if __name__ == '__main__': 20 | 21 | n = int(input()) 22 | 23 | a = list(map(int, input().rstrip().split())) 24 | 25 | result = lonelyinteger(a) 26 | 27 | print(result) 28 | 29 | -------------------------------------------------------------------------------- /binary_reversal.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge binary reversal proposed on Coderbyte at https://coderbyte.com/challenges 3 | 4 | """ 5 | First, we need to convert the given string to binary. After eliminating its two first characters, which are usually 6 | 0b, we should revert it. If its length is not a multiple of 8, we have to add as many 0s as necessary to obtain 7 | a multiple of 8. Finally, we should convert the string to a binary number 8 | """ 9 | 10 | def BinaryReversal(string): 11 | n = str(bin(int(string)))[2:][::-1] 12 | if len(n) % 8 != 0: 13 | n += "0" * (8-(len(n) % 8)) 14 | return int(n, 2) 15 | 16 | # keep this function call here 17 | print(BinaryReversal(input())) 18 | 19 | -------------------------------------------------------------------------------- /scope.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/30-scope/problem 3 | 4 | # The solution of the problem could be implemented just taking the absolute value between the last and the first 5 | # element of the list a, sorted according to ascending order 6 | 7 | class Difference: 8 | def __init__(self, a): 9 | self.__elements = a 10 | self.maximumDifference = 0 11 | def computeDifference(self): 12 | self.maximumDifference = abs(sorted(a)[len(a)-1]-sorted(a)[0]) 13 | 14 | # End of Difference class 15 | 16 | _ = input() 17 | a = [int(e) for e in input().split(' ')] 18 | 19 | d = Difference(a) 20 | d.computeDifference() 21 | 22 | print(d.maximumDifference) -------------------------------------------------------------------------------- /pick_numbers.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/picking-numbers/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | # read the input from terminal 10 | 11 | n = int(input().strip()) 12 | a = list(map(int,input().strip().split(' '))) 13 | 14 | maximum = 0 # initialize the maximum at 0 15 | 16 | for k in list(set(a)): # loop over the single elements of a list with no duplicates 17 | n1 = a.count(k) # number of occurrences of the element k in the list 18 | n2 = a.count(k-1) # number of the occurrences of the element k-1 in the list 19 | maximum = max(maximum, n1+n2) # maximum between the maximum calculated at the previous step and n1 + n2 20 | 21 | print(maximum) 22 | 23 | 24 | -------------------------------------------------------------------------------- /maximiz_xors.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/maximizing-xor/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | # In order to find the maximum value of xor between two numbers, we should build a double for loop that could allow 10 | # us to store the result of the XOR operation between any two numbers 11 | 12 | def maximizingXor(l, r): 13 | 14 | xors = [] 15 | 16 | for i in range(l,r+1): 17 | for j in range(r+1-i): 18 | xors.append(i^(i+j)) 19 | 20 | return max(xors) 21 | 22 | 23 | if __name__ == '__main__': 24 | 25 | l = int(input()) 26 | 27 | r = int(input()) 28 | 29 | result = maximizingXor(l, r) 30 | 31 | print(result) 32 | 33 | -------------------------------------------------------------------------------- /permutation.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/permutation-equation/problem 3 | 4 | # The solution of the problem can be implemented by carring out binary search twice 5 | 6 | import math 7 | import os 8 | import random 9 | import re 10 | import sys 11 | 12 | # Complete the permutationEquation function below. 13 | 14 | n = int(input()) 15 | 16 | p = list(map(int, input().rstrip().split())) 17 | 18 | inds = [] 19 | 20 | for i in range(n): 21 | for item in p: 22 | if item == (i+1): 23 | inds.append(p.index(item)+1) 24 | 25 | inds2 = [] 26 | 27 | for item in inds: 28 | for number in p: 29 | if item == number: 30 | inds2.append(p.index(number)+1) 31 | 32 | print('\n'.join(map(str,inds2))) 33 | 34 | -------------------------------------------------------------------------------- /min_abs.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the minimumAbsoluteDifference function below. 10 | 11 | def minimumAbsoluteDifference(arr): 12 | 13 | n = len(arr) 14 | 15 | sortedarr = sorted(arr) # sort the array according to ascending order 16 | 17 | diff = [] # array in which differences between consecutive numbers will be stored 18 | 19 | for i in range(n-1): 20 | difference = abs(sortedarr[i+1] - sortedarr[i]) 21 | diff.append(difference) 22 | 23 | return min(diff) 24 | 25 | 26 | if __name__ == '__main__': 27 | 28 | n = int(input()) 29 | 30 | arr = list(map(int, input().rstrip().split())) 31 | 32 | print(minimumAbsoluteDifference(arr)) 33 | 34 | -------------------------------------------------------------------------------- /pairs.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Solution of the challenge Pairs proposed on HackerRank at https://www.hackerrank.com/challenges/pairs/problem 4 | 5 | import math 6 | import random 7 | import re 8 | import sys 9 | 10 | # Given the array arr, we should add the target value k to each of its elements, so that we get a new array called 11 | # sum_set. After converting both arr and sum_set to sets, the answer is the length of the intersection between 12 | # the two sets. 13 | 14 | 15 | def pairs(k, arr): 16 | 17 | sum_set = set(item + k for item in arr) 18 | 19 | return len(set.intersection(set(arr), sum_set)) 20 | 21 | 22 | if __name__ == '__main__': 23 | 24 | nk = input().split() 25 | 26 | n = int(nk[0]) 27 | 28 | k = int(nk[1]) 29 | 30 | arr = list(map(int, input().rstrip().split())) 31 | 32 | result = pairs(k, arr) 33 | 34 | print(result) 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /find_intersection.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge FindIntersection proposed on Coderbyte at https://coderbyte.com/challenges 3 | 4 | """ 5 | After converting the input into two lists of integers, we should convert these lists to sets. If the 6 | intersection of these sets is empty, we return false. Otherwise, we return all the elements of the 7 | intersection 8 | """ 9 | 10 | def FindIntersection(strArr): 11 | 12 | first = [int(item) for item in strArr[0].split(", ")] 13 | second = [int(item) for item in strArr[1].split(", ")] 14 | 15 | first_set = set(first) 16 | second_set = set(second) 17 | 18 | inter = first_set.intersection(second_set) 19 | inter = list(inter) 20 | 21 | if len(inter) == 0: 22 | return "false" 23 | else: 24 | return ','.join(str(x) for x in sorted(inter)) 25 | 26 | # keep this function call here 27 | print(FindIntersection(input())) 28 | 29 | -------------------------------------------------------------------------------- /two_strings.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge proposed on Hackerrank at shorturl.at/myDOW 3 | 4 | 5 | # In order to know whether two strings share a common substring, it suffices to determine if they have 6 | # at least one common letter. This implies that, after converting them into sets, their intersection 7 | # should not be empty. 8 | 9 | 10 | 11 | import math 12 | 13 | import random 14 | import re 15 | import sys 16 | 17 | 18 | def twoStrings(s1, s2): 19 | 20 | str1 = set(s1) 21 | str2 = set(s2) 22 | 23 | intr = str1.intersection(str2) 24 | 25 | 26 | if intr != set(): 27 | return "YES" 28 | else: 29 | return "NO" 30 | 31 | if __name__ == '__main__': 32 | 33 | q = int(input()) 34 | 35 | for q_itr in range(q): 36 | s1 = input() 37 | 38 | s2 = input() 39 | 40 | result = twoStrings(s1, s2) 41 | 42 | print(result) 43 | 44 | 45 | -------------------------------------------------------------------------------- /angry_professor.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/angry-professor/problem 3 | 4 | 5 | 6 | import math 7 | import random 8 | import re 9 | import sys 10 | 11 | # To solve this problem, we should count how many elements from the array a are larger than the threshold k 12 | 13 | def angryProfessor(k, a): 14 | 15 | ontime = 0 16 | 17 | for i in range(len(a)): 18 | if a[i] <= 0: 19 | ontime += 1 20 | 21 | if ontime >= k: 22 | return 'NO' 23 | else: 24 | return 'YES' 25 | 26 | 27 | if __name__ == '__main__': 28 | 29 | t = int(input()) 30 | 31 | for t_itr in range(t): 32 | nk = input().split() 33 | 34 | n = int(nk[0]) 35 | 36 | k = int(nk[1]) 37 | 38 | a = list(map(int, input().rstrip().split())) 39 | 40 | result = angryProfessor(k, a) 41 | 42 | print(result) 43 | -------------------------------------------------------------------------------- /unfairness.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/angry-children/problem 3 | 4 | 5 | 6 | import math 7 | import random 8 | import re 9 | import sys 10 | 11 | # The minimum unfairness is can be found just by looking for the minimum difference between the first and the final 12 | # element of all sublists. 13 | 14 | def maxMin(k, arr): 15 | 16 | arr = sorted(arr) 17 | 18 | unfairs = [] # empty list in which storing all the unfairness values 19 | 20 | for j in range(len(arr)-k+1): 21 | 22 | unfairs.append(arr[j+k-1]-arr[j]) 23 | 24 | 25 | return min(unfairs) 26 | 27 | 28 | 29 | if __name__ == '__main__': 30 | 31 | n = int(input()) 32 | 33 | k = int(input()) 34 | 35 | arr = [] 36 | 37 | for _ in range(n): 38 | arr_item = int(input()) 39 | arr.append(arr_item) 40 | 41 | result = maxMin(k, arr) 42 | 43 | print(str(result)) 44 | -------------------------------------------------------------------------------- /longest_word.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge LongestWord proposed on Coderbyte at https://coderbyte.com/challenges 3 | 4 | """ 5 | After converting the input to a list, we should remove all the characters which are not letters. Therefore, 6 | the words are stored into a list. Then, after storing each word length into a list, we should get the index of the 7 | first word with maximal length and print it. 8 | """ 9 | 10 | def LongestWord(sen): 11 | sent = list(sen.split(' ')) 12 | 13 | words = [] 14 | for item in sent: 15 | word = str() 16 | for i in range(len(item)): 17 | if item[i].isalpha(): 18 | word += item[i] 19 | 20 | words.append(word) 21 | 22 | # print(words) 23 | 24 | lens = [] 25 | for word in words: 26 | lens.append(len(word)) 27 | 28 | m = next(lens.index(x) for x in lens if x == max(lens)) 29 | 30 | return sent[m] 31 | 32 | # keep this function call here 33 | print(LongestWord(input())) 34 | -------------------------------------------------------------------------------- /ice_cream_parlour.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge Ice Cream Parlor proposed on Hackerrank at https://www.hackerrank.com/challenges/missing-numbers/problem 3 | 4 | import random 5 | import re 6 | import sys 7 | 8 | # We should build a double for-loop over the array arr. As soon as the unique pair of indices has been found, 9 | # the indices should be translated by 1 and then returned by the function 10 | 11 | def icecreamParlor(m, arr): 12 | 13 | 14 | for i in range(len(arr) - 1): 15 | for j in range(i + 1, len(arr)): 16 | if arr[i] + arr[j] == m: 17 | ind1 = i + 1 18 | ind2 = j + 1 19 | 20 | return [ind1, ind2] 21 | 22 | 23 | if __name__ == '__main__': 24 | 25 | t = int(input()) 26 | 27 | for t_itr in range(t): 28 | m = int(input()) 29 | 30 | n = int(input()) 31 | 32 | arr = list(map(int, input().rstrip().split())) 33 | 34 | result = icecreamParlor(m, arr) 35 | 36 | print(result) 37 | 38 | 39 | -------------------------------------------------------------------------------- /kangaroo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/kangaroo/problem 4 | 5 | 6 | import math 7 | import random 8 | import re 9 | import sys 10 | 11 | 12 | def kangaroo(x1, v1, x2, v2): 13 | 14 | if x2-x1 > v1 and v1 < v2: # if the first kangaroo starts before than the second and has a shorter skip, it will never catch it up 15 | answer = "NO" 16 | else: 17 | if v1 != v2: 18 | if (x2-x1) % (v2-v1) == 0: # if the gap between the initial positions is a multiple of the skips gap, they will meet 19 | answer = "YES" 20 | else: 21 | answer = "NO" 22 | else: 23 | answer = "NO" 24 | 25 | return answer 26 | 27 | if __name__ == '__main__': 28 | 29 | x1V1X2V2 = input().split() # read the input 30 | 31 | x1, v1, x2, v2 = int(x1V1X2V2[0]), int(x1V1X2V2[1]), int(x1V1X2V2[2]), int(x1V1X2V2[3]) # split the previous input on different lines 32 | 33 | print(kangaroo(x1, v1, x2, v2)) 34 | 35 | 36 | -------------------------------------------------------------------------------- /jim_orders.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/jim-and-the-orders/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | 10 | def jimOrders(orders): 11 | 12 | total = [] # list of lists 13 | 14 | for i in range(len(orders)): 15 | a = orders[i][0]+orders[i][1] 16 | total.append([i+1,a]) # the first element is the customer number, the second element is prep time + order number 17 | 18 | total = sorted(total, key=lambda x: x[1]) # sort the previous list according to ascending order 19 | 20 | ord = [] # array in which customer numbers will be stored 21 | 22 | for i in range(len(total)): 23 | ord += [total[i][0]] 24 | 25 | return ord 26 | 27 | 28 | 29 | if __name__ == '__main__': 30 | 31 | n = int(input()) 32 | 33 | orders = [] 34 | 35 | for _ in range(n): 36 | orders.append(list(map(int, input().rstrip().split()))) 37 | 38 | result = ''.join(map(str, jimOrders(orders))) 39 | 40 | print(result) 41 | -------------------------------------------------------------------------------- /beaut_pairs.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/beautiful-pairs/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | n = int(input().strip()) # size of A and B 10 | A = [int(number) for number in input().strip().split(' ')] 11 | B = [int(number) for number in input().strip().split(' ')] 12 | 13 | # sort both arrays 14 | 15 | A.sort() 16 | B.sort() 17 | a, b, counter = 0, 0, 0 # a and b are indices, counter is a variable 18 | 19 | while a < n and b < n: 20 | if A[a] > B[b]: # if the element in A is larger than the correspondent one in B, increase b by 1 21 | b += 1 22 | elif A[a] < B[b]: # if the element in A is smaller than the correspondent one in B, increase a by 1 23 | a += 1 24 | else: # if the element in A is equal to the correspondent one in B, raise counter by 1 and go ahead with the indices 25 | counter += 1 26 | a += 1 27 | b += 1 28 | 29 | if counter == n: 30 | print(n-1) # one value must be changed 31 | else: 32 | print(counter+1) 33 | -------------------------------------------------------------------------------- /cut_the_sticks.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge Cut the Sticks proposed on HackerRank at https://www.hackerrank.com/challenges/cut-the-sticks/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | 10 | # A list called occ contains the occurrences of all non-dubplicate elements from arr sorted into ascending order. 11 | # A list called recurr should start with len(arr) and go ahead with the difference between len(arr) and the first 12 | # element of occ. Iterating this process until the difference recurr[i]-occ[i] = 0 will solve the problem. 13 | 14 | def cutTheSticks(arr): 15 | 16 | occ = [arr.count(item) for item in sorted(list(set(arr)))] 17 | 18 | recurr = [len(arr)] 19 | 20 | for i in range(len(occ)): 21 | m = recurr[i]-occ[i] 22 | if m != 0: 23 | recurr.append(m) 24 | 25 | return recurr 26 | 27 | if __name__ == '__main__': 28 | 29 | n = int(input()) 30 | 31 | arr = list(map(int, input().rstrip().split())) 32 | 33 | result = cutTheSticks(arr) 34 | 35 | print('\n'.join(map(str, result))) 36 | 37 | 38 | -------------------------------------------------------------------------------- /strong_psw.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/strong-password/problem 3 | 4 | 5 | import math 6 | import random 7 | import re 8 | import sys 9 | 10 | # The function will initialize a variable count to 0, which will be raised by 1 for each character contained into 11 | # one of the sets of digits, lowercase, uppercase letters and symbols. Eventually, the function returns the maximum 12 | # between count and 6-n. We should remember that the minimum password length is indeed 6. 13 | 14 | def minimumNumber(n, password): 15 | 16 | 17 | count = 0 18 | 19 | if any(i.isdigit() for i in password) == False: 20 | count += 1 21 | if any(i.islower() for i in password) == False: 22 | count += 1 23 | if any(i.isupper() for i in password) == False: 24 | count += 1 25 | if any(i in '!@#$%^&*()-+' for i in password) == False: 26 | count += 1 27 | 28 | 29 | return max(count, 6 - n) 30 | 31 | 32 | if __name__ == '__main__': 33 | 34 | n = int(input()) 35 | 36 | password = input() 37 | 38 | answer = minimumNumber(n, password) 39 | 40 | print(str(answer)) 41 | -------------------------------------------------------------------------------- /making_anagrams.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/making-anagrams/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | # Once the two strings have been merged, we should count how many times a certain character appears in both. 10 | # If the character appears in both strings, we count the difference of the numbers of occurrences in the strings. 11 | # If the character appears in only one string, we count how many times it does. 12 | # The total count is exactly the number of letters we should delete to make an anagram. 13 | 14 | def makeAnagram(a, b): 15 | 16 | characters = list(set(a+b)) 17 | 18 | counts = 0 19 | 20 | for item in characters: 21 | if item in list(a) and item in list(b): 22 | counts += abs(a.count(item)-b.count(item)) 23 | elif item in list(a) and item not in list(b): 24 | counts += a.count(item) 25 | elif item in list(b) and item not in list(a): 26 | counts += b.count(item) 27 | 28 | return counts 29 | 30 | 31 | if __name__ == '__main__': 32 | 33 | a = input() 34 | 35 | b = input() 36 | 37 | res = makeAnagram(a, b) 38 | 39 | print(res) 40 | 41 | -------------------------------------------------------------------------------- /funny_strings.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge Funny String proposed on HackerRank at https://www.hackerrank.com/challenges/funny-string/problem 3 | 4 | 5 | import math 6 | import random 7 | import re 8 | import sys 9 | 10 | # After converting each letter of s to its ascii value, we do the same for the reverted string s. Two arrays 11 | # containing the absolute value of the differences between consecutive elements are then computed. 12 | # If the two arrays are equal, then we return "Funny", otherwise we return "Not Funny" 13 | 14 | def funnyString(s): 15 | 16 | ascii_values = [ord(item) for item in list(s)] 17 | 18 | ascii_values_rev = [ord(item) for item in list(s)[::-1]] 19 | 20 | diff_ascii_values = [abs(ascii_values[i+1]-ascii_values[i]) for i in range(len(ascii_values)-1)] 21 | diff_ascii_values_rev = [abs(ascii_values_rev[i+1]-ascii_values_rev[i]) for i in range(len(ascii_values_rev)-1)] 22 | 23 | 24 | if diff_ascii_values == diff_ascii_values_rev: 25 | return "Funny" 26 | else: 27 | return "Not Funny" 28 | 29 | 30 | if __name__ == '__main__': 31 | 32 | q = int(input()) 33 | 34 | for q_itr in range(q): 35 | s = input() 36 | 37 | result = funnyString(s) 38 | 39 | print(result) 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /guess_number.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Challenges proposed at https://www.codementor.io/@ilyaas97/6-python-projects-for-beginners-yn3va03fs 4 | 5 | import random 6 | import numpy as np 7 | 8 | 9 | # Guess the Number 10 | 11 | 12 | 13 | if __name__ == '__main__': 14 | 15 | num = np.random.randint(0,20) # random integer drawn from (0,20) 16 | 17 | # function to decide whether you have won or not 18 | # this function takes the guessed number as the argument and prints out three different messages 19 | # the number of available attempts is 6 20 | 21 | count = 0 22 | while count < 6: 23 | guess = int(input("Guess an integer between 0 and 20: ")) 24 | if num == guess: 25 | print("Congratulations, your guess is correct. You win!") 26 | break 27 | elif num < guess: 28 | print("Sorry, your guess is too high. Please, retry. You still have " + str(6-count) + " attempts left.") 29 | count += 1 30 | elif num > guess: 31 | print("Sorry, your guess is too low. Please, retry. You still have " + str(6-count) + " attempts left.") 32 | count += 1 33 | 34 | 35 | if num != guess: 36 | print("Sorry, you have lost. The number to guess was " + str(num)) 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Jclouds_rev.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge Jumping on Clouds: revisited proposed on HackerRank at https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited/problem 3 | 4 | import math 5 | import random 6 | import re 7 | import sys 8 | 9 | # In order to find the cumulative number of points lost, we should first check whether the length of c is a 10 | # multiple of k. If this happens, we just retain c. Otherwise, we would need to append to c a number of its copies 11 | # equal to k-1. This array is named c_long. Next, starting from the first element, we should make jumps on the 12 | # next clouds with a step size equal to k until completion. If we end up on 0, we should lower count by 1, 13 | # if we end up on 1, we should lower count by 3. 14 | 15 | def jumpingOnClouds(c, k): 16 | 17 | if len(c)%k == 0: 18 | c_long = c 19 | else: 20 | c_long = c*k 21 | 22 | count = 100 # initial score 23 | 24 | for i in range(0,len(c_long),k): 25 | if c_long[i] == 0: 26 | count -= 1 27 | else: 28 | count -= 3 29 | 30 | return count 31 | 32 | 33 | if __name__ == '__main__': 34 | 35 | nk = input().split() 36 | 37 | n = int(nk[0]) 38 | 39 | k = int(nk[1]) 40 | 41 | c = list(map(int, input().rstrip().split())) 42 | 43 | result = jumpingOnClouds(c, k) 44 | 45 | print(result) 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /missing_numbers.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution of the challenge Missing Numbers proposed on Hackerrank at https://www.hackerrank.com/challenges/missing-numbers/problem 3 | 4 | 5 | import math 6 | import random 7 | import re 8 | import sys 9 | 10 | # First, we need to get each element of brr only once, so we build a list called brrset containing all elements of brr without duplicates. 11 | # For each element of brrset, we should first find the number of occurrences of the same element in arr and brr and append this number to a new pair of lists. 12 | # After calculating the difference between the two lists and storing them into a list called diffs, for each non-zero element of diffs we should 13 | # retrieve the index of the corresponding element in brrset 14 | 15 | def missingNumbers(arr, brr): 16 | 17 | brrset = list(set(brr)) 18 | 19 | occ_arr, occ_brr = [], [] 20 | 21 | for item in brrset: 22 | occ_arr.append(arr.count(item)) 23 | occ_brr.append(brr.count(item)) 24 | 25 | diffs = [] 26 | 27 | for i in range(len(occ_arr)): 28 | diffs.append(occ_brr[i]-occ_arr[i]) 29 | 30 | missing = [] 31 | 32 | for i in range(len(diffs)): 33 | if diffs[i] != 0: 34 | missing.append(brrset[i]) 35 | 36 | return missing 37 | 38 | 39 | 40 | if __name__ == '__main__': 41 | 42 | n = int(input()) 43 | 44 | arr = list(map(int, input().rstrip().split())) 45 | 46 | m = int(input()) 47 | 48 | brr = list(map(int, input().rstrip().split())) 49 | 50 | result = missingNumbers(arr, brr) 51 | 52 | print(' '.join(map(str, result))) 53 | -------------------------------------------------------------------------------- /scissors_rock_paper.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Challenges proposed at https://www.codementor.io/@ilyaas97/6-python-projects-for-beginners-yn3va03fs 4 | 5 | import random 6 | import numpy as np 7 | import string 8 | 9 | # Rock, scissors, paper 10 | 11 | # A first function, representing the virtual player, will pick randomly an item between scissors, rock and paper 12 | # A second function compares the user input with the virtual player choice and prints out a statement. 13 | 14 | def virtual_player(): 15 | 16 | return random.choice(["scissors", "rock", "paper"]) 17 | 18 | def win_or_lose(guessed, virtual): 19 | 20 | if (guessed == "scissors" and virtual == "paper") or (guessed == "rock" and virtual == "scissors") or \ 21 | (guessed == "paper" and virtual == "rock"): 22 | statement = "Your rival has picked " + virtual + ". You win." 23 | elif (guessed == "paper" and virtual == "scissors") or (guessed == "scissors" and virtual == "rock") or \ 24 | (guessed == "rock" and virtual == "paper"): 25 | statement = "Your rival has picked " + virtual + ". You lose." 26 | else: 27 | statement = "Nobody wins. You are even." 28 | 29 | return statement 30 | 31 | 32 | if __name__ == '__main__': 33 | 34 | while True: 35 | try: 36 | choice = input("Pick between scissors, rock and paper: ").lower() 37 | break 38 | except ValueError: 39 | print("Error. Please, pick between scissors, rock and paper.") 40 | 41 | result = win_or_lose(choice, virtual_player()) 42 | print(result) 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /greedy_florist.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions of the challenge proposed on Hackerrank at https://www.hackerrank.com/challenges/greedy-florist/problem 3 | 4 | 5 | import math 6 | import random 7 | import re 8 | import sys 9 | 10 | # The idea behind the solution of the problem is that the most expensive flowers should be bought first and the cheapest 11 | # ones should be bought last. This will require to sort the c array into descending order and to multiply its first 12 | # elements (largest ones) by the lowest number of friends. A greedy algorithm built with this idea would yield the 13 | # optimal result. 14 | 15 | def getMinimumCost(k, c): 16 | 17 | c = sorted(c, reverse=True) # sort c according to descending order 18 | 19 | a = len(c) // k # quotient between n and k 20 | 21 | b = len(c) % k # reminder n mod k 22 | 23 | arr = [] 24 | 25 | # slice the list of costs, c, into sublists, each of length k 26 | 27 | if b == 0: 28 | for i in range(a): 29 | arr += [c[k*i : k*(i+1)]] 30 | else: 31 | for i in range(a): 32 | arr += [c[k * i:k * (i + 1)]] 33 | arr += [c[k * a:n]] 34 | 35 | sums = [] 36 | 37 | for i in range(len(arr)): 38 | sums += [sum(arr[i])] # to store the sums of the previous sublists 39 | 40 | prices = [sums[i] * (i+1) for i in range(len(sums))] # to save the prices of the greedy florist 41 | 42 | return sum(prices) 43 | 44 | 45 | if __name__ == '__main__': 46 | 47 | nk = input().split() 48 | 49 | n = int(nk[0]) 50 | 51 | k = int(nk[1]) 52 | 53 | c = list(map(int, input().rstrip().split())) 54 | 55 | print(getMinimumCost(k, c)) 56 | -------------------------------------------------------------------------------- /password_generator.py: -------------------------------------------------------------------------------- 1 | 2 | # Challenges proposed at https://www.codementor.io/@ilyaas97/6-python-projects-for-beginners-yn3va03fs 3 | 4 | import random 5 | import numpy as np 6 | import string 7 | 8 | # Password generator 9 | 10 | # function to create a random password 11 | # We should define some random variables. A first variable, p1, draws a number from (0.4, 0.7) that defines 12 | # the proportion of letters. If the password length is n, the proportion of letters will be given by int(p1*n). 13 | # The latter, p2, is uniformly drawn from (0.15, 0.3) and defines the proportion of special characters. 14 | # Moreover, we draw uniformly a variable, p, from (0,1), such that if it is bigger than 0.5, the appended letter is 15 | # uppercase, otherwise it is lowercase. Once the password has been created, we shuffle all its characters randomly. 16 | # Note that the minimum length of the password must be 7 and the previous intervals guarantee that the password contains 17 | # all of letters, characters and numbers with no exclusions. For example, even in the case p2 = 0.15 and n=7, 18 | # we would have at least b=1 special character. 19 | 20 | def create_psw(n): 21 | 22 | letters = "abcdefghijklmnopqrstuvwxyz" 23 | characters = ",-_.*'!?^|#@()[]{}&%$£/=+" 24 | numbers = "0123456789" 25 | 26 | p1 = np.random.uniform(0.4, 0.7) 27 | p2 = np.random.uniform(0.15,0.3) 28 | 29 | a = int(p1*n) # proportion of letters 30 | b = int(p2*n) # proportion of special characters 31 | c = n-b-a # proportion of numbers 32 | 33 | psw = "" 34 | 35 | 36 | for i in range(a): 37 | p = np.random.uniform(0, 1) 38 | if p > 0.5: 39 | psw += random.choice(letters).upper() 40 | else: 41 | psw += random.choice(letters).lower() 42 | 43 | for i in range(b): 44 | psw += random.choice(characters) 45 | 46 | for i in range(c): 47 | psw += random.choice(numbers) 48 | 49 | psw_list = list(psw) 50 | random.shuffle(psw_list) 51 | password = ''.join(psw_list) 52 | 53 | return password 54 | 55 | # Function to call if the password length is smaller than 6, in which case it would not be safe 56 | def error(): 57 | return "Sorry, this password length makes the password weak. Try with a length equal to or higher than 6." 58 | 59 | 60 | if __name__ == '__main__': 61 | 62 | while True: 63 | try: 64 | psw_length = int(input("Type the length of your password: ")) 65 | break 66 | except ValueError: 67 | print("Error. Type a number that indicates the length of your password.") 68 | 69 | if psw_length > 6: 70 | result = create_psw(psw_length) 71 | print(result) 72 | else: 73 | print(error()) 74 | 75 | 76 | -------------------------------------------------------------------------------- /hangman.py: -------------------------------------------------------------------------------- 1 | 2 | # Challenges proposed at https://www.codementor.io/@ilyaas97/6-python-projects-for-beginners-yn3va03fs 3 | 4 | import numpy as np 5 | import string 6 | import random 7 | import urllib.request 8 | 9 | def pick_a_word(): # function to download the library sowpods, composed of thousands of words 10 | 11 | url = "http://norvig.com/ngrams/sowpods.txt" 12 | 13 | file = urllib.request.urlopen(url) # download the file 14 | 15 | words = [] 16 | 17 | # decode the file using "UTF-8" and choose only words with more than 3 letters for a reason of game difficulty 18 | 19 | for line in file: 20 | if len(line.decode("utf-8")) > 3: 21 | words.append(line.decode("utf-8")) 22 | 23 | output_word = random.choice(words).lower() # convert to lowercase 24 | 25 | output_word = output_word[0:len(output_word)-1] # delete the final character, "\n" 26 | 27 | return output_word 28 | 29 | # function to guess the word. It should return only the first and the last letter of the word to guess 30 | 31 | def guess_a_letter(word): 32 | 33 | m = len(word) # length of the word to guess 34 | lett_list = ['-']*m # build a list composed of hyphens and with length equal to m 35 | lett_list[0], lett_list[m-1] = word[0], word[m-1] 36 | # replace the first and the last hyphen with the first and the last letter 37 | 38 | return ''.join(map(str, lett_list)) # return the list converted into a string 39 | 40 | # function to fill the word with the exact letters 41 | 42 | def locate_letter(incomplete_word, complete_word, let): 43 | 44 | incomp_list = list(incomplete_word) 45 | comp_list = list(complete_word) 46 | 47 | # the exact letter should be appended to the incomplete word 48 | 49 | for i in range(len(comp_list)): 50 | if let == comp_list[i]: 51 | incomp_list[i] = let 52 | 53 | return ''.join(map(str, incomp_list) # return the incomplete word filled with the exact letters 54 | 55 | 56 | if __name__ == '__main__': 57 | 58 | word_to_guess = pick_a_word() 59 | to_guess = guess_a_letter(word_to_guess) 60 | 61 | print("Welcome, you are playing hangman. The word you should guess is: ", to_guess) 62 | 63 | # the total number of attempts by the user should not overcome 6 64 | 65 | count = 0 66 | while count < 7: 67 | if to_guess != word_to_guess: 68 | l = str(input("Type a letter, please:")).lower() # l = letter typed by the user 69 | if l in word_to_guess[1:len(word_to_guess)-1]: # is l one of the letters of the word, different from the first and the last one? 70 | print("The word becomes", locate_letter(to_guess, word_to_guess, l)) 71 | to_guess = locate_letter(to_guess, word_to_guess, l) 72 | else: # if l does not belong to the word, decrease the number of available attempts by 1 73 | count += 1 74 | print("Sorry, this letter does not belong to the word. You still have " + str(7 - count) + " attempts left.") 75 | 76 | 77 | 78 | if to_guess != word_to_guess: 79 | print("Sorry, you lose. The word was: "+str(word_to_guess)) 80 | else: 81 | print("Congratulations, you win.") 82 | 83 | 84 | 85 | 86 | 87 | 88 | --------------------------------------------------------------------------------