blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
93acee56de7fa9fca2d2514f708b04f73af009d7
zayntoorawa/PythonLockdownGame
/Gamecode.py
18,325
4
4
# For the code lets say: # At the beginning of the code, we have a print to explain the game! # Then an input asking the user to pree enter to start the game ! # And then we have ten methods one per question they'll be called in sequences from q one to q ten ! # Every method contain print for the questions and the answers form 1 to 4, and int(input) so the user can pick a number # Four global variables one per lockdown! # At the end we have an if condition to print the result depending on the score form the global variables ! import sys counter_lockdown1=0 counter_lockdown2=0 counter_lockdown3=0 counter_lockdown4=0 def the_game(): q_one() q_two() q_three() q_four() q_five() q_six() q_sven() q_eight() q_nine() q_ten() check_the_res() print("#################################################################################################") print("# What lockdown are you! #") print("# Find out what lockdown you are from your favourite things! #") print("#################################################################################################") start_the_game= input(" -_- Press enter to start the game -_- ") ###################### Question 1 ################################ def q_one(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("1-What's your Favourite Season?\n\n") # Spring 1, Summer 2, Autumn 3, Winter 4 print("1-Spring\n2-Summer\n3-Autumn\n4-Winter \n\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 1: counter_lockdown1 += 1 elif the_answer == 2: counter_lockdown2 += 1 elif the_answer == 3: counter_lockdown3 += 1 elif the_answer == 4: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_one() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 2 ####################################### def q_two(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("2-What's your Favourite Colour Combination?\n\n") #Rainbow 1, Pastel 2, Warm 3, Cool 4 print("1-Rainbow\n2-Pastel\n3-Warm\n4-Cool\n\n ") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list:")) if the_answer == 1: counter_lockdown1 += 1 elif the_answer == 2: counter_lockdown2 += 1 elif the_answer == 3: counter_lockdown3 += 1 elif the_answer == 4: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_two elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 3 ####################################### def q_three(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("3-What's your Favourite Exercise?\n\n") # Running 1, Gym 2, Nothing 3, Zoom Workouts 4 print("1-Running\n2-Gym\n3-Nothing\n4-Zoom Workouts\n\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 2: counter_lockdown1 += 1 elif the_answer == 1: counter_lockdown2 += 1 elif the_answer == 4: counter_lockdown3 += 1 elif the_answer == 3: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_three() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 4 ####################################### def q_four(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("4-What's your Favourite Mealtime?\n\n") # Breakfast 1, Lunch 2, Dinner 3, Brunch 4 print("1-Breakfast\n2-Lunch\n3-Dinner\n4-Brunch\n\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 3: counter_lockdown1 += 1 elif the_answer == 4: counter_lockdown2 += 1 elif the_answer == 1: counter_lockdown3 += 1 elif the_answer == 2: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_four() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 5 ####################################### def q_five(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("5-What's your Favourite TV Genre?\n\n") #TV Genre – Action 1, Romance 2, Horror 3, Comedy 4 print("1-Action\n2-Romance\n3-Horror\n4-Comedy\n\n ") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 4: counter_lockdown1 += 1 elif the_answer == 3: counter_lockdown2 += 1 elif the_answer == 2: counter_lockdown3 += 1 elif the_answer == 1: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_five() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 6 ####################################### def q_six(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("6-What's your Favourite Music Genre?\n\n") # Music Genre – Pop 1, Country 2, R&B 3, Rock 4 print("1-Pop\n2-Country\n3-R&B\n4-Rock\n\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 1: counter_lockdown1 += 1 elif the_answer == 2: counter_lockdown2 += 1 elif the_answer == 3: counter_lockdown3 += 1 elif the_answer == 4: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_six() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 7 ####################################### def q_sven(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("7-What's your Favourite Social Media App?\n\n") #Social Media App – House Party 1, Instagram 2, Twitter 3, TikTok 4 print("1-House Party\n2-Instagram\n3-Twitter\n4-TikTok\n\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 1: counter_lockdown1 += 1 elif the_answer == 2: counter_lockdown2 += 1 elif the_answer == 3: counter_lockdown3 += 1 elif the_answer == 4: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_sven() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 8 ####################################### def q_eight(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("8-What's your Favourite Outfit?\n\n") #– Loungewear 1, Fancy 2, Work Wear 3, Gym Wear 4 print("1-Loungewear\n2-Fancy\n3-Work Wear\n4-Gym Wear\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 4: counter_lockdown1 += 1 elif the_answer == 3: counter_lockdown2 += 1 elif the_answer == 2: counter_lockdown3 += 1 elif the_answer == 1: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_eight() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 9 ####################################### def q_nine(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("9-What's your Favourite Type of Hoarder?\n\n") #Toilet Paper 1, Hand Sanitizer 2, Fruit 3, Cupboard food 4 print("1-Toilet Paper\n2-Hand Sanitizer\n3-Fruit\n4-Cupboard Food\n ") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 1: counter_lockdown1 += 1 elif the_answer == 2: counter_lockdown2 += 1 elif the_answer == 3: counter_lockdown3 += 1 elif the_answer == 4: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_nine() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() ########################## Question 10 ####################################### def q_ten(): print("#############################################################################################") global counter_lockdown1 global counter_lockdown2 global counter_lockdown3 global counter_lockdown4 print("10-What's your Favourite Pass Time?\n\n") #Reading 1, Gaming 2, Watching TV 3, Learning a New Skill 4, print("1-Reading\n2-Gaming TV\n3-Watching TV\n4-Learning a New Skill\n") print("Press 0+Enter to skip - 9+Enter to exit the game - 8+Enter to restart the game\n") print("Pssst... Type the numbers not the words!\n") the_answer= int(input("Select form the list: ")) if the_answer == 1: counter_lockdown1 += 1 elif the_answer == 2: counter_lockdown2 += 1 elif the_answer == 3: counter_lockdown3 += 1 elif the_answer == 4: counter_lockdown4 += 1 elif the_answer not in [1, 2, 3, 4, 9, 0, 8]: print(" \nPlese select from the above list ! ") q_ten() elif the_answer == 9: print("Thanks !") sys.exit() elif the_answer == 0: pass elif the_answer == 8: the_game() def check_the_res(): def computer(): print(" ,---------------------------, ") print(" | /---------------------\ | ") print(" | | | | ") print(" | | THANK YOU | | ") print(" | | FOR | | ") print(" | | PLAYING! | | ") print(" | | | | ") print(" | \_____________________/ | ") print(" |___________________________| ") print(" ,---\_____ [] _______/------, ") print(" / /______________\ /| ") print(" /___________________________________ / |__ ") print(" | | | ) ") print(" | _ _ _ [-------] | | ( ") print(" | o o o [-------] | / )_ ") print(" |__________________________________ |/ / / ") print(" /-------------------------------------/ /()/ ") print(" /-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-// ") print(" /-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-// ") print(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ") if counter_lockdown1 > counter_lockdown2 and counter_lockdown1> counter_lockdown3 and counter_lockdown1 >counter_lockdown4: print("*************************************************************************************") print("* You are in Lockdown One! *") print("You love to stick to the rules, and you really value the key workers who keep you safe.\n#ClapfortheNHS") print("*************************************************************************************") computer() elif counter_lockdown2 > counter_lockdown1 and counter_lockdown2> counter_lockdown3 and counter_lockdown2 >counter_lockdown4: print("*************************************************************************************") print("* You are in Lockdown Two! *") print("You are a party animal and love to be round your friends having fun and enjoying food!\n#EatOuttoHelpOut") print("*************************************************************************************") computer() elif counter_lockdown3 > counter_lockdown1 and counter_lockdown3> counter_lockdown2 and counter_lockdown3 >counter_lockdown4: print("*************************************************************************************") print("* You are in Lockdown Three! *") print("Back inside again! You love to troll the forums and addicted to watching Boris \n“try” and control the nation. #ChristmasTiers") print("*************************************************************************************") computer() elif counter_lockdown4 > counter_lockdown1 and counter_lockdown4> counter_lockdown2 and counter_lockdown4 >counter_lockdown3: print("*************************************************************************************") print("* You are in Lockdown Four! *") print("Time to achieve those new year’s resolutions! That is all you can do anyways…\n#Lockdownneverends") print("*************************************************************************************") computer() ending_option=input("Type E+Enter to exit the game or P+Enter to play again -_-") if ending_option == "E": print("Thanks !") elif ending_option=="P": the_game() q_one() q_two() q_three() q_four() q_five() q_six() q_sven() q_eight() q_nine() q_ten() check_the_res() the_game() # print(counter_lockdown1) # print(counter_lockdown2) # print(counter_lockdown3) # print(counter_lockdown4)
077272c7209aa0cad6370beb1b020642bc464334
htchoi1006/python_algorithm
/뒤집은 소수/뒤집은소수.py
806
3.890625
4
''' 문제 n개의 자연수가 입력되면 각 자연수를 뒤집은 후 뒤집은 수가 소수이면 그 수를 출력하는 프로그램을 작성하라. 뒤집는 함수인 def reverse(x)와 소수인지를 확인하는 함수 def isPrime(x)을 반드시 작성하라. ''' import math import sys sys.stdin = open("input.txt", "r") def reverse(x): res = 0 while(x > 0): t = x%10 res = res*10 + t x = x//10 return res def isPrime(x): if(x == 1): return False cnt = 0 for i in range(2, int(math.sqrt(x))+1): if(x%i == 0): return False else: return True n = int(input()) a = list(map(int, input().split())) for i in a: tmp = reverse(i) if (isPrime(tmp)): print(tmp)
c40e5df2a97060a3bd3195dfe1ee6b083f62a5fc
AdityaAshvin/amfoss-tasks
/task 2/hackerrank/time-conversion.py
501
4.03125
4
string1 = input() if (string1[-2:] == "AM" and string1[ :2] == "12"): print( "00" + string1[2:-2]) #checking if the last two digits of the string is AM or PM and changing 12 with 00 elif (string1[-2: ] == "AM"): print(string1[ :-2]) #dropping AM elif (string1[-2:] == "PM" and string1[ :2] == "12"): print( "12" + string1[2:-2]) else: print(str(int(string1[:2]) + 12) + string1[2:8]) #printing in 24 hour format.
ec6d711859a35f36d13f2585839371a7ed32f241
CaCampos/ProjetoPython
/strings e funções.py
1,555
4.25
4
"""primeiro exemplo""" def checar_ocorrencias_letra_em_texto(texto, checar_letra): numero_ocorrencias = 0 for indice in range(len(texto)): letra = texto[indice] if checar_letra == letra: numero_ocorrencias = numero_ocorrencias + 1 return numero_ocorrencias texto_usuario = input("Digite um texto: ") letra_usuario = input("Digite uma letra: ") ocorrencias = checar_ocorrencias_letra_em_texto(texto_usuario, letra_usuario) print("A letra '{}' está presente {} vezes no texto '{}'.".format(letra_usuario, ocorrencias, texto_usuario)) """segundo exemplo""" def contar_numeros_pequenos(numeros): total = 0 for numero in numeros: if numero < 10: total = total + numero return total lista = [1,2,3, 20, 50, 100, 150, 200] total_soma = contar_numeros_pequenos(lista) print(total_soma) def somar(numero1, numero2, numero3, numero4): print("somar") print(numero1) print(numero2) print(numero3) print(numero4) total = numero1 + numero2 + numero3 + numero4 print(total) return total resultado = somar(1,2,3,4) print(resultado * 12) """exemplo com args""" def somar(*numeros): print("somar") print(numeros) total = sum(numeros) print(total) return total resultado = somar (1,2,3,4,5,6,7,8,9,10) print(resultado * 600) """exemplo com listas""" def criar_lista(quantidade_numeros): print("criar lista") lista = [] for numero in range (quantidade_numeros): numero_digitado = int(input("Digite o {}º número: "))
417df046a337be6d529ad2db614c8fd9eabe8ed9
Iron-Rush/python_pycharm
/day7/Recursive.py
708
3.9375
4
# Recursive.py # n! n的阶乘,递归求法 def fact(n): if n == 0: #n=0为基例,停止递归,返回1 return 1 else: return n * fact(n-1) #递归,继续求解 # 字符串反转递归求法 def rvs(s): if s == '': #若s为空,返回s本身 return s else: #对s初首字符之外进行反转,并将首字符拼接至末尾 return rvs(s[1:]) + s[0] # 斐波那契数列 1、1、2、3、5、8、13、21、34、… # F(n) = F(n-1) + F(n-2) def f(n): if n == 1 or n == 2: return 1 else: return f(n-1) + f(n-2) out = fact(5) print(out) strIn = "你好啊~" strOut = rvs(strIn) print(strOut) print(f(10))
8489165fbd98926d00b18d3e3fdbd62fe71e67f7
harkhuang/harkcode
/python/study_myself/7_io_opt/7_5_writefile.py
465
3.515625
4
fileread = open('abc.txt') try: all_the_text = fileread.read() print all_the_text finally: fileread.close #write string output1 = open('data','w') #write binary output1 = open('data','wb') #write append output1 = open('data','w+') file1 = open('thefile.txt','w') file1.write(all_the_text) file1.close() file2 = open('thefile.txt','r') try: all_the_text = file2.read() print all_the_text finally: file2.close()
dee72e7d2e262a25ef6b409ba606e50cbd63bb2c
brianchiang-tw/leetcode
/2020_July_Leetcode_30_days_challenge/Week_1_Arranging Coins/by_math.py
1,551
4.0625
4
''' Description: You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3. ''' from math import sqrt class Solution: def arrangeCoins(self, n: int) -> int: #quick response if n <= 1: return n #solve k(k+1)/2 <= n , keep k as large as possible k = int( (-1 + sqrt( 1 + 8*n )) / 2 ) return k # Time Complexity: O( 1 ) # # The overhead in time is the cost of formula computation, which is of O( 1 ) ## Space Complexity: O( 1 ) # # The overhead in space is the storage for temporary variable, which is of O( 1 ) import unittest class Testing( unittest.TestCase ): def test_case_1( self ): result = Solution().arrangeCoins( n = 5 ) self.assertEqual( result, 2) def test_case_2( self ): result = Solution().arrangeCoins( n = 8 ) self.assertEqual( result, 3) def test_case_3( self ): result = Solution().arrangeCoins( n = 11 ) self.assertEqual( result, 4) if __name__ == '__main__': unittest.main()
156009d99c5653cf26b218ad2660d47fa6896b8c
DariaKnyazeva/project_euler
/tests/tests_problems050_100.py
3,615
3.75
4
import unittest from problems.p054 import Card, Hand, Game class Problem54Test(unittest.TestCase): def test_card(self): card1 = Card("TS") card2 = Card("9S") self.assertTrue(card1 > card2) def test_hand_high_card(self): hand = Hand("8C TS KC 9H 4S 7D 2S 5D 3S AC") self.assertEqual(14, hand.high_card()) hand = Hand("2C 5C 7D 8S QH") self.assertEqual(12, hand.high_card()) def test_hand_one_pair(self): hand = Hand("QD AS 6H JS 2C") self.assertEqual(0, hand.pair()) hand = Hand("2C 5C QD QH") self.assertEqual(12, hand.pair()) def test_hand_two_pairs(self): hand = Hand("QD QH 2C 2H") self.assertEqual(12, hand.two_pairs()) hand = Hand("2C 2H 2D 2S") self.assertEqual(2, hand.two_pairs()) def test_hand_three_of_a_kind(self): hand = Hand("2C 2H QD QH") self.assertEqual(0, hand.three_of_a_kind()) hand = Hand("2C 2H 2D QH") self.assertEqual(2, hand.three_of_a_kind()) def test_hand_straight(self): hand = Hand("2C 2H QD QH") self.assertEqual(0, hand.straight()) hand = Hand("2C 3H 4D 5H") self.assertEqual(5, hand.straight()) def test_hand_flush(self): hand = Hand("2C 2H QD QH") self.assertFalse(hand.flush()) hand = Hand("2C 3C QC KC") self.assertTrue(hand.flush()) def test_hand_full_house(self): hand = Hand("2C 2H QD QH AC") self.assertFalse(hand.full_house()) hand = Hand("2C 2H 2S KC KH") self.assertTrue(hand.full_house()) hand = Hand("2C 2H 2S 2D KH") self.assertFalse(hand.full_house()) def test_hand_four_of_a_kind(self): hand = Hand("2C 2H QD QH AC") self.assertFalse(hand.four_of_a_kind()) hand = Hand("2C 2H 2D 2S AC") self.assertEqual(2, hand.four_of_a_kind()) def test_hand_straigt_flush(self): hand = Hand("2C 3C 4C 5C 6C") self.assertTrue(hand.straight_flush()) hand = Hand("2C 3C 4C 5C TC") self.assertFalse(hand.straight_flush()) hand = Hand("2C 3C 4C 5C 6S") self.assertFalse(hand.straight_flush()) def test_hand_royal_flush(self): hand = Hand("2C 2H QD QH AC") self.assertFalse(hand.royal_flush()) hand = Hand("TC JC QC KC AC") self.assertTrue(hand.royal_flush()) hand = Hand("TC JC QC KC AD") self.assertFalse(hand.royal_flush()) def test_game_win_with_pair(self): """ Checking the scenario Player 1 Player 2 Winner 1 5H 5C 6S 7S KD 2C 3S 8S 8D TD Player 2 Pair of Fives Pair of Eights """ game = Game("5H 5C 6S 7S KD 2C 3S 8S 8D TD") self.assertEqual("5H 5C 6S 7S KD", str(game.hand1)) self.assertEqual("2C 3S 8S 8D TD", str(game.hand2)) self.assertEqual(0, game.win()) def test_game_win_with_highest_card(self): """ Testing the scenario Player 1 wins with Highest card 5D 8C 9S JS AC 2C 5C 7D 8S QH Highest card Ace Highest card Queen """ game = Game("5D 8C 9S JS AC 2C 5C 7D 8S QH") self.assertEqual(1, game.win()) def test_game_win(self): game = Game("2D 9C AS AH AC 3D 6D 7D TD QD") self.assertEqual(0, game.win()) game = Game("4D 6S 9H QH QC 3D 6D 7H QD QS") self.assertEqual(1, game.win()) game = Game("2H 2D 4C 4D 4S 3C 3D 3S 9S 9D") self.assertEqual(1, game.win()) unittest.main()
cd8b9591961be54a9073087a7c00abb98a7a3385
SagnikDev/Infytq-Programme-Codes
/Dynamic Programming/Knapsack/rod_cutting_problem.py
574
3.859375
4
length=[1,2,3,4,5,6,7,8] price=[1,5,8,9,10,17,17,20] n=8 table=[[None for i in range(n+1)] for j in range(n+1)] for row in range(0,n+1): for column in range(0,n+1): if(row==0 or column==0): table[row][column]=0 for row in range(1,n+1): for column in range(1,n+1): if(length[row-1]<=column): table[row][column]=max(price[row-1]+table[row][column-length[row-1]],table[row-1][column]) else: table[row][column]=table[row-1][column] for i in table: print(i) print("Maximum price:") print(table[n][n])
f73a4309408d2025a9effdfc186c9aea503e30b4
yair-go/Functional-Programming
/Lectures/Decarators/Dec.py
385
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 23 23:11:10 2018 @author: Yair """ def plus1(some_func): def inner(*args): print ("before ...") ret = some_func(*args) return ret + 1 return inner def foo(x): return 2 * x @plus1 def bar(x): return 3 * x if __name__ == "__main__" : dec = plus1(foo) print (dec(4)) print (bar(2))
0933c7665c48866446ed499657d40633828632b4
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_201/2890.py
2,823
3.71875
4
import sys import random def open_file(file_name, mode): try: the_file = open(file_name, mode) except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the enter key to exit.") sys.exit() else: return the_file def next_line(the_file): line = the_file.readline() line = line.replace("\n", "") return line def getSpace(initial): StartPos = [] Size = [] TempInt = 0 j = 0 while j <= len(Initial)-1: k = Initial[j] if k == "." and TempInt == 0: TempInt += 1 StartPos.append(j+1) elif k == ".": TempInt += 1 elif k == "O" and TempInt > 0: Size.append(TempInt) TempInt = 0 j += 1 Stop = "N" z = max(Size) j = 0 while j <= len(Size)-1 and Stop == "N": k = Size[j] if k == z: Start = StartPos[j] Stop = "Y" else: j += 1 Array = [z, Start] return Array def getMiddle(z, Size, StartPos): if Size%2 == 0: Position = (StartPos-1) + (Size / 2) else: Position = (StartPos-1) + ((Size + 1) / 2) return Position file = open("C-small-1-attempt0.in") Count = int(next_line(file)) MaxA = [] MinA = [] i = 0 while i <= Count-1: z = next_line(file).split() N = int(z[0]) K = int(z[1]) Initial = "O" + ("." * N) + "O" ToiletA = [] ToiletA.append(Initial) j = 0 while j <= (K - 1): Initial = ToiletA[len(ToiletA)-1] z = getSpace(Initial) Size = z[0] StartPos = z[1] Position = int(getMiddle(z, Size, StartPos)) Part1 = Initial[:(Position - 1)] Part2 = "O" Part3 = Initial[Position:] Final = Part1 + Part2 + Part3 ToiletA.append(Final) j += 1 Final = ToiletA[len(ToiletA)-1] Stop = "N" Left = 0 LeftS = Final[:(Position-1)] j = len(LeftS)-1 while j >= 0 and Stop == "N": k = LeftS[j] if k == ".": Left += 1 else: Stop = "Y" j -= 1 Stop = "N" Right = 0 RightS = Final[Position:] j = 0 while j <= len(RightS)-1 and Stop == "N": k = RightS[j] if k == ".": Right += 1 else: Stop = "Y" j += 1 MinA.append(min(Left, Right)) MaxA.append(max(Left, Right)) i += 1 file.close() file = open_file("C output small.in", "a") i = 0 while i <= Count-1: file.write("Case #" + str(i+1) + ": " + str(MaxA[i]) + " " + str(MinA[i]) + "\n") i += 1 file.close()
1a822ef911d77660abb8522eea2e0f6af8fdaa64
hoatd/Ds-Algos-
/GeeksforGeeks/Random-problems/permutation.py
539
3.59375
4
def permute(s, l, r): if l == r: if s == None: pass else: print(s) else: for i in range(l, r): #swapping characters lst = list(s) tmp=lst[l] lst[l]=lst[i] lst[i]=tmp s=''.join(lst) permute(s, l+1, r) #backrack lst = list(s) tmp=lst[l] lst[l]=lst[i] lst[i]=tmp s=''.join(lst) s = "ABC" l = 0 r = len(s) print(permute(s, l, r))
176e3375bf0622f304fd54715f1a68140378b305
sdotpeng/Python_Jan_Plan
/Feb_2/student.py
1,261
4.21875
4
'''student.py Our very first class on OOP! Represents a Student TODO: Make Student class with methods: - Construtor with 2 parameters: name and year - get methods - set year method Main code: - Create two students - Get and print their names and years - Set one of their years - Print both years ''' class Student: # Constructor def __init__(self, name, gradYear): '''This is the constructor self is always the first parameter for a class method. It is a ''bundle of instance variables'' for the current object ''' # Create internal values for name and gradYear self.name = name # Tell Python we want to save info as an internal value self.year = gradYear # IVs don't need to have the same name as parameters def __len__(self): return 0 def getName(self): return self.name # You CAN NOT DO THIS: # return name # name went away after constructor ended def getGradYear(self): return self.year if __name__ == '__main__': Yixin = Student('Yixin', 2024) print(Yixin.getName()) print(Yixin.getGradYear()) print(len(Yixin)) # len([1,23]) # len('str') # def len(object): # return object.__len__()
0a15b2a63c2fdd742abcae1e3794a9191b28cbc9
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_06_dictionaries/cubes.py
1,614
4.375
4
""" Alice and Bob like to play with colored cubes. Each child has its own set of cubes and each cube has a distinct color, but they want to know how many unique colors exist if they combine their block sets. To determine this, the kids enumerated each distinct color with a random number from 0 to 108. At this point their enthusiasm dried up, and you are invited to help them finish the task. Given two integers that indicate the number of blocks in Alice's and then Bob's sets N and M. The following N lines contain the numerical color value for each cube in Alice's set. Then the last M rows contain the numerical color value for each cube in Bob's set. Find three sets: the numerical colors of cubes in both sets, the numerical colors of cubes only in Alice's set, and the numerical colors of cubes only in Bob's set. For each set, print the number of elements in the set, followed by the numerical color elements, sorted in ascending order. """ def print_set(example_set): print(len(example_set)) for i in example_set: print(i) def main(): cubes = [int(cubes) for cubes in input().split()] alice_cubes = set() bob_cubes = set() for i in range(cubes[0]): alice_cubes.add(int(input())) for i in range(cubes[1]): bob_cubes.add(int(input())) intersection = alice_cubes & bob_cubes alice_only = alice_cubes - bob_cubes bob_only = bob_cubes - alice_cubes sorted(intersection) sorted(alice_only) sorted(bob_only) print_set(intersection) print_set(alice_only) print_set(bob_only) if __name__ == '__main__': main()
32d76d2508f42ec91e2df741c46156ecafb28922
ivanpetrushev/pynsects
/nn2.py
1,093
4
4
import numpy as np # https://enlight.nyc/projects/neural-network/ class NeuralNetwork: def __init__(self, inputSize = 2, outputSize = 2, hiddenSize = 4): #parameters self.inputSize = inputSize self.outputSize = outputSize self.hiddenSize = hiddenSize self.randomize() def randomize(self): #weights self.W1 = np.random.randn(self.inputSize, self.hiddenSize) # (3x2) weight matrix from input to hidden layer self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # (3x1) weight matrix from hidden to output layer def run(self, X): #forward propagation through our network self.z = np.dot(X, self.W1) # dot product of X (input) and first set of 3x2 weights self.z2 = self.sigmoid(self.z) # activation function self.z3 = np.dot(self.z2, self.W2) # dot product of hidden layer (z2) and second set of 3x1 weights o = self.sigmoid(self.z3) # final activation function return o def sigmoid(self, s): # activation function return 1/(1+np.exp(-s))
765522cc9d9734458ca873a32ca1da9e1f72d740
adhirajgupta/vihan-code
/lenofnum.py
143
3.796875
4
no = int(input("enter no to find length")) cnt =0 while(no>0): a = no % 10 cnt= cnt+1 no = no // 10 print("len of no = ",cnt)
9b250372ee6b3756314e15f750ae06bc4b02071c
Python-with-Friyank/Python-Basics
/Python Hello World/Python Hello World/Classes.py
320
3.921875
4
# Class class Point: # Constructor def __init__(self,X,Y): self.x = X self.y = Y # MEthods of Class def move(self): print(f"Move {self.x} , {self.y}") # Method of Class def Draw(self): print(f"Draw {self.x} {self.y}") pointObj = Point(11,22) pointObj.move()
f58fa6324894c4e65abe48c862f4556f4562fe17
deadydragon/Ranger
/SecondLesson.py
712
3.671875
4
import pygame WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) sizy = input().split() side = int(sizy[1]) - 1 N = int(sizy[0]) K = int(sizy[1]) pygame.init() size = width, height = N * K * 3 * 2, N * K * 3 * 2 screen = pygame.display.set_mode(size) def draw(): screen.fill((0, 0, 0)) for i in range(K): pygame.draw.circle(screen, BLUE, (K * N * 3, K * N * 3), ((K - i) * N * 3)) pygame.draw.circle(screen, GREEN, (K * N * 3, K * N * 3), ((K - i) * N * 3) - N) pygame.draw.circle(screen, RED, (K * N * 3, K * N * 3), ((K - i) * N * 3) - N * 2) pygame.display.flip() while pygame.event.wait().type != pygame.QUIT: draw() pygame.quit()
7c26bcc02a1a3d72f47bbb294a13a8b8cf73f9c1
ray-abel12/python
/student_score.py
1,003
4.125
4
def getInput(): while True: try: grade = int(input("enter grade number ")) if 0 <= grade <= 100: return grade print('score should be between 1 1nd 100!\n') except: print("invalid input") def determine_grade(grade): if(grade >= 70 ) & (grade <= 100): return 'A' elif(grade >= 60) & (grade <= 69): return 'B' elif(grade >= 50) & (grade <= 59): return 'C' elif(grade >= 45) & (grade <= 49): return 'D' elif(grade >= 40) & (grade <= 45): return 'E' elif(grade >= 0) & (grade <= 39): return 'F' else: return 'no value entered' grade= getInput() #determine_grade(grade) print(determine_grade(grade)) def readScore(filepath): ''' create another file that contain the student names and their grades ''' student_score = open(filepath) for score in file: gradeScore(grade) open('stuednt_grade.txt','w') return
d76f88088784c5fd1fee7f950fd22a67bd30fb38
vikasptl07/DataBricks
/Notebooks/Learning-Spark/Python/Chapter05/higher-order-functions-tutorial-python (1).py
24,902
3.765625
4
# Databricks notebook source # MAGIC %md # Higher-Order and Lambda Functions: Explore Complex and Structured Data in SQL # COMMAND ---------- # MAGIC %md This tutorial walks you through four higher-order functions. While this in-depth [blog](https://databricks.com/blog/2017/05/24/working-with-nested-data-using-higher-order-functions-in-sql-on-databricks.html) explains the concepts, justifications, and motivations of _why_ handling complex data types such as arrays are important in SQL, and equally explains why their existing implementation are inefficient and cumbersome, this tutorial shows _how_ to use higher-order functions in SQL in processing structured data and arrays in IoT device events. In particular, they come handy and you can put them to good use if you enjoy functional programming and can quickly and can efficiently write a lambda expression as part of these higher-order SQL functions. # MAGIC # MAGIC This tutorial explores four functions and how you can put them to a wide range of uses in your processing and transforming array types: # MAGIC # MAGIC * `transform()` # MAGIC * `filter()` # MAGIC * `exists()` # MAGIC * `aggregate()` # MAGIC # MAGIC The takeaway from this short tutorial is that there exists myriad ways to slice and dice nested JSON structures with Spark SQL utility functions. These dedicated higher-order functions are primarily suited to manipulating arrays in Spark SQL, making it easier and the code more concise when processing table values with arrays or nested arrays. # COMMAND ---------- # MAGIC %md Let's create a simple JSON schema with attributes and values, with at least two attributes that are arrays, namely _temp_ and _c02_level_ # COMMAND ---------- from pyspark.sql.functions import * from pyspark.sql.types import * schema = StructType() \ .add("dc_id", StringType()) \ .add("source", MapType(StringType(), StructType() \ .add("description", StringType()) \ .add("ip", StringType()) \ .add("id", IntegerType()) \ .add("temp", ArrayType(IntegerType())) \ .add("c02_level", ArrayType(IntegerType())) \ .add("geo", StructType() \ .add("lat", DoubleType()) \ .add("long", DoubleType())))) # COMMAND ---------- js="""{ "dc_id": "dc-101", "source": { "sensor-igauge": { "id": 10, "ip": "68.28.91.22", "description": "Sensor attached to the container ceilings", "temp":[35,35,35,36,35,35,32,35,30,35,32,35], "c02_level": [1475,1476,1473], "geo": {"lat":38.00, "long":97.00} }, "sensor-ipad": { "id": 13, "ip": "67.185.72.1", "description": "Sensor ipad attached to carbon cylinders", "temp": [45,45,45,46,45,45,42,35,40,45,42,45], "c02_level": [1370,1371,1372], "geo": {"lat":47.41, "long":-122.00} }, "sensor-inest": { "id": 8, "ip": "208.109.163.218", "description": "Sensor attached to the factory ceilings", "temp": [40,40,40,40,40,43,42,40,40,45,42,45], "c02_level": [1346,1345, 1343], "geo": {"lat":33.61, "long":-111.89} }, "sensor-istick": { "id": 5, "ip": "204.116.105.67", "description": "Sensor embedded in exhaust pipes in the ceilings", "temp":[30,30,30,30,40,43,42,40,40,35,42,35], "c02_level": [1574,1570, 1576], "geo": {"lat":35.93, "long":-85.46} } } }""" # COMMAND ---------- df=spark.createDataFrame(sc.parallelize(js),schema) # COMMAND ---------- # MAGIC %md This helper Python function converts a JSON string into a [Python DataFrame](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.html#pyspark-sql-dataframe). # COMMAND ---------- # Convenience function for turning JSON strings into DataFrames. def jsonToDataFrame(json, schema=None): # SparkSessions are available with Spark 2.0+ reader = spark.read if schema: reader.schema(schema) return reader.json(sc.parallelize([json])) # COMMAND ---------- # MAGIC %md Using the schema above, create a complex JSON stucture and create into a Python DataFrame. Display the DataFrame gives us two columns: a key (dc_id) and value (source), which is JSON string with embedded nested structure. # COMMAND ---------- dataDF = jsonToDataFrame( """{ "dc_id": "dc-101", "source": { "sensor-igauge": { "id": 10, "ip": "68.28.91.22", "description": "Sensor attached to the container ceilings", "temp":[35,35,35,36,35,35,32,35,30,35,32,35], "c02_level": [1475,1476,1473], "geo": {"lat":38.00, "long":97.00} }, "sensor-ipad": { "id": 13, "ip": "67.185.72.1", "description": "Sensor ipad attached to carbon cylinders", "temp": [45,45,45,46,45,45,42,35,40,45,42,45], "c02_level": [1370,1371,1372], "geo": {"lat":47.41, "long":-122.00} }, "sensor-inest": { "id": 8, "ip": "208.109.163.218", "description": "Sensor attached to the factory ceilings", "temp": [40,40,40,40,40,43,42,40,40,45,42,45], "c02_level": [1346,1345, 1343], "geo": {"lat":33.61, "long":-111.89} }, "sensor-istick": { "id": 5, "ip": "204.116.105.67", "description": "Sensor embedded in exhaust pipes in the ceilings", "temp":[30,30,30,30,40,43,42,40,40,35,42,35], "c02_level": [1574,1570, 1576], "geo": {"lat":35.93, "long":-85.46} } } }""", schema) display(dataDF) # COMMAND ---------- # MAGIC %md By examining its schema, you can notice that the DataFrame schema reflects the above defined schema, where two of its elments are are arrays of integers. # COMMAND ---------- dataDF.printSchema() # COMMAND ---------- # MAGIC %md Employ `explode()` to explode the column `source` into its individual columns. # COMMAND ---------- explodedDF = dataDF.select("dc_id", explode("source")) display(explodedDF) # COMMAND ---------- explodedDF.select("dc_id", "key", "value.*").show() # COMMAND ---------- # MAGIC %md Now you can work with the `value` column, which a is `struct`, to extract individual fields by using their names. # COMMAND ---------- # # use col.getItem(key) to get individual values within our Map # devicesDataDF = explodedDF.select("dc_id", "key", \ "value.ip", \ col("value.id").alias("device_id"), \ col("value.c02_level").alias("c02_levels"), \ "value.temp") display(devicesDataDF) # COMMAND ---------- # MAGIC %md For sanity let's ensure what was created as DataFrame was preserved and adherent to the schema declared above while exploding and extracting individual data items. # COMMAND ---------- devicesDataDF.printSchema() # COMMAND ---------- # MAGIC %md Now, since this tutorial is less about DataFrames API and more about higher-order functions and lambdas in SQL, create a temporary table or view and start using the higher-order SQL functions mentioned above. # COMMAND ---------- devicesDataDF.createOrReplaceTempView("data_center_iot_devices") # COMMAND ---------- # MAGIC %md The table was created as columns in your DataFrames and it reflects its schema. # COMMAND ---------- # MAGIC %sql select * from data_center_iot_devices # COMMAND ---------- # MAGIC %sql describe data_center_iot_devices # COMMAND ---------- # MAGIC %md ## SQL Higher-Order Functions and Lambda Expressions # COMMAND ---------- # MAGIC %md ### How to use `transform()` # COMMAND ---------- # MAGIC %md Its functional signature, `transform(values, value -> lambda expression)`, has two components: # MAGIC # MAGIC 1. `transform(values..)` is the higher-order function. This takes an array and an anonymous function as its input. Internally, `transform` takes care of setting up a new array, applying the anonymous function to each element, and then assigning the result to the output array. # MAGIC 2. The `value -> expression` is an anonymous function. The function is further divided into two components separated by a `->` symbol: # MAGIC * **The argument list**: This case has only one argument: value. You can specify multiple arguments by creating a comma-separated list of arguments enclosed by parenthesis, for example: `(x, y) -> x + y.` # MAGIC * **The body**: This is a SQL expression that can use the arguments and outer variables to calculate the new value. # MAGIC # MAGIC In short, the programmatic signature for `transform()` is as follows: # MAGIC # MAGIC `transform(array<T>, function<T, U>): array<U>` # MAGIC This produces an array by applying a function<T, U> to each element of an input array<T>. # MAGIC Note that the functional programming equivalent operation is `map`. This has been named transform in order to prevent confusion with the map expression (that creates a map from a key value expression). # MAGIC # MAGIC This basic scheme for `transform(...)` works the same way as with other higher-order functions, as you will see shortly. # COMMAND ---------- # MAGIC %md # MAGIC The following query transforms the values in an array by converting each elmement's temperature reading from Celsius to Fahrenheit. # MAGIC # MAGIC Let's transform (and hence convert) all our Celsius reading into Fahrenheit. (Use conversion formula: `((C * 9) / 5) + 32`) The lambda expression here is the formula to convert **C->F**. # MAGIC Now, `temp` and `((t * 9) div 5) + 32` are the arguments to the higher-order function `transform()`. The anonymous function will iterate through each element in the array, `temp`, apply the function to it, and transforming its value and placing into an output array. The result is a new column with tranformed values: `fahrenheit_temp`. # COMMAND ---------- # MAGIC %sql select key, ip, device_id, temp, # MAGIC transform (temp, t -> ((t * 9) div 5) + 32 ) as fahrenheit_temp # MAGIC from data_center_iot_devices # COMMAND ---------- # MAGIC %md While the above example generates transformed values, this example uses a Boolean expression as a lambda function and generates a boolean array of results instead of values, since the expression # MAGIC `t->t > 1300` is a predicate, resulting into a true or false. # COMMAND ---------- # MAGIC %sql select dc_id, key, ip, device_id, c02_levels, temp, # MAGIC transform (c02_levels, t -> t > 1300) as high_c02_levels # MAGIC from data_center_iot_devices # MAGIC # COMMAND ---------- # MAGIC %md ### How to use `filter()` # COMMAND ---------- # MAGIC %md As with `transform`, `filter` has a similar signature, `filter(array<T>, function<T, Boolean>): array<T>` # MAGIC Unlike `transform()` with a boolean expression, it produces an output array from an input array by *only* adding elements for which predicate `function<T, Boolean>` holds. # MAGIC # MAGIC For instance, let's include only readings in our `c02_levels` that exceed dangerous levels (`cO2_level > 1300`). Again the functional signature is not dissimilar to `transform()`. However, note the difference in how `filter()` generated the resulting array compared to _transform()_ with similar lambda expression. # COMMAND ---------- # MAGIC %sql select dc_id, key, ip, device_id, c02_levels, temp, # MAGIC filter (c02_levels, t -> t > 1300) as high_c02_levels # MAGIC from data_center_iot_devices # COMMAND ---------- # MAGIC %md Notice when the lambda's predicate expression is reversed, the resulting array is empty. That is, it does not evaluate to values true or false as it did in `tranform()`. # COMMAND ---------- # MAGIC %sql select dc_id, key, ip, device_id, c02_levels, temp, # MAGIC filter (c02_levels, t -> t < 1300 ) as high_c02_levels # MAGIC from data_center_iot_devices # COMMAND ---------- # MAGIC %md ### How to use `exists()` # COMMAND ---------- # MAGIC %md A mildly different functional signature than the above two functions, the idea is simple and same: # MAGIC # MAGIC `exists(array<T>, function<T, V, Boolean>): Boolean` # MAGIC Return true if predicate `function<T, Boolean>` holds for any element in input array. # MAGIC # MAGIC In this case you can iterate through the `temp` array and see if a particular value exists in the array. Let's acertain if any of your values contains 45 degrees Celsius or determine of a c02 level in any of the readings equals to 1570. # COMMAND ---------- # MAGIC %sql select dc_id, key, ip, device_id, c02_levels, temp, # MAGIC exists (temp, t -> t = 45 ) as value_exists # MAGIC from data_center_iot_devices # COMMAND ---------- # MAGIC %sql select dc_id, key, ip, device_id, c02_levels, temp, # MAGIC exists (c02_levels, t -> t = 1570 ) as high_c02_levels # MAGIC from data_center_iot_devices # COMMAND ---------- # MAGIC %md ### How to use `reduce()` # COMMAND ---------- # MAGIC %md By far this function and its method is more advanced than others. It also allows you to do aggregation, as seen in the next section. # MAGIC Its signature allows us to some extra bit with the last lambda expression as its functional argument. # MAGIC # MAGIC `reduce(array<T>, B, function<B, T, B>, function<B, R>): R` # MAGIC Reduce the elements of `array<T>` into a single value `R` by merging the elements into a buffer B using `function<B, T, B>` and by applying a finish `function<B, R>` on the final buffer. The initial value `B` is determined by a `zero` expression. # MAGIC # MAGIC The finalize function is optional, if you do not specify the function the finalize function the identity function (`id -> id`) is used. # MAGIC This is the only higher-order function that takes two lambda functions. # MAGIC # MAGIC For instance, if you want to compute an average of the temperature readings, use lambda expressions: The first one accumulates all the results into an internal temporary buffer, and the second function applies to the final accumulated buffer. With respect to our signature above, `B` is `0`; `function<B,T,B>` is `t + acc`, and `function<B,R>` is `acc div size(temp)`. Furthermore, in the finalize lambda expression, convert the average temperature to Fahrenheit. # COMMAND ---------- # MAGIC %sql select key, ip, device_id, temp, # MAGIC reduce(temp, 0, (t, acc) -> t + acc, acc-> (acc div size(temp) * 9 div 5) + 32 ) as average_f_temp, # MAGIC reduce(temp, 0, (t, acc) -> t + acc, acc-> acc) as f_temp # MAGIC from data_center_iot_devices # MAGIC sort by average_f_temp desc # COMMAND ---------- # MAGIC %md Simillarly, `reduce()` is employed here to get an average of c02_levels. # COMMAND ---------- # MAGIC %sql select key, ip, device_id, c02_levels, # MAGIC reduce(c02_levels, 0, (t, acc) -> t + acc, acc-> acc div size(c02_levels)) as average_c02_levels # MAGIC from data_center_iot_devices # MAGIC sort by average_c02_levels desc # COMMAND ---------- # MAGIC %md ### How to use `aggregate()` # COMMAND ---------- # MAGIC %md # MAGIC Aggregate is an alias of `reduce`. It has the same inputs, and it will produce the same results. # MAGIC # MAGIC Let's compute a geomean of the c02 levels and sort them by descending order. Note the complex lambda expression with the above functional signature. # COMMAND ---------- # MAGIC %sql select key, ip, device_id, c02_levels, # MAGIC aggregate(c02_levels, # MAGIC (1.0 as product, 0 as N), # MAGIC (buffer, c02) -> (c02 * buffer.product, buffer.N+1), # MAGIC buffer -> round(Power(buffer.product, 1.0 / buffer.N))) as c02_geomean # MAGIC from data_center_iot_devices # MAGIC sort by c02_geomean desc # COMMAND ---------- # MAGIC %md ## Another example using similar nested structure with IoT JSON data. # MAGIC # MAGIC Let's create a DataFrame based on this schema and check if all is good. # COMMAND ---------- from pyspark.sql.types import * schema2 = StructType() \ .add("device_id", IntegerType()) \ .add("battery_level", ArrayType(IntegerType())) \ .add("c02_level", ArrayType(IntegerType())) \ .add("signal", ArrayType(IntegerType())) \ .add("temp", ArrayType(IntegerType())) \ .add("cca3", ArrayType(StringType())) \ .add("device_type", StringType()) \ .add("ip", StringType()) \ .add("timestamp", TimestampType()) # COMMAND ---------- dataDF2 = jsonToDataFrame("""[ {"device_id": 0, "device_type": "sensor-ipad", "ip": "68.161.225.1", "cca3": ["USA", "United States"], "temp": [25,26, 27], "signal": [23,22,24], "battery_level": [8,9,7], "c02_level": [917, 921, 925], "timestamp" :1475600496 }, {"device_id": 1, "device_type": "sensor-igauge", "ip": "213.161.254.1", "cca3": ["NOR", "Norway"], "temp": [30, 32,35], "signal": [18,18,19], "battery_level": [6, 6, 5], "c02_level": [1413, 1416, 1417], "timestamp" :1475600498 }, {"device_id": 3, "device_type": "sensor-inest", "ip": "66.39.173.154", "cca3": ["USA", "United States"], "temp":[47, 47, 48], "signal": [12,12,13], "battery_level": [1, 1, 0], "c02_level": [1447,1446, 1448], "timestamp" :1475600502 }, {"device_id": 4, "device_type": "sensor-ipad", "ip": "203.82.41.9", "cca3":["PHL", "Philippines"], "temp":[29, 29, 28], "signal":[11, 11, 11], "battery_level":[0, 0, 0], "c02_level": [983, 990, 982], "timestamp" :1475600504 }, {"device_id": 5, "device_type": "sensor-istick", "ip": "204.116.105.67", "cca3": ["USA", "United States"], "temp":[50,51,50], "signal": [16,16,17], "battery_level": [8,8, 8], "c02_level": [1574,1575,1576], "timestamp" :1475600506 }, {"device_id": 6, "device_type": "sensor-ipad", "ip": "220.173.179.1", "cca3": ["CHN", "China"], "temp": [21,21,22], "signal": [18,18,19], "battery_level": [9,9,9], "c02_level": [1249,1249,1250], "timestamp" :1475600508 }, {"device_id": 7, "device_type": "sensor-ipad", "ip": "118.23.68.227", "cca3": ["JPN", "Japan"], "temp":[27,27,28], "signal": [15,15,29], "battery_level":[0,0,0], "c02_level": [1531,1532,1531], "timestamp" :1475600512 }, {"device_id": 8, "device_type": "sensor-inest", "ip": "208.109.163.218", "cca3": ["USA", "United States"], "temp":[40,40,41], "signal": [16,16,17], "battery_level":[ 9, 9, 10], "c02_level": [1208,1209,1208], "timestamp" :1475600514}, {"device_id": 9, "device_type": "sensor-ipad", "ip": "88.213.191.34", "cca3": ["ITA", "Italy"], "temp": [19,28,5], "signal": [11, 5, 24], "battery_level": [0,-1,0], "c02_level": [1171, 1240, 1400], "timestamp" :1475600516 }, {"device_id": 10, "device_type": "sensor-igauge", "ip": "68.28.91.22", "cca3": ["USA", "United States"], "temp": [32,33,32], "signal": [26,26,25], "battery_level": [7,7,8], "c02_level": [886,886,887], "timestamp" :1475600518 }, {"device_id": 11, "device_type": "sensor-ipad", "ip": "59.144.114.250", "cca3": ["IND", "India"], "temp": [46,45,44], "signal": [25,25,24], "battery_level": [4,5,5], "c02_level": [863,862,864], "timestamp" :1475600520 }, {"device_id": 12, "device_type": "sensor-igauge", "ip": "193.156.90.200", "cca3": ["NOR", "Norway"], "temp": [18,17,18], "signal": [26,25,26], "battery_level": [8,9,8], "c02_level": [1220,1221,1220], "timestamp" :1475600522 }, {"device_id": 13, "device_type": "sensor-ipad", "ip": "67.185.72.1", "cca3": ["USA", "United States"], "temp": [34,35,34], "signal": [20,21,20], "battery_level": [8,8,8], "c02_level": [1504,1504,1503], "timestamp" :1475600524 }, {"device_id": 14, "device_type": "sensor-inest", "ip": "68.85.85.106", "cca3": ["USA", "United States"], "temp": [39,40,38], "signal": [17, 17, 18], "battery_level": [8,8,7], "c02_level": [831,832,831], "timestamp" :1475600526 }, {"device_id": 15, "device_type": "sensor-ipad", "ip": "161.188.212.254", "cca3": ["USA", "United States"], "temp": [27,27,28], "signal": [26,26,25], "battery_level": [5,5,5], "c02_level": [1378,1376,1378], "timestamp" :1475600528 }, {"device_id": 16, "device_type": "sensor-igauge", "ip": "221.3.128.242", "cca3": ["CHN", "China"], "temp": [10,10,11], "signal": [24,24,23], "battery_level": [6,5,6], "c02_level": [1423, 1423, 1423], "timestamp" :1475600530 }, {"device_id": 17, "device_type": "sensor-ipad", "ip": "64.124.180.215", "cca3": ["USA", "United States"], "temp": [38,38,39], "signal": [17,17,17], "battery_level": [9,9,9], "c02_level": [1304,1304,1304], "timestamp" :1475600532 }, {"device_id": 18, "device_type": "sensor-igauge", "ip": "66.153.162.66", "cca3": ["USA", "United States"], "temp": [26, 0, 99], "signal": [10, 1, 5], "battery_level": [0, 0, 0], "c02_level": [902,902, 1300], "timestamp" :1475600534 }, {"device_id": 19, "device_type": "sensor-ipad", "ip": "193.200.142.254", "cca3": ["AUT", "Austria"], "temp": [32,32,33], "signal": [27,27,28], "battery_level": [5,5,5], "c02_level": [1282, 1282, 1281], "timestamp" :1475600536 } ]""", schema2) display(dataDF2) # COMMAND ---------- dataDF2.printSchema() # COMMAND ---------- # MAGIC %md As above, let's create a temporary view to which you can issue SQL queries and do some processing using higher-order functions. # COMMAND ---------- dataDF2.createOrReplaceTempView("iot_nested_data") # COMMAND ---------- # MAGIC %md ### How to use `transform()` # COMMAND ---------- # MAGIC %md Use transform to check battery level. # COMMAND ---------- # MAGIC %sql select cca3, device_type, battery_level, # MAGIC transform (battery_level, bl -> bl > 0) as boolean_battery_level # MAGIC from iot_nested_data # COMMAND ---------- # MAGIC %md Note that you are not limited to only a single `transform()` function. In fact, you can chain multiple transformation, as this # MAGIC code tranforms countries to both lower and upper case. # COMMAND ---------- # MAGIC %sql select cca3, # MAGIC transform (cca3, c -> lcase(c)) as lower_cca3, # MAGIC transform (cca3, c -> ucase(c)) as upper_cca3 # MAGIC from iot_nested_data # COMMAND ---------- # MAGIC %md ### How to use `filter()` # COMMAND ---------- # MAGIC %md Filter out any devices with battery levels lower than 5. # COMMAND ---------- # MAGIC %sql select cca3, device_type, battery_level, # MAGIC filter (battery_level, bl -> bl < 5) as low_levels # MAGIC from iot_nested_data # COMMAND ---------- # MAGIC %md ### How to use `reduce()` # COMMAND ---------- # MAGIC %sql select cca3, device_type, battery_level, # MAGIC reduce(battery_level, 0, (t, acc) -> t + acc, acc -> acc div size(battery_level) ) as average_battery_level # MAGIC from iot_nested_data # MAGIC sort by average_battery_level desc # COMMAND ---------- # MAGIC %sql select cca3, device_type, temp, # MAGIC reduce(temp, 0, (t, acc) -> t + acc, acc -> acc div size(temp) ) as average_temp # MAGIC from iot_nested_data # MAGIC sort by average_temp desc # COMMAND ---------- # MAGIC %sql select cca3, device_type, c02_level, # MAGIC reduce(c02_level, 0, (t, acc) -> t + acc, acc -> acc div size(c02_level) ) as average_c02_level # MAGIC from iot_nested_data # MAGIC sort by average_c02_level desc # COMMAND ---------- # MAGIC %md You can combine or chain many `reduce()` functions as this code shows. # COMMAND ---------- # MAGIC %sql select cca3, device_type, signal, temp, c02_level, # MAGIC reduce(signal, 0, (s, sacc) -> s + sacc, sacc -> sacc div size(signal) ) as average_signal, # MAGIC reduce(temp, 0, (t, tacc) -> t + tacc, tacc -> tacc div size(temp) ) as average_temp, # MAGIC reduce(c02_level, 0, (c, cacc) -> c + cacc, cacc -> cacc div size(c02_level) ) as average_c02_level # MAGIC from iot_nested_data # MAGIC sort by average_signal desc # COMMAND ---------- # MAGIC %md ## Summary # COMMAND ---------- # MAGIC %md The point of this short tutorial has been to demonstrate the ease of utility of higher-order functions and lambda expressions in SQL, to work with JSON attributes nested structures and arrays. Once you have flattened or parsed the desired values into respective DataFrames or Datasets, and after saving them as a SQL view or table, you can as easily manipulate and tranform your arrays with higher-order functions in SQL as you would with DataFrame or Dataset API. # MAGIC # MAGIC Finally, it is easy to employ higher-order functions than to write UDFs in Python or Scala. Read the original blog on [SQL higher-order functions](https://databricks.com/blog/2017/05/24/working-with-nested-data-using-higher-order-functions-in-sql-on-databricks.html) to get more information on the _whys_.
f9373a41dd175e680e68a174171a77d2d249de72
aanivia/leetcode
/easy/有效的括号.py
311
3.5
4
class Solution(object): def isVaild(self, s: str) -> bool: stack = ["?"] dic = {"(": ")", "[": "]", "{": "}"} for i in s: if i in dic: stack.append(i) elif i != dic.get(stack.pop()): return False return len(stack) == 1
742349631149c8f17ef4c0a30793a20f937b81d4
Fengyongming0311/TANUKI
/小程序/001.ReverseString/把GBK字节转换为utf-8字节.py
516
3.71875
4
#encode 是编码 #decode 是解码 """s = "周杰伦" bs1 = s.encode("GBK") bs2 = s.encode("utf-8") print (bs1) print (bs2) """ #把一个GBK字节转化成utf-8的字节 gbk = b'\xd6\xdc\xbd\xdc\xc2\xd7' s = gbk.decode("gbk") #解码 因为原编码就是GBK所以用GBK方式解码 print (s) utf8 = s.encode("utf-8") #用utf-8编码 print (utf8) don = utf8.decode("utf-8") print ("###################") print (don) """ 1. str.encode("编码") 进行编码 2. bytes.decode("编码") 进行解码 """
69bf94b8418ad7fa291f1d3f450b1190cd58b313
rashigupta26/testrepository
/prime.py
224
4.28125
4
#check if a number is prime or not a=int(input("enter any number ")) if a>1: for i in range(2,a): if (a%i)==0 : print(a,"is not prime") else: print(a,"is a prime") else: print(a,"is not a prime number")
6864fc7b7d0a991a046b00210abca583b088130d
JiJingYu/Python-Algorithm
/DP/a1098.py
490
3.859375
4
# 1098. Insertion or Heap Sort import bisect def insert_(nums, i): # i start from 1 s, s_no = nums[:i], nums[i+1:] bisect.insort_left(s, nums[i]) return s+s_no n=int(input()) nums = [int(x) for x in input().split()] tag = [int(x) for x in input().split()] tmp = nums[:] for i in range(1, n-1): tmp = insert_(tmp, i) if tmp==tag: print("Insertion Sort") tmp = insert_(tmp, i+1) print(" ".join(map(str, tmp))) exit(0) print("Heap Sort")
dba0492edad611c00d9d0009778881147a7d42ef
Geeorgee23/Socios_cooperativa_MVC
/main.py
2,652
3.671875
4
from socios import Socios from controlador import Controlador from datetime import datetime controlador = Controlador() while True: print("Actualmente hay ",controlador.numSocios()," socios") print("1.- Añadir Socio") print("2.- Eliminar Socio") print("3.- Listar Socios") print("4.- Registrar Productos") print("5.- Actualizar Saldo") print("6.- Ficha de Socio") print("7.- Salir") while True: try: op=int(input("Introduce opción:")) if op>=1 and op<=7: break else: print("Introduce un numero del 1 al 7!") except ValueError: print("Introduce un numero!") if op==7: break if op==1: print() id_socio=input("Introduce el id del socio: ") dni=input("Introduce el dni del socio: ") nombre=input("Introduce el nombre del socio: ") apellidos=input("Introduce los apellidos del socio: ") fecha= datetime.now() hoy = str(fecha.strftime("%d-%m-%Y")) socio = Socios(id_socio,dni,nombre,apellidos,hoy) if controlador.addSocio(socio): print("Socio añadido correctamente!") else: print("Error al añadir el socio!") print() if op==2: print() id_socio=input("Introduce el id del socio a eliminar: ") if controlador.delSocio(id_socio): print("Socio eliminado correctamente!") else: print("Error al eliminar el socio!") print() if op ==3: print() print("Socios: ") for i in controlador.listarSocios(): print(i) print() if op ==4: print() print("Registrando productos...") id_socio=input("Introduce el id del socio: ") print("Productos:") print(controlador.getProductos()) producto=input("Introduce el nombre del producto: ") kilos=input("Introduce el numero de kilos: ") if controlador.addProducto(id_socio,producto,kilos): print("Producto añadido correctamente!") else: print("Error al añadir el producto!") print() if op ==5: print() id_socio=input("Introduce el id del socio: ") if controlador.actualizaSaldo(id_socio): print("Saldo actualizado correctamente!") else: print("Error al actualizar saldo!") print() if op==6: print() id_socio=input("Introduce el id del socio: ") print(controlador.fichaSocio(id_socio)) print()
4c1232202cfb8831948175956d0b448d08d74259
prash21/FIT2004_3
/trie.py
22,220
3.75
4
# FIT2004 ASSIGNMENT 3 # PRASHANT MURALI - 29625564 import sys # TASK 1 class TrieNode(): """ This TrieNode class is essentially an implementation for the node. """ def __init__(self): """ Initializer for the class. Time complexity: Best: O(1) Worst: O(1) Space complexity: Best: O(1) Worst: nk (num of records that match id_prefix) or nl (num of records that match last_name_prefix). Error handle: None Return: None Parameter: None Precondition: None """ # Initialize the lists where the numbers and alphabets will be placed. # 62 spaces because 10 numbers + 26 lowercase letters + 26 uppercase letters. self.children = [None]*62 # This list would hold the index of which that character from the record was placed. self.index_list=[] self.match=False self.character=None self.checked=False def splitSpace(file_list): """ This function splits whitespace between characters and puts them into a list. Time complexity: Best: O(NM) Worst: O(NM) Space complexity: Best: O(NM) Worst: O(NM) Error handle: None Return: A list with lists of the items in the row from data in the database. Parameter: file_list, which is a list that contains the data that has already been split by newlines. Precondition: Parameter must be a file of rows divided by newlines. """ word="" list1=[] list2=[] for index in range(len(file_list)): for item in range(len(file_list[index])): # If the character is not a whitespace, it is added to the list. if file_list[index][item] != ' ': word += file_list[index][item] if item == (len(file_list[index]) - 1): list1.append(word) word="" else: list1.append(word) word = "" # The list is then added to the final list which is list2. list2.append(list1) list1=[] return list2 def splitNewLine(file): """ This function splits the rows in the database file (between newlines). Time complexity: Best: O(NM) Worst: O(NM) Space complexity: Best: O(NM) Worst: O(NM) Error handle: None Return: A list with each row in the database file. Parameter: file, which is the data from the database file. Precondition: The parameter must be a list with each row as an item in it. """ word="" input_file=[] for index in range(len(file)): # If the current character is not a newline, it is added to the list. if file[index] != '\n': word += file[index] if index == (len(file) - 1): input_file.append(word) else: # Basically gets split when there is a newline. input_file.append(word) word = "" return input_file def getIndex(char): """ This function gets the index of the character that is passed into the function. Time complexity: Best: O(1) Worst: O(1) Space complexity: Best: O(1) Worst: O(1) Error handle: None Return: The index value for that character. Parameter: char, which is the character that needs to get its index found. Precondition: parameter character must be lowercase/uppercase letters and integers only. """ # If the ord value of the char is less than 57, it is taken as a digit (0,1...9), # and its appropriate index is returned. if ord(char)<=57: index=ord(char)-48 # If the ord value of the char is less than 90, it is taken as an uppercase char (A,B...Z), # and its appropriate index is returned. elif ord(char)<=90: index=ord(char)-55 # If the ord value of the char is less than 122, it is taken as a lowercase char (a,b...z), # and its appropriate index is returned. elif ord(char)<=122: index=ord(char)-61 # index is returned. return index def addData(root,row): """ This function adds the characters into the Trie. Time complexity: Best: O(T) Worst: O(T) Space complexity: Best: O(T) Worst: O(T) Error handle: None Return: None, as any changes are simply done in the nodes. Parameter: root, which is the initialization of the TrieNode class, and row, which is the row of which the id and lastname columns will be added to the Trie. Precondition: root must be a reference to the TrieNode class, and row should have all items in it. """ # This would be the last name. last_name=row[3] # This would be the id. id=row[1] # This would be the index for the row from which the last names and id are in. ind=row[0] # Adding the last names into the Trie. # Set the node to the root, (the start basically). node=root for char in last_name: # Get the index of the character. index=getIndex(char) # If the character doesn't exist, create a new Trie at that index. if node.children[index]==None: node.children[index]=TrieNode() # Append that rows index into this positions index_list. if node.index_list==[]: node.index_list.append(ind) elif node.index_list[-1]!=ind: node.index_list.append(ind) # Set the node to its child now. node=node.children[index] # Now add the id's into the Trie. # Set the node to the root, (back to the start again). node=root for char in id: # Get the index of the character. index=getIndex(char) # If the character doesn't exist, create a new Trie at that index. if node.children[index]==None: node.children[index]=TrieNode() # Append that rows index into this positions index_list. if node.index_list == []: node.index_list.append(ind) elif node.index_list[-1] != ind: node.index_list.append(ind) # Set the node to its child now. node=node.children[index] def query(filename, id_prefix, last_name_prefix): """ This function, given a file of records and two parameters, id_prefix and last_name_prefix, finds the indices of all records which have an identification number (id) whose prefix is id_prefix and last name whose prefix is last_name_prefix. Time complexity: Best: O(k + l + nk + nl) - for the queries only. Worst: O(k + l + nk + nl) - for the queries only. Space complexity: Best: O(T + NM) Worst: O(T + NM) Error handle: Upon opening the file, if the file is empty, the function is exited. Return: A list of indices. Parameter: filename, which is the name of the database, id_prefix, which is the prefix of the id that is used to find the id's, and last_name_prefix which is the prefix used to find the last names. Precondition: filename must exist, id_prefix must be integers, last_name_prefix must be upper/lower case letters. """ # Initialize the TrieNode. root=TrieNode() # Open the file. Note that errors in the FILENAME has already been checked in the # main block, so its no longer checked here. # The file however is later checked to see if its empty or not. file=open(filename,"r") # Read the file. file=file.read() # If the file is empty, the function is exited. if file == "": sys.exit() # Split the data in the file between newlines. Essentially putting every # row as an item into the list. file=splitNewLine(file) # Now, the items in that list is split for its whitespace. list_file=splitSpace(file) # Add the items into the Trie. Note that the row is sent in to the add function here. # The add function would get the columns for the id and last name in its function. for row in (list_file): addData(root,row) # Now that the data has been added into the Trie, we can query it using the prefix # given. # Point the node to the root, which is the start of the Trie. node = root for char in (last_name_prefix): index = getIndex(char) # If the character in the prefix is not found in the Trie, then an # an empty list is returned because it simply means no items had match. if node.children[index]==None: return [] # Set the node to its child. node = node.children[index] # Set the id_index_list to the row indexes found up to this point. last_name_index_list=(node.index_list) # Now search for the prefix of the last name. # Set the node back to the root, (basically going back to the start). node = root for char in id_prefix: index = getIndex(char) # If the character in the prefix is not found in the Trie, then an # an empty list is returned because it simply means no items had match. if node.children[index]==None: return [] # Set the node to its child. node = node.children[index] # Set the last_name_index_list to the row indexes found up to this point. id_index_list=(node.index_list) # The list below would hold the final indexes that match in both the id_index_list # and last_name_index_list. final_index_list=[] # Now that we have two lists that contain the matched indexes for the prefix id's and # last names, we can find the indexes when both id prefix and last name prefix match are present # in the Trie. To do this, when both lists have the same index, it would be taken and placed # into the final list, and an efficient method to do this is done below. Note the method done # below is applicable only if the two list of indexes are sorted, which in this case they are. # Find the smaller list and bigger list correspondingly. if len(id_index_list)<len(last_name_index_list): smallerlist=id_index_list biggerlist=last_name_index_list else: smallerlist=last_name_index_list biggerlist=id_index_list i=0 j=0 # Loops through the smaller list, so i times as most. while i<len(smallerlist): # If the indexes match, put them into the final list. if int(smallerlist[i])==int(biggerlist[j]): final_index_list.append(int(smallerlist[(i)])) i+=1 j+=1 elif int(smallerlist[i])>int(biggerlist[j]): j+=1 else: i+=1 # The final list is returned. return final_index_list # TASK 2 def reverseSubstrings(filename): """ This function finds all substrings of length > 1 whose reverse also exists in the text. Time complexity: Best: O((K^2 + P) Worst: O((K^2 + P) Space complexity: Best: O(K^2 + P) Worst: O(K^2 + P) Error handle: Upon opening the file, if the file is empty, the function is exited. Return: A list of lists, where each inner list will contain two values. Parameter: filename, which is the file that has the string which will be used. Precondition: filename must exist, and characters in lowercase. """ file = open(filename, "r") # Read the file. file = file.read() # If the file is empty, the function is exited. if file == "": sys.exit() # print(file) # One variable to hold the original string, and another to hold the reverse of it. ori_str=file rev_str=file[::-1] # Generate all suffixes of the original string. ori_suffix=[] for i in range(len(ori_str)): temp_str="" for j in range(i,len(ori_str)): temp_str+=ori_str[j] ori_suffix.append(temp_str) # Generate all suffixes of the reverse string. rev_suffix=[] for i in range(len(rev_str)): temp_str="" for j in range(i,len(rev_str)): temp_str+=rev_str[j] rev_suffix.append(temp_str) # Add the suffix of the original string into the Trie. (a new Trie). root=TrieNode() for i in range(len(ori_suffix)): addOriSuffix(root,ori_suffix[i],i) # Add the suffix of the reverse string into the Trie. (the same Trie). for i in range(len(rev_suffix)): addRevSuffix(root,rev_suffix[i]) # Now go through the Trie and retrieve the nodes that had its "matched" variable # set to True, because it means that the characters from the original suffix and reverse # suffix are intersecting. So, those nodes would be part of the substring that has a reverse # that exists in the original word. index_list=[] mylist=[] # Loop through all the original suffixes. for word in ori_suffix: node = root string="" counter=0 # Loop through each character in the suffix. for char in word: index = getIndex(char) # In the event that the position is None, the list is returned, # but it would never go here because we're searching for the # words that we know we have inserted into the Trie earlier. if node.children[index] == None: return mylist # Given that the position is not empty, point the node to its child. node = node.children[index] # Previously, we have marked the nodes where the original suffix and reverse suffix # intersect, so here we check if it does. If it does intersect, we get the character # of that position and add it to a string. if node.match==True: if node.character!=None: string+=node.character # Here, we will extract the nodes (character) if the last character of # that string has not been checked yet. if node.checked==False: if mylist==[]: # Can't be just one character. if len(string)>1: mylist.append(string) index_list.append((node.index_list)) counter+=1 # Can't be just one character. if len(string)>1 : if counter==0: mylist.append(string) index_list.append((node.index_list)) counter+=1 # If the previous item has the same length of the current item in this round of iteration # of the outerloop, then it means that the word is repeated, so it is made sure that the # repeated word is not added into the list. elif len(string)!=len(mylist[-1]): mylist.append(string) index_list.append((node.index_list)) # Once the string has been added to the list, the last character of that string is marked as # checked so that the same sequence of strings won't be checked for again. node.checked = True # Finally, get all the strings from mylist and its corresponding indexes from index_list, and format # them accordingly by putting them as a list of list into the final_list, before finally returning the # final_list. final_list=[] for index in range(len(index_list)): i=0 while i<len(index_list[index]): final_list.append([mylist[index],index_list[index][i]]) i+=1 # Return the final_list. return(final_list) def addOriSuffix(root,suffix,position_index): """ This function adds suffixes into the Trie. Time complexity: Best: O((K) Worst: O((K) Space complexity: Best: O(K) Worst: O(K) Error handle: None. Return: None. Parameter: root, which is a reference to the TrieNode class; suffix which are all the suffixes of a given string, and position_index, which is the index of the suffixes. Precondition: the suffix parameter must be a suffix of the string. """ # Point the node to the root. node=root # Add all the characters from the original suffix into the Trie. for char in suffix: # Get the index of the character. index = getIndex(char) # If the character doesn't exist, create a new Trie at that index. if node.children[index] == None: node.children[index] = TrieNode() # Point the node to its child. node = node.children[index] # Append the index of the character from the string into the nodes index_list. if node.index_list == []: node.index_list.append(position_index) # Ensure the same index is not repeated. elif node.index_list[-1] != position_index: node.index_list.append(position_index) # Set that nodes character to the current character. node.character = char def addRevSuffix(root,suffix): """ This function adds suffixes into the Trie. Time complexity: Best: O((K) Worst: O((K) Space complexity: Best: O(K) Worst: O(K) Error handle: None. Return: None. Parameter: root, which is a reference to the TrieNode class, and suffix which are all the suffixes of a given string. Precondition: the suffix parameter must be a suffix of the string. """ # Point the node to the root. node = root # Put all the characters from the reverse suffix into the Trie. for char in suffix: # Get the index of the character. index = getIndex(char) # If the character doesn't exist, create a new Trie at that index. if node.children[index] == None: node.children[index] = TrieNode() # If character does exist, point to its child and mark it as match. # Marking it as matched would simply mean that this character in the reverse # substring has intersected with a character from the original list. if node.children[index] != None: node = node.children[index] # Mark true if they match. node.match = True # Set its character to the current character. node.character = char # MAIN BLOCK if __name__ == '__main__': LINES = "---------------------------------------------------------------------" print("TASK-1:") print(LINES) # Try input the filename and open it. If successful, continue to get id prefix input. bflag=False while bflag==False: try: database_file=input("Enter the file name of the query database : ") openTestfile = open(database_file, "r") bflag = True except NameError: bflag = False except TypeError: bflag = False except FileNotFoundError: bflag = False except IOError: bflag = False # Try input the id prefix. If successful, continue to get last name prefix input. bflag=False while bflag==False: try: prefix_id_input=input("Enter the prefix of the identification number: ") if prefix_id_input=="": bflag=True else: int(prefix_id_input) bflag=True except NameError: bflag = False except TypeError: bflag = False except ValueError: bflag = False except IOError: bflag = False # Try input the last name prefix. If successful, continue to run the query function. bflag=False while bflag==False: try: prefix_lastname_input=input("Enter the prefix of the last name : ") if prefix_lastname_input == "": bflag = True else: bflag=True except NameError: bflag = False except TypeError: bflag = False except ValueError: bflag = False except IOError: bflag = False mylist=(query(database_file,prefix_id_input,prefix_lastname_input)) print(LINES) print(str(len(mylist))+" record found") for i in mylist: print("Index number : "+str(i)) print(LINES) print("TASK-2:") # Try input the filename for reverse substring search. If successful, continue to run the function. bflag=False while bflag==False: try: file_input=input("Enter the file name for searching reverse substring: ") openTestfile = open(file_input, "r") bflag=True except NameError: bflag = False except TypeError: bflag = False except FileNotFoundError: bflag = False except IOError: bflag = False print(LINES) string="" result=(reverseSubstrings(file_input)) # Displaying the result as depicted in the assignment spec sheet. for i in range(len(result)): string+=str(result[i][0]) string+="{" string+=str(result[i][1]) string+="}" if i<len(result)-1: string+=(",") string+=(" ") print(string) print(LINES) print("Program end") # END OF ASSIGNMENT
1b983317aac058ac6cff850cf5eaf37d0380769b
jarydhunter/Cracking_the_code_interview
/1.7.py
724
3.75
4
# Zero out rows and columns that have at least one 0. Assuming the matrix is # represented as a nested list. def zero_out(mat): zero_out_i = set() zero_out_j = set() for i in range(len(mat)): for j in range(len(mat[0])): if mat[i][j] == 0: zero_out_i.add(i) zero_out_j.add(j) for i in zero_out_i: mat[i] = [0]*len(mat[i]) for j in zero_out_j: for i in range(len(mat)): mat[i][j] = 0 return mat if __name__ == '__main__': test1 = [[1,4,6],[2,0,7],[3,5,8]] print(zero_out(test1)) test2 = [] print(zero_out(test2)) test3 = [[3,6,2],[1,2,3],[0,1,6],[5,5,4],[1,4,5],[1,0,6]] print(zero_out(test3))
9d284e5ad0d0f810f653600ac65b9c2c9f12b5b3
PiyushAgrawal98/standblogclone
/cond.py
156
3.734375
4
piyush = input('enter a number') try: agra = int(piyush) except: agra = -1 if agra> 0 : print('yes its number') else: print('type a numbe')
26e167b888c7f3a827a28ec65cf40242c1ade0b1
SergioGutzB/Learning-python
/ex29.py
711
4.1875
4
people = 20 cats = 30 dogs = 15 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry!" dogs += 5 if people >= dogs: print "People are greater than or equal to dogs." if people <= dogs: print "People are less than or equal to dogs." if people == dogs: print "People are dogs." #python necesita de intentacion exacta, para poderse ejecutar corretamente. esto creo q es por que #python no necesita de corchetes para delimtar el codigo de un bucle, condicion o funcion #su codigo se diferencia por la identacion.
7c2dfc5877fd1c08b2264f8134f2816df36888d7
joelhrobinson/Python_Code
/For_string.py
420
3.890625
4
############# tag_name ############################### temp_list = [] print (temp_list) temp_list.append("one") temp_list.append("two") print (temp_list) temp_list.append("three") print (temp_list) #################### string = "Hello World" for x in string: print('print letters to Hello World', x) collection = ['In', 5, 'Beginning'] for x in collection: print('this is a collection:', x)
e756ee75b6149be425afd8902cfb6730c1123cc5
redfast00/daily-algorithm-challenge
/src/calculate_maximum_profit.py
536
4.125
4
def calculate_max_profit(prices): '''Calculates the maximum profit given a list of prices of a stock by buying and selling exactly once. >>> calculate_max_profit([9, 11, 8, 5, 7, 10]) 5 >>> calculate_max_profit([10, 9, 8, 5, 2]) 0 ''' smallest_element_so_far = float('inf') largest_gain = 0 for value in prices: smallest_element_so_far = min(value, smallest_element_so_far) largest_gain = max(value - smallest_element_so_far, largest_gain) return largest_gain
d7a90c38de1f01606e99b644c29a0bd641cb5c95
a19singh/Dryp
/test_cal.py
1,951
3.984375
4
import unittest import calculator class TestCalculator(unittest.TestCase): def test_add(self): self.assertEqual(calculator.addition(10, 5), 15) #addition of two positive numbers self.assertEqual(calculator.addition(-5, 2), -3) #one positive and other negative, where negative > positive self.assertEqual(calculator.addition(-10,-10), -20) #addition of two negative numbers self.assertEqual(calculator.addition(10, -5), 5) #one positive and other negative, where positive > negative def test_sub(self): self.assertEqual(calculator.subtraction(10, 5), 5) #subtraction of two positive numbers self.assertEqual(calculator.subtraction(-5, 2), -7) #one positive and other negative, where negative > positive self.assertEqual(calculator.subtraction(-10,-10), 0) #subtraction of two negative numbers self.assertEqual(calculator.subtraction(10, -5), 15) #one positive and other negative, where negative > positive def test_mul(self): self.assertEqual(calculator.multiplication(10, 5), 50) #multiplication of two positive numbers self.assertEqual(calculator.multiplication(-5, 2), -10) #one positive and other negative self.assertEqual(calculator.multiplication(-10,-10), 100) #multiplication of two negative numbers self.assertEqual(calculator.multiplication(5, 0), 0) #multiplication by zero def test_div(self): self.assertEqual(calculator.division(10, 5), 2) #divison without remainder self.assertEqual(calculator.division(5, 2), 2.5) #divison having remainder self.assertEqual(calculator.division(-10,-10), 1) #divison of two negative numbers self.assertEqual(calculator.division(10, -5), -2) #divison of one positive and one negative number self.assertRaises(ValueError, calculator.division, 10, 0) #check for divide by zero error if __name__ == "__main__": unittest.main()
b9b5e80887a4d4f777d1fcae84cbf302fc5b5c36
hwangt17/MIS3640
/session10/ex_05.py
1,271
4.15625
4
#exercise 5 def any_lowercase1(s): """ If the string in variable s has all lowercase in it, return True. If not, return False. """ for c in s: if c.islower(): return True else: return False def any_lowercase2(s): """ If the string in variable 'c' is lowercase, return True. If not, return False. """ for c in s: if 'c'.islower(): return 'True' else: return 'False' def any_lowercase3(s): """ Store whether string in variable s has any lowercase in it in flag and return the flag. """ for c in s: flag = c.islower() return flag def any_lowercase4(s): """ If the string in variable s has any lowercase in it, return True. If not, return False. """ flag = False for c in s: flag = flag or c.islower() return flag def any_lowercase5(s): """ If the string in variable s does not all have lowercase in it, return False. If not, return True. """ for c in s: if not c.islower(): return False return True print(any_lowercase1('Back')) print(any_lowercase2('BACK')) print(any_lowercase3('BACK')) print(any_lowercase4('BACK')) print(any_lowercase5('Back'))
b7e9413d8990951d6d4e85d175b820fe2769d296
CiceroLino/Learning_python
/Curso_em_Video/Mundo_1_Fundamentos/Tratando_dados_e_fazendo_contas/ex008.py
428
4.25
4
#Desafio 008 do curso em video #Programa que converte medidas #https://www.youtube.com/watch?v=KjcdG05EAZc&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=9 medida = float(input('Uma distância em metros: ')) km = medida * 0.001 hm = medida * 0.01 dam = medida * 0.1 dm = medida * 10 cm = medida * 100 mm = medida * 1000 print(f'A medida de {medida} corresponde a:\n{km}km\n{hm}hm\n{dam}dam\n{dm}dm\n{cm}cm\n{mm}mm') print()
d75d720925f1ca79793d09d5e47646833da73fb9
nameera0408/Practical-introduction-to-python_Brainheinold
/ch2_12sol.py
86
3.828125
4
n=int(input('Enter the height to the triangle:')) for i in range(0,n): print('*'*i)
5a936189d6b1a6281d638c0cbfa8bd6d32a5e331
Ramaraj2020/100
/Linked List/Odd Even Linked List/prog.py
862
3.828125
4
# https://leetcode.com/problems/odd-even-linked-list/description/ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def oddEvenList(self, head): oddDummy = ListNode(None) evenDummy = ListNode(None) oddDummy.next = head evenDummy.next = head oddTail = oddDummy evenTail = evenDummy i = 1 while head: if i % 2 == 1: oddTail.next = head oddTail = oddTail.next else: evenTail.next = head evenTail = evenTail.next head = head.next i += 1 evenTail.next = None oddTail.next = evenDummy.next return oddDummy.next
a79e2bf9f6c98c08f54a3d64d8ab9ea71d4ff983
antunsz/connect_four_fcup
/utils/MachinePlayerAbstract.py
6,026
3.75
4
import time from .Player import Player class MachinePlayerAbstract(Player): """ Computer Player controlled by an IA """ def __init__(self, color): """ Constructor :param color: character entered in the grid for example: `o` or `x` :return: """ super(MachinePlayerAbstract, self).__init__(color) self._type = "IA" self._difficulty = 5 #depth def get_move(self, grid): """ Returns the best "move" (column index) calculated by IA :param grid: the current grid of the game :return: the best move found by IA (MinMax algorithm) """ return self._get_best_move(grid) def _get_best_move(self, grid): pass def _find(self, depth, grid, curr_player_color): pass def _is_legal_move(self, column, grid): """ Boolean function to check if a move (column) is a legal move """ for i in range(len(grid) - 1, -1, -1): if grid[i][column] == ' ': # once we find the first empty, we know it's a legal move return True # if we get here, the column is full return False def _game_is_over(self, grid): if self._find_streak(grid, 'x', 4) > 0: return True elif self._find_streak(grid, 'o', 4) > 0: return True else: return False def _simulate_move(self, grid, column, color): """ Simulate a "move" in the grid `grid` by the current player with its color `color. :param grid: a grid of connect four :param column: column index :param color: color of a player :return tmp_grid: the new grid with the "move" just added """ tmp_grid = [x[:] for x in grid] for i in range(len(grid) - 1, -1, -1): if tmp_grid[i][column] == ' ': tmp_grid[i][column] = color return tmp_grid def _eval_game(self, depth, grid, player_color): pass def _find_streak(self, grid, color, streak): """ Search streaks of a color in the grid :param grid: a grid of connect four :param color: color of a player :param streak: number of consecutive "color" :return count: number of streaks founded """ count = 0 # for each box in the grid... for i in range(len(grid)): for j in range(len(grid[0])): # ...that is of the color we're looking for... if grid[i][j] == color: # check if a vertical streak starts at index [i][j] of the grid game count += self._find_vertical_streak(i, j, grid, streak) # check if a horizontal streak starts at index [i][j] of the grid game count += self._find_horizontal_streak(i, j, grid, streak) # check if a diagonal streak starts at index [i][j] of the grid game count += self._find_diagonal_streak(i, j, grid, streak) # return the sum of streaks of length 'streak' return count def _find_vertical_streak(self, row, col, grid, streak): """ Search vertical streak starting at index [row][col] in the grid :param row: row the grid :param col: column of the grid :param grid: a grid of connect four :param streak: number of "color" consecutive :return: 0: no streak found, 1: streak founded """ consecutive_count = 0 if row + streak - 1 < len(grid): for i in range(streak): if grid[row][col] == grid[row + i][col]: consecutive_count += 1 else: break if consecutive_count == streak: return 1 else: return 0 def _find_horizontal_streak(self, row, col, grid, streak): """ Search horizontal streak starting at index [row][col] in the grid :param row: row the grid :param col: column of the grid :param grid: a grid of connect four :param streak: number of "color" consecutive :return: 0: no streak found, 1: streak founded """ consecutive_count = 0 if col + streak - 1 < len(grid): for i in range(streak): if grid[row][col] == grid[row][col + i]: consecutive_count += 1 else: break if consecutive_count == streak: return 1 else: return 0 def _determine_color(self): if self._color == "x": return "o" else: return "x" def _find_diagonal_streak(self, row, col, grid, streak): """ Search diagonal streak starting at index [row][col] in the grid It check positive and negative slope :param row: row the grid :param col: column of the grid :param grid: a grid of connect four :param streak: number of "color" consecutive :return total: number of streaks founded """ total = 0 # check for diagonals with positive slope consecutive_count = 0 if row + streak - 1 < len(grid) and col + streak - 1 < len(grid[0]): for i in range(streak): if grid[row][col] == grid[row + i][col + i]: consecutive_count += 1 else: break if consecutive_count == streak: total += 1 # check for diagonals with negative slope consecutive_count = 0 if row - streak + 1 >= 0 and col + streak - 1 < len(grid): for i in range(streak): if grid[row][col] == grid[row - i][col + i]: consecutive_count += 1 else: break if consecutive_count == streak: total += 1 return total
9596039d9de22001e449deadf3d9c7bf10c23790
ojudz08/Python-Beginner
/Exercises/Chapter 5/Exercise28.py
575
3.953125
4
print('\nExercise 28. Modified Listing 5.9 flexibletimestable.py') print('Modified such that multiplication table depends on the user input.') MAX = eval(input('Input the maximum row by column:')) product = 0 print(end=' ') for column in range(1, MAX + 1): print(end=" %2i " % column) print() print(end=' +') for column in range(1, MAX + 1): print(end='----') print() for row in range(1, MAX + 1): print(end="%2i | " % row ) for column in range(1, MAX + 1): product = row*column; print(end="%3i " % product) print()
0884f85f394412ca5941bafeafa2263683f17b69
dannyyiu/410coffee
/src/chai_cloud_deploy/_scripts/_simulate.py
2,929
3.828125
4
#!/usr/bin/env python import sqlite3 import random def populate_inventory(fname, release=False): """ Populate all stores with some random menu items. """ conn = sqlite3.connect(fname) cur = conn.cursor() # Get all store info; Dynamic for production, static for testing. if release: query = "select store_id, name from Store" else: query = "select store_id, name from Store where name='api'" cur.execute(query) stores = dict(cur.fetchall()) # Get all categories {int: str} cur.execute('''select cat_id, cat_name from Category''') categories = dict(cur.fetchall()) # Get customer IDs (for orders) cur.execute('''select cust_id from Customer''') customers = [i[0] for i in cur.fetchall()] #print customers for store_id in stores: print "[DEBUG] Generating inventory for %s..." % stores[store_id] # Generate random menu for each store # At least one of every category, 50%-100% of Menu for each # 50%-100% of options for each menu item. prods = [] # products to add per store for cat_id in categories: # Menu subset within category cur.execute( '''select prod_id, price from Menu where cat_id=?''', (cat_id,)) menu = dict(cur.fetchall()) # Random number of menu items, no less than 50% total_menu = int(random.uniform(0.5, 1.0)*len(menu)) # Get product IDs for insert prods += random.sample(menu, total_menu) insert_list = [] for prod_id in prods: stock = random.randint(200,1000) # random inventory stock active = 1 discount = 1.0 insert_list += [(prod_id, stock, discount, active, store_id,)] print "[DEBUG] Inventory generated successfully." store_db_insert(fname, "inventory", insert_list, stores[store_id]) def store_db_insert(dbname, table, data, store_name): """ Insert into dynamic store tables, given store name and table type. Data must be a list of tuples for insert. """ #table_name = "%s_%s" % (store_prefix, table) conn = sqlite3.connect(dbname) cur = conn.cursor() if table == "inventory": query = "insert or ignore into Inventory (prod_id, stock," + \ " discount, active, store_id) values (?, ?, ?, ?, ?)" print "[DEBUG] Inserting data into Inventory for %s..." % store_name cur.executemany(query, data) conn.commit() print "[DEBUG] Inventory inserted successfully." if __name__ == '__main__': # ====== STATIC STORE SIMULATION ===== # Populate all dynamic tables (tables for each store) populate_inventory('db.sqlite3') #assign_customers('db.sqlite3') #random_orders('db.sqlite3') # ====== DYNAMIC STORE SIMULATION ===== #
80cf7a7938ee929c6b473a9da7dd12ef986f731b
Mayankjh/Python_ML_Training
/Python Training/Day 2/Taskq3.py
628
4.15625
4
#Program to swap two no. without using third variable print("#Program to swap two no. without using third variable") a= int(input("Enter the First Number :-")) b =int(input("Enter the Second Number :-")) a=a+b b=a-b a=a-b print('Value of first no. after swapping is :',a,'\n Value of second no. after swapping :',b) #Program to swap two no. using third variable print("#Program to swap two no. using third variable") c= int(input("Enter the First Number :-")) d =int(input("Enter the Second Number :-")) temp = c c = d d = temp print('Value of first no. after swapping is :',c,'\n Value of second no. after swapping :',d)
9fe32bba6572e8327198cd1a6c9fd85699498c6d
crystal616/8480Group
/test code for debug/Movie2.py
1,083
3.578125
4
''' @author: Ying ''' import pandas as pd import numpy as np movie_genre = pd.read_csv("ratings.csv") movie_genre = movie_genre.drop(columns="timestamp") print(movie_genre.head()) def filter_by_threshold(df, group_col, filter_col, threshold): entry_count = df.groupby(group_col)[filter_col].apply(np.array).apply(np.unique).apply(len) entry_count.sort_values(ascending = True, inplace=True) # determine which items to drop drop_entries = entry_count[entry_count > threshold] drop_entries = drop_entries.to_frame(name='entry_count').reset_index().drop('entry_count', axis=1) row_number_before = df.shape[0] df = df.merge(drop_entries, how='inner', on=group_col) print("Filter {}: shape before {}, shape after {}".format(filter_col, row_number_before, df.shape[0])) return df filter_data = filter_by_threshold(movie_genre, 'userId', 'movieId', 25) filter_data = filter_by_threshold(filter_data, "movieId", "userId", 10) len(filter_data) filter_data.to_csv("filter-ratings.csv", index = False)
5cd15908fc0ecd6bfd0f580d0da4bb4fcb735441
ivaturi/pythonthehardway
/ex20.py
794
4.21875
4
#!/usr/bin/python # exercise 20: functions and files from sys import argv # get the input file from the user script, input_file = argv # print the contents of the file def print_all(f): print f.read() # move to the beginning of the file def rewind(f): f.seek(0) # print a line at the specified position def print_a_line(line_count, f): print line_count, f.readline() # open file for processing current_file = open(input_file) print "First, let's print the whole file: \n" print_all(current_file) print "Now, let's rewind to the beginning.\n" rewind(current_file) print "Let's print 3 lines:" current_line = 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file)
77cac9302a745c840c415bd06ffe8ab5b512bd98
iCodeIN/algorithms-9
/solutions/Dynamic Programming/RegularExpressionMatching.py
1,969
3.703125
4
## Website:: Interviewbit ## Link:: https://www.interviewbit.com/problems/regular-expression-ii/ ## Topic:: Dynamic Programming ## Sub-topic:: 2D ## Difficulty:: Medium ## Approach:: This is tricky since you can match 0 characters as well.. ## Time complexity:: O(MN) ## Space complexity:: O(M) ## Notes:: Here, the * is like a modifier, so you can just pre-process the input to make it into a format that is easy to use. ## Bookmarked:: No class Solution: def _match(self, s, p): return s == p or p == '.' # @param A : string # @param B : string # @return an integer def isMatch(self, A, B): string = A.strip() pattern = B l = len(string) # Convert into alphabets, single/multiple new_pattern = [[None, 0]] for p in pattern: if p == '*': new_pattern[-1][1] = 1 continue new_pattern.append([p, 0]) # print(new_pattern) # match prefixes! # print(l, string) dp = [0] * (l + 1) dp[0] = 1 for p, multiple in new_pattern[1:]: # print('foo') ndp = [0] * (l + 1) if multiple: # 0 matches possible with this character ndp[0] = dp[0] for ix, s in enumerate(string): match = self._match(s, p) # last char can be multiple matched if multiple: if not match: ndp[ix + 1] = dp[ix + 1] else: ndp[ix + 1] = int(dp[ix + 1] or dp[ix] or ndp[ix]) continue # Single matching char in pattern if match: ndp[ix + 1] = dp[ix] else: ndp[ix + 1] = 0 # print(ndp) dp = ndp # print(dp) return dp[-1]
3edf63d2163836e351cb7cff782b26b789a41e16
learntoautomateforfuture/PythonProject
/4_Tuple/15_AboutTuple.py
1,058
4.53125
5
""" Tuple are used to store multiple items in a single variable. Created using round brackets Tuple items are indexed, starts with [0] Items in the tuple can be of any datatype Tuple items are ordered, unchangeable(Immutable), and allow duplicate values. - Ordered : that the items have a defined order, and that order will not change. - unchangeable : we cannot change, add or remove items after the tuple has been created. - Allow duplicate values: tuple can have items with the same value """ tuple1 = ("Apple", "Banana") tuple2 = (89, 4, 90, 675) tuple3 = ("Apple", "Banana", 89, 4.8, True, 89) print (tuple1) # len() method is used to find the no:of items in the tuple print (len(tuple1)) tuple3 = ("Apple", "Banana", 89, 4.8, True, 89) print (tuple3[3]) """ To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognise it as a tuple """ tuple2 = (("ABC", )) print (tuple2) print (type(tuple2)) # tuple() constructor to make a tuple tuple3 = tuple(("Apple", "Banana", 89)) print (tuple3)
225cf71ff2ef27e84ee5f0537348bc46fea41053
divya-github18/PythonSelinumTesting
/PracticeExamples/pythonBasics/loops.py
641
3.78125
4
greeting = "Good Morning" a = 4 if a > 2: print(" Condition matches") print("second line") else: print("condition do not match") print("if else condition code is completed") #for loop obj= [2, 3, 5, 7, 9] for i in obj: print(i*2) # sum of First Natural numbers 1+2+3+4+5 = 15 #range(i,j) -> i to j-1 summation = 0 for j in range(1, 6): summation = summation + j print(summation) print("*******************************") for k in range(1, 10, 5): print(k) print("**************SKIPPING FIRST INDEX*****************") for m in range(10): print(m)
0db22bb9e81420d500144d1d97ad259addf5e82c
closcruz/wallbreakers-code
/week4/validParenthesis.py
499
3.78125
4
class ValidParenthesis: def checkParenthesis(self, s): if not s: return True check = list(s) out = [] while check: out.append(check.pop()) if len(out) > 1: if (out[-1] == '(' and out[-2] == ')') or (out[-1] == '[' and out[-2] == ']') or (out[-1] == '{' and out[-2] == '}'): del out[-1], out[-1] return True if not out else False print(ValidParenthesis().checkParenthesis('()'))
77a11c371e267bcf8d83063ebc0d9105e86378d4
Udayan-Coding/examples
/session-7/return.py
135
3.671875
4
# max function returns print(max(1, 3)) # our function def print_name(name): return "Hello " + name print(print_name("Jane Doe"))
12b0be9fca2e44d7bd1083c9156500a93a135546
Alexmachado81/ExerciciosPython_Resolvidos
/exe024a.py
96
3.9375
4
city = str(input(' Em que cidade voce nasceu? \n')).strip() print(city[:5].upper() == "SANTO")
f2fca3adff49f861a0c03acd4efe05ad23e2439f
ThompsonNJ/CSC231-Introduction-to-Data-Structures
/Quiz 2/priority_queue.py
1,108
4
4
class Queue: def __init__(self): self.queue = [] def enqueue(self, item): i = 0 while i < len(self.queue) and self.queue[i].priority < item.priority: i += 1 self.queue.insert(i, item) ## if self.is_empty(): ## self.queue.append(item) ## else: ## current = 0 ## found = False ## while not found: ## if item.priority == self.queue[current].priority: ## self.queue.insert(current-1, item) ## found = True ## elif item.priority > self.queue[current].priority: ## self.queue.insert(current, item) ## found = True ## elif item.priority < self.queue[current].priority: ## current += 1 def dequeue(self): if self.is_empty(): return None else: return self.queue.pop() def is_empty(self): return self.size() == 0 def size(self): return len(self.queue)
7622e9a4ea8db60485d92342d4450886f9f425ad
dandrews19/TicTacToePlayer
/ITP115_A8_Andrews_Dylan.py
5,683
4.25
4
# Dylan Andrews, dmandrew@usc.edu # ITP 115, Fall 2020 # Assignment 8 # Description: # This program uses functions to simulate a two player game of Tic Tac # Toe. The program will allow the two players to place an “x” or an “o” somewhere on # the board and determine when someone wins or when a stalemate is reached. import TicTacToeHelper # prints a nice board def printPrettyBoard(boardList): print("") print(boardList[0] + "| " + boardList[1] + "| " + boardList[2]) print("---------") print(boardList[3] + "| " + boardList[4] + "| " + boardList[5]) print("---------") print(boardList[6] + "| " + boardList[7] + "| " + boardList[8]) print("") # checks if players spot request is in range and it is not taken def isValidMove(boardList, spot): if (0 <= spot <= 8) and (boardList[spot] != "x " and boardList[spot] != "o "): return True else: return False # replaces selected spot with the player letter def updateBoard(boardList, spot, playerLetter): boardList[spot] = playerLetter # runs game with x as the start def playGame1(): boardList = ["0 ", "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 "] winner1 = "n" move_counter = 0 winner2 = "n" # runs game until there is a winner while winner2 == "n" and winner1 == "n": printPrettyBoard(boardList) spot = input("Player x, pick a spot: ") while spot.isdigit() == False: spot = input("Player x, pick a spot: ") playerLetter = "x " valid = isValidMove(boardList, int(spot)) while valid == False: print("Invalid move, please try again.") spot = input("Player x, pick a spot: ") valid = isValidMove(boardList, int(spot)) if valid == True: updateBoard(boardList, int(spot), playerLetter) move_counter += 1 winner1 = TicTacToeHelper.checkForWinner(boardList, move_counter) if winner1 == "n": printPrettyBoard(boardList) spot = input("Player o, pick a spot: ") while spot.isdigit() == False: spot = input("Player o, pick a spot: ") playerLetter = "o " valid = isValidMove(boardList, int(spot)) while valid == False: print("Invalid move, please try again.") spot = input("Player o, pick a spot: ") valid = isValidMove(boardList, int(spot)) if valid == True: updateBoard(boardList, int(spot), playerLetter) move_counter += 1 winner2 = TicTacToeHelper.checkForWinner(boardList, move_counter) printPrettyBoard(boardList) # prints results print("Game Over!") if winner1 == "x ": print("Player x is the winner!") if winner2 == "o ": print("Player o is the winner!") if winner1 == "s" or winner2 == "s": print("Stalemate reached!") # runs the game with o as the start def playGame2(): boardList = ["0 ", "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 "] winner1 = "n" move_counter = 0 winner2 = "n" # runs the game until there is a winner, switching between x and o for moves while winner2 == "n" and winner1 == "n": printPrettyBoard(boardList) spot = input("Player o, pick a spot: ") while spot.isdigit() == False: spot = input("Player o, pick a spot: ") playerLetter = "o " valid = isValidMove(boardList, int(spot)) while valid == False: print("Invalid move, please try again.") spot = input("Player o, pick a spot: ") valid = isValidMove(boardList, int(spot)) if valid == True: updateBoard(boardList, int(spot), playerLetter) move_counter += 1 winner1 = TicTacToeHelper.checkForWinner(boardList, move_counter) if winner1 == "n": printPrettyBoard(boardList) spot = input("Player x, pick a spot: ") while spot.isdigit() == False: spot = input("Player x, pick a spot: ") playerLetter = "x " valid = isValidMove(boardList, int(spot)) while valid == False: print("Invalid move, please try again.") spot = input("Player x, pick a spot: ") valid = isValidMove(boardList, int(spot)) if valid == True: updateBoard(boardList, int(spot), playerLetter) move_counter += 1 winner2 = TicTacToeHelper.checkForWinner(boardList, move_counter) printPrettyBoard(boardList) # states outcome of game print("Game Over!") if winner1 == "o ": print("Player o is the winner!") if winner2 == "x ": print("Player x is the winner!") if winner1 == "s" or winner2 == "s": print("Stalemate reached!") # continues the game while player wants to play, and asks user which symbol they want to start with def main(): print("Welcome to Tic Tac Toe!") game = "Y" while game == "Y" or game == "y": start = input("Choose which player you want to start (x or o): ") while start != "x" and start != "X" and start != "o" and start != "O": start = input("Choose which player you want to start (x or o): ") if start == "x" or start == "X": playGame1() elif start == "o" or start == "O": playGame2() game = input("Would you like to play another round? (y/n): ") while game != "Y" and game != "y" and game != "n" and game != "N": game = input("Would you like to play another round? (y/n): ") print("Goodbye!") main()
1b55028a71c3b2af3898afde4cb21553fbaa1e43
Bryan-Cee/algorithms
/python/string_permutation.py
1,225
3.921875
4
import unittest def get_permutations(string): # Generate all permutations of the input string if len(string) <= 1: return set([string]) else: new_list = [] for i in range(len(string)): first = string[i] rest = string[:i] + string[i + 1:] for l in get_permutations(rest): new_list.append(first + l) return set(new_list) # Tests class Test(unittest.TestCase): def test_empty_string(self): actual = get_permutations('') expected = set(['']) self.assertEqual(actual, expected) def test_one_character_string(self): actual = get_permutations('a') expected = set(['a']) self.assertEqual(actual, expected) def test_two_character_string(self): actual = get_permutations('ab') expected = set(['ab', 'ba']) self.assertEqual(actual, expected) def test_three_character_string(self): actual = get_permutations('abc') expected = set(['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) self.assertEqual(actual, expected) unittest.main(verbosity=2) if __name__ == "__main__": perms = get_permutations("abc") print(perms)
927e550bc8446dbbb208bc848c87d00c95d53f67
Elisaveta45/Python_Data_Engineer_Test
/Task1.py
190
3.765625
4
def power(base, exp=4): if all([type(x) != int for x in (base, exp)]): raise TypeError("Both arguments should be integer") else: return base**exp print(power(2, 3))
36d2910f72136bfc4b67129fe80373d38e93ce5d
jschnab/leetcode
/sort_logs.py
738
3.9375
4
# script to sort list of logs with the following format: # ['aw2 act car zoo', 'di9 1 8 4', 'po9 act car zoo', 'me7 9 4 6', 'ml4 cat dog bob'] # first element of log is index, all other elements are body # sort letter-containing logs alphanumerically based on body then break ties with index # do not sort digit-containing logs # return list of sorted letter logs then digits logs def sort_logs(logs): """Sort logs.""" # sorting key function def fun(log): id_, body = log.split(' ', 1) return (0, body, id_) if body[0].isalpha() else (1,) return sorted(logs, key=fun) if __name__ == '__main__': logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] print(sort_logs(logs))
1abe5b7d0fd1c295c917dec8eeebc17c6d32c015
rbarramansa/cursophyton
/Exercicio com manipulação de strings/00.py
429
3.8125
4
frase = 'Curso em Video Python' dividido = frase.split() print(frase[9::3]) len(frase) print(len(frase)) print(frase.count('o')) print(frase.count('o',0,13)) print(frase.find('dea')) print('Curso'in frase) print(frase.replace('Curso','Android')) print(frase.upper()) print(frase.lower()) print(frase.capitalize()) print(frase.title()) print(frase.strip()) print(frase.split()) print('*'.join(frase)) print (' '.join(dividido))
6b7f031b8155e6bf9ab3c257e071f7c1c76bf1fc
CodenameCypher/Dice-Rolling-Simulator-Using-Tkinter
/dice_roll.py
2,708
3.953125
4
from tkinter import * import random import time def animate(): mainLabel['image'] = dice3 time.sleep(0.05) root.update() mainLabel['image'] = dice5 time.sleep(0.05) root.update() mainLabel['image'] = dice2 time.sleep(0.05) root.update() mainLabel['image'] = dice6 time.sleep(0.1) root.update() mainLabel['image'] = dice4 time.sleep(0.1) root.update() mainLabel['image'] = dice2 time.sleep(0.1) root.update() mainLabel['image'] = dice6 time.sleep(0.2) root.update() mainLabel['image'] = dice4 time.sleep(0.2) root.update() mainLabel['image'] = dice1 time.sleep(0.25) root.update() mainLabel['image'] = dice5 time.sleep(0.28) root.update() mainLabel['image'] = dice2 def roll(): temp = random.randint(1,6) animate() if temp is 1: mainLabel['image'] = dice1 textLabel['text'] = "It's a 1!" elif temp is 2: mainLabel['image'] = dice2 textLabel['text'] = "It's a 2!" elif temp is 3: mainLabel['image'] = dice3 textLabel['text'] = "It's a 3!" elif temp is 4: mainLabel['image'] = dice4 textLabel['text'] = "It's a 4!" elif temp is 5: mainLabel['image'] = dice5 textLabel['text'] = "It's a 5!" else: mainLabel['image'] = dice6 textLabel['text'] = "It's a 6!" root.update() def reset(): mainLabel['image'] = PhotoImage(file='images/empty.png') textLabel['text'] = '' root.update() root = Tk() root.resizable(0,0) root.configure(background='#3C176C') root.geometry('500x500+550+100') root.title('Roll A Dice!') root.iconbitmap('images/icon.ico') #images dice1 = PhotoImage(file = 'images/1.png') dice2 = PhotoImage(file = 'images/2.png') dice3 = PhotoImage(file = 'images/3.png') dice4 = PhotoImage(file = 'images/4.png') dice5 = PhotoImage(file = 'images/5.png') dice6 = PhotoImage(file = 'images/6.png') #labels frame = Frame(root,height=380,width=600,bg = "#1B1B1B") frame.pack() frame.place(x=0,y=150) mainLabel = Label(frame,bg="#1B1B1B") #image and animation label mainLabel.pack() mainLabel.place(x = 150, y = 70) textLabel = Label(frame,bg="#1B1B1B",font=('fixedsys',20,'bold'),fg='white') #result label textLabel.pack() textLabel.place(x = 170,y=280) #button btn = Button(root,text='Roll the dice',command=roll,font=('times new roman',16,'bold'),bg="#553492",fg='white',relief=RAISED,width=20,height=2) btn.pack() btn.place(x = 130, y = 35) resetbtn = Button(root,text='Reset',command=reset,font=('times new roman',14,'bold'),bg="#fc3232",fg='white',relief=GROOVE) resetbtn.pack() resetbtn.place(x = 10, y = 100) root.mainloop()
1f2dfa92b7cbae9c926a817fa0edb1ddabb91b85
nekapoor7/Python-and-Django
/PYTHON PROGRAMS/PythonNumpy/array_create.py
627
3.96875
4
import numpy as np arr = np.array([1,2,3]) print(arr) arr1 = np.array([[1,2,3], [4,5,6], [7,8,9]]) print(arr1) arr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0]]) print("Initial Array: ") print(arr) # Printing a range of Array # with the use of slicing method sliced_array = arr[:2, ::2] print("Sliced Array \n",sliced_array) # Printing elements at # specific Indices Index_arr = arr[[1, 1, 0, 3], [3, 2, 1, 0]] print ("\nElements at indices (1, 3), " "(1, 2), (0, 1), (3, 0):\n", Index_arr)
52691909f285b835276bba596014c8a9fc66cfb1
gitHirsi/PythonNotes
/001基础/010公共操作/05容器类型转换.py
316
3.609375
4
""" @Author:Hirsi @Time:2020/5/30 0030 9:31 """ list1=[10,20,30,20,60,80] s1={100,200,300,500} t1=('aa','bb','cc','dd','ee','ff') # tuple() # print(tuple(list1)) # print(tuple(s1)) # list() # print(list(s1)) # print(list(t1)) # set() 集合有去重功能,会丢失重复数据 print(set(t1)) print(set(list1))
75ad294709b9191d882e38c6cb3036b545c3dbe6
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-031.py
411
3.953125
4
# Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem cobrando R$ 0,50 por Km para viagens de até 200Km e R$ 0,45 para viagens mais longas. distancia = int(input('Qual a distância em KM da viagem? ')) if distancia <= 200: preco = distancia*0.50 else: preco = distancia*0.45 print('O valor da viagem de {} Km é de R$ {:.2f} .' .format(distancia, preco))
758c65c4fe3c0041148784b68797433987118628
Lopezcd/252
/FinalProject.py
3,993
3.546875
4
#Written by Chandler Lopez and Austin Jones #Computational Project #Due April 26 #Source codes for histogram and scatter plot (which have been edited to meet our needs) were found on # warning handling was found on https://stackoverflow.com/questions/3920502/how-to-suppress-a-third-party-warning-using-warnings-filterwarnings #pickling from https://stackoverflow.com/questions/27745500/how-to-save-a-list-to-a-file-and-read-it-as-a-list-type/27745539#27745539 #creats empty class lists for the required subject to be used later MathGrade=[]; #imports libraries that will be used in the computing, outputing, and warning handling import random import statistics import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt import warnings import pickle #makes a random list with values between 0 and 100 given the length n i=0 def makelist(n): randlist=[] for i in range(n): x = random.randint(0, 100) randlist.append(x) i=i+1 return randlist #user inputs an int n, n must be between 15 and 25 to continue n=int(input("please enter the amount of students: ")) boolean = False while (boolean==False): if (15<=n and n<=25): boolean=True else: print("you need to input a value between 15 and 25") n=int(input("please enter the amount of students: ")) #Fills the class lists with random values given the length n MathGrade=makelist(n) print("Math Grades are:" , MathGrade) #finds min of the given list def calcmin(TempList): minimum=min(TempList) return minimum #finds max of the given list def calcmax(TempList): maximum=max(TempList) return maximum #finds med of the given list def calcmed(TempList): median=statistics.median(TempList) return median #finds average of the given list def calcav(TempList): total=sum(TempList) average=total/n return average #finds standered deviation of the given list def calstdev(TempList): stdev=statistics.stdev(TempList) return stdev #reads and writes values from the txt file #Pickles the list into the txt file with open("input.txt", "wb") as pic: pickle.dump(MathGrade, pic) # Unpickles the list from the txt file as TempList to be used throught the code with open("input.txt", "rb") as pic: TempList = pickle.load(pic) print("For Math grades: min= " , calcmin(TempList) ,", max= ", calcmax(TempList),", median= ", calcmed(TempList),", average= ", calcav(TempList),", standered deviation= ", calstdev(TempList)) #comparing grades of each student using a scatter plot #the x axis goes from 1-n+1 #y values are dependent upon the class x = range(1,n+1) y1 = TempList #labels both axis plt.xlabel('Student', fontsize=18) plt.ylabel('Grade', fontsize=18) #plots all values on the same x axis with different markers and/or colors plt.scatter(x, y1, c='b', marker="s", label='Math') #adds a legend appearing in the top right corer plt.legend(loc='upper left'); #displays the scatter plot plt.show() #histogram # defines a variable for the mean of distribution mu = calcav(TempList) # defines a variable for the standard deviation of distribution sigma = calstdev(TempList) #grades are on the x axis(only for math class as asked by the assighnment) x=TempList #thicknes/ amount of bars num_bins = 50 #plots values fig, ax = plt.subplots() # the histogram of the data n, bins, patches = ax.hist(x, num_bins, density=1) # add a 'best fit' line #catches the warnings (made for depricaton) and ignores them with warnings.catch_warnings(): warnings.simplefilter("ignore") y = mlab.normpdf(bins, mu, sigma) #lables and plots ax.plot(bins, y, '--') ax.set_xlabel('Grades') ax.set_ylabel('Probability density') ax.set_title('Histogram of Math Grades') # Tweak spacing to prevent clipping of ylabel fig.tight_layout() plt.show()
895eb31c382be1ee16447951944851e5beb9b69a
sakabar/nlpKnock
/3rd/cut.py
633
3.515625
4
#coding: utf-8 import sys # コマンドライン引数で区切り文字と何列目を抜き出すかを指定する # $python cut.py '\t' 1 #既知のバグ 1 #delimでタブ文字を指定しても、うまくいかない。 #既知のバグ 2 #パイプでつなぐとエラーになる(broken pipe) # $python cut.py < hoge.txt | head -n 10 def main(): if len(sys.argv) == 3: delim = sys.argv[1] # '\t' col = int(sys.argv[2]) # 1 if col >= 1: for line in sys.stdin: # arr = line.split(delim) arr = line.rstrip().split('\t') print arr[col-1] if __name__ == '__main__': main()
777b6a9cc0505c22dd47829d075cf1fc8f221d8e
pengjinfu/Python3
/Python04/05-字典操作.py
318
3.515625
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Authour:Dreamer # Tmie:2018.6.1 dict1 = {"name":"123","age":18} """增加键值""" dict1["boy"] = True print(dict1) """删除键值对""" # del dict1["boy"] #删除指定的键值对 age = dict1.pop("age") print(dict1) """修改对应的值""" dict1["name"] = "小明"
9ebada8a837481bc97f22cf40781ea8db408eb3b
Prashant-Bharaj/A-December-of-Algorithms
/December-22/python_raf1800.py
563
3.703125
4
def counter(): file = open("testfile.txt", "r") words = file.readlines() words = words[0].split(' ') words.sort() count = {i : 0 for i in words} for i in words: for j in count.keys(): if(j==i): count.update({j : count.get(j)+1}) for key in count.keys(): print ("{} : {}".format(key,count.get(key))) file.close() def main(): file = open("testfile.txt","w") x=input("Enter a string: ") file.write(x) file.close() counter() if __name__ == "__main__": main()
25c583b82d38c4e3c5ebecfe5b39925a7c21dbaa
erjantj/hackerrank
/search-suggestions-system.py
1,270
3.75
4
class Node: def __init__(self): self.trie = {} self.cache = [] class Solution: def suggestedProducts(self, products, searchWord): if not products: return [] products.sort() if not searchWord: return products[:3] root = Node() for product in products: currNode = root for letter in product: if letter not in currNode.trie: currNode.trie[letter] = Node() currNode = currNode.trie[letter] currNode.cache.append(product) result = [] currNode = root lost = False for letter in searchWord: if not lost and letter in currNode.trie: currNode = currNode.trie[letter] result.append(currNode.cache[:3]) else: lost = True result.append([]) return result products = ["mobile","mouse","moneypot","monitor","mousepad"] searchWord = "mouse" products = ["havana"] searchWord = "havana" products = ["bags","baggage","banner","box","cloths"] searchWord = "bags" products = ["havana"] searchWord = "tatiana" print(Solution().suggestedProducts(products, searchWord))
73e2ead568eb6287ece116aff27d75b4c1f46297
skm0416/Works-From-2017
/2018_1_Computer Graphics/assign1_d3.py
518
3.734375
4
class Student(object): def __init__(self,name): self.name = name def set_age(self,age): self.age = age def set_major(self,major): self.major = major anna = Student('anna') anna.set_age(21) anna.set_major('physics') print(anna.name) print(anna.age) print(anna.major) class MasterStudent(Student): def set_lab(self,lab): self.lab = lab tom = MasterStudent('tom') tom.set_age(25) tom.set_major('computer science') tom.set_lab('graphics lab') print(tom.name) print(tom.age) print(tom.major) print(tom.lab)
0c99fab0621dc9ebfa717738a83cb5a5c4bd3462
Saksham142002/code-source
/sa10.py
278
3.578125
4
x=[[1, 2, 3], [4, 5 ,6], [7, 8, 7]] y=[[7, 8, 9], [3, 4, 5], [9, 3, 2]] result= [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in range (len(x)): for j in range (len(x[0])): result[i][j]= x[i][j] + y[i][j] for r in result : print(r)
364bf4d9d3d2e83da9e336b937137b7076714553
paruuy/learn-python
/exercicios/exercises_string2.py
2,065
4.09375
4
#!/usr/bin/python -tt # coding: utf-8 import unittest # Dado uma string, se o seu comprimento for pelo menos 3, adicione 'ing' ao final. # Caso já termine em 'ing' adicionar "ly". # Se o comprimento da string for inferior a 3, deixe-o inalterado. # Retorne a string resultante. def verbing(s): if "ing" in s: return s + "ly" elif len(s) >= 3: return s + "ing" else: return s # (google solution) def verbingV2(s): if len(s) > 3: if s.endswith("ing"): return s + "ly" else: return s + "ing" return s # Dado um astring, procurar a primeira ocorrência da substring 'not' e 'bad' # Se 'bad' vier após o 'not' # substituir todo o trecho "not ... bad" por 'good' # Retorne a string resultante. def not_bad(s): n = s.find('not') b = s.find('bad') if n != -1 and b != -1 and b > n: s = s[:n] + 'good' + s[b+3:] return s # Considere dividir uma string em duas metades. # Se o comprimento for par, a parte da frete (front) e a parte de trás (back) são do mesmo tamanho. # Se o comprimento for ímpar, o caracter extra irá para a aprte da frente. # # Dado 2 strings, 'a' e 'b', retornar um string na forma # a front + b front + a back + b back def front_back(a, b): pass class MyTest(unittest.TestCase): def test_verbing(self): self.assertEqual(verbing('hail'), 'hailing') self.assertEqual(verbing('swiming'), 'swimingly') self.assertEqual(verbing('do'), 'do') def test_not_bad(self): self.assertEqual(not_bad('This movie is not so bad'), 'This movie is good') self.assertEqual(not_bad('This dinner is not that bad!'), 'This dinner is good!') self.assertEqual(not_bad('This tea is not hot'), 'This tea is not hot') self.assertEqual(not_bad("It's bad yet not"), "It's bad yet not") def test_front_back(self): self.assertEqual(front_back('abcd', 'xy'), 'abxcdy') self.assertEqual(front_back('abcde', 'xyz'), 'abcxydez') self.assertEqual(front_back('Kitten', 'Donut'), 'KitDontenut') if __name__ == '__main__': unittest.main()
1eefeb4a5bbd1763797dba7f00c01e73057117a4
fdas3213/Leetcode
/1048-longest-string-chain/1048-longest-string-chain.py
787
3.515625
4
class Solution: def longestStrChain(self, words: List[str]) -> int: """ step 1. sort the input array by word length step 2. for each word, remove one character at a time, and see if the new word exists in the hashmap or not; if it exists, check it's previous sequence length """ wordMap=defaultdict(list) words.sort(key=lambda x: len(x)) ans = 1 for word in words: curLen = 1 l = len(word) for i in range(l): newWord = word[:i] + word[i+1:] prevLen = wordMap.get(newWord, 0) curLen = max(curLen, prevLen+1) wordMap[word] = curLen ans = max(ans, curLen) return ans
b29b85e268f0e71a27a8f8a216f8f33d664da025
thiakx/leetcode
/leetcode/206_reverse_linked_list.py
762
3.90625
4
class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev = None curr = head while curr: next_temp = curr.next curr.next = prev prev = curr curr = next_temp return prev # #recursion # def reverseList(self, head): # if head is None or head.next is None: # return head # else: # solution = Solution() # prev = solution.reverseList(head.next) # # let n_(k+1) point back to n_k # head.next.next = head # # drop the original pointer so wont have loop # head.next = None # return prev
448d6fcd1520c54caee12be902895d7024f5ef81
CSC1-1101-TTh9-S21/samplecode
/week10/pretendgrades-calculations.py
937
3.84375
4
import numpy as np # laborious code for reading in a csv file grades = [] people= [] f= open("pretendgrades.csv") labels = f.readline().rstrip().split(",") for line in f: parts = line.rstrip().split(",") grades.append([int(p) for p in parts[1:]]) people.append(parts[0]) f.close() # convert list of list to numpy array! print(grades) npgrades = np.array(grades) print(npgrades) # print out mean of first row print(np.mean(npgrades[0,:])) # print out mean of first column print(np.mean(npgrades[:,0])) # print out averages of *each* row and *each* column print(np.mean(npgrades, axis=0)) print(np.mean(npgrades, axis=1)) # Print out who got the highest grade on the first quiz highestgrade = np.max(npgrades[:,0]) highestindex = np.argmax(npgrades[:,0]) print(highestgrade, highestindex) print(people[highestindex], "got the highest grade", highestgrade) # quicker way to do it! print(people[np.argmax(npgrades[:,0])])
246dbb0afe15a03dd85f7a2fffe90045f025ab89
ywcmaike/OJ_Implement_Python
/leetcode/786. 第 K 个最小的素数分数.py
954
3.671875
4
# author: weicai ye # email: yeweicai@zju.edu.cn # datetime: 2020/7/27 下午2:25 # 一个已排序好的表 A,其包含 1 和其他一些素数.  当列表中的每一个 p<q 时,我们可以构造一个分数 p/q 。 # # 那么第 k 个最小的分数是多少呢?  以整数数组的形式返回你的答案, 这里 answer[0] = p 且 answer[1] = q. # # 示例: # 输入: A = [1, 2, 3, 5], K = 3 # 输出: [2, 5] # 解释: # 已构造好的分数,排序后如下所示: # 1/5, 1/3, 2/5, 1/2, 3/5, 2/3. # 很明显第三个最小的分数是 2/5. # # 输入: A = [1, 7], K = 1 # 输出: [1, 7] # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/k-th-smallest-prime-fraction # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 from typing import List class Solution: def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]: if __name__ == "__main__": pass
c4dfd064c0ddf2ec4e67783b37d2eab4e93af544
rpraneeth264/DemoDevOps
/DemoProg.py
347
3.640625
4
n1=24 n2=6 sum=n1+n2 sub=n1-n2 prod=n1*n2 quot=n1//n2 rem=n1%n2 div=n1/n2 print("sum of",n1,",",n2,"is",sum) print("subtraction of",n1,",",n2,"is",sub) print("product of",n1,",",n2,"is",prod) print("quotient in division of ",n1,",",n2,"is",quot) print("remainder in division of",n1,",",n2,"is",rem) print("perfect division of",n1,",",n2,"is",div)
0a88473a7edfe3858721413feb2ca8f5f422d6b0
wyf19901121/LeetCodeForPython
/Base7504.py
625
3.546875
4
""" 504. Base 7 504. 七进制数 给定一个整数,将其转化为7进制,并以字符串形式输出。 示例 1: 输入: 100 输出: "202" 示例 2: 输入: -7 输出: "-10" 注意: 输入范围是 [-1e7, 1e7] """ class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ if num == 0: return "0" curNum = abs(num) curStr = "" while curNum != 0: curStr += str(curNum%7) curNum /= 7 curStr = "".join(reversed(curStr)) return curStr if num > 0 else "-" + curStr
afac590c436c5a6dd9a7c1a0af5ca27264d3f68a
vedantdas/Machine-Learning-py-files
/Sum of Multiple of 3 and 5.py
218
4.125
4
sum =0 for x in range(1000): #print("x =", x) if (x % 3 == 0) or (x % 5 == 0): #print("x after condition =", x) sum=sum + x #print('sum =', sum) print("Sum of Multiple of 3 and 5 =",sum)
97acbd8d43edb4cad96af137e7dd6e10de780376
josejpalacios/codecademy-python3
/Lesson 05: Loops/Lesson 02: Code Challenge: Loops/Exercise 05: Odd Indices.py
666
4.40625
4
# Create a function named odd_indices() that has one parameter named lst. # The function should create a new empty list and add every element from lst that has an odd index. # The function should then return this new list. # For example, odd_indices([4, 3, 7, 10, 11, -2]) should return the list [3, 10, -2]. #Write your function here def odd_indices(lst): # Create new lsit new_lst = [] # Iterate through lst's odd indices for i in range(1, len(lst), 2): # Add i element from lst to new_lst new_lst.append(lst[i]) # Return new_lst return new_lst #Uncomment the line below when your function is done print(odd_indices([4, 3, 7, 10, 11, -2]))
55bb00829103c75a75dde9a19601d1550119df7d
srstka/my_files
/training/03_Product.py
196
3.609375
4
product = input("Please enter the product here: ") print("Country code is: ",product.split("-")[0]) print("Product code is: ",product.split("-")[1]) print("Batch code is: ",product.split("-")[2])
0e19eb07a3820c33eee148640c8be0544507d1bc
ZanataMahatma/Python-Exercicios
/Tuplas em Python/ex074.py
1,121
4.25
4
'''Exercício Python 074: Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.''' # correção from random import randint numeros = (randint(1,10),randint(1,10),randint(1,10),randint(1,10),randint(1,10)) print('Os numeros sorteados foram: ',end='') for n in numeros: print(f'{n}',end=' ') print(f'\nO NUMERO MAIOR SORTEADOR FOI: {max(numeros)}') print(f'O NUMERO MENOR SORTEADO FOI: {min(numeros)}') # minha resposta incompleta . '''from random import choice n1 = n2 = n3 = n4 =n5 = maior = menor = 0 tupla= (10,5,8,9,4) if tupla != 0: n1 = choice(tupla) print(n1,end=' ') n2 = choice(tupla) print(n2,end=' ') n3 = choice(tupla) print(n3,end=' ') n4 = choice(tupla) print(n4,end=' ') n5 = choice(tupla) print(n5,) elif n1 > n2: maior = n1 if n3 < n2: maior = n1 elif n4 < n3: maior = n1 elif n5 < n4: maior = n1 else: menor = n2 print(tupla.index(maior)) '''
77a4baff34707d19793d2e3feeac6d5a1a823740
michelleweii/Leetcode
/03_树与二叉树/104-二叉树的最大深度.py
2,212
3.6875
4
""" easy 2021-12-02 二叉树属性 计算每个子树的高度,再+1。 有关于二叉树深度与高度概念区别:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E9%80%92%E5%BD%92 """ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepth(self, root): if root is None: return 0 # 左子树高度 LD = self.maxDepth(root.left) # 右子树高度 RD = self.maxDepth(root.right) return max(RD,LD)+1 # 定义queue,层次队列 def maxDepth2(self, root): if not root:return 0 q, depth = [root], 0 while q: cur_level, size = [],len(q) for i in range(size): node = q.pop(0) if node.left: q.append(node.left) if node.right: q.append(node.right) # 出当前层 depth += 1 return depth # 真正求取二叉树的最大深度,代码应该写成如下:(前序遍历) """ class Solution { public: int result; void getDepth(TreeNode* node, int depth) { result = depth > result ? depth : result; // 中 if (node->left == NULL && node->right == NULL) return ; if (node->left) { // 左 depth++; // 深度+1 getDepth(node->left, depth); depth--; // 回溯,深度-1 } if (node->right) { // 右 depth++; // 深度+1 getDepth(node->right, depth); depth--; // 回溯,深度-1 } return ; } int maxDepth(TreeNode* root) { result = 0; if (root == NULL) return result; getDepth(root, 1); return result; } }; """ if __name__ == '__main__': a = TreeNode(3) b = TreeNode(9) c = TreeNode(20) d = TreeNode(15) e = TreeNode(7) a.right = c a.left = b c.right = e c.left = d print(Solution().maxDepth(a)) print(Solution().maxDepth2(a))
f2b06363eb7bf486e5d397ffbf4c68f88ba6c5bc
Xiangyaojun/Algorithms
/栈和队列/用栈实现队列.py
1,886
4.125
4
# coding:utf-8 ''' leetcode 224 题目:使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 说明: 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。 ''' class MyQueue: def __init__(self): self.stack_1 = [] self.stack_2 = [] def push(self, x): while len(self.stack_2)>0: temp = self.stack_2.pop(-1) self.stack_1.append(temp) self.stack_1.append(x) def pop(self): while len(self.stack_1) > 0: temp = self.stack_1.pop(-1) self.stack_2.append(temp) return self.stack_2.pop() def peek(self): while len(self.stack_1) > 0: temp = self.stack_1.pop(-1) self.stack_2.append(temp) result = self.stack_2[-1] while len(self.stack_2) >0: temp = self.stack_2.pop(-1) self.stack_1.append(temp) return result def empty(self): if len(self.stack_1)==0 and len(self.stack_2)==0: return True else: return False # Your MyQueue object will be instantiated and called as such: obj = MyQueue() obj.push(1) obj.push(2) obj.push(3) print(obj.pop()) print(obj.pop()) print(obj.pop())
f1af60ab4c1d00259368639dc7bd7c320d86a5df
Boson220/python_practice
/google-python-exercises/python_practice.py
771
4.09375
4
#!/usr/bin/env python # import modules used here -- sys is a very standard one import sys def repeat(s, exclaim): """ Returns the string 's' repeated 3 times. If exclaim is true, add exclamation marks. """ result = s + s + s # can also use "s * 3" which is faster (Why?) if exclaim: result = result + '!!!' return result # Gather our code in a main() function def main(): # Defines a "repeat" function that takes 2 arguments. print repeat('hello',1) # Command line args are in sys.argv[1], sys.argv[2] ... # sys.argv[0] is the script name itself and can be ignored # Standard boilerplate to call the main() function to begin # the program. if __name__ == '__main__': main()
8d71a83dec2bed6159d8db48146cb8da8b19ae9a
Shatoon/Alg_on_Python
/week6/task_E/Solution_E.py
2,814
3.953125
4
N = int(input()) # Вводится количество студентов student_list = [[] for i in range(N)] # Создаем список студентов с пустыми списками их оценок, где N - Количество вложенных списков def grades_list(student_list): # Ф-ция формирует список успеваемости "grades list" while True: x = input() if x == '#': break student_grade = list(map(int, x.split())) # создаем список натуральных чисел из полученных в перменной "х" значений (2 числа) student_id = student_grade[0] # Первый элемент присваивем переменной "student_id" value = student_grade[1] # Второй элемент присваивем переменной "value" student_list[student_id].append(value) # Добавляем "value" во вложенный в "student_list" список №"student_id" по счету return student_list #Возвращаем список "student_list" def revers_sort(l): # Ф-ция возвращает сумму чисел из вложенного списка if isinstance(l, list): # Если елемент списка является списком return sum(revers_sort(x) for x in l) # Вернуть сумму всех элементов данного вложенного списка else: # Иначе return l # Вернуть значениеединого элемента def revers_sort_in_list(l): # Ф-ция реверсной сортировки вложенных списков по сумме их элементов for i in range(len(l)): # Итерация через длинну основного списка l[i].sort(reverse=True) # каждый элемент списка сортируем от большего к меньшему return l # Возвращаем список в отсортированном виде grades_list(student_list) # Запускаем ф-цию получения списка student_list.sort(key=revers_sort, reverse=True) # Сортируем список по убыванию ллюч"key=revers_sort" revers_sort_in_list(student_list) # Запускаем ф-цию реверсной сортировки вложенных списков student_list = [str(j) for i in student_list for j in i] # Выносим элементы вложенных списков в основной список print(" " . join(student_list)) # Выводим на печать все элементы списка в одну строку, методом ".join"
5fbfcf2755a321ada5634079bb1c181fde3233d9
720315104023/phython-program
/median.py
128
3.609375
4
print("enter the values"); a = [int(x) for x in input().split()] p,s,t=a w=a.sort() median=a[2] print("Median is : %i" %median)
21686a46e537590d66582ae9acd02d121dc928d3
ricardosaraiva/python_estudos
/repeticao/repeticao_tabuada.py
266
4
4
numero = 1; while numero <= 10: multiplicador = 1 print('tabuada do %d' %numero) while multiplicador <= 10 : print('%d x %d = %d' %(numero, multiplicador, numero * multiplicador)) multiplicador = multiplicador + 1 numero = numero + 1
ca3ec8db704eda018f27b6d625b833fa61e0154a
MariiaChernetska/pythonhw
/6/6.1.py
292
3.859375
4
def prime_gen(start, end): while start <= end: isPrime = True for x in range(2, start): if start % x == 0: isPrime = False break if isPrime: yield start start += 1 print(list(prime_gen(5, 100)))
a839bd76cae69d9130d00d48500f27a5f36ba351
AvinashIkigai/Art-of-Doing
/RockPaperScissor.py
3,032
4.03125
4
import random print("Welcome to a game of Rock Paper Scissors") rounds = int(input("\nHow many rounds would you like to play: ")) moves = ['rock','paper','scissors'] p_score = 0 c_score = 0 #The main game loop for game_round in range(rounds): print("\nRound "+str(game_round + 1)) print("Player: " + str(p_score) + "\tComputer: " + str(c_score)) #Get the computer moves c_index = random.randint(0,2) c_choice = moves[c_index] #Get the players move p_choice = input("Time to pick...rock, paper, scissors: ").lower().strip() #If the player makes a valid choice if p_choice in moves: print("\tComputer: " + c_choice) print("\tPlayer: " + p_choice) #Computer chooses rock if p_choice == 'rock' and c_choice == 'rock': winner = 'tie' phrase = 'It is a tie, how boring!' elif p_choice == 'paper' and c_choice == 'rock': winner = 'player' phrase = 'Paper covers rock!' elif p_choice == 'scissors' and c_choice == 'rock': winner = 'computer' phrase = 'Rocks smashes scissors!' #Computer chooses paper elif p_choice == 'rock' and c_choice == 'paper': winner = 'computer' phrase = 'Paper covers rock!' elif p_choice == 'paper' and c_choice == 'paper': winner = 'tie' phrase = 'It is a tie, how boring!' elif p_choice == 'scissors' and c_choice == 'paper': winner = 'player' phrase = 'Scissors cut paper!' #Computer chooses scissors elif p_choice == 'rock' and c_choice == 'scissors': winner = 'player' phrase = 'Rocks smashes scissors!' elif p_choice == 'paper' and c_choice == 'scissors': winner = 'computer' phrase = 'Scissors cut paper!' elif p_choice == 'scissors' and c_choice == 'scissors': winner = 'tie' phrase = 'It is a tie, how boring!' else: print("Round winner not calculated.") winner = 'tie' phrase = 'It is a tie, how boring!' #Display round result print("\t"+ phrase) if winner == 'player': print("\tYou win round " + str(game_round + 1) +".") p_score += 1 elif winner == 'computer': print("\tComputer wins round " + str(game_round + 1)+".") c_score += 1 else: print("\tThis round was a tie.") #Else the player did not make a valid move else: print("This is not a valid game option!") print("Computer gets the point!") c_score += 1 #Game has ended, Print results print("\nFinal Game Results") print("\tRounds Played: " + str(rounds)) print("\tPlayer Score: " + str(p_score)) print("\tComputer Score: " + str(c_score)) if p_score > c_score: print("\tWinner: PLAYER!!!") elif c_score > p_score: print("\tWinner: COMPUTER :-(") else: print("\tThe Game was a tie")
348ed159b842b78bf2451f221b93b5e69685cf91
Marcelo2691/Python-Project-Bachelor
/scratch the return.py
4,127
3.6875
4
global Agenda,DNA,values values = [] Agenda = {} DNA = [] def MenuPrincipal(Agenda,values): print("1 - Introduzir novo cliente") print("2 - Associar um contacto de um cliente") print("3 - Associar um DNA de um cliente") print("4 - Testar gene de um DNA") print("5 - Excluir um contacto de um cliente ") print("6 - Consultar Agenda") print("7 - Gravar dados para um ficheiro") print("8 - Ler dados de um ficheiro \n ") print("0 - Sair do programa") opcao =int(input("Escolha uma opção")) if opcao == 1: menu1(Agenda,values) elif opcao ==2: menu2(Agenda,values) elif opcao ==3: menu3(Agenda, values) elif opcao ==4: menu4(Agenda,values) elif opcao ==5: menu5(Agenda,values) elif opcao ==6: menu6(Agenda,values) elif opcao ==7: menu7() elif opcao ==8: menu8() else: print("Thank your come again!") def menu1(Agenda,values): contactos=[] NomeCliente = input("Diga o nome do Cliente") Agenda[NomeCliente]= contactos contacto = int(input("Diga o contacto do Cliente")) contactos.append(contacto) x = True while x: contacto = int(input("Diga o contacto do Cliente")) if contacto != 0: contactos.append(contacto) Agenda[NomeCliente] = contactos else: x = False values.append(contactos) print(Agenda) MenuPrincipal(Agenda,values) def menu2(Agenda,values): contactos=[] if Agenda == {}: menu1(Agenda, contactos, values) else: NomeCliente = input("Diga o nome do cliente para adicionar--") if Agenda[NomeCliente]: contacto = int(input("Diga o contacto do Cliente")) contactos.append(contacto) x = True while x: contacto = int(input("Diga o contacto do Cliente")) if contacto != 0: contactos.append(contacto) Agenda[NomeCliente] = contactos else: x = False values.append(contactos) Agenda[NomeCliente]=values print(Agenda) MenuPrincipal(Agenda, values) def menu3(Agenda,values,): values=[] DNA=[] aminoacidos=['A','T','G','C'] if Agenda == {}: menu1(Agenda, values) else: NomeCliente = input("Diga o nome do cliente para adicionar") if NomeCliente in Agenda.keys(): values=Agenda.get(NomeCliente) DNA = input("Insira a sequência de DNA: ").upper() DNA=[i for i in DNA] for i in range(len(DNA)): if DNA[i] in aminoacidos: pass else: print("ERRO: A sequência de DNA não é valida", "\n") menu3(Agenda,values) DNA = "".join(DNA) values=values.append(DNA) Agenda[NomeCliente]=DNA else: print("Contacto nao encontrado") MenuPrincipal(Agenda, values) print(Agenda) MenuPrincipal(Agenda,values) def menu4(Agenda,values,): if Agenda == {}: menu1(Agenda,values) else: NomeCliente = input("Diga o nome do cliente para teste do seu DNA") if NomeCliente in Agenda.keys(): DNA= Agenda.get(NomeCliente) if DNA[0:3] == "ATG" and len(DNA) % 3 == 0: if DNA[-3:] == "TAG" or "TAA" or "TGA": print("O gene é XPT") else: print("O gene nao é XPT") def menu6 (Agenda,values): NomeCliente = input("Diga o nome do cliente") if NomeCliente in Agenda.keys(): print("Contacto", values(NomeCliente)) def menu5(Agenda,values): NomeCliente = input("Diga o nome do cliente") if NomeCliente in Agenda.keys(): Agenda.pop(NomeCliente) MenuPrincipal(Agenda,values) if __name__ == '__main__': MenuPrincipal(Agenda,values)
344a04d45bb8865249faa5cbefbbff5416c710b7
lisnb/lintcode
/MergeSortedArrayII.py
981
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: LiSnB # @Date: 2015-04-26 14:42:31 # @Last Modified by: LiSnB # @Last Modified time: 2015-04-26 15:03:48 class Solution: """ @param A: sorted integer array A which has m elements, but size of A is m+n @param B: sorted integer array B which has n elements @return: void """ def mergeSortedArray(self, A, m, B, n): # write your code here i = m+n-1 ia, ib = m-1, n-1 if n==0: return if m==0: A[:]=B return while ia >= 0 and ib >=0: if A[ia]>B[ib]: A[i]=A[ia] ia-=1 else: A[i]=B[ib] ib-=1 i-=1 if ia<0: A[:ib+1] = B[:ib+1] if __name__ == '__main__': s = Solution() A = [4,5,6, None, None] B = [1,2] s.mergeSortedArray(A, 3, B, 2) print A
a979c18e83331c5e068adf0e4496efc6af6d05e3
juishah14/Accessing-Web-Data
/spidering_bs4.py
1,545
3.984375
4
# Assignment from University of Michigan's Coursera Course Using Python to Access Web Data # For this assignment, we must write a Python program to use urllib and Beautiful Soup to parse HTML, extract the link at the given pos, # and follow that link, repeating the process count number of times to report the last name that we find. # Test with http://py4e-data.dr-chuck.net/known_by_Tyelor.html, letting count = 7 and position = 18. Answer is Erika. from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # data collection url = input('Enter URL: ') count = int(input('Enter count: ')) pos = int(input('Enter position: ')) print('Retrieving: %s' % url) for i in range(count): html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') # getting anchor tags tags = soup('a') # list of all anchor tags ps = 0 for tag in tags: ps += 1 # if we reach the tag at the pos that we want, then if ps == pos: # we extract href values and now open up the link at that pos print('Retrieving: %s' % str(tag.get('href', None))) # we now reset the url to be that link, open the url, and again go to the url at the pos we want url = str(tag.get('href', None)) ps = 0 break # repeat process count number of times
8ca235ae1506704b64b417f98da3e6b1bc408f97
Seungjin22/TIL
/00_StartCamp/02_Day/05_reverse_content.py
274
3.578125
4
#1. 각각의 라인을 리스트의 요소로 불러오기 with open('writelines_ssafy.txt', 'r') as f: lines = f.readlines() #2. 뒤집기 lines.reverse() #3. line을 작성하기 with open('reverse_ssafy.txt', 'w') as f: for line in lines: f.write(line)
8387a68bcc9ff2ac689b77e5a7465b566e4621f3
jiningzhao/MachineLearing
/04Regression/R_Square.py
630
3.578125
4
import numpy as np def polyfit(x,y,degree): #degree是多项式拟合方程中x指数的最大值 retults={} #字典 # 多项式拟合 coeffs=np.polyfit(x,y,degree) #coeffs是得到的方程系数 print(coeffs) # 给定x,计算其预测值yhat p=np.poly1d(coeffs) #以coeffs作为参数生成一个最高一次幂的拟合模型 yhat=p(x) # 计算R-Squared y_mean=np.mean(y) ssr=np.sum((yhat-y_mean)**2) sst=np.sum((y-y_mean)**2) r_Square=ssr/sst return r_Square X=[1,3,8,7,9] Y=[10,12,24,21,34] print(polyfit(X,Y,1))
da46149bec7a3551efd2ce2204efa84520bfe65a
dandraden/Python-Projects
/project-01/FibExample.py
736
3.640625
4
import datetime memo = {} fibd = {} def fib (n): if n <= 2: f = 1 else: f = fib(n - 1) + fib(n - 2) return f def fib2 (n): if n in memo: return memo[n] if n <= 2: f = 1 else: f = fib2(n - 1) + fib2(n - 2) memo[n] = f return f def fib3 (n): for k in range(1,n+1): if k <= 2: f = 1 else: f = fibd[k - 1] + fibd[k - 2] fibd[k] = f return fibd[n] a = datetime.datetime.now() result_fib = fib(40) b = datetime.datetime.now() print (result_fib) print(b-a) a = datetime.datetime.now() result_fib = fib2(40) b = datetime.datetime.now() print (result_fib) print(b-a) a = datetime.datetime.now() result_fib = fib3(40) b = datetime.datetime.now() print (result_fib) print(b-a)
aa1d0c64023cbecc74156eb20fd5f6220eba71af
nirjharij/cracking-the-coding-interview-in-python
/recursion_and_dp/magic_index.py
848
3.8125
4
# sorted array with distinct values def find_magic_index(arr, start, end): mid = (start + end) // 2 if arr[mid] == mid: return mid elif arr[mid] < mid: index = find_magic_index(arr, mid + 1, end) else: index = find_magic_index(arr, start, mid - 1) return index # sorted array with non distinct values def magic_index(arr, start, end): if end < start: return -1 mid = (start + end) // 2 if arr[mid] == mid: return mid left_index = min(mid - 1, arr[mid]) left = magic_index(arr, start, left_index) if left >= 0: return left right_index = max(arr[mid], mid+1) right = magic_index(arr, right_index, end) return right # print(find_magic_index([-10, -5, 0, 3, 5, 6, 7, 8, 9], 0, 9)) print(magic_index([-1, 0, 1, 2, 6, 6, 6, 7, 8, 9], 0, 9))
e25bcb943b0f959d00dc3c86a48aa530471654f3
daniel-reich/ubiquitous-fiesta
/SQZoHFDfizBTP4HSx_17.py
510
3.59375
4
def missing_alphabets(txt): x="abcdefghijklmnopqrstuvwxyz" res='' if len(x)==len(txt): return "" b=txt.count(txt[1]) if b==1: for i in x: if i not in txt: res+=i return res else: rs='' for i in x: c=txt.count(i) if c>1 and i not in rs: rs+=i*c else: res+=i*c if i not in res: res+=i*b return res
c8d8d1bff8b652a41be8745d170f57b2dcf77717
JoeyZhen/Life_data_analysis
/jxz5374/ranking.py
2,992
3.765625
4
""" file:ranking.py author: Joey Zhen created: 12/09/2017 """ from utils import * from jxz5374.utils import CountryValue, read_data, filter_region, filter_income def expectancy(country): """ This function returns the key for sorting the life expectancy of countries in a typically year. :param country: :return: """ return country.value def sorted_ranking_data(data,year): """ This function returns a list of CountryValue structures, sorted in descending order (highest to lowest). :param data: :param year: :return: """ lst=[] index=year-1960 country1=data[0] for i in country1: if country1[i].expectancy[index] != "": country=CountryValue(i,float(country1[i].expectancy[index])) lst.append(country) lst=sorted(lst,key=expectancy,reverse=True) return lst def main(): """ This main function run the function above and return data which contains data for the specified year are included in the sorted list. :return: """ dabase= read_data("worldbank_life_expectancy") while True: years=int(input("Enter year of interest: ")) if years>2015 or years<1960: print("inalid years") elif years==-1: break else: region1=str(input("Enter region: ")) data=filter_region(dabase,region1) if data == None: pass else: region2=str(input("Enter income category: ")) data=filter_income(data,region2) if data == None: pass else: data=sorted_ranking_data(data,years) if len(data)<11-1: num=1 print("\nTop 10 Life Expectancy for",str(years)) for i in data: print(str(num)+":",i.country,str(i.value)) num+=1 num=len(data) print("\nBottom 10 Life Expectancy for",str(years)) for i in range(len(data)-1,-1,-1): print(str(num)+":",data[i].country,str(data[i].value)) num=num-1 else: num=1 print("\nTop 10 Life Expectancy for",str(years)) for i in range(0,10): print(str(num)+":",data[i].country,str(data[i].value)) num=num+1 num=len(data) print("\nBottom 10 Life Expectancy for", str(years)) for i in range(len(data) - 1,len(data)-11,-1): print(str(num)+":",data[i].country, str(data[i].value)) num=num-1 print() main()
c325a5d16eb1deffe629791df8084cfdf9461e5b
jiceR/france-ioi
/python/karvas.py
337
3.515625
4
nbKarvas = int(input()); karvas= 0; for loop in range(nbKarvas): poidKarvas= int(input("poid du karvas: ")); ageKarvas= int(input("age du karvas: ")); corneKarvas= int(input("cornes du karvas: ")); tailleKarvas= int(input("taille du karvas: ")); noteKarvas= (corneKarvas*tailleKarvas)+poidKarvas; karvas+=1; print(noteKarvas);
5a34582be69ad3111a1d5a8ba471bc1b3b02add8
boada/py-astro-stat
/week4/cheapEM.py
4,466
3.75
4
# cheapEM # # This is a very quick and dirty (and ugly!) implementation of # Expectation-Maximization algorithm. Hopefully it is a fairly # transparent implementation of the book's algorithm. Ideally, the # model parameters should converge upon the correct values regarless # of the initialization values. # # Karen Lewis (June 10, 2014) from matplotlib import pyplot as plt import numpy as np from sklearn.mixture import GMM #------------------------------------------------------------ # Set up the dataset. We'll use scikit-learn's Gaussian Mixture # Model to sample data from a mixture of Gaussians. The usual way of # using this involves fitting the mixture to data: we'll see that # below. Here we'll set the internal means, covariances, and weights # by-hand. np.random.seed(1) Ndata=10000 gmm = GMM(3, n_iter=1) gmm.means_ = np.array([[-1], [0], [3]]) gmm.covars_ = np.array([[1.5], [0.3], [0.5]]) ** 2 gmm.weights_ = np.array([0.3, 0.5, 0.2]) X = gmm.sample(Ndata) #Plot histogram of data so we know what we're dealing with plt.hist(X, 50, normed=True, histtype='stepfilled', alpha=0.4) plt.show() #Initialize the variables. # Note on weights: The w's are the so-called responsibilities. # Each is an array with Ndata elements that effectively states # what fraction of that data point can be contributed to each # of the components in the model. The responsibility for a # particular component should be quite large for data points close to # its mean and progressively smaller farther away from the mean. # There are really two alternatives for initilizing. # 1) Select an initial guess for # the mu's, variances, and alphas and then calculate an initial # set of w's. # 2) Or, if you wanted to run this more "hands-off" on data, you might # not want to specify initial values and simply set every w_i equal # to 1/M where M is the number of model components. # Right now this is set to option 1 and I encourage you to try both # ways and see if it makes any practical difference. # Choose sensible mu mu1=-0.9 mu2=0.1 mu3=2.9 # Choose sensible variance var1=1.3**2 var2=0.25**2 var3=0.55**2 # Choose sensible coefficients a1=0.25 a2=0.55 a3=0.25 # Use these values to calculate weights following 4.21. # The following are the numerators in 4.21. tmp1=(a1/np.sqrt(2*np.pi*var1))*np.exp(-(X-mu1)**2/(2*var1)) tmp2=(a2/np.sqrt(2*np.pi*var2))*np.exp(-(X-mu2)**2/(2*var2)) tmp3=(a3/np.sqrt(2*np.pi*var3))*np.exp(-(X-mu3)**2/(2*var3)) # The following is essentially the current model prediction for # each data point. It is also the deonomicator in 4.21 tmp=tmp1+tmp2+tmp3 # Now we have everything to calculate the weights. w1=tmp1/tmp w2=tmp2/tmp w3=tmp3/tmp # Print a sample of the the weights print "End of 1st iteration sample w's" for i in range(0,10,1): print X[i],w1[i],w2[i],w3[i] # Now that we've gotten everything initialized, enter a loop # to iterate on the maximization and estimation steps Niteration=21 for k in range(0,Niteration,1): # Update mus according to 4.26 mu1=np.sum(w1*X)/np.sum(w1) mu2=np.sum(w2*X)/np.sum(w2) mu3=np.sum(w3*X)/np.sum(w3) # Update variances according to 4.27 var1=np.sum(w1*(X-mu1)**2)/np.sum(w1) var2=np.sum(w2*(X-mu2)**2)/np.sum(w2) var3=np.sum(w3*(X-mu3)**2)/np.sum(w3) # Calculate new scale factors, following 4.28 a1=np.sum(w1)/Ndata a2=np.sum(w2)/Ndata a3=np.sum(w3)/Ndata # Use these values to calculate new weights following 4.21, as above tmp1=(a1/np.sqrt(2*np.pi*var1))*np.exp(-(X-mu1)**2/(2*var1)) tmp2=(a2/np.sqrt(2*np.pi*var2))*np.exp(-(X-mu2)**2/(2*var2)) tmp3=(a3/np.sqrt(2*np.pi*var3))*np.exp(-(X-mu3)**2/(2*var3)) tmp=tmp1+tmp2+tmp3 w1=tmp1/tmp w2=tmp2/tmp w3=tmp3/tmp # Output results of every 5th iteration. The % action is the modulo # operator. if (k%5 == 0): # the %i means insert a variable that is an integer print "Iteration %i done" % (k) # print "" # for i in range(0,5,1): # print w1[i],w2[i],w3[i] print "mu:", mu1,mu2,mu3 print "variance:", var1, var2, var3 print "scale:",a1, a2, a3 print "" # Show progress on responsibilities plt.scatter(X,w1,color='red') plt.scatter(X,w2,color='blue') plt.scatter(X,w3,color='green') plt.show()
067990ec42d6a73cdd78c1006e6ad204dd3568d1
patiregina89/Desafios-Prof_Guanabara
/Desafio8.py
249
4.09375
4
#escreva um programa que leia o valor em metros e exiba convertido em centímetro e milímetros. m = float (input('Informe o tamanho em metros: ')) cm = m * 100 mm = m * 1000 print('{} metros = {} centrimetros = {} milimetros'.format(m, cm, mm))
974123192d25fd70169ff2acb981549cc5ee3520
tevtonez/PRACTICEPYTHON.org
/12_list_ends.py
607
4.34375
4
''' ---------------------------------------- TASK 12 from http://www.practicepython.org/ ---------------------------------------- Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. ''' # # SOLUTION # created by Kostya # on 4 Jan 2017 # Time spent: 3 min # if __name__ == '__main__': def first_n_last( l ): new_list = [] new_list.extend( ( l[0], l[-1] ) ) print( new_list ) a = [5, 10, 15, 20, 25] first_n_last( a )
ba72ae6729ae6a8647143c01f6d8df45d2908d42
lkwilson/math451
/h2/p2.py
2,604
3.671875
4
#!/usr/bin/env python3 import numpy as np import math from methods import pretty_print from methods import zeroOut def getB(size): """Post: An is set and global. n is set and global.""" n = size B = np.matrix([[getBij(r, c, n) for c in range(1, n+1)] for r in range(1, n+1)]) return (B,n) def getBij(r, c, n): """Used for generating A not accessing A. To access A, use A[r,c]""" return 2 if r==c else 1 if r==c-1 or r==c+1 else 0 def Pi(i, a, b, n): """ P1 A should have a zero at 1,0 P2P1A should have a zero at 1,0 and 2,1 ... Pi Pi-1...A should have zero at 1,0, ..., i,i-1 [c -s, s c] [Ai-1,i-1 Ai,i-1]T = [r 0]T where r = l2 norm of A vector Rewrite the matrix in terms of c and s instead of A components. Now [c s]T = [a/r -b/r]T Add that to the matrix, and viola Args: i: a 1 based index of where the fancy rotation stuff is. Top left is i = 1. a: the diagonal element b: the element below the diagonal (the one that should be zero) n: the size of P """ i = i-1 # because i in the program is really zero based r = math.sqrt(a**2 + b**2) c = a/r s = -b/r ret = np.identity(n) ret[i,i] = c ret[i,i+1] = -s ret[i+1,i] = s ret[i+1,i+1] = c return ret def qrDecomp(A): """ A1 = A A2 = P1T P1 A A3 = P2T P1T P1 P2 A A4 = (P1T P2T P3T) (P3 P2 P1 A) ... An = QR Finding Pi, see P """ n = len(A) Q = np.identity(n) R = A for i in range(1,n): P = Pi(i, R[i-1, i-1], R[i, i-1], n) R = P*R Q = np.matmul(Q,P.T) for r in range(n): for c in range(n): if abs(Q[r,c]) < 1e-10: Q[r,c] = 0 if abs(R[r,c]) < 1e-10: R[r,c] = 0 return (Q,R) def doTest(i): print('Performing QR decomp for $B_{}$'.format(i), end=' \\\\\n') B,_ = getB(i) print('$B=$', end=' \\\\\n') pretty_print(B) Q,R = qrDecomp(B) print('$Q=$', end=' \\\\\n') pretty_print(Q) print('$R=$', end=' \\\\\n') pretty_print(R) print('Note that it\'s triangular', end=' \\\\\n') print('QR=', end=' \\\\\n') pretty_print(np.matmul(Q,R)) print('Note that it\'s $B$ again', end=' \\\\\n') print('$QQ^T=$', end=' \\\\\n') pretty_print(np.matmul(Q,Q.T)) #q,r = np.linalg.qr(B) #print('q') #print(q) #print('r') #print(r) def test(): pass if __name__ == '__main__': for i in range(2, 9): doTest(i)
b80322e861a5a22802d633881d7d4662b9b97f25
daanbakker1995/studieSuccesVoorspellerAI
/tensorDemo/test.py
1,074
3.890625
4
import pandas as pd import numpy as np import sklearn from sklearn import linear_model from sklearn.utils import shuffle # first we'll read the dataset and seperate it data = pd.read_csv("student-mat.csv", sep=";") # since this PoC is merely to demonstrate training a model, we'll only use a couple parameters data = data[["G1", "G2", "G3", "studytime", "failures", "absences"]] # G3 is the 3rd grade. that's the parameter we'll predict predict = "G3" # array of attributes and labels without G3, which we are going to predict x = np.array(data.drop([predict], 1)) y = np.array(data[predict]) # splitting arrays into training and testing arrays. 10% test sample x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1) linear = linear_model.LinearRegression() # produce best fit line linear.fit(x_train, y_train) # calculate accuracy of trainingmodel acc = linear.score(x_test, y_test) predictions = linear.predict(x_test) # print G3 predictions for x in range(len(predictions)): print(predictions[x], x_test[x], y_test[x])
6a49586fd141fbf6821c38ca761f9a9e06297b53
jrvanderveen/tinyurl
/urlShortener/urlShortener.py
3,229
3.6875
4
''' 1. Shorten a URL - When the user provides a URL, shorten it using a generated unique identifier. For example, given the URL `https://www.t-mobile.com/cell-phone/samsung-galaxy-note10-plus-5g?sku=610214662927`, a value similar to `http://localhost/abc123` might be returned. 1.b. No Duplicates - If a URL has already been shortened, do not generate a new shortened URL (return the previous value) 3. Hit Counter - Track the number of times a shortened URL has been accessed 4. Custom URLs - The user should have an option to set a desired URL (e.g. http://localhost/custom-value) rather than an assigned ID. ''' import string from random import randint class UrlShortener(): letters = string.ascii_letters + string.digits url2Long = dict() url2Short = dict() urlIdLength = 6 prefix = "http://localhost/" urlCount = "counter" urlVal = "longUrl" CUSTOM_ID_PRESENT = 1 CUSTOM_ID_MIS_MATCH = 2 # https://www.t-mobile.com/cell-phone/samsung-galaxy-note10-plus-5g?sku=610214662927 -> http://localhost/abc123 def encodeUrl(self, longUrl): # reutn shortened url if longUrl not in UrlShortener.url2Short: while True: shortId = "" for _ in range(UrlShortener.urlIdLength): shortId = shortId + UrlShortener.letters[randint(0, 61)] if shortId not in UrlShortener.url2Long: UrlShortener.url2Long[shortId] = { UrlShortener.urlVal: longUrl, UrlShortener.urlCount: 0} UrlShortener.url2Short[longUrl] = shortId break return UrlShortener.prefix + UrlShortener.url2Short[longUrl] def encodeUrlCustom(self, longUrl, customId): if customId in UrlShortener.url2Long: return UrlShortener.CUSTOM_ID_PRESENT if longUrl in UrlShortener.url2Short: if customId in UrlShortener.url2Long and UrlShortener.url2Long[customId] != longUrl: return UrlShortener.CUSTOM_ID_MIS_MATCH else: return UrlShortener.prefix + UrlShortener.url2Short[longUrl] UrlShortener.url2Long[customId] = { UrlShortener.urlVal: longUrl, UrlShortener.urlCount: 0} UrlShortener.url2Short[longUrl] = customId return UrlShortener.prefix + UrlShortener.url2Short[longUrl] def decodeUrl(self, shortUrl): # ensure we get an id try: urlId = shortUrl.split("/")[-1] except ValueError: return None # if the id has a long url return it other wise none if urlId in UrlShortener.url2Long: UrlShortener.url2Long[urlId][UrlShortener.urlCount] += 1 return UrlShortener.url2Long[urlId][UrlShortener.urlVal] else: return None def getHitCountForShortenedUrl(self, shortUrl): try: urlId = shortUrl.split("/")[-1] except ValueError: return 0 # if the id has a long url return it other wise none if urlId in UrlShortener.url2Long: return UrlShortener.url2Long[urlId][UrlShortener.urlCount] else: return 0