blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b21cdeeb67581bbf29ddc2ef1aec3e1e8ac0d802
Ttibsi/AutomateTheBoringStuff
/Ch.07 - Pattern Matching with Regular Expressions/FindPhoneNumberUsingRegex.py
333
4.25
4
# Finding Patterns of Text with Regular Expressions #import regex module import re #What to search for phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #String to search though mo = phoneNumRegex.search('my number is 415-555-4242') #Result comes as an object with a .group() method print('phone number found: ' + mo.group())
4b2448a39ac25e131b9b8bb257d1a4f5cbfbae47
thaus03/Exercicios-Python
/Aula09/Desafio027.py
332
4.1875
4
# Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamente # Ex: Ana Maria de Souza # primeiro: Ana # ultimo: Souza nome = str(input('Digite o nome completo: ')) print(f'Primeiro: {nome.split()[0].capitalize()}') print(f'Ultimo: {nome.split()[-1].capitalize()}') print('--FIM--')
8ac5b19e03aafd149f181f8c12fb7f02c527c226
xavigu/Blockchain_management
/utils/hash_util.py
696
3.671875
4
"""Provides hash generator helper methods""" import hashlib import json def hash_string_256(string): return hashlib.sha256(string).hexdigest() # ---------------------------------------------------- # function to create hashed block def create_hash_block(block): # hash the block and convert to string with json library and encode to utf-8 and hexdigest to have normal characters # Convert the block object to a copy of a dictionary hashable_block = block.__dict__.copy() hashable_block['transactions'] = [tx.to_ordered_dict() for tx in hashable_block['transactions']] hash_block = hash_string_256(json.dumps(hashable_block, sort_keys=True).encode()) return hash_block
5b86aaaec105ef7fb0018d84eb73318f0c953f4b
mayanksoni052/substraction
/substraction.py
122
3.578125
4
a, b = map(int, input("Enter numbers for substraction ").split()) print("The substraction of", a, "and", b, "is = ", a-b)
81d4d41664f6692db685b50475007e615c7e3b15
udhayprakash/PythonMaterial
/python3/07_Functions/029_closures_ex.py
1,817
4.8125
5
#!/usr/bin/python3 """ Purpose: closures in python - Closures can avoid the use of global values. - It provides some form of data hiding. - When there are few methods (one method in most cases) to be implemented in a class, closures can provide a better solution. But when the number of attributes and methods are more, it is better to implement a class. - It is a way of keeping alive a variable even when the function has returned. So, in a closure, a function is defined along with the environment. In Python, this is done by nesting a function inside the encapsulating function and then returning the underlying function. """ def outer(): print("outer function - start ") def inner(): print("inner function - start") return "something" # case 1: # inner() # case 2: # return inner() # case 3: return inner outer() # inner() # NameError: name 'inner' is not defined result = outer() print(f"{type(result) = } {result =}") # type(result) = <class 'str'> result ='something' # type(result) = <class 'function'> result =<function outer.<locals>.inner at 0x0000018A71DBE700> # outer.<locals>.inner ---> closure # inner() # NameError: name 'inner' is not defined print(f"{result() =}") # 'something' print(f"{outer()() =}") # 'something' print() # === Partial functions with closures def make_multiplier_of(n): def multiplier(x): return x * n return multiplier # Multiplier of 3 mul3 = make_multiplier_of(3) print(f"{type(mul3)} {mul3}") # make_multiplier_of.<locals>.multiplier print(f"mul3(10):{mul3(10)}") # 30 print(f"mul3(7) :{mul3(7)}") # 21 mul5 = make_multiplier_of(5) print(f"{type(mul5)} {mul5}") print(f"mul5(10):{mul5(10)}") # 50 print(f"mul5(7) :{mul5(7)}") # 35
4f6d66f754fb19fdfeaba874749812a98c86e6db
john-odonnell/csc_212
/labs/lab4.py
3,204
4.0625
4
import unittest import time def sum(n: int) -> int: """ Sum of Numbers. Returns the sum of all integers in the range [0, 10] """ if n == 0: return 0 else: return n + sum(n - 1) def running_time_sum(): values = [10, 100, 250, 500] run_times = [] for value in values: start = time.time() sum(value) end = time.time() run_times.append(end - start) print("Run times of Sum Function:") for i in range(len(values)): print(str(values[i]) + ":\t" + str(run_times[0])) print("\n") def gcd(a: int, b: int) -> int: """ Greatest Common Divisor. Returns the greatest common divisor between a and b. """ if b == 0: return a else: return gcd(b, a % b) def print_nums(n: int) -> str: """ The Natural Numbers. Prints all integers in the range [1, n], wrapping the output every 10 numbers. """ if n == 1: return str(n) else: if n % 10 == 0: return print_nums(n - 1) + " " + str(n) + "\n" elif n % 10 == 1: return print_nums(n - 1) + str(n) else: return print_nums(n - 1) + " " + str(n) def fibonacci(n: int) -> int: """ Fibonacci Series. Returns the nth Fibonacci number. """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def num_len(num: int) -> int: """ Number of Digits. Returns the length of an integer n. """ if num < 10: return 1 else: return 1 + num_len(int(num / 10)) class Tests(unittest.TestCase): """ Use these to test your algorithms """ def test_sum(self): # test for simple number self.assertEqual(sum(10),55) # test for larger number self.assertEqual(sum(30), 465) # test for value 1 self.assertEqual(sum(1),1) # test for value 0 self.assertEqual(sum(0),0) return def test_gcd(self): # test self.assertEqual(gcd(10, 12), 2) # test self.assertNotEqual(gcd(10, 12), 6) # test self.assertEqual(gcd(81, 96), 3) # test self.assertEqual(gcd(1, 1), 1) # test self.assertEqual(gcd(11, 0), 11) # test self.assertEqual(gcd(0, 0), 0) def test_print_nums(self): self.assertEqual(print_nums(35), "1 2 3 4 5 6 7 8 9 10\n11 12 13 14 15 16 17 18 19 20\n" "21 22 23 24 25 26 27 28 29 30\n" "31 32 33 34 35") def test_fibonacci(self): # test self.assertEqual(fibonacci(2), 1) # test self.assertEqual(fibonacci(4), 3) # test self.assertEqual(fibonacci(10), 55) def test_num_len(self): # test self.assertEqual(num_len(1), 1) # test self.assertEqual(num_len(11), 2) # test self.assertEqual(num_len(12345), 5) # test self.assertEqual(num_len(0), 1) # test self.assertNotEqual(num_len(12), 3) if __name__ == "__main__": unittest.main()
da58a577253b61aa0281faa1974c1356fb660733
domengabrovsek/academic-fri
/programming-1/Vaje/Vaje 0/trikotnik.py
570
3.703125
4
import math stranica1 = float(input('Vnesi prvo stranico: ')) stranica2 = float(input('Vnesi drugo stranico: ')) stranica3 = float(input('Vnesi tretjo stranico: ')) s = float((stranica1 + stranica2 + stranica3) / 2) p = float(math.sqrt(s*(s-stranica1)*(s-stranica2)*(s-stranica3))) r = float(p/s) r2 = float((stranica1 * stranica2 * stranica3) / (4*p)) ploscina_vcrtana = float((3.14 * r**2)) ploscina_ocrtana = float((3.14 * r2**2)) print('Ploscina ocrtane kroznice je:' ,ploscina_ocrtana, 'm') print('Ploscina vcrtane kroznice je:' ,ploscina_vcrtana, 'm')
9a9848cdccdea87c952eb3078584663bd62a52cf
JPTIZ/the-pragmatic-programmer
/exercises/077-plain-text/pre/addrbook.py
1,617
3.5625
4
'''Address book database management.''' from struct import pack, iter_unpack from typing import NamedTuple class Address(NamedTuple): name: str phone: str address: str number: int def save(data, filename='book.db'): with open(filename, 'wb') as f: for item in data: _data = [elm.encode('utf-8') if isinstance(elm, str) else elm for elm in item] f.write(pack('30s30s30si', *_data)) def load(data, filename='book.db'): def to_str(text): return text.decode('utf-8').split('\0')[0] with open(filename, 'rb') as f: return [Address( name=to_str(name), phone=to_str(phone), address=to_str(address), number=int(number)) for name, phone, address, number in iter_unpack('30s30s30si', f.read())] if __name__ == '__main__': data = [ Address(name='Alice', phone='0000-0000', address='Street', number=0), Address(name='Bob', phone='1111-1111', address='Road', number=1), Address(name='C', phone='2222-2222', address='Avenue', number=42), Address(name='Eva', phone='6666-6666', address='Nowhere', number=66), ] save(data) for item in load(data): print(item)
b14717066dffe23c694cfa8d2fa4a863cb88d071
jiwonjulietyoon/Algorithm
/Tasks/1_IM/190228.py
607
3.890625
4
# 1974. 스도쿠 검증 def sudoku(arr): # 9x9 sudoku for i in range(9): # search each row and column col = [arr[j][i] for j in range(9)] if len(set(arr[i])) != 9 or len(set(col)) != 9: return 0 for i in [0, 3, 6]: # search each 3x3 section for k in [0, 3, 6]: sub = [] for j in range(3): sub.extend(arr[i+j][k:k+3]) if len(set(sub)) != 9: return 0 return 1 for T in range(int(input())): arr = [list(map(int, input().split())) for _ in range(9)] print(f"#{T+1} {sudoku(arr)}")
cd5b63885aa8cfea1d12df64193ab16542327443
rupesh1219/python
/leet_code/daily/move_zeros.py
884
3.828125
4
############################################################################### # given a list move all zeros to the end of the list # dont change the order of elements in list # dont use extra data structures # try to minimize your operations ############################################################################### def count_zeros(lst): ''' returns count of zeros in list ''' count = 0 for i in range(len(lst)): if lst[i] == 0: count += 1 return count def move_zeros(lst): ''' move zeros to the end of the list ''' count1 = count_zeros(lst) print(count1) for i in range(count1): for j in range(len(lst)-1): if lst[j] == 0: temp = lst[j] lst[j] = lst[j+1] lst[j+1] = temp return lst print(move_zeros([1,2,3,0,5,0,0,8,7,5]))
3efc51a371e7f25cc11c39c9f798e707c0d8d79d
codeLovingYogi/Algorithms
/binarysearch.py
513
4.03125
4
def binary_search(data, target, low, high): """Return true if target found in data. Search only considers portion from data[low] to data[high]. """ # interval empty, no match if low > high: return False else: mid = (low + high) // 2 # match found if target == data[mid]: return True elif target < data[mid]: # recurse on first half of data return binary_search(data, target, low, mid - 1) else: # recurse on second half of data return binary_search(data, target, mid + 1, high)
afa953a39e3f71aec770002bb2b04d341aafc75b
LinoSun/LeetCodeByPython
/daily/2.两数之和.py
1,657
3.765625
4
''' 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: n = l1.val + l2.val l3 = ListNode(n % 10) l3.next = ListNode(n // 10) p1 = l1.next p2 = l2.next p3 = l3 while True: if p1 and p2: sum = p1.val + p2.val + p3.next.val p3.next.val = sum % 10 p3.next.next = ListNode(sum // 10) p1 = p1.next p2 = p2.next p3 = p3.next elif p1 and not p2: sum = p1.val + p3.next.val p3.next.val = sum % 10 p3.next.next = ListNode(sum // 10) p1 = p1.next p3 = p3.next elif not p1 and p2: sum = p2.val + p3.next.val p3.next.val = sum % 10 p3.next.next = ListNode(sum // 10) p2 = p2.next p3 = p3.next else: if p3.next.val == 0: p3.next = None break return l3
02ef1e44f1273cc07d688be8c257bb3954534fb5
Yogini824/NameError
/PartB_q3b.py
1,213
4.1875
4
'''Develop a Python Program which prints factorial of a given number (Number should be User defined)''' def factorial(n): # defining function to calculate factorial of a number if n<0: # condition to check the number is negative or not print("Enter a positive number") # print to enter positive number if the condition is true elif n==0: # condition to check the number is 0 or not print("Factorial of 0 is 1") # print the factorial of 0 is the condition is true else: # if the number is positive fact=1 # take a variable to store the factorial of a given number for i in range(1,n+1): # taken for loop to run from 1 to given number fact*=i # multiplying the numbers and storing it in variable print("Factorial of",n,"is",fact) # print the factorial value of given number n=int(input("Enter a number : ")) # to take number as input factorial(n) # calling the function to get factorial value
d6d130a41913d0027cd9c34d9901c11b88da621d
romildodcm/learning_python
/python_for_Beginners/aula28_demoLoops.py
502
4.09375
4
people = ['Ro', 'Ka', 'Li', 'Ma'] print('-----------------------------------') print(f'Numero de nomes: {str(len(people))}') index = 0 while index < len(people): print(people[index]) index += 1 print('-----------------------------------') print(people) people.sort() print(people) print('-----------------------------------') # outro jeito mais fácil de printar nomes em uma lista #bem menor que os whiles acima for name in people: print(name) print('-----------------------------------')
16c529ebe518eaa13b8b6128dd7143d482f2c607
Skolekode/Introduksjon
/Skolekoding/introduksjon/4_3kodeflyt.py
512
3.625
4
""" I denne oppgaven lager vi en bankkonto. Kjøp på Vinslottet gjør at penger går ut. Utprinter gjør at vi stadig får et innblikk i hvordan bankkontoen ser ut. del 1 Beskriv med en tegning hva som skjer i dette programmet og hva utprintene blir total_sum = int(input("Skriv en fiktiv sum på din bankkonto i heltall\n")) bank_oppdatering = "Din gjenværende sum er:" print(bank_oppdatering, total_sum) kjop_sum = total_sum / 3 total_sum = total_sum - kjop_sum print(bank_oppdatering, total_sum) """
79b25550187bb9298a68762a48fd1835447a2004
matxa/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
214
3.921875
4
#!/usr/bin/python3 """function read_file()""" def read_file(filename=""): """read from a filename """ with open(filename, encoding="utf-8") as file: text = file.read() print(text, end="")
31f50660ed1df085e1347d96cc3537508dc8bb92
ardavast/hackerrank
/python/08_date_and_time/p02.py
428
3.53125
4
#!/usr/bin/env python3 # coding: utf-8 """ Time Delta https://www.hackerrank.com/challenges/python-time-delta """ import datetime if __name__ == '__main__': n = int(input()) for _ in range(n): ts1 = datetime.datetime.strptime(input(), "%a %d %b %Y %H:%M:%S %z") ts2 = datetime.datetime.strptime(input(), "%a %d %b %Y %H:%M:%S %z") dt = ts1 - ts2 print(int(abs(dt.total_seconds())))
a6dfdcb34df09eb475bd477d2ce01aa43e9bad3c
decayedcross/shaunlearnpython
/basic_string_operations.py
1,369
3.96875
4
class Basic_String: def __init__(self): pass def printer(self, message, s): print(message, s) return def form_printer(self, message, a): print(message.format(s.count(a))) s = "Hey there! what should this string be?" p = Basic_String() # Length should be 20 p.printer("Length of s =", len(s)) # First occurrence of "a" should be at index 8 p.printer("The first occurrence of the letter a =", s.index("a")) # Number of a's should be 2 p.form_printer("a occurs {} times" , "a") # Slicing the string into bits p.printer("The first five characters are", s[:5]) p.printer("The next five characters are", s[5:10]) p.printer("The thirteenth character is", s[12]) p.printer("The characters with odd index are", s[1::2]) p.printer("The last five characters are", s[-5:]) # Convert everything to uppercase p.printer("String in uppercase:", s.upper()) # Convert everything to lowercase p.printer("String in lowercase:", s.lower()) # Check how a string starts if s.startswith("Str"): print("String starts with 'Str'. Good!") p.printer("String starts with 'Str'. Good!") # Check how a string ends if s.endswith("ome!"): print("String ends with 'ome!'. Good!") p.printer("String in lowercase:", s.lower()) # Split the string into three separate strings, # each containing only a word p.printer("Split the words of the string: ", s.split(" "))
67b365c7779a1b03373ffb475a3e8d96a2767867
verma-shivani/DSA-Library
/Project_Euler/1-Multiple_Of_3_And_5/1-Multiple_Of_3_And_5.py
171
4.09375
4
sum0 = 0 # If i is divisible by 3 or 5, add to sum for i in range(100): if (i%3 == 0 or i%5==0): sum0 += i # Print answer print('The sum is: ' + str(sum0))
d9da437cd7e1865a36df8b03b18e06d73b8c09f9
HARICHANDANAKARUMUDI/chandu
/amstrng17.py
140
3.6875
4
c=int(input("")) temp=c sum=0 while(c>0): rem=c%10 sum=rem**3+sum c=c//10 if(temp==sum): print("yes") else: print("no")
2fce8ef6f2f4da6b5ec27373e15a5ba6d4632783
jazibahmed333/Mini-projects
/AI/lab1/lab1/part 2/Lab1_Agents_Task2_PokerPlayer.py
14,820
3.859375
4
import random # identify if there is one or more pairs in the hand Rank = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] Suit = ['s', 'h', 'd', 'c'] # 2 example poker hands # CurrentHand1 = ['Ad', '2d', '2c'] # CurrentHand2 = ['5s', '5c', '5d'] # Randomly generate two hands of n cards # def generate_2hands(nn_card=3): def generate_2hands(Rank, Suit): deck = [] # print(R,S) # print(str(R)+str(S)) for i in Rank: for j in Suit: deck.append(i+j) # R=random.choice(Rank) # S=random.choice(Suit) #slctd_cards = (random.sample(deck, 6)) return deck # generate_2hands(Rank,Suit) # identify hand category using IF-THEN rule ######################### # Game flow # ######################### ######################### # phase 1: Card Dealing # ######################### player1=[] player2=[] def card_dealing(): d = generate_2hands(Rank, Suit) # print(d) # print(len(d)) shuffle = random.sample(d,6) print(shuffle) player1 = random.sample(shuffle,3) player2 = list(set(shuffle)-set(player1)) return player1,player2 ######################### # phase 2: Bidding # ######################### def randombidding(): bid=[] for i in range(3): bid.append(random.randint(0,50)) return bid def fixed_bidding(): bid=[] for i in [12,33,44]: bid.append(i) return bid def reflex_agent(): c3=[] c4=[] ct1 = 0 ct2 = 0 for i in range(3): b1 = 0 b2 = 0 player1, player2 = card_dealing() print('player1: ', player1, '\nplayer2: ', player2) P1 = analyseHand(player1) P2 = analyseHand(player2) opt = input("Press 1 for Fixed Agent VS Reflex Agent or 2 for Random Agent VS Reflex Agent: ") bid1 = [] bid2 = [] if (opt == '1'): bid2 = fixed_bidding() if (P1['name'] == 'Three of a kind'): bid1.append(50) if ((bid1[0] >= bid2[0]) and (Rank.index(P1['rank'], 0, len(Rank))) > 10): bid1.append(43) else: bid1.append(30) if (bid1[1] >= bid2[1]): bid1.append(50) else: bid1.append(37) print( bid1,bid2) elif (P1['name'] == 'pair'): bid1.append(37) if ((bid1[0] >= bid2[0]) and (Rank.index(P1['rank'], 0, len(Rank))) > 11): bid1.append(42) else: bid1.append(30) if (bid1[1] >= bid2[1]): bid1.append(40) else: bid1.append(20) print(bid1, bid2) elif (P1['name'] == 'High Cards'): bid1.append(25) if ((bid1[0] >= bid2[0]) and (Rank.index(P1['rank'], 0, len(Rank))) > 10): bid1.append(37) else: bid1.append(22) if (bid1[1] >= bid2[1]): bid1.append(30) else: bid1.append(0) print(bid1, bid2) if (opt == '2'): bid1 = [] bid2 = randombidding() if (P1['name'] == 'Three of a kind'): bid1.append(50) if ((bid1[0] >= bid2[0]) and (Rank.index(P1['rank'], 0, len(Rank))) > 10): bid1.append(47) else: bid1.append(30) if (bid1[1] >= bid2[1]): bid1.append(50) else: bid1.append(25) elif (P1['name'] == 'pair'): bid1.append(37) if ((bid1[0] >= bid2[0]) and (Rank.index(P1['rank'], 0, len(Rank))) > 11): bid1.append(42) else: bid1.append(28) if (bid1[1] >= bid2[1]): bid1.append(38) else: bid1.append(10) elif (P1['name'] == 'High Cards'): bid1.append(27) if ((bid1[0] >= bid2[0]) and (Rank.index(P1['rank'], 0, len(Rank))) > 11): bid1.append(37) else: bid1.append(17) if (bid1[1] >= bid2[1]): bid1.append(35) else: bid1.append(0) for b in range(len(bid1)): b1 += bid1[b] print("Amount Bidded by Player1: ", bid1) for b in range(len(bid2)): b2 += bid2[b] print("Amount Bidded by Player2: ", bid2) Pot = b1 + b2 if (P1['name'] == P2['name']): print("Player 1 has: ", P1['name'], "\nPlayer 2 has: ", P2['name']) c1, c2 = Samecards(player1, player2, Pot, count1, count2) c3.append(c1) c4.append(c2) ct1 += c3[i] ct2 += c4[i] elif (P1['name'] != P2['name']): print("Player 1 has: ", P1['name'], "\nPlayer 2 has: ", P2['name']) c1, c2 = DiffCards(P1, P2, Pot, count1, count1) c3.append(c1) c4.append(c2) ct1 += c3[i] ct2 += c4[i] print("No of Games Won by Player1: ", ct1, "\nNo of Games Won by Player2: ", ct2) if (ct1 > ct2): print("Player 1 Won") elif (ct1 == ct2): print("Tie") else: print("Player 2 Won") ######################### # phase 2: Showdown # ######################### #def Showdown(): def Highcard(Hand_): if(len(Hand_)==2): ind1 = Rank.index(Hand_[0][0], 0, len(Rank)) ind2 = Rank.index(Hand_[1][0], 0, len(Rank)) if (ind1 > ind2): yield dict(name='High Cards', rank=Hand_[0][0], suit1=Hand_[0][1], suit2='', suit3='') return if (ind2 > ind1): yield dict(name='High Cards', rank=Hand_[1][0], suit1=Hand_[1][1], suit2='', suit3='') return def identifyHand(Hand_): if (Hand_[0][0]==Hand_[1][0]==Hand_[2][0]) : print ("You have 3 of kinds") yield dict(name = 'Three of a kind', rank = Hand_[0][0], suit1 = Hand_[0][1], suit2 = Hand_[1][1], suit3 = Hand_[2][1]) return for c1 in Hand_: for c2 in Hand_: if (c1[0] == c2[0]) and (c1[1] < c2[1]): yield dict(name='pair', rank=c1[0], suit1=c1[1], suit2=c2[1], suit3='') return if(len(Hand_)==3): ind1 = Rank.index(Hand_[0][0], 0, len(Rank)) ind2 = Rank.index(Hand_[1][0], 0, len(Rank)) ind3 = Rank.index(Hand_[2][0], 0, len(Rank)) if ((ind1 > ind2) and (ind1 > ind3)): yield dict(name='High Cards', rank=Hand_[0][0], suit1=Hand_[0][1], suit2='', suit3='') elif ((ind2 > ind1) and (ind2 > ind3)): yield dict(name='High Cards', rank=Hand_[1][0], suit1=Hand_[1][1], suit2='', suit3='') elif ((ind3 > ind1) and (ind3 > ind2)): yield dict(name='High Cards', rank=Hand_[2][0], suit1=Hand_[2][1], suit2='', suit3='') Highcard(Hand_) # Print out the result def analyseHand(Hand_): HandCategory = dict() functionToUse = identifyHand #print(functionToUse) for category in functionToUse(Hand_): #print('Category: ') for key in "name rank suit1 suit2 suit3".split(): #print(key, "=", category[key]) HandCategory[key]=category[key] return HandCategory def analyseHand1(Hand_): HandCategory = dict() functionToUse = Highcard #print(functionToUse) for category in functionToUse(Hand_): #print('Category: ') for key in "name rank suit1 suit2 suit3".split(): #print(key, "=", category[key]) HandCategory[key]=category[key] return HandCategory #analyseHand(player1) # for i in range(3): def Samecards(player1,player2,Pot,count1,count2): P1 = analyseHand(player1) P2 = analyseHand(player2) if ((P1['name'] == "High Cards") and (P2['name'] == "High Cards")): if (Rank.index(P1['rank'], 0, len(Rank)) > Rank.index(P2['rank'], 0, len(Rank))): print("Player 1 is winner") count1 +=1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) < Rank.index(P2['rank'], 0, len(Rank))): print("Player 2 is winner") count2 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) == Rank.index(P2['rank'], 0, len(Rank))): player1.remove(P1['rank'] + P1['suit1']) player2.remove(P2['rank'] + P2['suit1']) P1 = analyseHand1(player1) P2 = analyseHand1(player2) if (Rank.index(P1['rank'], 0, len(Rank)) > Rank.index(P2['rank'], 0, len(Rank))): print("Player 1 is winner") count1 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) < Rank.index(P2['rank'], 0, len(Rank))): print("Player 2 is winner") count2 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) == Rank.index(P2['rank'], 0, len(Rank))): player1.remove(P1['rank'] + P1['suit1']) player2.remove(P2['rank'] + P2['suit1']) if (Rank.index(player1[0][0], 0, len(Rank)) > Rank.index(player2[0][0], 0, len(Rank))): print("Player 1 is winner") count1 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(player1[0][0], 0, len(Rank)) < Rank.index(player2[0][0], 0, len(Rank))): print("Player 2 is winner") count2 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(player1[0][0], 0, len(Rank)) == Rank.index(player2[0][0], 0, len(Rank))): print("Its a Tie") elif ((P1['name'] == "pair") and (P2['name'] == "pair")): if (Rank.index(P1['rank'], 0, len(Rank)) > Rank.index(P2['rank'], 0, len(Rank))): print("Player 1 is winner") count1 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) < Rank.index(P2['rank'], 0, len(Rank))): print("Player 2 is winner") count2 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) == Rank.index(P2['rank'], 0, len(Rank))): player1.remove(P1['rank'] + P1['suit1']) player1.remove(P1['rank'] + P1['suit2']) player2.remove(P2['rank'] + P2['suit1']) player2.remove(P2['rank'] + P2['suit2']) P1 = analyseHand1(player1) P2 = analyseHand1(player2) if (Rank.index(P1['rank'], 0, len(Rank)) > Rank.index(P2['rank'], 0, len(Rank))): print("Player 1 is winner") count1 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) < Rank.index(P2['rank'], 0, len(Rank))): print("Player 2 is winner") count2 += 1 print("Total Amount Won is: ", Pot, "$") else: print("Its a Tie") elif ((P1['name'] == 'Three of a kind') and (P2['name'] == 'Three of a kind')): if (Rank.index(P1['rank'], 0, len(Rank)) > Rank.index(P2['rank'], 0, len(Rank))): print("Player 1 is winner") count1 += 1 print("Total Amount Won is: ", Pot, "$") elif (Rank.index(P1['rank'], 0, len(Rank)) < Rank.index(P2['rank'], 0, len(Rank))): print("Player 2 is winner") count2 += 1 print("Total Amount Won is: ", Pot, "$") return count1,count2 def DiffCards(P1,P2,Pot,count1,count2): if ((P1['name'] == 'pair') and (P2['name'] == 'Three of a kind')): print("Player 2 is winner") count2 +=1 print("Total Amount Won is: ", Pot, "$") elif ((P1['name'] == 'Three of a kind') and (P2['name'] == 'pair')): print("Player 1 is winner") count1 +=1 print("Total Amount Won is: ", Pot, "$") elif ((P1['name'] == 'Three of a kind') and (P2['name'] == 'High Cards')): print("Player 1 is winner") count1 +=1 print("Total Amount Won is: ", Pot, "$") elif ((P1['name'] == 'High Cards') and (P2['name'] == 'Three of a kind')): print("Player 2 is winner") count2 +=1 print("Total Amount Won is: ", Pot, "$") elif ((P1['name'] == 'High Cards') and (P2['name'] == 'pair')): print("Player 2 is winner") count2 +=1 print("Total Amount Won is: ", Pot, "$") elif ((P1['name'] == 'pair') and (P2['name'] == 'High Cards')): print("Player 1 is winner") count1 +=1 print("Total Amount Won is: ", Pot, "$") return count1,count2 count1 = 0 count2 = 0 def Gameflow(): c3=[] c4=[] ct1 = 0 ct2 = 0 for i in range(50): bid1 = 0 bid2 = 0 player1, player2 = card_dealing() print('player1: ', player1, '\nplayer2: ', player2) P1 = analyseHand(player1) P2 = analyseHand(player2) b1 = randombidding() b2 = fixed_bidding() print("Amount Bidded by Player1: ", b1) for b in range(len(b1)): bid1 += b1[b] print("Amount Bidded by Player2: ", b2) for b in range(len(b2)): bid2 += b2[b] Pot = bid1 + bid2 if (P1['name'] == P2['name']): print("Player 1 has: ", P1['name'], "\nPlayer 2 has: ", P2['name']) c1,c2 = Samecards(player1, player2, Pot,count1,count2) c3.append(c1) c4.append(c2) ct1 += c3[i] ct2 += c4[i] elif (P1['name'] != P2['name']): print("Player 1 has: ", P1['name'], "\nPlayer 2 has: ", P2['name']) c1,c2 = DiffCards(P1, P2, Pot,count1,count1) c3.append(c1) c4.append(c2) ct1 += c3[i] ct2 += c4[i] print("No of Games Won by Player1: ",ct1,"\nNo of Games Won by Player2: ",ct2) if (ct1 > ct2): print("Player 1 Won") elif (ct1 == ct2): print("Tie") else: print("Player 2 Won") #Gameflow() #reflex_agent() Input = input("Press 1 for Random VS fixed agent or 2 for Reflex VS Random or Fixed Agent: ") if (Input == '1'): Gameflow() elif (Input == '2'): reflex_agent() else: print("Invalid Input")
1af63bcd9f63bfdbada541c2f8b4b4b18bfd827f
devopsvj/PythonAndMe
/simple-programs/distance_traveled.py
321
4.28125
4
print "Distance Travelled by a Car" print "--------------------------" speed=input("Enter speed of the Car per hour in miles :") hr=input("Enter the hours to calculate the distance : ") distance=speed*hr print "The Distance traveled by the car at "+str(speed)+" miles per hour in "+str(hr)+" hours is : "+str(distance)
858021018578e7e6231336d94c21f4c92a4a01fb
NehaFarkya/PythonLearning
/ExNumber.py
140
4.21875
4
import math r=float(input("enter the radius")) areaofcircle=math.pi*(r**2) areaofcircum=2*math.pi*r print(areaofcircle) print(areaofcircum)
080961659666148c500ccc608b9e60154b3e8371
michelgalle/hackerrank
/CrackingTheCodingInterview/16-TimeComplexity-Primality.py
507
4.15625
4
def is_prime(a): if a < 2: return False if a == 2 or a == 3: return True # manually test 2 and 3 if n & 1 == 0 or a % 3 == 0: return False # exclude multiples of 2 and 3 maxDivisor = a ** 0.5 d, i = 5, 2 while d <= maxDivisor: if a % d == 0: return False d += i i = 6 - i # this modifies 2 into 4 and viceversa return True p = int(input().strip()) for a0 in range(p): n = int(input().strip()) print("Prime" if is_prime(n) else "Not prime")
a599d5da58c615b922ff9e1c310c2f37ceac907f
sharvilshah1994/LeetCode
/LinkedLists/HasCycle.py
684
3.640625
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None def build_linked_list(): l = ListNode(1) l1 = ListNode(2) l2 = ListNode(3) l3 = ListNode(4) l4 = ListNode(5) l.next = l1 l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l return l class Solution(object): def has_cycle(self, head): try: slow = fast = head while head: slow = slow.next fast = fast.next.next if slow.val == fast.val: return True except: return False print(Solution().has_cycle(build_linked_list()))
eed9447e7faf3a8dec6faf38be751b83981b4ac8
aishtiks/LearnPython
/ConditionalStatements.py
249
4.03125
4
num_Value1 = 23 if num_Value1 < 21: print("You cannot marry now.") elif num_Value1 is 21: print("You just reached marriage age, wait and enjoy life. What is the hurry?") else: print("You are in perfectly valid age for marriage.")
dd6c05b3e7f2e0eaaab325c2704261315e54041e
MAPLE-Robot-Subgoaling/IPT
/data/HW5/hw5_066.py
569
4.15625
4
def main(): width = int(input("Please enter the width of the box:")) height = int(input("Please enter the height of the box:")) symbol = input("Please enter a symbol for the box outline:") fill = input("Please enter a symbol for the box to fill:") newHeight = 1 for s in symbol: print(s*width) while newHeight < height and newHeight < height - 1: print(s + fill*(width - 2) + s) newHeight = newHeight + 1 newHeight = newHeight + 1 if newHeight == height: print(s*width) main()
9d47324ba4d2e37c4ddfe6e2d190b2f29a6192aa
amtfbky/git_py
/dg/base/09-2匿名函数扩展.py
245
3.546875
4
def tst(a,b,func): #res = a+b res = func(a,b) return res #func_new = input("请输入一个匿名函数:") func_new = 'lambda x,y:x*y+100' # 这里要字符串才行 func_new = eval(func_new) num = tst(11,22,func_new) print(num)
10ff22e857f7f81195c6c93afc03a956f3c8f58a
FarsBein/Maze_A_Star
/Maze_A_Star.py
8,366
3.546875
4
import pygame import random from queue import PriorityQueue pygame.init() WIDTH = 800 SCREEN = pygame.display.set_mode((WIDTH,WIDTH)) pygame.display.set_caption("A* Maze generator") BLACK = (0, 0, 0) WHITE = (250, 250, 250) RED = (255,0,0) BLUE = (0,0,255) LIGHT_BLUE = (173, 216, 230) GREEN =(0,255,0) GRAY = (220,220,220) PINK = (255,182,193) class Node: def __init__(self,row,col,size,total_row): self.row = row self.col = col self.size = size self.x = size*row self.y = size*col self.color = WHITE self.down = True self.right = True self.neighbors = [] self.total_row = total_row def get_pos(self): return self.row,self.col def get_pixel_pos(self): return self.x,self.y def draw(self,screen): pygame.draw.rect(screen,self.color,(self.x+4,self.y+4,self.size-6,self.size-6)) def is_down(self): return self.down def is_right(self): return self.right def make_start(self): self.color = GREEN def make_end(self): self.color = RED def make_down(self,condition): self.down = condition def make_right(self,condition): self.right = condition def make_player(self): self.color = GRAY def make_empty(self): self.color = WHITE def make_open(self): self.color = LIGHT_BLUE def make_closed(self): self.color = BLUE def make_path(self): self.color = GREEN def update_neighbors(self, grid): self.neighbors=[] if self.row > 0 and not grid[self.row-1][self.col].is_right(): self.neighbors.append(grid[self.row-1][self.col]) if self.col > 0 and not grid[self.row][self.col-1].is_down(): self.neighbors.append(grid[self.row][self.col-1]) if self.row < self.total_row-1 and not grid[self.row][self.col].is_right(): self.neighbors.append(grid[self.row+1][self.col]) if self.col < self.total_row-1 and not grid[self.row][self.col].is_down(): self.neighbors.append(grid[self.row][self.col+1]) def __it__(self,other): return False def draw_node(screen,grid): for row in grid: for node in row: node.draw(screen) pygame.display.update() def h(pos_1,pos_2): y1,x1 = pos_1 y2,x2 = pos_2 return abs(x1-x2) + abs(y1-y2) def draw_final_line(draw, came_from, current): while current in came_from: current = came_from[current] current.make_path() draw() def a_star(draw,grid,start,end): count = 0 open_set = PriorityQueue() open_set.put((0,count, start)) came_from = {} g_score = {node:float("inf") for row in grid for node in row} g_score[start]=0 f_score = {node:float("inf") for row in grid for node in row} f_score[start]=h(start.get_pos(),end.get_pos()) open_set_hash = {start} while not open_set.empty(): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() break current = open_set.get()[2] #current node open_set_hash.remove(current) if current == end: draw_final_line(draw,came_from, current) return True for neighbor in current.neighbors: temp_g_score = g_score[current]+1 if temp_g_score < g_score[neighbor]: came_from[neighbor] = current g_score[neighbor] = temp_g_score f_score[neighbor] = temp_g_score + h(neighbor.get_pos(),end.get_pos()) if neighbor not in open_set_hash: count+=1 open_set.put((f_score[neighbor],count,neighbor)) open_set_hash.add(neighbor) neighbor.make_open() draw() def make_grid(rows,width): size=width//rows grid=[] for i in range(rows): grid.append([]) for j in range(rows): node = Node(i,j,size,rows) grid[i].append(node) return grid def draw_grid(screen,grid,size): for i in range(len(grid)): for j in range(len(grid)): node = grid[i][j] row,col = node.get_pixel_pos() if node.is_down(): pygame.draw.line(screen,BLACK,[row,col+size],[row+size,col+size],3) if node.is_right(): pygame.draw.line(screen,BLACK,[row+size,col],[row+size,col+size],3) pygame.display.update() def random_direction(row,col,len_grid,grid,visited): x=0 y=0 possible_directions = [] if row - 1 >= 0 and grid[row-1][col] not in visited: possible_directions.append(0) if col + 1 < len_grid and grid[row][col+1] not in visited: possible_directions.append(1) if row + 1 < len_grid and grid[row+1][col] not in visited: possible_directions.append(2) if col - 1 >= 0 and grid[row][col-1] not in visited: possible_directions.append(3) if len(possible_directions) == 0: return y,x rand_dir = possible_directions[random.randrange(len(possible_directions))] if rand_dir == 0: y-=1 if rand_dir == 1: x+=1 if rand_dir == 2: y+=1 if rand_dir == 3: x-=1 return y,x def gen_maze(grid): len_grid = len(grid) visited = [grid[0][0]] row = 0 col = 0 grid[3][0].make_right(False) while len(visited) < len_grid**2: for event in pygame.event.get(): if event.type == pygame.QUIT: break y,x = random_direction(row,col,len_grid,grid,visited) if y == 0 and x == 0: visited.insert(0,visited.pop()) else: if y != 0: if row > row+y: grid[row+y][col].make_right(False) else: grid[row][col].make_right(False) visited.append(grid[row+y][col]) if x != 0: if col > col+x: grid[row][col+x].make_down(False) else: grid[row][col].make_down(False) visited.append(grid[row][col+x]) row,col = visited[-1].get_pos() def main(screen,width): ROWS=20 gameRunning = True grid = make_grid(ROWS,width) size=width//ROWS screen.fill(WHITE) pygame.display.update() made_grid = False start = grid[0][0] end = grid[ROWS-1][ROWS-1] while gameRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: gameRunning = False if pygame.mouse.get_pressed()[0]: row,col = pygame.mouse.get_pos() row = row//size col = col//size if (row == 0 and col == 0 ) or (row == ROWS-1 and col == ROWS-1): pass else: grid[row][col].make_player() grid[row][col].draw(screen) pygame.display.update() if pygame.mouse.get_pressed()[2]: row,col = pygame.mouse.get_pos() row = row//size col = col//size if (row == 0 and col == 0 ) or (row == ROWS-1 and col == ROWS-1): pass else: grid[row][col].make_empty() grid[row][col].draw(screen) pygame.display.update() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and made_grid: for row in grid: for node in row: node.update_neighbors(grid) a_star(lambda: draw_node(screen,grid),grid,start,end) if event.type == pygame.K_r: gameRunning = False main(screen,width) if not made_grid: gen_maze(grid) start.make_start() end.make_end() start.draw(screen) end.draw(screen) draw_grid(screen,grid,size) pygame.display.update() made_grid = True pygame.quit() main(SCREEN,WIDTH)
5bef7ff469e99ac96e2f2f675e3e7b95e425e25e
ck7up/ccnb-python
/Exercice4/exercice4.py
1,231
4.1875
4
from math import sqrt print("# Faire un programme qui demande à un utilisateur d'entrer les 3 coefficients d'un équation quadratique, soient a, b, c. => y = ax^2 + bx + c #") run = 0 while run != 1: a = float(input("Entrez la valeur de a = ")) b = float(input("Entrez la valeur de b = ")) c = float(input("Entrez la valeur de c = ")) input(">>> Toutes les valeurs sont entrées, appuyez sur ENTER pour calculer le DÉTERMINANT D = (b**2)-(4*a*c)...\n") det = float((b**2)-(4*a*c)) print("DETERMINANT est D =",det) if det < 0 : print("Il n'existe pas de solution.\n") elif det == 0 : print("Il existe une solution double qui est : X2=X1=X2.") input(">>> Presser Enter pour effectuer le calcul de X=X1=X2...") X=-b/(2*a) print("X =",X,"\n") elif det > 0 : print("Il existe deux solutions X1 et X2.\n") input(">>> Presser Enter pour effectuer le calcul de X1...") X1 = (-b + sqrt(det))/(2*a) print("X1 =",X1,"\n") input(">>> Presser Enter pour effectuer le calcul de X2...") X2 = (-b - sqrt(det))/(2*a) print("X1 =",X2,"\n") input("Presser '0' ensuite ENTER pour recommencer le calcul : ")
fa86ce2391094972d3fec275b68f6ccfede1ce3f
imranali18/RPA4
/source/class_code/Lec16_imdb.py
506
3.828125
4
imdb_file = input("Enter the name of the IMDB file ==> ").strip() count_list = [] for line in open(imdb_file, encoding="utf-8"): words = line.strip().split('|') name = words[0].strip() found = False for pair in count_list: if pair[0] == name: pair[1] += 1 found = True break if not found: new_pair = [name, 1] count_list.append(new_pair) for pair in count_list: print("{} appeared in {} movies".format(pair[0], pair[1]))
422aa38bd83af5af23cde23d9652c7ece323c96a
Lethons/PythonExercises
/PythonProgram/chapter_10/10-04/10-04.py
223
3.625
4
while True: name = input("Please input your name: ") if name == 'quit': break print("Nice to meet you %s." % name.title()) with open('guest_book.txt', 'a') as f: f.write(name.title() + '\n')
c022b6576b66950f41641b403df5a24009a266e3
jespel2013/Python-Programs
/linked_list.py
1,327
3.5625
4
''' Name: Jesse Pelletier Description: This file contains the class LinkedList that represents the data structure of the same name. It was taken from the practice problems for CSC 120. FileName: linked_list.py ''' class LinkedList: def __init__(self): self._head = None def getHead(self): return self._head # search the list for item and return True if found and False otherwise def find(self, item): currNode = self._head #make current node the first node in list while (currNode != None): if item == currNode.getName(): #if the nodes value is equal to the item True is returned return True currNode = currNode.getNext() #to avoid an infinite loop, iterate to the next node in linked list return False #returns false otherwise # add a node to the head of the list def add(self, node): if self._head == None: self._head = node else: node.setNext(self._head) self._head = node def __str__(self): string = 'List[' curr_node = self._head while curr_node != None: string += str(curr_node) + ' ' curr_node = curr_node.getNext() string += ']' return string
13096ed1a1cf7762d3c50f559025c68780f0ba16
aizhan00000/game
/lection10.py
1,312
3.984375
4
# def user_num(): # num = int(input("enter a num: ")) # return num # # # def main(a): # for i in range(1, a+1): # print(i) # # # main(user_num()) # def user_num(): # num = int(input("enter a num: ")) # return num # # # def main(a): # print([i for i in range(1, a+1)]) # # # main(user_num()) # def user_num(): # import random # low = int(input("enter a low num: ")) # high = int(input("enter a high one: ")) # comp_num = random.randint(low, high) # return comp_num # # # def kkk(): # print("i am thinking of a number...") # user_choice = int(input("what is that num: ")) # return user_choice # # # def main(): # a = user_num() # b = kkk() # if a == b: # return "you win!" # else: # while True: # main() # print(main()) def num(): print( "1: Addition\n", "2: Subtraction\n", "enter 1 or 2: " ) def number(): b = int(input('enter a num: ')) return b def main(): import random a = number() if a == 1: x = random.randint(("5", "20")) return x elif a == 2: g = random.randint(i for i in range(1, 20)) elif a == 10: print("aijan, ty krasivays") else: print("aijan ty loh") main()
fea04496f5f6c2557f4ad468a69e7f098a60a54c
nicksim1/learning
/test.py
244
4.09375
4
program_loop = True while program_loop: box = raw_input("what number? ") if box == "exit": program_loop = False else: try: box = int(box) for x in range(13): print box * x except Exception as e: print "Thats not a Number!"
b35a65b5e0f824cc894a5a98c5635103fcd594e7
nsakki55/AtCoder
/python_basic/abc028_a.py
132
3.65625
4
n=int(input()) if n<=59:print('Bad') elif 60<=n and n<=89:print('Good') elif 90<=n and n<=99:print('Great') else: print('Perfect')
a6705c45cad7a51729a9d8e9f0d1a50a6b1cac04
scottwedge/Python-4
/module_1/ExceptionHandling/exceptions.py
1,490
4.53125
5
#!/usr/bin/python ## handling exception in python using try block ## if there is an exception in the try block ## the except block will execute, and if there is no exception ## else block is executed ## finally block will be executed no matter what try: a = 0/0 except: print "Exception handled" else: print "no exceptions" finally: print "finally clean up" try: a = 1/1 except: print "Exception handled" else: print "no exceptions" finally: print "finally clean up" ## except block can also take a error message as an arugment as well ## this is for handling specific errs ## below is an example ## this way we can set the exception as any variable, and we can handle ## that specific exception try: a = 1/0 except Exception as exceptionVariable: print exceptionVariable else: print "no exceptions" finally: print "finally clean up" ## OKAY LETS DEFINE OUR OWN EXCEPTIONS ## by defining a base err class, with parent of Exception ## Any other exceptions can have this bass err class class Error(Exception): """Base Class for all Exceptions""" pass class evenErr(Error): """raised when even""" pass class oddErr(Error): """Raised when odd""" pass num = 1 while num < 5: try: if num % 2 == 0: num = num + 1 raise evenErr else: num = num + 1 raise oddErr except evenErr: print "ERROR ITS EVEN!" except oddErr: print "ERROR ITS ODD!!" else: print "this should never print" finally: print "this should always print"
2e933a022d33f4c77bf43cee528c37e0d41f5382
ertugrulMustafa/Tetris-2048
/game_grid.py
17,301
3.578125
4
import pygame import stddraw # the stddraw module is used as a basic graphics library from color import Color # used for coloring the game grid import numpy as np from tile import Tile from point import Point # fundamental Python module for scientific computing import point import math import copy from playsound import playsound # Class used for modelling the game grid class GameGrid: # Constructor for creating the game grid based on the given arguments def __init__(self, grid_h, grid_w): # set the dimensions of the game grid as the given arguments self.grid_height = grid_h self.grid_width = grid_w # create the tile matrix to store the tiles placed on the game grid self.tile_matrix = np.full((grid_h, grid_w), None) # the tetromino that is currently being moved on the game grid self.current_tetromino = None self.next_tetromino=None # game_over flag shows whether the game is over/completed or not self.game_over = False # set the color used for the empty grid cells self.empty_cell_color = Color(206, 195, 181) # set the colors used for the grid lines and the grid boundaries self.line_color = Color(189, 175, 162) self.boundary_color = Color(132, 122, 113) # thickness values used for the grid lines and the grid boundaries self.line_thickness = 0.002 self.box_thickness = 4* self.line_thickness self.score=0 self.score_color=Color(0,0,0) pygame.mixer.init() self.clear_sound=pygame.mixer.Sound("clear.wav") self.game_speed=180 # Method used for displaying the game grid def display(self): # playsound('pewdiepie-wow-sound-effect.mp3') # clear the background canvas to empty_cell_color stddraw.clear(self.empty_cell_color) # draw the game grid self.draw_grid() # draw the current (active) tetromino if self.current_tetromino != None: self.current_tetromino.draw() if self.next_tetromino != None: self.next_tetromino.draw() # draw a box around the game grid self.draw_boundaries() ### show the score on the window stddraw.setFontFamily("Pacifico") stddraw.setFontSize(45) stddraw.setPenColor(self.score_color) text = "Score" real_score=self.score stddraw.text(15,18, text) stddraw.text(15,17,str(self.score)) # show the resulting drawing with a pause duration = 250 ms #stddraw.show(250) if self.score<100 : stddraw.show(self.game_speed) elif self.score>100 and self.score<500: self.game_speed=150 stddraw.show(self.game_speed) else: self.game_speed = 120 stddraw.show(self.game_speed) # Method for drawing the cells and the lines of the grid def draw_grid(self): # draw each cell of the game grid for row in range(self.grid_height): for col in range(self.grid_width): # draw the tile if the grid cell is occupied by a tile if self.tile_matrix[row][col] != None :#and grid_w self.tile_matrix[row][col].draw() # draw the inner lines of the grid stddraw.setPenColor(self.line_color) stddraw.setPenRadius(self.line_thickness) # x and y ranges for the game grid start_x, end_x = -0.5, self.grid_width - 0.5 start_y, end_y = -0.5, self.grid_height - 0.5 for x in np.arange(start_x + 1, end_x, 1): # vertical inner lines stddraw.line(x, start_y, x, end_y) for y in np.arange(start_y + 1, end_y, 1): # horizontal inner lines stddraw.line(start_x, y, end_x, y) stddraw.setPenRadius() # reset the pen radius to its default value # Method for drawing the boundaries around the game grid def draw_boundaries(self): # draw a bounding box around the game grid as a rectangle stddraw.setPenColor(self.boundary_color) # using boundary_color # set the pen radius as box_thickness (half of this thickness is visible # for the bounding box as its lines lie on the boundaries of the canvas) stddraw.setPenRadius(self.box_thickness) # coordinates of the bottom left corner of the game grid pos_x, pos_y = -0.5, -0.5 stddraw.rectangle(pos_x, pos_y, self.grid_width, self.grid_height) stddraw.setPenRadius() # reset the pen radius to its default value # Method used for checking whether the grid cell with given row and column # indexes is occupied by a tile or empty def is_occupied(self, row, col): # return False if the cell is out of the grid if not self.is_inside(row, col): return False # the cell is occupied by a tile if it is not None return self.tile_matrix[row][col] != None # Method used for checking whether the cell with given row and column indexes # is inside the game grid or not def is_inside(self, row, col): if row < 0 or row >= self.grid_height: return False if col < 0 or col >= self.grid_width: return False return True # Method for updating the game grid by placing the given tiles of a stopped # tetromino and checking if the game is over due to having tiles above the # topmost game grid row. The method returns True when the game is over and # False otherwise. def update_grid(self, tiles_to_place): # place all the tiles of the stopped tetromino onto the game grid n_rows, n_cols = len(tiles_to_place), len(tiles_to_place[0]) min_x=self.grid_width-1 max_x=0 for col in range(n_cols): for row in range(n_rows): # place each occupied tile onto the game grid if tiles_to_place[row][col] != None: pos = tiles_to_place[row][col].get_position() if self.is_inside(pos.y, pos.x) and not self.is_occupied(pos.y,pos.x): self.tile_matrix[pos.y][pos.x] = tiles_to_place[row][col] if pos.x<min_x: min_x=pos.x elif pos.x>max_x: max_x=pos.x # the game is over if any placed tile is out of the game grid else: self.game_over = True for col in range(min_x, max_x + 1): while self.ismergeble(col): self.merge(col) n = len(self.tile_matrix) for row in range(n): if self.line_is_full(n-1-row): self.clear_line(n-1-row) self.clear_sound.play() continue current_labels=self.for_connected_labelling() while(len(self.flying_tetromino(current_labels))!=0): for row in range(self.grid_height): for col in range(self.grid_width): # draw the tile if the grid cell is occupied by a tile if self.tile_matrix[row][col] != None: if len(self.flying_tetromino(current_labels))!=0 and self.tile_matrix[row][col].label==self.flying_tetromino(current_labels)[0]: self.tile_matrix[row][col].move(0,-1) self.tile_matrix[row-1][col]=self.tile_matrix[row][col] self.tile_matrix[row][col]=None current_labels = self.for_connected_labelling() return self.game_over """ It checks all cols in the same row.If all the tiles are empty in same row, it results False. """ def line_is_full(self, row): n = len(self.tile_matrix[0])#ROW for i in range(n): if self.tile_matrix[row][i] == None:#goes on every column in a row return False return True """ """ def clear_line(self, row): nrow, ncolumn=len(self.tile_matrix), len(self.tile_matrix[0]) for i in range(ncolumn): self.score+=self.tile_matrix[row][i].number self.score_color = Color(91, 251, 174) self.tile_matrix[row][i].background_color=Color(91, 251, 174) self.display() for i in range(ncolumn): self.tile_matrix[row][i]=None for i in range(row+1, nrow): for j in range(ncolumn): if self.tile_matrix[i][j]!=None: self.tile_matrix[i][j].move(0, -1) self.tile_matrix[i-1][j] = self.tile_matrix[i][j]#shift down self.tile_matrix[i][j]=None """ If the tile on it and itself is full and they both have the same number, adds the number with itself. @param: inside- takes the logarithm of the number on the tile. """ def merge(self, col): colors = [Color(238, 228, 218), Color(237, 224, 200), Color(242, 177, 121), Color(245, 149, 99),Color(246, 124, 95),Color(178,102,255),Color(102,0,204),Color(51,255,255),Color(102,0,204),Color(42,70,183),Color(255,0,0)] for i in range(self.grid_height-1): if self.tile_matrix[i][col]!=None and self.tile_matrix[i+1][col]!=None: if self.tile_matrix[i][col].number==self.tile_matrix[i+1][col].number: self.tile_matrix[i+1][col].background_color=Color(91, 251, 174) self.tile_matrix[i][col].background_color=Color(91, 251, 174) self.game_speed=100 self.display() if self.score < 100: self.game_speed = 180 elif self.score > 100 and self.score < 500: self.game_speed = 150 else: self.game_speed = 120 stddraw.show(self.game_speed) self.tile_matrix[i][col].number += self.tile_matrix[i][col].number self.score+=self.tile_matrix[i][col].number self.score_color=Color(91, 251, 174) self.display() self.score_color=Color(0, 0, 0) inside = int(math.log2(self.tile_matrix[i][col].number))#takes the logarithm of the number on the tile self.tile_matrix[i][col].background_color = colors[inside - 1]#According to logarithm result, takes if inside >= 3: self.tile_matrix[i][col].foreground_color = Color(255, 255, 255) #n.th element from colors array.Assign inside as a background colour self.tile_matrix[i + 1][col] = None#deletes the upper tile for j in range(i+2, self.grid_height): if self.tile_matrix[j][col] == None: return False self.tile_matrix[j][col].move(0, -1) self.tile_matrix[j - 1][col] = self.tile_matrix[j][col] self.tile_matrix[j][col] = None self.display() def ismergeble(self, col): for i in range(self.grid_height-1): if self.tile_matrix[i][col]!=None and self.tile_matrix[i+1][col]!=None: if self.tile_matrix[i][col].number==self.tile_matrix[i+1][col].number: return True return False def for_connected_labelling(self): self.all_labels=[0] current_label = 0 for row in range(self.grid_height-1, -1, -1): for col in range(self.grid_width): if self.tile_matrix[row][col] != None: if row == 19 and col == 0: self.tile_matrix[row][col].label = current_label current_label += 1 elif row == 19: if self.tile_matrix[row][col - 1] != None: self.tile_matrix[row][col].label = self.tile_matrix[row][col - 1].label else: self.tile_matrix[row][col].label = current_label current_label += 1 elif col == 0: if self.tile_matrix[row + 1][col] != None: self.tile_matrix[row][col].label = self.tile_matrix[row + 1][col].label else: self.tile_matrix[row][col].label = current_label current_label += 1 else: if self.tile_matrix[row + 1][col] != None: self.tile_matrix[row][col].label = self.tile_matrix[row + 1][col].label if self.tile_matrix[row][col - 1] != None: self.tile_matrix[row][col].label=self.tile_matrix[row][col-1].label if self.tile_matrix[row + 1][col] != None: if self.tile_matrix[row + 1][col].label<self.tile_matrix[row][col-1].label: self.tile_matrix[row][col].label=self.tile_matrix[row + 1][col].label point=col if point>0: while(point!=0 and self.tile_matrix[row][point-1]!=None): self.tile_matrix[row][point- 1].label=self.tile_matrix[row][point].label if self.tile_matrix[row+1][point- 1]!=None: self.tile_matrix[row + 1][point - 1].label=self.tile_matrix[row][point].label point2=row+1 if point2<19: while(point2!=19 and self.tile_matrix[point2+1][point - 1]!=None ): self.tile_matrix[point2 + 1][point - 1].label=self.tile_matrix[row + 1][point - 1].label point2+=1 point-=1 if self.tile_matrix[row + 1][col].label>self.tile_matrix[row][col-1].label: self.tile_matrix[row + 1][col].label = self.tile_matrix[row][col-1].label point = col point1=row point3=col if point < 11: while (point != 11 and self.tile_matrix[row+1][point+1] != None): self.tile_matrix[row+1][point + 1].label = self.tile_matrix[row][col].label point2=row+1 if point2<19: while(point2!=19 and self.tile_matrix[point2+1][point+1]!=None): self.tile_matrix[point2 + 1][point + 1].label=self.tile_matrix[row][col].label point2+=1 point += 1 if point1<19: while(point1!=19 and self.tile_matrix[point1+1][col] != None): self.tile_matrix[point1+1][col].label=self.tile_matrix[point1][col].label if point3>0: while(point3!=0 and self.tile_matrix[point1+1][point3-1] != None): self.tile_matrix[point1 + 1][point3 - 1].label=self.tile_matrix[point1][col].label point3=1 point1+=1 if self.tile_matrix[row][col - 1] == None and self.tile_matrix[row+1][col] == None: self.tile_matrix[row][col].label = current_label current_label += 1 for row in range(self.grid_height): for col in range(self.grid_width): if self.tile_matrix[row][col] != None: if self.tile_matrix[row][col].label not in self.all_labels: self.all_labels.append(self.tile_matrix[row][col].label) return self.all_labels def flying_tetromino(self,label_list): copy_labels= copy.deepcopy(label_list) i=0 while(i<len(label_list)): for row in range(self.grid_height): for col in range(self.grid_width): if self.tile_matrix[row][col] != None and self.tile_matrix[row][col].label==label_list[i]: position=self.tile_matrix[row][col].get_position() if position.y==0: if self.tile_matrix[row][col].label in copy_labels: copy_labels.remove(self.tile_matrix[row][col].label) row=0 col=0 i+=1 return copy_labels # def flyingtiles(self, row, col): # if col != self.grid_height - 1 or col != 0: # if self.tile_matrix[row][col] != None: # if self.tile_matrix[row - 1][col] == None and self.tile_matrix[row + 1][col] == None: # if self.tile_matrix[row][col - 1] == None and self.tile_matrix[row][col + 1] == None: # self.tile_matrix[row][col].move(0, -1) # self.tile_matrix[row - 1][col] = self.tile_matrix[row][col] # self.tile_matrix[row][col] = None
789ee70da6706f78561b2aec3e8cd48dcf85dc99
ademaas/python-ex
/studyplanProject/student.py
1,189
4.0625
4
import course class Student: #initialization of the class with #student name, student id and list of courses the student is taking. def __init__(self,name,student_no): self.__name = name self.__id = student_no self.__courseList = [] # returns the name of the student def get_name(self): return self.__name #returns the student id def get_id(self): return self.__id #return the list of courses selected def get_course_list(self): return self.__courseList #get a list of courses from the course class and store them in course list def course_catalog(self,course_list): self.__courseList= course_list.copy() #This Method prints the annual study plan of a student def annual_course(self): for period in self.__courseList: for p in period: print(' {:s} \t{:>10s}\t{:s}\t{:>2s}\t{:>s}\n'.format(p[0],p[1],p[2],p[3],p[4])) # prints the student object def __str__(self): str1 = "Student name: "+ self.__name + " ID: " + str(self.__id) return str1
0ff22db30c427ab029037c4baf842aca22137e02
RuningBird/pythonL
/day01/wordgame.py
174
3.828125
4
print("-------------------") temp = input("心中数字:") guess = int(temp) if guess == 8: print("right") else: print("wrong") print("game over") # print(type(temp))
dcdfe25a7d298f3d369584bfa3d54b9c8eca2c4c
marianesc/LP1
/miniteste_while.py
184
3.765625
4
contador = 0.0 auxiliar = 0 soma = 0 p = float(input()) print(contador) while 2 - soma > p: contador += 1 / 2 ** auxiliar auxiliar += 1 soma = contador print(contador)
69ec364ec6ed6b82e67d70fb03abecd4e6073f98
JeeHwan21/CS550
/Fibonacci_binary.py
314
3.671875
4
import sys import math def fib(a): if a == 1: return 1 elif a == 2: return 1 else: return fib(a-1) + fib(a-2) print(fib(int(sys.argv[1]))) def bin(a): sum = 0 for x in range(len(str(a))): # print(sum, x, a[-x-1]) sum = sum + math.pow(2, x) * int(a[-x-1]) return sum print(int(bin(sys.argv[2])))
d9caddbea257bb1abb4664a5b39c8ebbecdcc17a
suryandpl/UberPreparationPrograms
/alok-tripathi-workplace/set3/p11.py
325
4.1875
4
''' Problem : # Get all substrings of string # Using list comprehension + string slicing Author : Alok Tripathi ''' test_str = "Alok" print("The original string is : " + str(test_str)) for i in range(len(test_str)): for j in range(i + 1, len(test_str) + 1): #from 1 to str(len+1) print(list(test_str[i: j]))
4cad2268990c9e58b0ae2677f7c68f657bbf1d74
johanarangel/condicionales_python
/ejercicios_practica.py
9,993
4.125
4
#!/usr/bin/env python ''' Condicionales [Python] Ejercicios de práctica --------------------------- Autor: Johana Rangel Version: 1.3 Descripcion: Programa creado para que practiquen los conocimietos adquiridos durante la semana ''' __author__ = "Johana Rangel" __email__ = "johanarang@hotmail.com" __version__ = "1.2" def ej1(): print('Ejercicios de práctica con números') ''' Realice un programa que solicite por consola 2 números Calcule la diferencia entre ellos e informe por pantalla si el resultado es positivo, negativo o cero. ''' numero_1 = float(input('Ingrese el primer número:\n')) numero_2 = float(input('Ingrese el segundo número:\n')) resultado = numero_1 - numero_2 if resultado == 0: print('El resultado de la diferencia entre {} y {} es igual a cero'.format(numero_1, numero_2)) elif resultado > 0: print('El resultado de la diferencia entre {} y {} es positivo'.format(numero_1, numero_2)) else: print('El resultado de la diferencia entre {} y {} es negativo'.format(numero_1, numero_2)) def ej2(): print('Ejercicios de práctica con números') ''' Realice un programa que solicite el ingreso de tres números enteros, y luego en cada caso informe si el número es par o impar. Para cada caso imprimir el resultado en pantalla. ''' entero_1 = int(input('Ingrese primer número entero:\n')) entero_2 = int(input('Ingrese segundo número entero:\n')) entero_3 = int(input('Ingrese tercer número entero:\n')) if (entero_1 % 2 == 0): print('El número {} es par'.format(entero_1)) else: print('El número {} es impar'.format(entero_1)) if (entero_2 % 2 == 0): print('El número {} es par'.format(entero_2)) else: print('El número {} es impar'.format(entero_2)) if (entero_3 % 2 == 0): print('El número {} es par'.format(entero_3)) else: print('El número {} es impar'.format(entero_3)) def ej3(): print('Ejercicios de práctica con números') ''' Realice una calculadora, se ingresará por línea de comando dos números Luego se ingresará como tercera entrada al programa el símbolo de la operación que se desea ejecutar - Suma (+) - Resta (-) - Multiplicación (*) - División (/) - Exponente/Potencia (**) Se debe efectuar el cálculo correcto según la operación ingresada por consola Imprimir en pantalla la operación realizada y el resultado ''' numero_uno = float(input('Ingrese un número: \n')) numero_dos = float(input('Ingrese otro número: \n')) simbolo_operacion = str(input('''Ingrese el simbolo de la operación a realizar (+ suma, - resta, * multiplicación, / división, **Potencia ): \n''')) if (simbolo_operacion == '+'): resultado = numero_uno + numero_dos print('El resultado de sumar {} y {} es {}'.format(numero_uno, numero_dos, resultado)) elif (simbolo_operacion == '-'): resultado = numero_uno - numero_dos print('El resultado de restar {} y {} es {}'.format(numero_uno, numero_dos, resultado)) elif (simbolo_operacion == '*'): resultado = numero_uno * numero_dos print('El resultado de multiplicar {} y {} es {}'.format(numero_uno, numero_dos, resultado)) elif (simbolo_operacion == '/'): resultado = numero_uno / numero_dos print('El resultado de dividir {} y {} es {}'.format(numero_uno, numero_dos, resultado)) elif (simbolo_operacion == '**'): resultado = numero_uno ** numero_dos print('El resultado de {} a la potencia {} es {}'.format(numero_uno, numero_dos, resultado)) else: print('Simbolo no corresponde con los indicados') def ej4(): print('Ejercicios de práctica con cadenas') ''' Realice un programa que solicite por consola 3 palabras cualesquiera Luego el programa debe consultar al usuario como quiere ordenar las palabras 1 - Ordenar por orden alfabético (usando el operador ">") 2 - Ordenar por cantidad de letras (longitud de la palabra) Si se ingresa "1" por consola se deben ordenar las 3 palabras por orden alfabético e imprimir en pantalla de la mayor a la menor Si se ingresa "2" por consola se deben ordenar las 3 palabras por cantidad de letras e imprimir en pantalla de la mayor a la menor ''' palabra_1 = str(input('Ingrese la primera palabra: \n')) palabra_2 = str(input('Ingrese la segunda palabra: \n')) palabra_3 = str(input('Ingrese la tercera palabra: \n')) consulta = str(input('Cómo quiere ordenar la palabras? \n Ingrese 1, si quiere ordenar por alfabético. \n Ingrese 2, si quiere ordenar por cantidad de palabras?: \n')) if consulta == '1': if palabra_1 > palabra_2 > palabra_3: print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_1, palabra_2, palabra_3)) elif palabra_2 > palabra_3 > palabra_1: print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_2, palabra_3, palabra_1)) elif palabra_3 > palabra_1 > palabra_2: print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_3, palabra_1, palabra_2)) elif palabra_1 > palabra_3 > palabra_2: print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_1, palabra_3, palabra_2)) elif palabra_2 > palabra_1 > palabra_3: print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_2, palabra_1, palabra_3)) else: print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_3, palabra_2, palabra_1)) if consulta == '2': if len(palabra_1) > len(palabra_2) > len(palabra_3): print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_1, palabra_2, palabra_3)) elif len(palabra_2) > len(palabra_3) > len(palabra_1): print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_2, palabra_3, palabra_1)) elif len(palabra_3) > len(palabra_1) > len(palabra_2): print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_3, palabra_1, palabra_2)) elif len(palabra_1) > len(palabra_3) > len(palabra_2): print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_1, palabra_3, palabra_2)) elif len(palabra_2) > len(palabra_1) > len(palabra_3): print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_2, palabra_1, palabra_3)) else: print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_3, palabra_2, palabra_1)) def ej5(): print('Ejercicios de práctica con números') ''' Realice un programa que solicite ingresar tres valores de temperatura De las temperaturas ingresadas por consola determinar: 1 - ¿Cuáles de ellas es la máxima temperatura ingresada? 2 - ¿Cuáles de ellas es la mínima temperatura ingresada? 3 - ¿Cuál es el promedio de las temperaturas ingresadas? En cada caso imprimir en pantalla el resultado ''' temperatura_1 = float(input('Ingrese el primer valor de temperatura: \n')) temperatura_2 = float(input('Ingrese el segundo valor de temperatura: \n')) temperatura_3 = float(input('Ingrese el tercer valor de temperatura: \n')) promedio = (temperatura_1 + temperatura_2 + temperatura_3)/3 if temperatura_1 > temperatura_2 > temperatura_3: print('La máxima temperatura es {}'.format(temperatura_1)) print('La mínima temperatura es {}'.format(temperatura_3)) print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2))) elif temperatura_2 > temperatura_3 > temperatura_1: print('La máxima temperatura es {}'.format(temperatura_2)) print('La mínima temperatura es {}'.format(temperatura_1)) print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2))) elif temperatura_3 > temperatura_1 > temperatura_2: print('La máxima temperatura es {}'.format(temperatura_3)) print('La mínima temperatura es {}'.format(temperatura_2)) print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2))) elif temperatura_1 > temperatura_3 > temperatura_2: print('La máxima temperatura es {}'.format(temperatura_1)) print('La mínima temperatura es {}'.format(temperatura_2)) print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2))) elif temperatura_2 > temperatura_1 > temperatura_3: print('La máxima temperatura es {}'.format(temperatura_2)) print('La mínima temperatura es {}'.format(temperatura_3)) print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2))) else: print('La máxima temperatura es {}'.format(temperatura_3)) print('La mínima temperatura es {}'.format(temperatura_1)) print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2))) if __name__ == '__main__': print("Ejercicios de práctica") ej1() #ej2() #ej3() #ej4() #ej5()
94dbf6e69a2f41864a6e73af49879f57c51913db
Punsach/Coding-Interview-Questions
/CTCI-Chapter1/CTCI-Chapter1-Problem1.py
1,608
4
4
#Determine if a string has all unique characters. #Assume ASCII characters, so max of 128 distinct characters import sys #Using another Data Structure def Solution1(someString): #By pigeonhole if the string has more than 128 characters, there must be some repeat if(len(someString) > 128): return True #Put characters into a dictionary. If the character is already there, return True. characters = {} for character in someString: if(character in characters): return True else: characters[character] = 1 return False #Without using another data structure [j] def Solution2(someString): if(len(someString) > 128): return True #Sort the string in O(nlogn) time sortedString = ''.join(sorted(someString)) #Since identical characters will now be next to each other, we can see if there are duplicates for index in range(0, len(sortedString) - 2): if(sortedString[index] == sortedString[index+1]): return True return False if(len(sys.argv) != 2): print("That is not the correct number of arguments! Please enter in only one word") else: if(Solution1(sys.argv[1])): print("Using a dictionary, we find there are dupicates! Solution takes O(n) time and O(n) space.") else: print("Using a dictionary, we know there are no duplicates! Solutions take O(n) time and O(n) space.") if(Solution2(sys.argv[1])): print("Without using another data structure, we find there are duplicates! Solution takes O(nlogn) time and O(1) space.") else: print("Without using another data structure, we know there are no duplicates! Solution takes O(nlogn) time and O(1) space.")
0e4ca0c383db411f748144478e50521af41292ce
srikanthpragada/PYTHON_06_APR_2020
/demo/ex/string_with_digits.py
224
4.1875
4
# Count strings with at least one digit count = 0 for i in range(5): s = input("Enter a string :") for c in s: if c.isdigit(): count += 1 break print("Strings with digits :", count)
deb608c8e93805fb1ac47d6624f188cf63432e27
Sidhijain/Algo-Tree
/Code/Python/Kth_Minimum_in_array.py
908
4.40625
4
# Python3 program to find k'th smallest element # Function to return k'th smallest element in a given array def kthSmallest(arr, n, k): # Sort the given array arr.sort() # Return k'th element in the return arr[k-1] # Driver code if __name__=='__main__': arr = [] n = int(input("Enter number of elements: ")) print("Enter elements: ") for i in range(n): element = int(input()) arr.append(element) k = int(input("Enter the number k: ")) print("K'th smallest element is", kthSmallest(arr, n, k)) ''' Time Complexity: O(N Log N) Space Complexity: O(N) Example 1: Input: Enter number of elements: 6 Enter elements: 7 10 4 3 20 15 Enter the number k: 3 Output: K'th smallest element is: 7 Example 2: Input: Enter number of elements: 7 Enter elements: 8 1 0 9 5 11 4 Enter the number k: 4 Output: K'th smallest element is: 5 '''
b49bdba2224574ee1e9451c79e86fb1bed0baba0
AnuragAnalog/project_euler
/Python/euler034.py
603
3.84375
4
#!/usr/bin/python3 """ 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. """ def fact(n): if n == 0 or n == 1: return 1 else: return n * fact(n-1) def euler34() -> int: tot = 0 for i in range(1, 10**6): if i in [1, 2]: continue l = list(map(int, list(str(i)))) if i == sum(list(map(fact, l))): tot = tot + i return tot tot = euler34() print(tot)
736b0dc4271de3e183edec65b85f33e05648ddf2
af-orozcog/Python3Programming
/Python functions,files and dictionaries/assesment1_1.py
240
3.9375
4
""" The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. Find the total number of characters in the file and save to the variable num. """ f = open("travel_plans.txt","r") num = len(f.read())
6b689e114e7a069fbfa51301d8c7cbdc0f1519e2
duheng18/python-study
/programQuick/chapterEight/demo1.py
426
4.125
4
import re path=input('请输入路径:') with open(path,'r') as f: file=f.read() regex=re.compile('ADJECTIVE|NOUN|ADVERB|VERB') while 1: if regex.search(file): x=regex.search(file).group().lower() print('Enter an %s',x) word=input() file=regex.sub(word,file,count=1) else: break path0=input("请输入路径:") with open(path0,'a') as f: f.write(file) print(file)
2e891d87430890bacd0c35e202a85609f498f656
Mrwang19960102/work
/model/machine_learning/sklearn/k_近邻.py
756
3.59375
4
# -*- coding: utf-8 -*- # @File: | k_近邻.py # @Date: | 2020/8/5 16:57 # @Author: | ThinkPad # @Desc: | import numpy as np import pandas as pd from pandas import DataFrame, Series # k邻近算法模型 from sklearn.neighbors import KNeighborsClassifier # 手动创建训练数据集 feature = np.array([[170, 65, 41], [166, 55, 38], [177, 80, 39], [179, 80, 43], [170, 60, 40], [170, 60, 38]]) target = np.array(['男', '女', '女', '男', '女', '女']) # 实例k邻近模型,指定k值=3 knn = KNeighborsClassifier(n_neighbors=3) # 训练数据 knn.fit(feature, target) # 模型评分 s = knn.score(feature, target) print('训练得分:{}'.format(s)) # 预测 p = knn.predict(np.array([[176, 71, 38]])) print(p)
19b0bd7054859746ac3fa9454a04761669d42234
MYMCO117/CFERUTAS
/NE-221-2-UNIVA/python/functions.py
600
3.90625
4
''' def say_hello(): return "Hello" print(say_hello) def say_hello_user(name): print("Hello " + name) name = "Jafet" say_hello_user(name) def user_year_old(actual_year, born_year): years_old =actual_year - born_year return years_old print(user_year_old(2021, 1998)) ''' def add_number(number_one, number_two): added_numbers = number_one + number_two return added_numbers print(add_number(20, 25)) def multiplication(number_1, number_2): result = number_1 * number_2 return result print (multiplication(10, 10))
e52c22317ff25d514fb4dcba51ed0a7576450b6d
here0009/LeetCode
/Python/499_TheMazeIII.py
4,932
4.125
4
""" There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up (u), down (d), left (l) or right (r), but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls on to the hole. Given the ball position, the hole position and the maze, find out how the ball could drop into the hole by moving the shortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directions by using 'u', 'd', 'l' and 'r'. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output "impossible". The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The ball and the hole coordinates are represented by row and column indexes.   Example 1: Input 1: a maze represented by a 2D array 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 Input 2: ball coordinate (rowBall, colBall) = (4, 3) Input 3: hole coordinate (rowHole, colHole) = (0, 1) Output: "lul" Explanation: There are two shortest ways for the ball to drop into the hole. The first way is left -> up -> left, represented by "lul". The second way is up -> left, represented by 'ul'. Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul". Example 2: Input 1: a maze represented by a 2D array 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 Input 2: ball coordinate (rowBall, colBall) = (4, 3) Input 3: hole coordinate (rowHole, colHole) = (3, 0) Output: "impossible" Explanation: The ball cannot reach the hole.   Note: There is only one ball and one hole in the maze. Both the ball and hole exist on an empty space, and they will not be at the same position initially. The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls. The maze contains at least 2 empty spaces, and the width and the height of the maze won't exceed 30. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/the-maze-iii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import heapq class Solution: def findShortestWay(self, maze, ball, hole) -> str: def inRange(i,j): return 0 <= i < row and 0 <= j < col row, col = len(maze), len(maze[0]) visited = set() shortest_dist = float('inf') res_list = [] directions = [(0,-1),(1,0),(0,1),(-1,0)] path_string = 'ldru' si,sj = ball pq = [] for d in range(4): heapq.heappush(pq, (0, path_string[d], si,sj,d)) visited.add((si,sj,d)) while pq: dist, path, i, j, d = heapq.heappop(pq) for next_d in range(4): if (i,j,next_d) not in visited: visited.add((i,j,next_d)) heapq.heappush(pq, (dist, path+path_string[next_d], i,j,next_d)) di,dj = directions[d] step = 1 while inRange(i+step*di, j+step*dj) and maze[i+step*di][j+step*dj] == 0: if [i+step*di, j+step*dj] == hole: tmp_dist = dist+step if tmp_dist < shortest_dist: res_list = [path] shortest_dist = tmp_dist elif tmp_dist == shortest_dist: res_list.append(path) step += 1 step -= 1 if (i+step*di, j+step*dj, d) not in visited and dist+step <= shortest_dist: heapq.heappush(pq, (dist+step, path, i+step*di, j+step*dj, d)) return min(res_list) if res_list else 'impossible' S = Solution() maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]] start = [0,4] destination = [4,4] print(S.findShortestWay(maze, start, destination)) maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]] start = [0,4] destination = [3,2] print(S.findShortestWay(maze, start, destination)) maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]] start = [4,3] destination = [0,1] print(S.findShortestWay(maze, start, destination)) maze =[[0,0,0,0,1,0,0],[0,0,1,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,1],[0,1,0,0,0,0,0],[0,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,1,0,0,0,1],[0,0,0,0,1,0,0]] start = [0,0] destination =[8,6] print(S.findShortestWay(maze, start, destination)) maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]] start = [4,3] destination = [0,1] print(S.findShortestWay(maze, start, destination))
115a29ace09db47a8bc56b90b40f02127f551860
ropable/udacity
/utils.py
2,045
3.59375
4
from __future__ import division import time from functools import update_wrapper def decorator(d): "Make function d a decorator: d wraps a function fn." def _d(fn): return update_wrapper(d(fn), fn) update_wrapper(_d, d) return _d @decorator def trace(f): indent = ' ' def _f(*args): signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args))) print '%s--> %s' % (trace.level*indent, signature) trace.level += 1 try: result = f(*args) print '%s<-- %s == %s' % ((trace.level-1)*indent, signature, result) finally: trace.level -= 1 return result trace.level = 0 return _f @decorator def memoize(f): '''Decorator that caches the return value for each call to f(args). Then when called again with same args, we can just look it up.''' cache = {} def _f(*args): try: return cache[args] except KeyError: cache[args] = result = f(*args) return result except TypeError: # some element of args refuses to be a dict key return f(args) _f.cache = cache return _f def average(numbers): '''Return the average (arithmetic mean) of a sequence of numbers.''' return sum(numbers) / float(len(numbers)) def timedcall(fn, *args): '''Call function with args; return the time in seconds and results.''' t0 = time.clock() result = fn(*args) t1 = time.clock() return t1-t0, result def timedcalls(n, fn, *args): '''Call fn(*args) repeatedly: n times if n is an int, or up to n seconds if n is a float; return the min, avg, and max time.''' if (isinstance(n, int)): times = [timedcall(fn,*args)[0] for _ in range(n)] else: times = [] while sum(times) < n: times.append(timedcall(fn,*args)[0]) return min(times), average(times), max(times)
f9dd9f4efd7c047afe6d72ecc42a759a503b7f2e
GustavoGajdeczka/IPOO
/aula5/ex9.py
162
3.9375
4
print("== Aumento ==") salario = float(input("= Informe o seu salario: R$")) print("## O seu salario com aumento é igual a : R$", (salario / 100) * 37 + salario)
7bee50a946906ff59bba3b5d02e2f8b29252f94a
cbayonao/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
241
3.859375
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): cpy = [] for a in range(len(my_list)): if my_list[a] != search: cpy.append(my_list[a]) else: cpy.append(replace) return cpy
5058f856415bee6698719729ad01c1f12732495f
asgore-undertale/ATCEE-Asgore-Text-Converter-Extractor-and-Enteror
/ConvertingScripts/Sort_lines.py
209
3.703125
4
def Sort(text, case = True): lines_list = text.split('\n') lines_list.sort(key=len) if case == False: lines_list = lines_list[::-1] text = '\n'.join(lines_list) return text
125b59275dba01b9ce4f8546fed08b5ee3a081e6
sajan777/ML_Begins
/DUCAT/Armstrong.py
206
3.8125
4
result = 0 n= int(input('Enter your number :')) temp = n while(temp>0): temp1 = temp%10 temp = temp// 10 result = result+temp1**3 if(result == n): print('Hell yeah') else: print('Nope')
1404b226df4e033b97d51b3a8ff00f6c7921475f
bgoonz/UsefulResourceRepo2.0
/_RESOURCES/awesome-git-user/ThinkComplexity2/code/Cell2D.py
3,945
3.6875
4
""" Code example from Complexity and Computation, a book about exploring complexity science with Python. Available free from http://greenteapress.com/complexity Copyright 2016 Allen Downey MIT License: http://opensource.org/licenses/MIT """ from __future__ import print_function, division import sys import numpy as np import matplotlib.pyplot as plt from matplotlib import animation from scipy.signal import convolve2d """ For animation to work in the notebook, you might have to install ffmpeg. On Ubuntu and Linux Mint, the following should work. sudo add-apt-repository ppa:mc3man/trusty-media sudo apt-get update sudo apt-get install ffmpeg """ class Cell2D: """Implements Conway's Game of Life.""" def __init__(self, n, m=None): """Initializes the attributes. n: number of rows m: number of columns """ m = n if m is None else m self.array = np.zeros((n, m), np.uint8) def add_cells(self, row, col, *strings): """Adds cells at the given location. row: top row index col: left col index strings: list of strings of 0s and 1s """ for i, s in enumerate(strings): self.array[row + i, col : col + len(s)] = np.array([int(b) for b in s]) def step(self): """Executes one time step.""" pass class Cell2DViewer: """Generates an animated view of an array image.""" cmap = plt.get_cmap("Greens") options = dict(interpolation="nearest", alpha=0.8, vmin=0, vmax=1, origin="upper") def __init__(self, viewee): self.viewee = viewee self.im = None self.hlines = None self.vlines = None # TODO: should this really take iters? def step(self, iters=1): """Advances the viewee the given number of steps.""" for i in range(iters): self.viewee.step() def draw(self, grid=False): """Draws the array and any other elements. grid: boolean, whether to draw grid lines """ self.draw_array(self.viewee.array) if grid: self.draw_grid() def draw_array(self, array=None, cmap=None, **kwds): """Draws the cells.""" # Note: we have to make a copy because some implementations # of step perform updates in place. if array is None: array = self.viewee.array a = array.copy() cmap = self.cmap if cmap is None else cmap n, m = a.shape plt.axis([0, m, 0, n]) plt.xticks([]) plt.yticks([]) options = self.options.copy() options["extent"] = [0, m, 0, n] options.update(kwds) self.im = plt.imshow(a, cmap, **options) def draw_grid(self): """Draws the grid.""" a = self.viewee.array n, m = a.shape lw = 2 if m < 7 else 1 options = dict(color="white", linewidth=lw) # the shift is a hack to get the grid to line up with the cells shift = 0.005 * n rows = np.arange(n) + shift self.hlines = plt.hlines(rows, 0, m, **options) cols = np.arange(m) self.vlines = plt.vlines(cols, 0, n, **options) def animate(self, frames=20, interval=200, grid=False): """Creates an animation. frames: number of frames to draw interval: time between frames in ms """ fig = plt.gcf() self.draw(grid) anim = animation.FuncAnimation( fig, self.animate_func, init_func=self.init_func, frames=frames, interval=interval, ) return anim def init_func(self): """Called at the beginning of an animation.""" pass def animate_func(self, i): """Draws one frame of the animation.""" if i > 0: self.step() a = self.viewee.array self.im.set_array(a) return (self.im,)
318777dd3cc975123076862176311e73349b817c
rohanaurora/daily-coding-challenges
/Problems/detect_capital.py
640
3.796875
4
# Detect Capital # Source - https://leetcode.com/problems/detect-capital/ # 1. All letters in this word are capitals, like "USA". # 2. All letters in this word are not capitals, like "leetcode". # 3. Only the first letter in this word is capital, like "Google". # class Solution: def detectCapitalUse(self, word): if word == word.upper() or word == word.lower(): return True elif (word == word.capitalize()): return True else: return False # return True if word.isupper() or word.islower() or word.istitle() else False s = Solution().detectCapitalUse("FlaG") print(s)
7dc9ffb485d94e7bb586b9716c092ffdc9391a5f
apterek/python_lesson_TMS
/lesson_10/homework/solution_home_01.py
2,098
3.734375
4
import math from math import pi class Point: def __init__(self, axis_x, axis_y): self.axis_x = axis_x self.axis_y = axis_y self.point_axis = [self.axis_x, self.axis_y] class Figure: def __init__(self): self.second_point = None self.first_point = None def line_length(self): return math.sqrt(pow(self.first_point[0] - self.second_point[0], 2) + pow(self.first_point[1] - self.second_point[1], 2)) class Circle(Figure): def __init__(self, first_point, second_point): super().__init__() self.second_point = second_point self.first_point = first_point self.radius = self.line_length() def area(self): return pi * pow(self.radius, 2) def perimeter(self): return pi * 2 * self.radius class Triangle(Figure): def __init__(self, point_A, point_B, point_C): super().__init__() self.point_C = point_C self.point_B = point_B self.point_A = point_A self.side_a = math.sqrt(pow(self.point_A[0] - self.point_B[0], 2) + pow(self.point_A[1] - self.point_B[1], 2)) self.side_b = math.sqrt(pow(self.point_B[0] - self.point_C[0], 2) + pow(self.point_B[1] - self.point_C[1], 2)) self.side_c = math.sqrt(pow(self.point_C[0] - self.point_A[0], 2) + pow(self.point_C[1] - self.point_A[1], 2)) def area(self): half_per = (self.side_a + self.side_b + self.side_c) / 2 return math.sqrt(half_per * (half_per - self.side_a) * (half_per - self.side_b) * (half_per - self.side_c)) def perimeter(self): return self.side_a + self.side_b + self.side_c class Square(Figure): def __init__(self, first_point, second_point): super().__init__() self.second_point = second_point self.first_point = first_point self.side = self.line_length() def area(self): return pow(self.side, 2) def perimeter(self): return self.side * 4
5521d9fb61ca6791eab0bff38dd80ee8be94518e
sashadroid/homework
/007_lists/007_homework_1_2_3.py
1,472
3.765625
4
# Задание 1 list = [8, 16, 0, 4, -23, 9] ma = max(list[0::]) print(" Наибольший элемент списка = ", ma) mi = min(list[0::]) print(" Наименьший элемент списка = ", mi) x = sum(list[0::]) print(" Сумма всех элементов списка = ", x) y = x/len(list) print(" Средняя арифметическая элементов списка = ", y) # Задание 2 stup = 5 l = [1, 2] for i in range(stup - 2): l.append(l[i]+l[i+1]) print(" Количество способов подняться на требуемую ступень = ", l) # Задание 3 line = [1, 2, 3, 4, 5, 6, 7, 8, 9] simple_list = [] for i in line: simple = True if i == 1: simple = False for y in range(2, i): if (i % y == 0): simple = False if simple == True: simple_list.append(i) print(i) x = input("Вы хотите сложить или умножить данные числа?(Да/Нет) ") if x == "Нет": print("Ну ладно, давай тогда.") elif x == "Да": z = input("Для умножения введите (*), для сложения введите (+): ") if z == "+": s = sum(simple_list[0::]) print("Сумма этих чисел = ", s) elif z == "*": w = 1 for f in simple_list: w *= f print("Произведение этих чисел = ", w)
62066d70d2b86f4f207ba74689d380d9266a110e
shiv-konar/Python-Projects
/warriors_battle.py
1,895
3.59375
4
''' Credit: Derek Banas https://www.youtube.com/watch?v=1AGyBuVCTeE&index=9&list=PLGLfVvz_LVvTn3cK5e6LjhgGiSeVlIRwt ''' import random import math class Warrior: def __init__(self, name="warrior", health = 0, attkMax = 0, blockMax = 0): self.name = name self.health = health self.attkMax = attkMax self.blockMax = blockMax def attack(self): attkAmt = self.attkMax * (random.random() + 0.5) return attkAmt def block(self): blockAmt = self.blockMax * (random.random() + 0.5) return blockAmt class Battle: def startFight(self, warrior1, warrior2): while True: if self.getAttackResult(warrior1, warrior2) == "Game Over": print "Game Over" break if self.getAttackResult(warrior2, warrior1) == "Game Over": print "Game Over" break @staticmethod def getAttackResult(warriorA, warriorB): warriorAAttkAmt = warriorA.attack() warriorBAttkAmt = warriorB.block() damageToWarriorB = math.ceil(warriorAAttkAmt - warriorBAttkAmt) warriorB.health = warriorB.health - damageToWarriorB print "{} attacks {} and deals {} damage".format(warriorA.name, warriorB.name, damageToWarriorB) print "{} is down to {} health\n".format(warriorB.name, warriorB.health) if warriorB.health <= 0: print "{} has Died and {} is Victorious".format(warriorB.name, warriorA.name) return "Game Over" else: return "Fight Again" def main(): paul = Warrior("Paul", 50, 20, 10) sam = Warrior("Sam", 50, 20, 10) battle = Battle() battle.startFight(paul, sam) main()
fb22fe19e70c1da9ef53038b6446a9cdd5a48f68
FangyangJz/Python_Cookbook_Practice_Code
/C1_数据结构和算法/c5_有关heap的测试.py
219
3.859375
4
import heapq def HeapSort(list): heapq.heapify(list) heap = [] print(list) while list: heap.append(heapq.heappop(list)) list[:] = heap return list print(HeapSort([1,3,5,7,9,2,4,6,8,0]))
178c5a9b39ee90226796232466a166996c00174c
Kashish24/hackerEarthCodingSolutions
/Efficient Huffman Coding for Sorted Input.py
1,430
3.71875
4
# Link to the Problem:- https://www.geeksforgeeks.org/efficient-huffman-coding-for-sorted-input-greedy-algo-4/ class createNode: def __init__(self, freq, symb, left = None, right = None): self.freq = freq; self.symb = symb; self.left = left; self.right = right; self.huff = ''; def printCode(node, val=''): newVal = val + str(node.huff); if(node.left): printCode(node.left, newVal); if(node.right): printCode(node.right, newVal); if(not node.left and not node.right): print(f'{node.symb} : {newVal}'); symbol = ['a', 'b', 'c', 'd', 'e', 'f'] freq = [5,9,12,13,16,45]; firstQueue = [] secondQueue = [] for i in range(len(symbol)): firstQueue.append(createNode(freq[i], symbol[i])); while((len(firstQueue)+len(secondQueue))>1): elem = [] for i in range(2): if(len(secondQueue) == 0): elem.append(firstQueue.pop(0)) elif(len(firstQueue) == 0): elem.append(secondQueue.pop(0)) else: if(firstQueue[0].freq < secondQueue[0].freq): elem.append(firstQueue.pop(0)); else: elem.append(secondQueue.pop(0)); elem[0].huff = '0'; elem[1].huff = '1'; newNode = createNode(elem[0].freq+elem[1].freq, elem[0].symb+elem[1].symb, elem[0], elem[1]); secondQueue.append(newNode); printCode(secondQueue[0]);
6eac2ab6429dc948341693d84bd48458e254d3d4
AnalyticsCal/AnalyticsCal-Classroom
/anova_class.py
1,920
3.796875
4
# How to use..? # 1. import anova # 2. Pass y_list=y vaues, y_cap_list=y predected values, degree_of_freedom= number of parameters to class import scipy.stats as stats import stats_team3 as common # Structure of the dictionary we deal with # This same dictionary will be returned with updated values once the computations are done successfully class Anova: def __init__(self, y_list, y_cap_list, degree_of_freedom): # calucation point required degree_of_freedom = degree_of_freedom number_of_data_points = len(y_cap_list) # ssr calcualtion self.ssr_drg_of_freedom = degree_of_freedom-1 self.ssr = self.sum_of_squred_regression(y_cap_list) self.msr = self.ssr/self.ssr_drg_of_freedom # sse calculation self.sse = self.sum_of_squred_error(y_list, y_cap_list) self.sse_dgr_pf_freedom = number_of_data_points-degree_of_freedom self.mse = self.sse/self.sse_dgr_pf_freedom # calculate F P and Model Confidence self.f = self.msr/self.mse self.p = stats.f.ppf(0.05,self.ssr_drg_of_freedom, self.sse_dgr_pf_freedom) self.model_confidence = self.get_model_confidence(self.p) def get_model_confidence(self,p:float): return (1-p)*100 # caluate sum of error def sum_of_squred_error(self, y_list: [], y_cap_list: []): return sum([(y-y_cap) ** 2 for y, y_cap in zip(y_list, y_cap_list)]) # cal sum of regression def sum_of_squred_regression(self, values): ymean = common.mean(values) return sum([(val - ymean) ** 2 for val in values]) if __name__ == "__main__": y_list=[] y_cap_list=[] degree_of_freedom=2 anova = Anova(y_list,y_cap_list,degree_of_freedom) print("ssr=" + anova.ssr) print("sse=" + anova.sse) print("msr=" + anova.msr) print("mse=" + anova.mse) print("f=" + anova.f) print("p=" + anova.p)
3e1230f951e90e560eb3bfc4d42b454bec1f9176
TheRea1AB/Python
/HighestValue.py
541
4.1875
4
# Which of the two numbers is greater def greatestNumber(Number1,Number2): if Number1 > Number2: print('Number 1 is the bigger number') return Number1 elif Number2 > Number1: print('Number 2 is the bigger number') return Number2 else: print('These two numbers are the same') return Number1 print('Enter Number 1: ') Number1 = int(input()) print('Enter Number 2: ') Number2 = int(input()) maxNumber = greatestNumber(Number1,Number2) print("The maximum is = {}".format(maxNumber))
fcd7d551a7803f90770ae13b0a5b991bfeac40b3
KADEEJASAFEER/python_test_2
/employeefile.py
761
3.875
4
#create class and employee objects class Employee: def __init__(self,eid,name,desig,mail,sal): self.eid=eid self.name=name self.desig=desig self.mail=mail self.sal=sal def printEmp(self): print(self.eid,",",self.name,",",self.desig,",",self.mail,",",self.sal) #read data from file 'employee' f=open("employee","r") emp=[] for data in f: #print(data) employee = data.rstrip("\n").split(",") eid = employee[0] name = employee[1] desig = employee[2] mail = employee[3] sal = int(employee[4]) ob=Employee(eid,name,desig,mail,sal) ob.printEmp() emp.append(ob) #maximum salary of employee for employee in emp: salary=employee.sal print(max(salary))
790ea4bd6b55427677264ceef12cf76fd5460976
lydia-tango/E27FinalProject
/clothes-net.py
3,251
3.96875
4
""" clothes-net.py uses the ANN libraries newConx to create a new class DeepFashion which is a BackpropNetwork to classify inputs data based on the target set. After getting a good training result, we will store the weights used in the network to evaluate novel inputs. """ from newConx import * from defClothes import * class DeepFashion(BackpropNetwork): """ A specialied backprop network for classifying face images for the position of head. """ def classify(self, output): """ This ensures that that output layer is the correct size for this task, and then tests whether the output value is within tolerance of 1 (meaning sunglasses are present) or 0 (meaning they are not). """ if len(output) != len(article_text): return '???' for i in range(len(article_text)): if output[i] > (1 - self.tolerance): return article_text[i] return '???' def evaluate(self): """ For the current set of inputs, tests each one in the network to determine its classification, compares this classification to the targets, and computes the percent correct. """ if len(self.inputs) == 0: print 'no patterns to evaluate' return correct = 0 wrong = 0 for i in range(len(self.inputs)): pattern = self.inputs[i] target = self.targets[i] output = self.propagate(input=pattern) networkAnswer = self.classify(output) correctAnswer = self.classify(target) if networkAnswer == correctAnswer: correct = correct + 1 else: wrong = wrong + 1 print 'network classified image #%d (%s) as %s' % \ (i, correctAnswer, networkAnswer) total = len(self.inputs) correctPercent = float(correct) / total * 100 wrongPercent = float(wrong) / total * 100 print '%d patterns: %d correct (%.1f%%), %d wrong (%.1f%%)' % \ (total, correct, correctPercent, wrong, wrongPercent) #create the network n = DeepFashion() scale = 1 w = 80/scale h = 60/scale * 4 # Add three layers, input size is 240*80 = 19200 , hidden layer size is 18, output layer is 9 n.addLayers(w * h, len(article_text) *2, len(article_text)) #get the input and target data rootname = "inputs/" # inputs: n.loadInputsFromFile("inputs/inputs.dat") # outputs: n.loadTargetsFromFile("inputs/targets.dat") #set the training parameters n.setEpsilon(0.3) n.setMomentum(0.1) n.setReportRate(1) n.setTolerance(0.2) #create the visualization windows n.showActivations('input', shape=(w,h), scale= scale) n.showActivations('hidden', scale=100) n.showActivations('output', scale=100) n.showWeights('hidden', shape=(w,h), scale= scale) # use 80% of dataset for training, 20% for testing n.splitData(80) print "Clothes recognition network is set up" # Type the following at the python prompt: # # >>> n.showData() # >>> n.showPerformance() # >>> n.evaluate() # >>> n.train() # >>> n.showPerformance() # >>> n.evaluate() # >>> n.swapData() # >>> n.showPerformance() # >>> n.evaluate()
65d2add97318d1cdca06f2909a3d5b18b7262127
Eternally1/web
/python/fullstacks/week4/day1/卡牌问题2.py
1,506
3.8125
4
# @author: "QiuJunan" # @date: 2018/3/28 15:12 # 2017年机试题目,这里可以输出所有结果为13的组合,之后在寻找一个卡牌数目最多的情况即可 # 目前能做到的是按照顺序将牌一次计算进来,但是不能做到 如不要1,直接从3开始的一些卡牌组合。 def opera(a, b, op): if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b elif op == '/': return a / b xm = 5 desk = [1, 3, 9, 2, 4, 4] i = 0 # desk = [1,3,4] stack = [5] count = 0 def mFind(num,i): if i<len(desk): global stack global count for op in ['+', '-', '*', '/']: stack.append(op) stack.append(desk[i]) num = opera(num,desk[i],op) if num == 13: count +=1 print(stack) mFind(num,i+1) # 这里通过递归可以获得所有的组合情况 n = stack.pop() # 这里是为了在回退到上一部的时候,对应的进栈数据需要出栈。 m = stack.pop() if m == '+': # num的值也要回退。 num = opera(num,n,'-') elif m =='-': num = opera(num, n, '+') elif m == '*': num = opera(num,n,'/') elif m == '/': num = opera(num,n,'*') else: # 在这里可以输出所有的组合情况 pass mFind(5,0) print(count)
d846fdc1ad1f0505a661a9e43b44480ff7170bc7
thecodingsophist/leetcode
/array_form_of_integer.py
264
3.625
4
''' For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1]. Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. '''
63d47c63efdf63f33035f0a7e01667e87c9c4b8a
katiemthom/word-counter
/wordcount.py
554
3.5
4
import sys import string dict_words_counts = {} file_to_count = open(sys.argv[1]) for line in file_to_count: line_list = line.split() for word in line_list: word = string.strip(word, ",.?/;:\'\"[]{}-()&%$#!`") word = word.lower() dict_words_counts[word] = dict_words_counts.get(word, 0) + 1 unsorted_list = dict_words_counts.items() for i in range(len(unsorted_list)): unsorted_list[i] = unsorted_list[i][::-1] sorted_list = sorted(unsorted_list) for i in range(len(sorted_list)): print sorted_list[i][1], sorted_list[i][0] #quicksort
b14b989b06090f93f64d89d41ae9df9a4183c146
panas-zinchenko/zinchenko_lab
/Lab6(1).py
1,088
3.90625
4
from re import * name = input('inter you name:') address = input('inter you email address:') phone = input('inter you phone:') def validateAddress(address): pattern = compile('(^|\s)[-a-z0-9_.]+@([-a-z0-9]+\.)+[a-z]{2,6}(\s|$)') is_valid = pattern.match(address) if is_valid: print('правильний email:', is_valid.group()) else: print('Некоректний email') def validatePhone(phone): pattern = compile('^((8|\+38)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$') is_valid = pattern.match(phone) if is_valid: print('правильний номер:', is_valid.group()) else: print('Некоректний номер телефону') def validateName(name): pattern = compile('(^|\s)[-a-z]{2,255}(\s|$)') is_valid = pattern.match(name) if is_valid: print('правильний name:', is_valid.group()) else: print('Некоректне ім\'я') print('\n-----------------------------------------\n') validateAddress(address) validatePhone(phone) validateName(name)
e93d2df0395c95a088ee849ae85a8a7ac6cef374
A-Alexander-code/150-Python-Challenges--Solutions
/Ejercicio_N017.py
250
3.890625
4
edad = int(input("Ingresa tu edad: ")) if edad>=18: print("Puedes votar") elif edad==17: print("Puedes aprender a conducir") elif edad==16: print("Puedes comprar un billete de lotería") else: print("Puedes pedir dulces en Halloween")
adb65030bc65ddc260bc84a50ef731d510b05a7e
AShar97/Interpreter
/toy.py
19,588
3.625
4
""" Toy Language Interpreter """ """ Grammar : compound_statement : statement_list statement_list : statement | statement SEMI statement_list statement : compound_statement | assignment_statement | loop_statement | conditional_statement | print_statement | println_statement | empty assignment_statement : variable ASSIGN expr loop_statement : WHILE cond_expr DO compound_statement DONE conditional_statement : IF cond_expr THEN compound_statement ELSE compound_statement END print_statement : PRINT expr println_statement : PRINTLN empty : cond_expr : ??? expr : string ??? | term ((PLUS | MINUS) term)* term : factor ((MUL | INTEGER_DIV | FLOAT_DIV) factor)* factor : PLUS factor | MINUS factor | INTEGER_CONST | REAL_CONST | LPAREN expr RPAREN | variable variable: ID """ from collections import OrderedDict ############################################################################### # # # LEXER # # # ############################################################################### # Token types # # EOF (end-of-file) token is used to indicate that # there is no more input left for lexical analysis INTEGER_CONST, REAL_CONST = ('INTEGER_CONST', 'REAL_CONST') #STRING = 'STRING' #QUOTE = 'QUOTE' PLUS, MINUS, MUL, INTEGER_DIV, FLOAT_DIV = ('PLUS', 'MINUS', 'MUL', 'INTEGER_DIV', 'FLOAT_DIV') LPAREN, RPAREN = ('LPAREN', 'RPAREN') ID = 'ID' ASSIGN = 'ASSIGN' SEMI = 'SEMI' ET, NET, LET, GET, LT, GT = ('ET', 'NET', 'LET', 'GET', 'LT', 'GT') AND, OR = ('AND', 'OR') WHILE, DO, DONE = ('WHILE', 'DO', 'DONE') IF, THEN, ELSE, END = ('IF', 'THEN', 'ELSE', 'END') PRINT = 'PRINT' PRINTLN = 'PRINTLN' EOF = 'EOF' class Token(object): def __init__(self, type, value): self.type = type self.value = value def __str__(self): """String representation of the class instance. Examples: Token(INTEGER, 3) Token(PLUS '+') Token(MUL, '*') """ return 'Token({type}, {value})'.format( type = self.type, value = repr(self.value) ) def __repr__(self): return self.__str__() RESERVED_KEYWORDS = { 'IF': Token('IF', 'IF'), 'THEN': Token('THEN', 'THEN'), 'ELSE': Token('ELSE', 'ELSE'), 'END': Token('END', 'END'), 'WHILE': Token('WHILE', 'WHILE'), 'DO': Token('DO', 'DO'), 'DONE': Token('DONE', 'DONE'), 'PRINT': Token('PRINT', 'PRINT'), 'PRINTLN': Token('PRINTLN', 'PRINTLN'), } #Breaking into series of tokens. class Lexer(object): def __init__(self, text): # client string input, e.g. "4 + 2 * 3 - 6 / 2" self.text = text # self.pos is an index into self.text self.pos = 0 self.current_char = self.text[self.pos] def error(self): raise Exception('Invalid character') def advance(self): """Advance the 'pos' pointer and set the 'current_char' variable.""" self.pos += 1 if self.pos > len(self.text) - 1: self.current_char = None # Indicates end of input else: self.current_char = self.text[self.pos] def peek(self): peek_pos = self.pos + 1 if peek_pos > len(self.text) - 1: return None else: return self.text[peek_pos] def skip_comment(self): while self.current_char != '}': self.advance() self.advance() # the closing curly brace def skip_whitespace(self): while self.current_char is not None and self.current_char.isspace(): self.advance() def string(self): """Return a string consumed from the input.""" result = '' while self.current_char != '\"': result += self.current_char self.advance() self.advance() # the ending '\"' symbol token = Token('STRING', result) return token def number(self): """Return a (multidigit) integer or float consumed from the input.""" result = '' while self.current_char is not None and self.current_char.isdigit(): result += self.current_char self.advance() if self.current_char == '.': result += self.current_char self.advance() while ( self.current_char is not None and self.current_char.isdigit() ): result += self.current_char self.advance() token = Token('REAL_CONST', float(result)) else: token = Token('INTEGER_CONST', int(result)) return token def _id(self): """Handle identifiers and reserved keywords""" result = '' while self.current_char is not None and self.current_char.isalnum(): result += self.current_char self.advance() token = RESERVED_KEYWORDS.get(result, Token(ID, result)) return token def get_next_token(self): """Lexical analyzer (also known as scanner or tokenizer) This method is responsible for breaking a sentence apart into tokens. One token at a time. """ while self.current_char is not None: if self.current_char == '{': self.advance() self.skip_comment() continue # if self.current_char == '\"': # self.advance() ## self.string() ## continue # return Token(QUOTE, '\"') if self.current_char.isspace(): self.skip_whitespace() continue if self.current_char.isdigit(): return self.number() if self.current_char.isalpha(): return self._id() if self.current_char == ':' and self.peek() == '=': self.advance() self.advance() return Token(ASSIGN, ':=') if self.current_char == '=' and self.peek() == '=': self.advance() self.advance() #token=Token(ET, '==') #return CondET(token) return Token(ET, '==') # return Cond(Token(ET, '==')) if self.current_char == '!' and self.peek() == '=': self.advance() self.advance() #token=Token(NET, '!=') #return CondNET(token) return Token(NET, '!=') # return Cond(Token(NET, '!=')) if self.current_char == '<' and self.peek() == '=': self.advance() self.advance() #token=Token(LET, '<=') #return CondLET(token) return Token(LET, '<=') # return Cond(Token(LET, '<=')) if self.current_char == '>' and self.peek() == '=': self.advance() self.advance() #token=Token(GET, '>=') #return CondGET(token) return Token(GET, '>=') # return Cond(Token(GET, '>=')) if self.current_char == '<' : self.advance() #token=Token(LT, '<') #return CondLT(token) return Token(LT, '<') # return Cond(Token(LT, '<')) if self.current_char == '>' : self.advance() #token=Token(GT, '>') #return CondGT(token) return Token(GT, '>') # return Cond(Token(GT, '>')) if self.current_char == '&' and self.peek() == '&': self.advance() self.advance() return Token(AND, '&&') if self.current_char == '|' and self.peek() == '|': self.advance() self.advance() return Token(OR, '||') if self.current_char == ';': self.advance() return Token(SEMI, ';') if self.current_char == '+': self.advance() return Token(PLUS, '+') if self.current_char == '-': self.advance() return Token(MINUS, '-') if self.current_char == '*': self.advance() return Token(MUL, '*') if self.current_char == '/' and self.peek() == '/': self.advance() self.advance() return Token(INTEGER_DIV, '//') if self.current_char == '/': self.advance() return Token(FLOAT_DIV, '/') if self.current_char == '(': self.advance() return Token(LPAREN, '(') if self.current_char == ')': self.advance() return Token(RPAREN, ')') self.error() return Token(EOF, None) ############################################################################### # # # PARSER # # # ############################################################################### # abstract-syntax trees class AST(object): pass class Compound(AST): """Represents a '...' block""" def __init__(self): self.children = [] class Assign(AST): def __init__(self, left, op, right): self.left = left self.token = self.op = op self.right = right class Num(AST): def __init__(self, token): self.token = token self.value = token.value #class String(AST): # def __init__(self, token): # self.token = token # self.value = token.value class Var(AST): """The Var node is constructed out of ID token.""" def __init__(self, token): self.token = token self.value = token.value class NoOp(AST): pass class UnaryOp(AST): def __init__(self, op, expr): self.token = self.op = op self.expr = expr class BinOp(AST): def __init__(self, left, op, right): self.left = left self.token = self.op = op self.right = right class LogOp(AST): def __init__(self, left, op, right): self.left = left self.token = self.op = op self.right = right class CondOp(AST): def __init__(self, left, op, right): self.left = left self.token = self.op = op self.type = op.type self.right = right #class Cond(AST): # def __init__(self, op): # self.left = None # self.token = self.op = op # self.type = op.type # self.right = None class Loop(AST): def __init__(self, cond, stmt): self.cond = cond self.stmt = stmt class Conditional(AST): def __init__(self, cond, then_stmt, else_stmt): self.cond = cond self.then_stmt = then_stmt self.else_stmt = else_stmt class PrintLN(AST): def __init__(self): pass class Print(AST): def __init__(self, expr): self.data = expr class Parser(object): ##class Parser(Lexer): def __init__(self, lexer): ##def __init__(self, text): self.lexer = lexer ##super(Parser,self).__init__(text) # set current token to the first token taken from the input self.current_token = self.lexer.get_next_token() ##self.current_token = self.get_next_token() def error(self): raise Exception('Invalid syntax') def eat(self, token_type): # compare the current token type with the passed token # type and if they match then "eat" the current token # and assign the next token to the self.current_token, # otherwise raise an exception. if self.current_token.type == token_type: self.current_token = self.lexer.get_next_token() ##self.current_token = self.get_next_token() else: self.error() def compound_statement(self): """ compound_statement: statement_list """ nodes = self.statement_list() root = Compound() for node in nodes: root.children.append(node) return root def statement_list(self): """ statement_list : statement | statement SEMI statement_list """ node = self.statement() results = [node] while self.current_token.type == SEMI: self.eat(SEMI) results.append(self.statement()) if self.current_token.type == ID: self.error() return results def statement(self): """ type of statement. """ if self.current_token.type == ID: node = self.assignment_statement() elif self.current_token.type == WHILE: node=self.loop_statement() elif self.current_token.type == IF: node=self.conditional_statement() elif self.current_token.type == PRINTLN: node=self.println_statement() elif self.current_token.type == PRINT: node=self.print_statement() else: node = self.empty() return node def assignment_statement(self): """ assignment_statement : variable ASSIGN expr """ left = self.variable() token = self.current_token self.eat(ASSIGN) right = self.expr() node = Assign(left, token, right) return node def loop_statement(self): """ loop_statement : WHILE cond_expr DO compound_statement DONE """ self.eat(WHILE) cond=self.cond_expr() self.eat(DO) stmt=self.compound_statement() self.eat(DONE) node = Loop(cond,stmt) return node def conditional_statement(self): """ conditional_statement : IF cond_expr THEN compound_statement ELSE compound_statement END """ self.eat(IF) cond=self.cond_expr() self.eat(THEN) then_stmt=self.compound_statement() self.eat(ELSE) else_stmt=self.compound_statement() self.eat(END) node = Conditional(cond,then_stmt,else_stmt) return node def println_statement(self): """ println_statement : PRINTLN """ self.eat(PRINTLN) node = PrintLN() return node def print_statement(self): """ print_statement : PRINT expr """ self.eat(PRINT) data = self.expr() node = Print(data) return node def cond_expr(self): node = self.cond_term() while self.current_token.type==OR: token = self.current_token self.eat(OR) node = LogOp(left=node, op=token, right=self.cond_term()) return node def cond_term(self): node = self.cond_factor() while self.current_token.type==AND: token = self.current_token self.eat(AND) node = LogOp(left=node, op=token, right=self.cond_factor()) return node def cond_factor(self): left = self.expr() # node = self.current_token token = self.current_token ##self.current_token=self.get_next_token() self.current_token=self.lexer.get_next_token() right=self.expr() # node.left=left # node.right=right node = CondOp(left=left, op=token, right=right) return node def variable(self): """ variable : ID """ node = Var(self.current_token) self.eat(ID) return node def empty(self): """An empty production""" return NoOp() def factor(self): """factor : PLUS factor | MINUS factor | INTEGER_CONST | REAL_CONST | LPAREN expr RPAREN | variable """ token = self.current_token if token.type == PLUS: self.eat(PLUS) node = UnaryOp(token, self.factor()) return node elif token.type == MINUS: self.eat(MINUS) node = UnaryOp(token, self.factor()) return node ### # elif token.type == QUOTE: # self.eat(QUOTE) # node = self.string() # node = self.expr() # self.eat(QUOTE) # return node elif token.type == INTEGER_CONST: self.eat(INTEGER_CONST) return Num(token) elif token.type == REAL_CONST: self.eat(REAL_CONST) return Num(token) elif token.type == LPAREN: self.eat(LPAREN) node = self.expr() self.eat(RPAREN) return node else: node = self.variable() return node def term(self): """term : factor ((MUL | INTEGER_DIV | FLOAT_DIV) factor)*""" node = self.factor() while self.current_token.type in (MUL, INTEGER_DIV, FLOAT_DIV): token = self.current_token if token.type == MUL: self.eat(MUL) elif token.type == INTEGER_DIV: self.eat(INTEGER_DIV) elif token.type == FLOAT_DIV: self.eat(FLOAT_DIV) node = BinOp(left=node, op=token, right=self.factor()) return node def expr(self): """ expr : string ??? | term ((PLUS | MINUS) term)* term : factor ((MUL | DIV) factor)* factor : PLUS factor | MINUS factor | INTEGER_CONST | REAL_CONST | LPAREN expr RPAREN | variable """ # if self.current_token.type == STRING: # self.eat(STRING) # return String(self.current_token) # else: node = self.term() while self.current_token.type in (PLUS, MINUS): token = self.current_token if token.type == PLUS: self.eat(PLUS) elif token.type == MINUS: self.eat(MINUS) node = BinOp(left=node, op=token, right=self.term()) return node def parse(self): node = self.compound_statement() if self.current_token.type != EOF: self.error() return node ############################################################################### # # # INTERPRETER # # # ############################################################################### class NodeVisitor(object): def visit(self, node): method_name = 'visit_' + type(node).__name__ visitor = getattr(self, method_name, self.generic_visit) return visitor(node) def generic_visit(self, node): raise Exception('No visit_{} method'.format(type(node).__name__)) class Interpreter(NodeVisitor): GLOBAL_SCOPE = OrderedDict() def __init__(self, parser): self.parser = parser def visit_Compound(self, node): for child in node.children: self.visit(child) def visit_NoOp(self, node): pass def visit_Assign(self, node): var_name = node.left.value self.GLOBAL_SCOPE[var_name] = self.visit(node.right) def visit_Var(self, node): var_name = node.value val = self.GLOBAL_SCOPE.get(var_name) if val is None: raise NameError(repr(var_name)) else: return val def visit_UnaryOp(self, node): op = node.op.type if op == PLUS: return +self.visit(node.expr) elif op == MINUS: return -self.visit(node.expr) def visit_BinOp(self, node): if node.op.type == PLUS: return self.visit(node.left) + self.visit(node.right) elif node.op.type == MINUS: return self.visit(node.left) - self.visit(node.right) elif node.op.type == MUL: return self.visit(node.left) * self.visit(node.right) elif node.op.type == INTEGER_DIV: return self.visit(node.left) // self.visit(node.right) elif node.op.type == FLOAT_DIV: return float(self.visit(node.left)) / float(self.visit(node.right)) def visit_LogOp(self, node): if node.op.type == AND: return self.visit(node.left) and self.visit(node.right) elif node.op.type == OR: return self.visit(node.left) or self.visit(node.right) def visit_CondOp(self, node): if node.op.type == ET: return self.visit(node.left) == self.visit(node.right) elif node.op.type == NET: return self.visit(node.left) != self.visit(node.right) elif node.op.type == GET: return self.visit(node.left) >= self.visit(node.right) elif node.op.type == LET: return self.visit(node.left) <= self.visit(node.right) elif node.op.type == GT: return self.visit(node.left) > self.visit(node.right) elif node.op.type == LT: return self.visit(node.left) < self.visit(node.right) # def visit_Cond(self, node): # if node.op.type == ET: # return self.visit(node.left) == self.visit(node.right) # elif node.op.type == NET: # return self.visit(node.left) != self.visit(node.right) # elif node.op.type == GET: # return self.visit(node.left) >= self.visit(node.right) # elif node.op.type == LET: # return self.visit(node.left) <= self.visit(node.right) # elif node.op.type == GT: # return self.visit(node.left) > self.visit(node.right) # elif node.op.type == LT: # return self.visit(node.left) < self.visit(node.right) def visit_Loop(self, node): while(self.visit(node.cond) == True): self.visit(node.stmt) ##if(self.cond.eval() ==True): ## self.stmt.eval() ## self.eval() def visit_Conditional(self, node): if(self.visit(node.cond) == True): self.visit(node.then_stmt) else: self.visit(node.else_stmt) def visit_PrintLN(self, node): print("\n", end="") def visit_Print(self, node): print(self.visit(node.data), end="") def visit_Num(self, node): return node.value def visit_String(self, node): return node.value def interpret(self): tree = self.parser.parse() return self.visit(tree) def main(): import sys text = open(sys.argv[1], 'r').read() lexer = Lexer(text) parser = Parser(lexer) ##parser = Parser(text) interpreter = Interpreter(parser) result = interpreter.interpret() # for k, v in sorted(interpreter.GLOBAL_SCOPE.items()): # print('%s = %s' % (k, v)) if __name__ == '__main__': main()
954f174a56381fe2736abfb4166f594fd597d1a5
alexartwww/geekbrains-python
/lesson_03/03.py
423
3.75
4
task = ''' Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. ''' def my_func(var1, var2, var3): vars = [var1, var2, var3] vars.sort(reverse=True) return sum(vars[0:2]) if __name__ == '__main__': print(task) print(my_func(1, 2, 3))
3881ff21671bb9468767d6cab3770b2c572bd0a4
daniel-reich/turbo-robot
/NWR5BK4BYqDkumNiB_4.py
2,076
4.1875
4
""" In this challenge, you have to verify if a number is exactly divisible by a combination of its digits. There are three possible conditions to test: * The given number is exactly divisible by **each of its digits excluding the zeros**. * The given number is exactly divisible by the **sum of its digits**. * The given number is exactly divisible by the **product of its digits**. Given an integer `n`, implement a function that returns: * If every test is true, a string `"Perfect"`. * If some test is true, the number of true tests (`1` or `2`). * If every test is false, a string `"Indivisible"`. ### Examples digital_division(21) ➞ 1 # Exactly divisible only by the sum of its digits (2 + 1 = 3). digital_division(128) ➞ 2 # Exactly divisible by each of its digits. # Exactly divisible by the product of its digits (1 * 2 * 8 = 16). digital_division(100) ➞ 2 # Exactly divisible by each of its digits (excluding zeros). # Exactly divisible by the sum of its digits (1 + 0 + 0 = 1). digital_division(12) ➞ "Perfect" # Exactly divisible by each of its digits. # Exactly divisible by 3 (sum of digits = 1 + 2). # Exactly divisible by 2 (product of digits = 1 * 2). digital_division(31) ➞ "Indivisible" # Every testing condition is false. ### Notes * Remember to exclude any 0-digit when testing if the given `n` is divisible by each of its digits (see example #3). * A number containing at least a 0-digit can't be exactly divided by the product of its digits (division by 0). * Trivially, every single-digit positive number greater than 0 is Perfect * Any given number will be a positive integer greater than 0. """ def digital_division(n): digFacCond=True prodNum=1 sumNum=0 for c in str(n): c=int(c) sumNum+=c prodNum*=c if c and n%c: digFacCond=False res=1 if digFacCond else 0 if not n%sumNum: res+=1 if prodNum and not n%prodNum: res+=1 if res==3: return 'Perfect' elif not res: return 'Indivisible' return res
8267909d103e212e448b2422fa09faaed78efe58
maryna-hankevich/test_repo
/game.py
2,731
3.59375
4
# Быки и Коровы import random def calculate_bulls_and_cows(player_n, secret_n): bulls = 0 cows = 0 for index in range(len(player_n)): if player_n[index] == secret_n[index]: bulls += 1 for index in range(len(player_n)): for j in range(len(secret_n)): if index != j and player_n[index] == secret_n[j]: cows += 1 return bulls, cows def check_player_num(player_n): is_player_num_correct = True if len(player_n) != 4: print("Only 4 digits allowed.") is_player_num_correct = False digits = 0 for i in player_n: if i.isnumeric(): digits += 1 if digits != 4: print("Only digits allowed.") is_player_num_correct = False if len(set(player_n)) != 4: print("Repeating numbers are not allowed.") is_player_num_correct = False return is_player_num_correct def start_game(): num_list = list() while len(num_list) < 4: start_num = 0 if len(num_list) == 0: start_num = 1 s = str(random.randint(start_num, 9)) if s not in num_list: num_list.append(s) secret_num = "".join(num_list) print(secret_num) rules = """Let's play a game! Try to guess a four digit number. All four digits should be different and can not start with 0. 'Cows' is total number of digits you guessed right. 'Bulls' shows how many of those that exists were placed at the right spot.""" print(rules) player_num = input("Type your variant here:") while player_num != secret_num: if not check_player_num(player_num): player_num = input("Please try again:") bulls, cows = calculate_bulls_and_cows(player_num, secret_num) print(f"Bulls:{bulls}, Cows:{cows}") player_num = input("Try again:") else: print("You win this one, my friend.") # start_game() # Строки с заданным символом def string_decorator(fn): def string_processing(str): result = [] for i in str: if i != '#': result.append(i) # print("Added", result) if i == "#": if len(result) > 0: result.pop() # print("Removed", result) fn(str) print("Output:", ''.join(result)) return ''.join(result) return string_processing @string_decorator def str_process(a: str): return str(a) # myfunc("a#bc#d") # myfunc("abc#d##c") # myfunc("abc##d######") # myfunc("#######") # Использование marks # Параметризация # Использование fixture
676971970b5bf39b2be55f91b35451d401074bad
rulaothman/AdvancedDataStorageRetrieval
/climateapp2.py
4,890
3.609375
4
#Routes #/api/v1.0/precipitation #Query for the dates and temperature observations from the last year. #Convert the query results to a Dictionary using date as the key and tobs as the value. #Return the JSON representation of your dictionary. #/api/v1.0/stations #Return a JSON list of stations from the dataset. #/api/v1.0/tobs #Return a JSON list of Temperature Observations (tobs) for the previous year #/api/v1.0/<start> and /api/v1.0/<start>/<end> #Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range. #When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date. #When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive. #import dependencies import datetime as dt import numpy as np import pandas as pd import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify engine=create_engine("sqlite:///Hawaii,sqlite") Base=automap_base() Base.prepare(engine, reflect=True) Station = Base.classes.station Measurement = Base.classes.measurement session=Session(engine) app = Flask(__name__) @app.route("/") def welcome(): "List all available api routes." return ( f"Available Routes:<br/>" f"<br/>" f"/api/v1.0/precipitation<br/>" f"- List of previous year rain totals from all stations<br/>" f"<br/>" f"/api/v1.0/stations<br/>" f"- List of Station numbers and names<br/>" f"<br/>" f"/api/v1.0/tobs<br/>" f"- List of prior year temperatures from all stations<br/>" f"<br/>" f"/api/v1.0/start<br/>" f"- When given the start date (YYYY-MM-DD), calculates the MIN/AVG/MAX temperature for all dates greater than and equal to the start date<br/>" f"<br/>" f"/api/v1.0/start/end<br/>" f"- When given the start and the end date (YYYY-MM-DD), calculate the MIN/AVG/MAX temperature for dates between the start and end date inclusive<br/>" ) @app.route("/api/v1.0/precipitation") def precipitation(): "Return a list of rain fall for prior year" last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() last_year = dt.date(2018, 8, 9) - dt.timedelta(days=365) rain = session.query(Measurement.date, Measurement.prcp).\ filter(Measurement.date > last_year).\ order_by(Measurement.date).all() rain_totals = [] for result in rain: row = {} row["date"] = rain[0] row["prcp"] = rain[1] rain_totals.append(row) return jsonify(rain_totals) @app.route("/api/v1.0/stations") def stations(): stations_query = session.query(Station.name, Station.station) stations = pd.read_sql(stations_query.statement, stations_query.session.bind) return jsonify(stations.to_dict()) @app.route("/api/v1.0/tobs") def tobs(): """Return a list of temperatures for prior year""" last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() last_year = dt.date(2018, 8, 9) - dt.timedelta(days=365) temperature = session.query(Measurement.date, Measurement.tobs).\ filter(Measurement.date > last_year).\ order_by(Measurement.date).all() temperature_totals = [] for result in temperature: row = {} row["date"] = temperature[0] row["tobs"] = temperature[1] temperature_totals.append(row) return jsonify(temperature_totals) @app.route("/api/v1.0/<start>") def trip1(start): # go back one year from start date and go to end of data for Min/Avg/Max temp start_date= dt.datetime.strptime(start, '%Y-%m-%d') last_year = dt.timedelta(days=365) start = start_date-last_year end = dt.date(2018, 8, 9) trip_data = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start).filter(Measurement.date <= end).all() trip = list(np.ravel(trip_data)) return jsonify(trip) @app.route("/api/v1.0/<start>/<end>") def trip2(start,end): # go back one year from start/end date and get Min/Avg/Max temp start_date= dt.datetime.strptime(start, '%Y-%m-%d') end_date= dt.datetime.strptime(end,'%Y-%m-%d') last_year = dt.timedelta(days=365) start = start_date-last_year end = end_date-last_year trip_data = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start).filter(Measurement.date <= end).all() trip = list(np.ravel(trip_data)) return jsonify(trip) if __name__ == "__main__": app.run(debug=True)
ee32adabd68222a70ea542fbedc0414966f252d7
petardmnv/SoftwareDevelopment
/Turtle/solution/turtle.py
3,553
3.734375
4
from typing import List # KISS class Turtle: canvas: List[List[int]] x: int y: int is_spawned: bool orientation: str def __init__(self, x: int, y: int): if x <= 0 or y <= 0: raise IndexError self.row = x self.column = y self.canvas = [[0] * y for i in range(x)] self.is_spawned = False self.orientation = "right" def spawn_at(self, row: int, column: int): if (row < 0) and (row >= self.row): raise IndexError if (column < 0) and (column >= self.column): raise IndexError self.is_spawned = True self.x = row self.y = column self.canvas[self.x][self.y] += 1 def move(self): if not self.is_spawned: raise RuntimeError orientations: dict = {"left": [0, -1], "up": [-1, 0], "right": [0, 1], "down": [1, 0]} x, y = orientations[self.orientation] self.x += x self.y += y self.x, self.y = self.transfer(self.x, self.y) self.canvas[self.x][self.y] += 1 # ugly :'( def transfer(self, x, y) -> list: if x < 0: x = self.row - 1 elif x >= self.row: x = 0 if y < 0: y = self.column - 1 elif y >= self.column: y = 0 return [x, y] def turn_right(self): orientations: tuple = ("left", "up", "right", "down") index: int = orientations.index(self.orientation) + 1 if index >= len(orientations): index = 0 self.orientation = orientations[index] def turn_left(self): orientations: tuple = ("left", "up", "right", "down") index: int = orientations.index(self.orientation) - 1 if index < 0: index = len(orientations) - 1 self.orientation = orientations[index] class SimpleCanvas: canvas: List[List[int]] symbols: List[str] def __init__(self, canvas: list, symbols: list): self.symbols = symbols self.canvas = canvas def draw(self) -> str: canvas_rows: int = len(self.canvas) canvas_columns: int = len(self.canvas[0]) pixels_count: int = max([self.canvas[i][j] for j in range(canvas_columns) for i in range(canvas_rows)]) pixelated_canvas: List[List[float]] = [[0.00] * canvas_columns for i in range(canvas_rows)] draw_canvas: List[List[str]] = [[""] * canvas_columns for i in range(canvas_rows)] symbols_range: float = 1 / (len(self.symbols) - 1) for i in range(canvas_rows): for j in range(canvas_columns): pixelated_canvas[i][j] = self.canvas[i][j] / pixels_count # drawing canvas if 0 == pixelated_canvas[i][j]: draw_canvas[i][j] = self.symbols[0] for k in range(len(self.symbols) - 2): if (k * symbols_range < pixelated_canvas[i][j]) and \ ((k + 1) * symbols_range >= pixelated_canvas[i][j]): draw_canvas[i][j] = self.symbols[k + 1] if ((1 - symbols_range) < pixelated_canvas[i][j]) and (1 >= pixelated_canvas[i][j]): draw_canvas[i][j] = self.symbols[len(self.symbols) - 1] return self.format_canvas(draw_canvas) @staticmethod def format_canvas(canvas: List[List[str]]) -> str: result: list = [] for i in range(len(canvas)): result.append(''.join(canvas[i])) return '\n'.join(result)
823714a1999e34aa22dd5d7a754f3d1636c941f2
kaparker/tutorials
/penguin-analysis/getting_started.py
2,032
4.34375
4
#!/usr/bin/env python3 import pandas as pd """ Data Analysis in python: Getting started with pandas Exploring Palmer Penguins Walk through of code in article: https://medium.com/@_kaparker/data-analysis-in-python-getting-started-with-pandas """ df = pd.read_csv('https://raw.githubusercontent.com/allisonhorst/palmerpenguins/47a3476d2147080e7ceccef4cf70105c808f2cbf/data-raw/penguins_raw.csv') # Alternatvie IO # import pymysql # con = pymysql.connect(host='localhost', user='root', password='', db='test') # read_sql(f'''SELECT * FROM table''', con) if len(df) > 0: print(f'Length of df {len(df)}, number of columns {len(df.columns)}, dimensions {df.shape}, number of elements {df.size}.') else: print(f'Problem loading df, df is empty.') df.info() df.info(memory_usage='deep') print(df.memory_usage(deep=True)) print(df.memory_usage(deep=True).sum()) print(df.head()) pd.set_option('display.max_columns', None) print(df.head()) keep_cols = ['Species', 'Region', 'Island', 'Culmen Length (mm)', 'Culmen Depth (mm)', 'Flipper Length (mm)', 'Body Mass (g)', 'Sex'] df = df.loc[:, keep_cols] print(df.columns) df.info(memory_usage='deep') print(df.isna().sum()) df['Sex'].fillna('Unknown', inplace=True) print(df.isna().sum()) df.dropna(inplace=True) print(df.isna().sum()) print(df['Species'].head()) print(df['Species'].nunique()) print(df['Species'].unique()) print(df.memory_usage(deep=True)) df['Species'] = df['Species'].astype('category') print(df.memory_usage(deep=True)) for col in ['Region','Island','Sex']: print(f'Column: {col}, number of unique values, {df[col].nunique()}, unique values: {df[col].unique()}') df.drop(columns=['Region'], inplace=True) print(df.columns) print((df['Sex']=='.').value_counts()) df['Sex'].replace('.','Unknown', inplace=True) print((df['Sex']=='.').value_counts()) df['Sex'] = df['Sex'].astype('category') df['Island'] = df['Island'].astype('category') print(df.memory_usage(deep=True)) print(df.memory_usage(deep=True).sum()) df.info(memory_usage='deep')
748fd364026cc32dad1622ee8ca7e87017396ade
parky83/python0209
/st01.Python기초/0301수업/py08반복문/py08_06_2단가로출력.py
478
4.15625
4
# 2단의 구구단을 가로 출력하는 프로그램을 만드시오. 끝날 때는 마침표를 붙인다. # 힌트. 출력할 문자열을 변수에 저장하고 마지막 한번만 변수값을 print()를 사용하야 출력해야 한다. for x in range(1, 10, 1): str = "2 * %d = %2d" % (x, 2*x ) # x가 9이면 마침표를 찍고 # 아니면 콤마를 찍어라. if(x == 9): print( str, "." ) else: print( str, "," ) print()
f1140d277c54cc6af29e854370e135e2e2ec2809
yeonhodev/python_lecture
/lecture47.py
1,091
4
4
class Student: def __str__(self): return "{} {}살".format(self.name, self.age) def __init__(self, name, age): print("객체가 생성되었습니다.") self.name = name self.age = age def __del__(self): print("객체가 소멸되었습니다.") def 출력(self): print(student.name, student.age) student = Student("윤인성", 3) student.출력() print(str(student)) class Student2: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return (self.age == other.age) and (self.name == other.name) def __ne__(self, other): return self.age != other.age def __gt__(self, other): return self.age > other.age def __ge__(self, other): return self.age >= other.age def __lt__(self, other): return self.age < other.age def __le__(self, other): return self.age <= other.age student2 = Student2("윤인성", 3) print(student2 == student2) print(student2 != student2) print(student2 > student2) print(student2 >= student2) print(student2 < student2) print(student2 <= student2)
9a1d6610edb77da0d1c96e7eef66ac15d891313a
MohnishShridhar/C100-project
/ATM.py
416
3.734375
4
class Card(object): def __init__(self, name, number, pin, amount): self.name=name self.number=number self.pin=pin self.amount=amount def withdraw(self): amt= input("How much do you want to withdraw: ") print("withdrawn " + amt) def know(self): print(self.amount) card1=Card("card1", "0000000000", "0000", 80) print(card1.know())
9790184d9c894d8a364dd4de235cd57116bfcc96
pato0301/cs50
/pset6/dna/dna.py
1,465
3.5
4
# Import library from cs50 import get_string import re import sys import csv # Get files file_db = sys.argv[1] file_sq = sys.argv[2] # Open sequence sq = open("{}".format(file_sq), "r") sq_str = sq.read() # Open Database reader = csv.reader(open(file_db, 'r')) db_dic = {} # Read each line of db for row in reader: key = row[0] if key in db_dic: # Implement your duplicate row handling here pass db_dic[key] = row[1:] # Get columns Headers headers = db_dic['name'] n = len(sq_str) len_head = len(headers) list_values = [] # Loop through each column for y in range(len_head): texto = db_dic['name'][y] len_text = len(texto) cur, maximo, loop_inc = 0, 0, 1 # Loop through each row for x in range(0, n, loop_inc): if sq_str[x: (x + len_text)] in texto: cur += 1 # Look sequence if (x < n - 1 and sq_str[x: (x + len_text)] == sq_str[x + len_text: (x + (len_text * 2))]): loop_inc = len_text else: if (cur > maximo): maximo = cur cur = 0 else: cur = 0 loop_inc = 1 # Append in alist list_values.append(str(maximo)) # Print name if exist name_exist = False for name, dna in db_dic.items(): if dna == list_values: print(name) name_exist = True # Else print 'No Match' if not name_exist: print("No match")
ff5263c06aee8fe38eb46144721f503a80b1897e
NipunSaha/C-106
/Ice_cream_vs_temp.py
963
3.515625
4
import csv import plotly.express as px import numpy as np def plot_fig(data_path): with open(data_path) as f: df = csv.DictReader(f) fig = px.scatter(df,x="Temperature",y="Ice-cream Sales") fig.show() def get_data_source(data_path): temp = [] ice_cream_sales = [] with open(data_path) as f: reader = csv.DictReader(f) for row in reader: temp.append(float(row["Temperature"])) ice_cream_sales.append(float(row["Ice-cream Sales"])) return { "x": temp, "y": ice_cream_sales } def find_correlation(data_source): correlation = np.corrcoef(data_source["x"],data_source["y"]) print("Correlation between Temperature and Ice cream sales are ",correlation) def main(): file_name = "temperatureVsIce-cream.csv" plot_fig(file_name) data_source = get_data_source(file_name) find_correlation(data_source) main()
529a397ac3dde8a9373cd0ae151e6398859f6cd0
shenchuang006/python
/Kitchen/Fridge.py
1,744
4.125
4
#coding=utf-8 class Fridge: """ This class implements a fridge where ingredients can be added and removed individually , or in groups. The fridge will retain a count of every ingredient added or removed, and will raise an error if a sufficient quantity of an ingredient isn't present. Methods: has() """ def __init__(self,items={}): """ Optionally pass in an initial dictionary of items :param items: """ if type(items) != type({}): raise TypeError("Fridge requires a dictionary but was given %s" % type(items)); self.items = items; return; def _add_multi(self,food_name,quantity): if(not food_name in self.items): self.items[food_name] = 0; self.items[food_name] = self.items[food_name] + quantity; def add_one(self,food_name): if type(food_name) != type(""): raise TypeError("add_one requires a string ,given a %s" % type(food_name)); else: self._add_multi(food_name,1); return True; def add_many(self,food_dict): if type(food_dict) != type({}): raise TypeError("add_many requires a dictionary,got a %s " % food_dict); for item in food_dict.keys(): self._add_multi(item,food_dict[item]); return ; def has(self,food_name,quantity=1): return self.has_various({food_name:quantity}); def has_various(self,foods): try: for food in foods.keys(): if self.items[food] < foods[food]: return False; return True; except KeyError: return False;
45e7a9010b5dd5c64c2806a33cac78e7892519bc
pascal19821003/python
/study/tutorial/if.py
105
4.03125
4
x=1 if x<1: print("greater than 1") elif x==1: print("equal to 1") else: print("less than 1")
043e99fe5c5c38f11d55e170be19446ab70df4d0
niki4/leetcode_py3
/easy/443_string_compression.py
4,193
4
4
""" Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space? Example 1: Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". """ class Solution: """ Runtime: 48 ms, faster than 96.81% of Python3 online submissions for String Compression. Memory Usage: 13 MB, less than 97.58% of Python3 online submissions for String Compression. Time complexity: O(N+K), where N because we iterated over chars list only once and K is size of elements for .extend() operations Space complexity: O(N-K) we're using temporary list for results, where N is the size of original list and K is say compression factor (it could be 0 though). """ def compress(self, chars: list) -> int: char_counts = [] i = 0 while i < len(chars): prev = chars[i] i += 1 count = 1 while i < len(chars) and prev == chars[i]: i += 1 count += 1 char_counts.extend([prev, *list(str(count))]) if count > 1 else char_counts.append(prev) chars.clear() chars.extend(char_counts) return len(chars) class Solution2: """ Runtime: 48 ms, faster than 96.81% of Python3. Memory Usage: 13.3 MB, less than 39.49% of Python3. Algorithm idea: Use 2 pointers - left and right, representing begin and end indexes of the sequence. Once found new char, use these left/right indexes to change source list in place, then move left index pointer onto new char, right pointer to left+1 and continue with next iteration. Time complexity: O(N) Space complexity: O(1) """ def compress(self, chars: list) -> list: if len(chars) <= 1: return len(chars) left, right = 0, 1 while right < len(chars): while right < len(chars) and chars[left] == chars[right]: right += 1 count = right - left if count > 1: chars[left+1:right] = str(count) left += 2 # offset to hold prev value counters e.g., ['a', '3'] right = left + 1 elif count == 1: left += 1 # offset to hold prev value unchanged, e.g. ['a'] right = left + 1 return len(chars) if __name__ == "__main__": s1 = Solution() s2 = Solution2() src1 = ["a","a","b","b","c","c","c"] src2 = ["a"] src3 = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] src4 = ["a","a","a","b","b","a","a"] assert s1.compress(src1) == len(src1) == 6 assert src1 == ["a","2","b","2","c","3"] assert s1.compress(src2) == len(src2) == 1 assert src2 == ["a"] assert s1.compress(src3) == len(src3) == 4 assert src3 == ["a","b","1","2"] assert s1.compress(src4) == len(src4) == 6 assert src4 == ["a","3","b","2","a","2"] src1 = ["a","a","b","b","c","c","c"] src2 = ["a"] src3 = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] src4 = ["a","a","a","b","b","a","a"] assert s2.compress(src1) == len(src1) == 6 assert src1 == ["a","2","b","2","c","3"] assert s2.compress(src2) == len(src2) == 1 assert src2 == ["a"] assert s2.compress(src3) == len(src3) == 4 assert src3 == ["a","b","1","2"] assert s2.compress(src4) == len(src4) == 6 assert src4 == ["a","3","b","2","a","2"] from timeit import Timer t1 = Timer('s1.compress(src1)', 'from __main__ import Solution, src1; s1 = Solution()') t2 = Timer('s2.compress(src1)', 'from __main__ import Solution2, src1; s2 = Solution2()') print('Solution1 time:', t1.timeit()) print('Solution2 time:', t2.timeit())
4b8ebcacdeba688f66c21c77c022d7393c9b288c
naimucar/8.hafta_odevler-Fonksiyonlar
/sayiokuma fonk.py
3,225
4.03125
4
#Kullanıcıdan 2 basamaklı bir sayı alın ve bu sayının okunuşunu bulan bir fonksiyon yazın. # Örnek: 97 ---------> Doksan Yedi def sayi_oku(rakam=(input('1.yol en cok 3 basamakli sayiyi giriniz :'))): if rakam.isdigit()==False: print('lutfen 3 basamakli sayi giriniz') return birler =['','bir','iki','üç','dört','beş','altı','yedi','sekiz','dokuz'] onlar =['','on','yirmi','otuz','kırk','elli','altmış','yetmiş','seksen','doksan'] yuzler =['yüz'] goster =[] #rakam bir basamakliysa girilen sayi birler listesindeki indexe giderek kendi sayisini okuyor #ornek olarak rakam[0] =5 ise bu deger birler[5] deki degere 'bes' e gitmis oluyor if len ( rakam ) == 1: goster = [birler[int ( rakam[0] )]] print (rakam,'------>' ,*goster ) #rakam iki basamakli ise rakam[0]=onlar listesi ve rakam[1]= birler listesindeki indexlere #giderek kendi degerlerini bulmus olurlar ##ornek olarak rakam[0] =3 --->onlar[3]'otuz' ve rakam[1] =5 ---> birler[5] 'bes' elif len(rakam)==2: goster = [onlar[int ( rakam[0] )] , birler[int ( rakam[1] )]] print (rakam,'------>' ,*goster) # rakam uc basamakli ise rakam[0]=yuzler listesi,rakam[1]=onlar listesi ve rakam[2]= birler listesindeki indexlere # giderek kendi degerlerini bulmus olurlar elif len(rakam)==3: if int(rakam[0])==1: #sadece yuz yazdirmak icin bu dongu kuruldu goster = [yuzler[0] , onlar[int ( rakam[1] )] , birler[int ( rakam[2] )]] print(rakam,'------>' ,*goster) elif int(rakam[0])==0: #yuzler basamagi 0 ise onlar ve birler basamagi yazilacak goster = [onlar[int ( rakam[1] )] , birler[int ( rakam[2] )]] print ( rakam,'------>' ,*goster) else : goster =[birler[int(rakam[0])]+yuzler[0],onlar[int(rakam[1])],birler[int(rakam[2])]] print (rakam,'------>' ,*goster) else: print('lutfen 3 basamakli sayi giriniz') #-------------------------------------------- sayi_oku() #-------------------------------------------- #sayinin 4 basamakli olmasi saglandi zfill(4) fonksiyonuyla def sayi_oku2(rakam=input('2.yol en cok 4 basamakli sayiyi giriniz ').zfill(4)): if len(rakam)>4: print('lutfen 4 basamakli sayi giriniz') return elif rakam.isdigit()==False: print('lutfen 4 basamakli sayi giriniz') return birler =['','bir','iki','üç','dört','beş','altı','yedi','sekiz','dokuz',''] onlar =['','on','yirmi','otuz','kırk','elli','altmış','yetmiş','seksen','doksan'] yuzler =['','yüz','ikiyüz','üçyüz','dörtyüz','beşyüz','altıyüz','yediyüz','sekizyüz','dokuzyüz'] binler =['','bin','ikibin','üçbin','dörtbin','beşbin','altıbin','yedibin','sekizbin','dokuzbin'] #hep 4 basamakli oldugu icin rakam[0]=binler ,rakam[1]=yuzler,rakam[2]=onlar,rakam[3]=birler listesindeki #indexler ile esli #3045 binler[3],yuzler[0],onlar[4],birler[5] goster =[binler[int ( rakam[0] )],yuzler[int ( rakam[1] )], onlar[int ( rakam[2] )] , birler[int ( rakam[3] )]] print (rakam,'------>:',*goster ) #---------------------------------------------------- sayi_oku2()
b8041320ef62fadfc8f1657299cea4864d301187
choicoding1026/data
/python/python09_문장2_반복문3_dict_comprehension.py
1,116
3.703125
4
''' dict Comprehension 형태: for문 + 조건문 혼합형태 for key,value in mm.items(): # [ (key,value), (key,value)...] print(key,value) 용도: 제공된 딕셔너리를 반복해서 조건 지정 및 임의의 연산을 적용해서 다시 딕셔너리로 반환하는 기능. 문법1: result = { k:v for k,v in dict.items()} 문법2: 단일 if 문 result = { k:v for k,v in dict.items() if 조건식 } 문법3: if~ else 문 ==> 3항연산자 result = { 참 if 조건 else 거짓 for k,v in dict.items()} ''' # 1. 문법1 m_dict ={"대한민국":"서울", "영국":"런던", "미국":"워싱턴", "일본":"도쿄"} #질문1: {나라:수도} ==> {수도:나라} 형태로 출력하시오. result = {v:k for k,v in m_dict.items() } print(result) # 2. 문법2 #질문2 : 2글자로 된 수도 이름만 dict로 출력하시오. {나라:수도} 포맷 result = {k:v for k,v in m_dict.items() if len(v)==2} print(result) # 3. 문법3 result = { "우리나라" if k=="대한민국" else "남의나라" for k,v in m_dict.items()} print(result)
2a03972f4c213faba1a592a70171d6ebf7e0aa75
chenjingtongxue/python
/13/copy_file/猜数字.py
354
3.703125
4
import random randnum=int(random.uniform(1,10))#光是random.uniform是返回带有小数的随机数 guessnum=int(input('请你猜一个1到10之间的整数:')) if randnum>guessnum: print('您猜小了,随机数是:',randnum) elif randnum==guessnum: print('恭喜,您猜中了') else: print('您猜大了,随机数是:',randnum)
a80562d9a9b5e22dc09942fd25e84635bbf5b5a9
jatin2504/Machine-Learning
/Part 1 - Data Preprocessing/data_preprocessing.py
833
3.71875
4
# Data Preprocessing #Importing the library import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing the dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[: , 3].values #Taking care of missing values from sklearn.preprocessing import SimpleImputer missingvalues = SimpleImputer(missing_values = np.nan, strategy = 'mean', verbose = 0) missingvalues = missingvalues.fit(X[:, 1:3]) X[:, 1:3] = missingvalues.transform(X[:, 1:3]) #Encoding Categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() X[:, 0] = labelencoder_X.fit_transform(X[:, 0]) onehotencoder = OneHotEncoder(categorical_features=[0]) X = onehotencoder.fit_transform(X).toarray() labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y)
a4f14ecdbcb335af275ed267324668264054d26b
adebayo5131/Python
/ReverseLinkedList.py
275
3.765625
4
#O(n) time and O(1) space where n is the number of nodes in the linkedlist def reverseLinkedList(head): current1 = None current2 = head while current2: current3 = current2.next current2.next = current1 current1 = current2 current2 = current3 return current1
011622bd8e0ee4d16bb0d9f1acfaed6d4fb1f0e8
VectorTensor/Mathematical_tools
/RK_4.PY
687
3.9375
4
# Solution of first order differential equation using RK-4 method. import math import matplotlib.pyplot as plt #function dy/dx=f(x,y) def f(x,y): return (1+x**2)*y h=0.02 #Step size x0=0 #initial value f(x0)=y0 y0=1 a=[x0] b=[y0] def y(x0,y0): #RK-4 Iteration function m1=f(x0,y0) m2=f(x0+(h/2),y0+(h/2)*m1) m3=f(x0+(h/2),y0+m2*(h/2)) m4=f(x0+h,y0+m3*h) m=(m1+2*m2+2*m3+m4)/6 y1=y0+h*m return y1 for i in range(1,100): it=y(x0,y0) x0=x0+h a.append(x0) y0=it b.append(y0) print (b) plt.plot(a,b,color='black') plt.xlabel('x') plt.ylabel('f(x)') plt.grid('both') plt.title('Solution to the differential equation') plt.show()
52ffe7537bc56f62df2db3c3f742763ebf37a05f
wenwenbbyy/python
/grade.py
353
3.984375
4
def computegrade(score): if score>=0.9 and score<=1.0: print 'A' elif score>=0.8 and score<0.9: print 'B' elif score>=0.7 and score<0.8: print 'C' elif score>=0.6 and score<0.7: print 'D' elif score<0.6 and score>0: print 'F' else: print 'Bad score' try: s=raw_input('Enter score:') computegrade(float(s)) except: print 'Bad score'
b99ada75d53844a69a19d7a38ea84b8d28cd0a5a
Aayushi-Mittal/Udayan-Coding-BootCamp
/session8/Markdown-Table-Generator.py
1,507
3.75
4
rows=int(input("Enter number of rows: ")) cols=int(input("Enter number of columns: ")) center=input("Do you want items to be centered? (true/false): ") headings=[] print("\nEnter the data for each cell respectively!") file = open("table.md", "w") print("Let's Generate a Table in Markdown Syntax:\n") for i in range(1, cols+1): value=input(f"Enter Heading for column{i} : ") if i==cols: entry= f"| {value} |\n" headings.append(value) else: entry= f"| {value} " headings.append(value) file.write(entry) print("Headings Received!") for i in range(0, cols): if i==cols-1: if center=="true" and len(headings[i])>2: entry= f"| :{'-'*(len(headings[i])-2)}: |\n" else: entry= f"| {'-'*len(headings[i])} |\n" else: if center=="true" and len(headings[i])>2: entry= f"| :{'-'*(len(headings[i])-2)}: " else: entry= f"| {'-'*len(headings[i])} " file.write(entry) print("Done!") for i in range(2, rows+1): print(f"\nEnter data for Row{i} : ") for j in range(1, cols+1): value=input(f"Row{i} Column{j} - {headings[j-2]}: ") if j==cols: entry= f"| {value} |\n" file.write(entry) else: entry= f"| {value} " file.write(entry) print("\nDone Succesfully! :)") print("Now check table.md or run 'cat table.md' in terminal to copy the syntax.\n") file.close()
9062c1ae5bb22b1b3885c2c66aaa9bc90732b5f3
lemonnader/LeetCode-Solution-Well-Formed
/string/Python/0005-longest-palindromic-substring(马拉车算法-pre).py
1,440
3.765625
4
class Solution: # Manacher 算法 def longestPalindrome(self, s: str) -> str: # 特判 size = len(s) if size < 2: return s # 得到预处理字符串 t = "#" for i in range(size): t += s[i] t += "#" # 新字符串的长度 t_len = 2 * size + 1 # 当前遍历的中心最大扩散步数,其值等于原始字符串的最长回文子串的长度 max_len = 1 # 原始字符串的最长回文子串的起始位置,与 max_len 必须同时更新 start = 0 for i in range(t_len): cur_len = self.__center_spread(t, i) if cur_len > max_len: max_len = cur_len start = (i - max_len) // 2 return s[start: start + max_len] def __center_spread(self, s, center): """ left = right 的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1 的时候,此时回文中心是任意一个字符,回文串的长度是偶数 """ size = len(s) i = center - 1 j = center + 1 step = 0 while i >= 0 and j < size and s[i] == s[j]: i -= 1 j += 1 step += 1 return step if __name__ == '__main__': s = "babad" solution = Solution() res = solution.longestPalindrome(s) print(res)
e4219692d4e2ff0a9c4cb092d930d9cd4800df74
TravisLeeWolf/ATBS
/Chapter_9/osWalk.py
407
3.765625
4
#! python3 # osWalk.py - Learning how to walk a directory tree import os for folderName, subFolders, fileNames in os.walk('S:\\Documents\\GitHub\\ATBS'): print('The current folder is ' + folderName) for subFolder in subFolders: print('SUBFOLER OF ' + folderName + ': ' + subFolder) for fileName in fileNames: print('FILE INSIDE ' + folderName + ': ' + fileName) print('')
eec920ddc92606a08179b834067f6085da2fe715
Shammy0786/Python-learning
/glob.py
470
3.75
4
# i=10 #global scoe vRIble # def function1(n): # i=5 #local # m=6 #local # global i # i=i+7 # print(i,m) # print(n,"yes it is") # # function1("really") # print(m) x=76 def shammy(): x=3 def azad(): global x # it cannot be global becouse we didnt define outside the fun x=66 # print("befor calling azad()",x) azad() print("after calling azad()",x) shammy() print(x) #its create global x