blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
747d582cd3bae72054eeae14f8dc682bb6b18496
vinayaka-2000/python_fileextension_
/radius_of_the_circle.py
134
4.21875
4
pi = 3.142 rad = float(input("INPUT THE RADIUS OF THE CIRCLE")) area = pi * rad**2 print("area of the circle is : "+ str(area))
c57a993f890040da6eb041ad1b25591cd958e024
zacharyarney/advent-of-code
/2019/python-solutions/day_2.py
697
3.5
4
def intcode_reader(input, noun=12, verb=2): arr = input.copy() arr[1] = noun arr[2] = verb for i in range(0, len(arr), 4): opcode = arr[i] arg_1 = arr[arr[i+1]] arg_2 = arr[arr[i+2]] if arr[i] == 1: arr[arr[i+3]] = arg_1 + arg_2 elif arr[i] == 2: arr[arr[i+3]] = arg_1 * arg_2 elif arr[i] == 99: return arr[0] else: return 'Something is wrong here...' def find_input(input_arr, output): for i in range(len(input_arr)): for j in range(len(input_arr)): if intcode_reader(input_arr, i, j) == output: return f'INPUT CODE: {100 * i + j}'
8903b21e2bacff2e9bcb28d135d384186eb51902
BellaShah/DataStructureProjects
/Queen.py
2,433
3.78125
4
class EightQueens (object): # Initialize the board def __init__ (self, n = 8): self.board = [] self.n = n self.numSolutions = 0 # Populate chess board with '*' before adding queens for i in range (self.n): row = [] for j in range (self.n): row.append ('*') self.board.append (row) # Check if a queen can be placed in row and col without being # captured by another queen currently on the board def isValid (self, row, col): # Check horizontal and vertical paths for i in range (self.n): if (self.board[row][i] == 'Q' or self.board[i][col] == 'Q'): return False # Check diagonal paths for i in range (self.n): for j in range (self.n): rowDiff = abs (row - i) colDiff = abs (col - j) if (rowDiff == colDiff) and (self.board[i][j] == 'Q'): return False return True # Find all possible solutions def recursiveSolve (self, col): if (col == self.n): self.printBoard() print() self.numSolutions += 1 else: # Check each row in current col to see if a Queen can be put there. # When each possible queen placement is found, there is a recursive # call to finish the possible solutions with the given queen placement. for i in range (self.n): if (self.isValid (i, col)): self.board[i][col] = 'Q' self.recursiveSolve (col + 1) self.board[i][col] = '*' # Initiate the solve function and print the number of solutions def solve (self): self.recursiveSolve (0) self.printNumSolutions() # Print each board def printBoard (self): for i in range (self.n): for j in range (self.n): print (self.board[i][j], end = ' ' ) print () def printNumSolutions(self): print("There are", self.numSolutions, "solutions for a", self.n, "x", self.n, "board.\n") def main(): print() # Get board size from user validInput = False while not validInput: try: size = eval(input("Enter the size of the board: ")) validInput = True except: validInput = False while size not in [1,2,3,4,5,6,7,8]: size = eval(input("Enter an integer in the range 1 to 8: ")) print() queens = EightQueens (size) queens.solve() main()
b8e8310c63f017af9df4856fa309a9e7a79c3aa6
KamilPrzybysz/python
/18.03.18/zad12/zad12.py
148
3.96875
4
s='abcaaabcaaabc' print('a)'+str(s.replace('ab','d'))) print('b)'+str(s.replace('ca','ff'))) print('c)'+str(s.upper())) print('d)'+str(s.lower()))
7563b6d1bbfe1f4bad829d482b19971a4bf0275e
erisaran/cosc150
/Lab 11/powers.py
1,062
4.1875
4
def print_powers(n, high): power = 1 while power <= high: print n**power, power += 1 def x(high): i = 1 while i <= high: power = 1 while power <= high: print i**power, power += 1 i += 1 print "" def is_prime(n): """ >>> is_prime(7) True >>> is_prime(9) False """ i = 2 count = 0 while i < n: x = n%i if x == 0: count += 1 i += 1 if count > 0: return False else: return True def primes(number): """ >>> primes(8) 1 2 3 5 7 """ n = 1 count = 0 i = 2 while n <= number: while i < n: x = n%i if x == 0: count += 1 i += 1 if count == 0: print n, n += 1 count = 0 i = 2 if __name__=="__main__": import doctest doctest.testmod(verbose=True)
8e57b65138f18ce049a4e488da6b8f214ebec7aa
thomas-rohde/Classes-Python
/exercises/exe31 - 40/exe032.py
181
3.640625
4
s = float(input('Qual o salário do funcionário? R$')) if s>1250: s0 = s * 1.10 else: s0 = s * 1.15 print('O seu salário era R${:.2f}, e agora é R${:.2f}'.format(s, s0))
2829e3b5d2654cb2347443d36f52d4db5e5f293a
HUAN99UAN/TestPython
/daily_programming/stringFormat.py
387
3.59375
4
def stringFormat(A, n, arg): while "%s" in A and len(arg) > 0: A = A.replace("%s", arg.pop(0), 1)# ython replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串), # 如果指定第三个参数max,则替换不超过 max 次。 return A + ''.join(arg) print(stringFormat("A%sC%sE",7,['B','D','F']))
fc4aae6e8e0ad3972b8636df9b543eb83f05c081
zhaoly12/dataStructAlgorithmPythonVer
/stack.py
3,113
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 15 16:44:47 2020 @author: 86156 """ from seqList import seqList from linkedList import linkedList class Stack(seqList): ''' stack is a special kind of linear list we can only add element in a stack from the top and can only delete element from the top all the other methods in stack are the same with that in sequential list ''' def __init__(self, length = 0, stack = [], top = 0, size = 100): self.length = length self.stack = stack self.top = top self.size = size def insert(self, pos, value): print("insert function is disabled in stack, please use push") def delete(self, pos): print("delete function is disabled in stack, please use pop") def update(self, pos, value): print("update function is disabled in stack") def push(self, value): if self.top == self.size: print("ERROR:stack overflow!") return self.length += 1 self.stack += [value] self.top += 1 def pop(self): if self.top == 0: return value = self.stack[self.top-1] del self.stack[self.top - 1] self.top -= 1 self.length -= 1 return value class linkedStack(linkedList, Stack): def __init__(self, length = 0, top = 0, size = 100, nodes = [], rear = -1, head = 0): Stack.__init__(self, length, nodes, top, size) linkedList.__init__(self, nodes, rear, head) def insert(self, pos, value): print("insert function is disabled in stack, please use push") def delete(self, pos): print("delete function is disabled in stack, please use pop") def update(self, pos, value): print("update function is disabled in stack") def push(self, value): if self.top == self.size: print("ERROR: stack overflow!") return if self.length == 0: self.head = 0 self.length += 1 newNode = self.node() newNode.value = value newNode.priorP = self.top-1 newNode.address = self.top if self.top != 0: self.nodes[self.top-1].nextP = self.top self.top += 1 self.nodes += [newNode] def pop(self): if self.top == 0: return value = self.nodes[self.top-1].value del self.nodes[self.top-1] if self.top > 1: self.nodes[self.top-2].nextP = -1 else: self.head = -1 self.top -= 1 self.length -= 1 return value # test if __name__ == '__main__': stack = Stack() i = 1 while i < 5: stack.push(2*i) print(stack.stack) i += 1 while stack.top != 0: value = stack.pop() print(stack.stack) lstack = linkedStack() i = 0 while i < 5: lstack.push(2*i) lstack.show() i += 1 while lstack.top != 0: value = lstack.pop() lstack.show()
ed3917e7ed1015587e1477f682067a877dd045f8
nathanthomashoang/blackjackgame
/blackjack.py
8,356
3.984375
4
'''global variables''' import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace') values = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,\ 'Queen':10,'King':10,'Ace':11,} playing = True '''Card class''' class Card(): #Attributes def __init__(self,rank,suit): self.rank = rank self.suit = suit def __str__(self): return f'{self.rank} of {self.suit}' '''Deck Class''' class Deck(): def __init__(self): self.deck = [] # start with an empty list for suit in suits: for rank in ranks: self.deck.append(Card(rank,suit)) def __str__(self): deck_comp = '' for card in self.deck: deck_comp += '\n'+ card.__str__() return 'The deck has: '+deck_comp def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card '''Hand Class''' class Hand(): def __init__(self): self.cards = [] # start with an empty list as we did in the Deck class self.value = 0 # start with zero value self.aces = 0 # add an attribute to keep track of aces def add_card(self,card): self.cards.append(card) self.value += values[card.rank] #track aces if card.rank == 'Ace': self.aces += 1 def adjust_for_ace(self): #If total value > 21 and I still have an ace, then change my ace to be a 1 instead of 11. while self.value > 21 and self.aces: #and self.aces means if it is greater than 1 self.value -= 10 self.aces -= 1 def __str__(self): hand_comp = '' for card in self.cards: hand_comp += '\n'+card.__str__() return hand_comp '''Chip Class''' class Chips(): def __init__(self): self.total = 100 # This can be set to a default value or supplied by a user input self.bet = 0 def win_bet(self): self.total += self.bet def lose_bet(self): self.total -=self.bet '''Function to take the player's bet''' def take_bet(playerchips): takebet = True while takebet == True: try: playerchips.bet = int(input('\nPlease enter your bet: ')) if playerchips.bet <= playerchips.total and playerchips.bet > 0: print('\n'*100) print(f'\nThank you. Your bet is {playerchips.bet}') takebet = False else: print('You cannot bet 0 chips or more than what you have available') except: print('Error - Please only enter a number.') '''function to HIT''' def hit(deck,hand): hand.add_card(deck.deal()) hand.adjust_for_ace() '''function to ask player to hit or stand''' def hit_or_stand(deck,hand): global playing # to control an upcoming while loop while True: try: decision = int(input('Would you like to hit or stand? "1" to hit and "2" to stand: ')) if decision == 1: hit(deck,hand) print('\n'*100) print('\n**HIT**\n') show_some(player1_hand,dealer_hand) break elif decision == 2: playing = False break except: print('Only select "1" or "2"') '''functions to show different hands''' def show_some(playerhand,dealerhand): print('******************************************') print(f"\nPlayer 1's cards:\n {playerhand}\n") print(f"Player 1's value: {playerhand.value}\n") print('******************************************') print(f"\nDealer's cards: {dealerhand.cards[1]}\n") print('******************************************') def show_all(playerhand,dealerhand): print('******************************************') print(f"\nPlayer 1's cards:\n {playerhand}\n") print(f"Player 1's value: {playerhand.value}\n") print('******************************************') print(f"\nDealer's cards:\n {dealerhand}\n") print(f"Dealer's value: {dealerhand.value}\n") print('******************************************') '''FUNCTIONS TO TEST GAME RESULTS''' def player_busts(playerhand,playerchips): if playerhand.value > 21: playerchips.lose_bet() print('You Lose. You have busted.') return True else: return False def player_wins(playerhand,dealerhand,playerchips): if playerhand.value > dealerhand.value: playerchips.win_bet() print("You Win. You have beaten the Dealer's hand.") return True else: return False def dealer_busts(dealerhand,playerchips): if dealerhand.value > 21: playerchips.win_bet() print('You Win. Dealer has busted.') return True else: return False def dealer_wins(playerhand,dealerhand,playerchips): if dealerhand.value > playerhand.value: playerchips.lose_bet() print("You Lose. The Dealer's hand has beaten yours.") return True else: return False def push(playerhand,dealerhand): if playerhand.value == dealerhand.value: print('Push') '''Game Start''' player1_chips = Chips() while True: '''opening statement''' print('Welcome to the Blackjack table.\n') '''deck creation, shuffle deck, and deal cards''' playing = True gamedeck = Deck() gamedeck.shuffle() player1_hand = Hand() dealer_hand = Hand() #dealing player1_hand.add_card(gamedeck.deal()) dealer_hand.add_card(gamedeck.deal()) player1_hand.add_card(gamedeck.deal()) dealer_hand.add_card(gamedeck.deal()) '''players chips set-up''' print(f'\nPlayer 1, you have {player1_chips.total} chips') '''take player bet''' take_bet(player1_chips) print('******************************************\n') print('\nShuffling deck...') print('Dealing cards...') '''show cards except one dealer card''' show_some(player1_hand,dealer_hand) while playing == True: # recall this variable from our hit_or_stand function '''hit or stand via player''' hit_or_stand(gamedeck,player1_hand) '''check if player bust and break if needed''' if player_busts(player1_hand,player1_chips) == True: break '''play dealer's hand until 17 or bust and show all cards''' elif playing == False: print('\n'*100) print('**Stand**\n') print('Dealer reveal:\n') show_all(player1_hand,dealer_hand) while dealer_hand.value < 17: print('Dealer HIT') hit(gamedeck,dealer_hand) show_all(player1_hand,dealer_hand) '''check resulting scenarios''' else: if dealer_busts(dealer_hand,player1_chips) == True: break elif player_wins(player1_hand,dealer_hand,player1_chips) == True: break elif dealer_wins(player1_hand,dealer_hand,player1_chips) == True: break elif push(player1_hand,dealer_hand) == True: break '''inform chip total to player''' print(f'\nPlayer 1 has a total of {player1_chips.total} chips\n') if player1_chips.total <= 0: print('You have 0 chips left.') break '''prompt player if they would like to play again''' play_again = input('Would you like to play again? (Select Y or N)') if play_again.upper() == "Y": print('\n'*100) pass else: print('\n'*100) break '''Game End''' print('\nGame Over. Thanks for playing!')
83046dc27bf8e0f1c042123e3f88c9f6b2f99a1c
NurFaizin/SDP
/Decorators/decorator1.py
247
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def outer(some_func): def inner(): print "before some_func" ret = some_func() return ret + 1 return inner def foo(): return 1 decorated = outer(foo) decorated()
c1a8d628e40254594a64478beadeb3539d0624b5
MohammadForouhesh/DataStructure_Python
/Stack_and_Queues/ArrayStack.py
1,496
3.765625
4
from Array import DynamicArray class ArrayStack: """ LIFO stack implementation using self-written DynamicArray based on c-types array as underlying storage. """ def __init__(self): self._contents = DynamicArray.DynamicArray() def __len__(self) -> int: """ :return: the length of the stack """ return len(self._contents) def isEmpty(self) -> bool: """ :return: bool True if Stack is empty. """ if len(self._contents) == 0: return True return False @property def pop(self) -> object: """ if the Stack is empty it will Rise empty exception :return: delete and return the last input """ # if self.isEmpty: # raise Exception("The Stack is empty") return self._contents.pop() @property def top(self) -> object: """ if the Stack is empty it will Rise empty exception :return: return the last input object and not delete """ # if self.isEmpty: # raise Exception("The Stack is empty") var = self._contents[-1] return var def push(self, element: object): """ :type element: object """ self._contents.append(element) if __name__ == '__main__': var_stack = ArrayStack() for s in "everestMountain": var_stack.push(s) for s in range(len(var_stack)): print(var_stack.pop)
c78cd78aad4ac1f0889cd31d61bc16a03bdb63c0
NithinNitz12/ProgrammingLab-Python
/Programs/strings.py
6,244
4.375
4
#Python Notes str = "It is easy to learn python" print("Swapcase:",str.swapcase()) print("Capitalize:",str.capitalize()) print("Title:",str.title()) print("Replace:",str.replace("is","was")) print("*****") str2 = "How easy is python to learn, Java is not so easy, c not at all easy to code" print(str2.replace("is","was")) print(str2.replace("is","was",1)) print(str2.count("is")) print("*****") s = "Hello" print(s + " All") print(s*3) print("*****") s = "Python Programming Lab" l = s.split() print("Split:",l) print("Length:",len(l)) print("Upper:",s.isupper()) print("Digit:",s.isdigit()) print("*****") s = "Hello All" print(s.find("e")) print(s.find("All")) print(s.find("l",4,8)) print("*****") print(max(5,20,30)) print(min(12,4,100)) print("*****") import math print(math.sqrt(25)) print("*****") li = [1,2,3] l1 = [1,"apple",3.4,20] print("List:",l1) print(l1*3) print(l1[1:4]) l = [20,1,12.5,0,100] print("Length:",len(l)) print("Max:",max(l)) print("Min:",min(l)) print("*****") s = "1 2 3 0" l = list(map(int,s.split())) print(l) l = max(list(map(int,s.split()))) print(l) print("*****") l = [1,2,3.5] l.append(100) print(l) l.append(2) print("Count:",l.count(2)) l.remove(2) print(l) del l[3] print(l) print("*****") a = [1,2,5] b = [3,4] a.extend(b) print("Extended:",a) print("*****") a.reverse() print(a) print("*****") a = [1,2,3,4] a.insert(2,100) a[4] = 300 print(a) print("*****") a.sort() print(a) a.sort(reverse=True) print("Reversed:",a) print("*****") a.clear() print(a) print("*****") l = [1,2,3.5,2+9j] a = l.copy() print(a) #H.W - 16,13,12,6 print("*****") t = (1,2,3) #Tuple print("Tuple:",t[1:]) t = (1,2.5,20) print("Min:",min(t)) print(list(t)) l = ["Hello","All"] s = tuple(l) #Conversion list to tuple print("s=",s) t = "apple",1,100 print(t) print("*****") x,y,z = t print("x=",x) print("y=",y) print("z=",z) print("*****") #set --- No duplication s = {1,2,3,4} print(s) s = {1,14,3,1} #Duplication ignored print(s) print("Len=",len(s)) print(sum(s)) print(sorted(s)) s.add(100) print(s) s.remove(100) #If the element is not present in the set it shows error print(s) s.discard(35) #No error by using discard() print(s) print("*****") #Math functions #Union s = {1,2,3} t = {20,2,100} u = s.union(t) #No change in s print("Union:",u) print(s|t) print(s.update(t)) #Change in s print(s) a = {1,2,3} b = {5} print(a.union(b)) print(a) print(b) #Intersection a = {1,2,3} b = {2,3,5} print("Intersection:",a.intersection(b)) a.intersection_update(b) print(a) print("a&b=",a&b) print(a.difference(b)) a = {2,3,5,10} b = {6,5,10,12,45} print(a-b) print(b-a) print("Symmetric Difference:",a.symmetric_difference(b)) l = [1,2,3,4,5] m = [10,13] a = set(l) b = set(m) print(a.isdisjoint(b)) s = frozenset({1,2,3}) #Elements cannot be altered print(s) print("*****") #Dictionary dict = {} dict['one'] = "Hello All" dict['two'] = "Stay Safe" dict['three'] = "Stay Healthy" print(dict) dict2 = {'name=':'Tony Stark','age':50,} print(dict2) print(dict['one']) print(dict.keys()) print(dict.values()) print(dict.items()) dict.update(dict2) print("After update function",dict) d = {'m1':20, 'm2':30} d1 = {'name':'Peter Parker'} s = d.copy() print(s) d.update(d1) print(d) d1['age'] = 24 print(d1) print(sorted(d1.items())) print(sorted(d1.keys())) print("*****") #name of the students and total marks display the result in desecending #order #H.W 17,18 ##n = int(input("Enter a number:")) ##if n==0: ## print("Zero") print("*****") n = [1,2,3,4,5,6,7,8,9,10] s = 0 for i in n: s = s + i print("sum=",s) print("*****") flowers = ['rose','lotus','jasmine'] for flower in flowers: print(flower) for letter in 'program': print(letter) s = 0 for i in range(11): s = s + i print('sum=',s) print("*****") s = 0 for i in range(2,12,2): s = s + i print('sum=',s) #Write a program to check whether a number is present in the list of given numbers s = [1,2,3] for i in range(len(s)): print(s[i]) print("*****") '''n = int(input("Enter the limit:")) s = 0 i = 1 while(i<=n): s = s+i i = i+1 print("Sum of first ",n," natural numbers is ",s)''' ##Factorial of a number ##Write a program to find the sum of the digit of a number ##Write a program to find number that are divisible by 7 and multiple of 5 # within the range 1000 and 2000 both included ##Write a ##To print true If 2 given numbers are equal or their sum is equal to ## s = [x**2 for x in range(11)] print(s) s = {x for x in 'abcdefghijklmnopqrstuvwxyz' if x not in 'aeiou'} print(s) s = [x for x in [20,23,45,26,72] if x%2==0] print(s) #Functions--------- '''def sum(a,b): s = a+b return s a = int(input('Enter the first number:')) b = int(input('Enter the second number:')) r = sum(a,b) print(r)''' def calc(a,b): s = a+b d = a-b p = a*b q = a/b return s,d,p,q s1,d1,p1,q1 = calc(20,10) print(s1) print(d1) print(p1) print(q1) #HW Write a prgm the value of equation 1+3/3!+5/5!+7/7!......... ## Write a function to display the armstrong numbers from 1 and 500 print("*****") # Lambda function...... x=lambda a,b,c:a*b*c print(x(2,3,5)) l = [1,2,3,4,5] print(l) n = list(map(lambda x:x+2,l)) print(n) n = list(filter(lambda x:x+2,l)) print(n) n = list(filter(lambda x:(x%2!=0),l)) print(n) ## Read a string from the keyboard write a function to find the # sum of uppercase and lowercase letters present in the string ## Write a program to check a string is palindrome or not # without using reverse function available in the string ## Write a function to find the common elements present in 2 list ## Write a function to check a number is perfect number or not print("*****") #Reverse_Module def reverse(st): rst = '' index = len(st) while(index>0): rst += st[index-1] index = index-1 return rst print(reverse('hello')) print("*****") import math print('Pi=',math.pi) print(math.sqrt(625)) ##Write a program to get a string from the keyboard and use that # module to check whether it is palindrome or not ##Write a python program to create a dictionary with values as # the squares of the numbers, import this module to create a # dictionary between the range of numbers
c0e4b865ee6b3374d76ffebc3b790d4d68514f46
GeorgianBadita/LeetCode
/easy/TwoSum.py
484
3.609375
4
# https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/546/ from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: sum_dict = {} for i in range(len(nums)): if target - nums[i] in sum_dict and sum_dict[target - nums[i]] != i: return [i, sum_dict[target - nums[i]]] sum_dict[nums[i]] = i print(Solution().twoSum([2, 4, 5, 5], 10))
7416176fa61807fb318c864783a9ef3e8a16bdfc
SardulDhyani/MCA3_lab_practicals
/MCA3A/Bhartendu_Pant_20711020_MCA3A/Q1.py
150
3.53125
4
a=4 b=6 #summation print(a+b) #substraction print(a-b) #Multiplication print(a*b) #Division print(a/b) #Exponent print(2**3) #floor print(b//a)
10dcfd0b45add42274d3ffc03109b4b1ac1d1a19
ashish010598/Regularity-check-of-a-language
/defLang.py
3,466
4
4
class Char: '''Class which defines any character in the string of a language inclusive of its power, whether or not the power is a constant or a variable, etc''' def __init__(self, base, exp, isVar, rangeOfVar = None): self.base = base self.exp = exp self.isVar = isVar # self.rangeOfVar = rangeOfVar def __str__(self): return str(self.base) + '^' + str(self.exp) class VarPow: '''Defines variable powers of a Character''' def __init__(self,coeff,var): self.coeff = coeff self.var = var def __str__(self): if self.coeff == 1: return str(self.var) return str(self.coeff)+(str(self.var)) '''This will define a language i.e. terminals and what form it takes''' class Language: '''Stores a list of Chars to form a language''' def __init__(self): self.rep = [] #list of characters self.rng = [] #string representation of ranges of variables self.vars = dict() #dict of variables mapped to their range def appendChar(self, ch = None): if ch is None: b = input('Enter a character of input: ') e = input('Enter its power; enter 1 for once: ') v = input('Is the power a constant Y/N: ') if v == 'Y': v = False ex = int(e) r = None else: v = True #this means that the exponent also has a coefficient try: if len(e) > 1: cf,e = int(e[:-1]),e[-1] #the coefficient and the variable ex = VarPow(cf,e) else: ex = VarPow(1,e) #no coeff hence it is 1 except ValueError: print('Invalid coefficient for power!') if e not in self.vars: #this is a new variable x,y = map(int,input('Enter the staring and ending ' + 'values of the variable separated by a space ').strip().split()) x,y = min(x,y),max(x,y) r = range(x,y+1) self.vars[e] = r #add new entry to the dict self.rng.append(e + ' in range[' + str(x) + ',' + str(y) + ']') # ex = e ch = Char(b,ex,v) # print(type(ch)) if(isinstance(ch,Char)): self.rep.append(ch) # print("appended") def __str__(self): res = [] for c in self.rep: #print all characters res.append(str(c)) if len(self.rng): res.append(';') res.extend(self.rng) return ' '.join(res) def isRegular(self): '''Tells whether the language is regular or not''' if not self.vars: return True #no variables hence must be regular seen = set() for ch in self.rep: #check each character and see if 2 variables are repeated, if they are, #then language cannot be regular else it is ex = ch.exp #get exponent of the character # print('the character is',ch) #if the exponent is a variable if isinstance(ex, VarPow): # print('The variable power is',ex.var) # print('Checklist',seen) if(ex.var in seen): return False seen.add(ex.var) #add variable to the checkset else: return True #all variables are distinct; language is regular if __name__ == '__main__': #main will ask user to create a language by appending characters and in the end will tell if it is regular or not import sys #input output redirection # sys.stdin = open('input','r') # sys.stdout = open('output','w') #create a new language l = Language() for t in range(int(input('Enter the number of characters your language has: '))): l.appendChar() print("\nThe language you entered is:") print(l) print() if l.isRegular(): print('The language is regular') else: print('The language is not regular')
618e2c559f456a45f1c51ebfd68bf20fb7cb029f
KritiShahi/30-Days-of-Python
/Day 10.py
1,910
4.625
5
"""1) Below is a tuple describing an album: ( "The Dark Side of the Moon", "Pink Floyd", 1973, ( "Speak to Me", "Breathe", "On the Run", "Time", "The Great Gig in the Sky", "Money", "Us and Them", "Any Colour You Like", "Brain Damage", "Eclipse" ) ) Inside the tuple we have the album name, the artist (in this case, the band), the year of release, and then another tuple containing the track list.Convert this outer tuple to a dictionary with four keys.""" album = { "name": "The Dark Side of the Moon", "band_name": "Pink Floyd", "year_of_release": "1973", "track_list": ( "Speak to Me", "Breathe", "On the Run", "Time", "The Great Gig in the Sky", "Money", "Us and Them", "Any Colour You Like", "Brain Damage", "Eclipse" ) } print(album) """2) Iterate over the keys and values of the dictionary you create in exercise 1. For each key and value, you should print the name of the key, and then the value alongside it.""" for key, value in album.items(): print(f"{key} : {value}") """3) Delete the track list and year of release from the dictionary you created. Once you've done this, add a new key to the dictionary to store the date of release. The date of release for The Dark Side of the Moon was March 1st, 1973. If you use a different album for the exercises, update the date accordingly.""" album.pop('year_of_release') album.pop('track_list') album.update({"year_of_release": "March 1st, 1973"}) print(album) """4) Try to retrieve one of the values you deleted from the dictionary. This should give you a KeyError. Once you've tried this, repeat the step using the get method to prevent the exception being raised.""" # print(album["track_list"]) This statement will give a KeyError print(album.get('track_list', "Unknown"))
514c4bc87c58bf712ebe80a20a7eafe0984d78e6
pandapranav2k20/Python-Programs
/Lab 5/ENGR102_504_23_iii.py
1,934
4.125
4
# By submitting this assignment, I agree to the following: # "Aggies do not lie, cheat, or steal, or tolerate those who do." # "I have not given or received any unauthorized aid on this assignment." # # Names: Damon Tran # Benson Nguyen # Matt Knauth # Pranav Veerubhotla # Section: 504 # Assignment: lab 5-1 III # Date: 23 Sept 2019 '''This program takes user input for side lengths of triangles and determines whether the triangle is equilateral, isoceles, scalene, or ill-formed. The program will continue to run until the user enters 'stop'.''' #Initialize a variable to hold the user input user_input = '' #Create an empty list to store the side lengths of the triangles sidelengths = [] #Create an empty variable to store the type of triangle triangle = '' while user_input != 'stop': #Fill the list lengths with the three side lengths of the trianlge while len(sidelengths) < 4: user_input = (input("Please enter side legnth:")) #If the user enters stop break the loop if user_input == 'stop': break #Otherwise convert the user input from Str to float else: user_input = float(user_input) sidelengths.append(user_input) #Determine whether the triangle is ill-formed, equilateral, or scalene if sidelengths[0] == sidelengths[1] and sidelengths[0] == sidelengths[2]: triangle = 'equilateral' elif sidelengths[0] == sidelengths[1] or sidelengths[0] == sidelengths[2]: triangle = 'isoceles' #Determine if the triangle ill formed, if it is not it must be scalene elif ((sidelengths[0] + sidelengths[1]) > sidelengths[2] and (sidelengths[0] + sidelengths[2]) > sidelengths[1]) and (sidelengths[1] + sidelengths[2]) > sidelengths[0]: triangle = 'scalene' else: triangle = 'ill-formed' #Output the type of triangle print("The triangle is:", triangle)
d9427801e00b3b0c88bf041916b516dd90a05397
AxelOrdonez98/Universidad_Proyectos_All
/Archivos_Python/Practicas/Practica_8_2.py
518
3.796875
4
estaturas= [] promedio = 0 menor = 0 mayor = 0 for x in range(5): valor = float(input("Ingrese estatura " + str(x+1) + ": ")) estaturas.append(valor) for x in range(5): promedio += estaturas[x] promedio = promedio / 5 for x in range(5): if estaturas[x] < promedio: menor = menor + 1 else: mayor = mayor + 1 print(estaturas) print("Promedio: " + str(promedio)) print("Personas mas altas que el promedio: " + str(mayor)) print("Personas mas bajas que el promedio: " + str(menor))
e12048380ddadc7813ac6f5c19bd25a5e7f5d3b9
wangyuan1024/python
/unit5/homework/homework11.py
496
3.953125
4
# -*- coding: UTF-8 -*- ########################################################################## # File Name: homework11.py # Author: Wang Yuan # mail: 853283581@qq.com # Created Time: 2019年08月05日 星期一 17时21分25秒 ######################################################################### #!/usr/bin/env python # coding=utf-8 num = input("Please input a number:") if num == 1: print("1st") elif num == 2: print("2nd") elif num == 3: print("3rd") else: print(str(num) + "th")
2643fc25d27d93089d5fe9f7cccf8f07fff98bfb
hrivera7777/Jobs
/estructuras_de_datos/clase 23-05-2019/Pila.py
547
4.1875
4
# program 3.1 programa_3_01.py # implementacion de un pila en python # asumiendo que el tope está al final de la lista class Pila: def __init__(self): self.items = []# esto es una lista def estaVacia(self): return self.items == [] def incluir(self, item): self.items.append(item)# metodo que agreada al final dela lista def extraer(self): return self.items.pop() def inspeccionar(self): return self.items[len(self.items)-1] def tamano(self): return len(self.items)
83aeb8f31d94003abd6db8aedbf0ea1cba87543c
mlawan/lpthw
/ex33/ex33.py
456
3.75
4
i = 0 x = 1 a = 0 b = 0 numbers = [] users = [] while i <= 6 and not x > 8: #print(f"At the top i is {i}") #print(f"At the top x is {x}") numbers.append(i) users.append(x) i = i + 1 x = x + 2 a = a + 1 b = b + 1 print(f"{a}. Numbers row{a}:{numbers}") print(f" Users row{a}:{users}") print(f"At the bottom i is {i}") print(f"At the bottom x is {x}") print("The Numbe") for nums in users: print(nums)
113f83554a248c7909f3039d3bab32e0111f0cff
Gaming32/Python-AlgoAnim
/algoanim/sorts/bubble.py
451
3.6875
4
from algoanim.array import Array from algoanim.sort import Sort class BubbleSort(Sort): name = 'Bubble Sort' def run(self, array: Array) -> None: for i in range(len(array), 0, -1): sorted = True for j in range(1, i): if array[j - 1] > array[j]: sorted = False array.swap(j - 1, j) if sorted: break SORT_CLASS = BubbleSort
250aa61a3890c9de1a2758e36c324d5f386ac658
mkozel92/algos_py
/data_structures/linear_probed_hash_table.py
1,403
3.875
4
from typing import Any class LinearProbedHashTable(object): """Simple hash table with linear probing""" def __init__(self, size:int = 100): """ initialize with lists for keys and values of given size :param size: size of table """ self.keys = [None] * size self.values = [None] * size self.size = size def put(self, key: Any, value: Any): """ insert key value pair into table complexity O(N) basically constant if table is at most half full :param key: key :param value: value """ i = abs(hash(key) % self.size) original_i = i while self.keys[i] is not None and self.keys[i] != key: i = (i+1) % self.size if i == original_i: print("table is full") return self.keys[i] = key self.values[i] = value def get(self, key: Any) -> Any: """ gets value associated with given key complexity O(N) basically constant if table is at most half full :param key: key :returns: value """ i = abs(hash(key) % self.size) original_i = i while self.keys[i] is not None and self.keys[i] != key: i = (i + 1) % self.size if i == original_i: return return self.values[i]
753bcaf056c38f841af2710d7b737d13695f6a3b
ChandrakalaBara/PythonBasics
/basicAssignments/assignment11.py
277
4.21875
4
# Write a program which accepts a sequence of comma-separated numbers from console and # generate a list and a tuple which contains every number. str = input('Enter comma seperated numbers').split(',') print(type(str)) print(str) tpl = tuple(str) print(type(tpl)) print(tpl)
9cdbef8d76941ae8ea10650f126146e27875a652
alexfear/crappycode
/palindrom.py
892
3.578125
4
import math isPalindrom = 0 isPrime = 0 def main(): j = m1 = m2 = max = 0 erat=[] for i in range(10001, 99999, 2): if isPrime(i): erat.append(i) j+=1 for i1 in range(0, j): for i2 in range(i1, j): p = erat[i1] * erat[i2] if isPalindrome(p) and p > max: max = p m1 = erat[i1] m2 = erat[i2] print "The number of primes in the interval is " + str(j) print "The multipliers are " + str(m1) + " * " + str(m2) print "The palindrome is " + str(max) def isPalindrome(orig): reversed = 0 n = orig; while n > 0: reversed = reversed * 10 + n % 10 n/=10 return orig==reversed def isPrime(orig): if orig == 2: return 1 if orig == 3: return 1 if orig%2 == 0: return 0 if orig%3 == 0: return 0 i = 5 w = 2 while i*i <= orig: if orig%i == 0: return 0 i+=w w=6-w return 1 main()
8c95ab0ddc5878864319afb165ea9e921f7ad85a
abusamrah2005/Python
/Week-10/Day-64.py
424
3.734375
4
# Python Week-10 Day-64 # Python Try-Except try: print(x) except NameError as err: print ("name 'x' is not defined") print("----") try: print("Welcome To My Code") except NameError as err: print("Something went wrong") else: print("Complete no errors") print("----") try: print(y) except NameError as err: print ("name 'y' is not defined") finally: print(" The Try Except Is Finished")
0e944a20f2d1d21e440edb516347e69718aad026
derick-droid/pythonbasics
/loops[lst].py
1,700
4.625
5
# looping over a list of an item magicians = ["alice", "nana", "caroh"] for magician in magicians: print(f"{magician.title()} you did a good work") print("I cannot wait to see your next trick \n") # exercise # 4-1. Pizzas: Think of at least three kinds of your favorite pizza. Store these # pizza names in a list, and then use a for loop to print the name of each pizza. # • Modify your for loop to print a sentence using the name of the pizza # instead of printing just the name of the pizza. For each pizza you should # have one line of output containing a simple statement like I like pepperoni # pizza. # • Add a line at the end of your program, outside the for loop, that states # how much you like pizza. The output should consist of three or more lines # about the kinds of pizza you like and then an additional sentence, such as # I really love pizza! pizza_name = [" Neapolitan Pizza", "chicago pizza", "Greek pizza"] for pizza in pizza_name: print(f"i like {pizza} , it is my favourite") print("I really like pizza") # exercise 2 # # 4-2. Animals: Think of at least three different animals that have a common char- # acteristic. Store the names of these animals in a list, and then use a for loop to # print out the name of each animal. # 60 Chapter 4 # • Modify your program to print a statement about each animal, such as # A dog would make a great pet. # • Add a line at the end of your program stating what these animals have in # common. You could print a sentence such as Any of these animals would # make a great pet! animals_name = ["dog", "cat", "horse"] for animals in animals_name: print(f"{animals} can make a good pet") print("I like pets")
31d5e14e28750c5c5b74fb3337532c69cab55883
feliperfdev/100daysofcode-1
/Introdução ao Python/week6/day38/propriedades_POO.py
5,218
4.125
4
''' POO - Propriedades Em linguagens de programação como o Java, ao declararmos atributos privados nas classes, costumamos criar métodos públicos para manipulação desses atributos. Esses métodos são chamados de 'getters' e 'setters'. Os getters retornam o valor do atributo e os setters alteram o valor do mesmo. ''' print() class Conta: contador = 0 def __init__(self, titular, saldo, limite): self.__id = Conta.contador + 1 self.__titular = titular self.__saldo = saldo self.__limite = limite Conta.contador = self.__id def extrato(self): print(f'O cliente {self.__titular} tem R${self.__saldo}.00 de saldo!') def depositar(self, valor): self.__saldo += valor def sacar(self, valor): self.__saldo -= valor def transferir(self, valor, destino): self.__saldo -= valor destino.__saldo += valor # Funções para acesso (getters e setters): def getSaldo(self): return self.__saldo def getTitular(self): return self.__titular def setTitular(self, titular): self.__titular = titular def getId(self): return self.__id def getLimite(self): return self.__limite def setLimite(self, limite): self.__limite = limite c1 = Conta('Felipe', 4000, 10000) c2 = Conta('Cesar', 5000, 15000) c1.extrato() c2.extrato() c1.depositar(1000) c1.extrato() c1.sacar(3000) c1.extrato() c2.transferir(4500, c1) c1.extrato() c2.extrato(); print() soma = c1._Conta__saldo + c2._Conta__saldo print(f'Soma dos saldos: R${soma}.00') ''' Perceba que foi acessado o saldo, mesmo ele sendo um atributo do tipo privado. Isso é possível, porém, não é o que seria recomendado. Afinal, se é privado, não deveria ser acessado. Então, para o bem da empresa ou até mesmo do cliente, esse tipo de coisa não deve ser feita. ''' # O que fazer então para poder acessar o saldo sem ser dessa maneira? # Criaremos funções dentro da classe para tornar isso possível, sem prejudicar a empresa ou cliente. print() soma = c1.getSaldo() + c2.getSaldo() print(f'Soma dos saldos: R${soma}.00') print(f'Id Conta 1: {c1.getId()}\nId Conta 2: {c2.getId()}'); print() print(f'Limite atual de {c1.getTitular()} -> R${c1.getLimite()}.00') c1.setLimite(20000) print(f'Novo limite de {c1.getTitular()} -> R${c1.getLimite()}.00') #================================================================================================= print() ''' No entanto, utilizar funções como 'getFuncao' ou 'setFuncao' está mais relacionado à linguagens como Java. Em Python, podemos utilizar decorators para facilitar a criação dos métodos de manipulação. Sendo o @property para criar os getters e o @nomeGetter.setter para o setter. ''' # Refatorando a classe: class Conta: contador = 0 def __init__(self, titular, saldo, limite): self.__id = Conta.contador + 1 self.__titular = titular self.__saldo = saldo self.__limite = limite Conta.contador = self.__id def extrato(self): print(f'O cliente {self.__titular} tem R${self.__saldo}.00 de saldo!') def depositar(self, valor): self.__saldo += valor def sacar(self, valor): self.__saldo -= valor def transferir(self, valor, destino): self.__saldo -= valor destino.__saldo += valor # Funções para acesso (getters e setters): @property # definindo um getter def limite(self): return self.__limite @limite.setter # definindo o setter --> nomeDoGetter.setter def limite(self, value): if isinstance(value, str): value = float(value) self.__limite = float(value) self.__limite = float(value) @property def saldo(self): return self.__saldo @saldo.setter def saldo(self, valor): if isinstance(valor, str): valor = float(valor) self.__saldo = float(valor) self.__saldo = float(valor) @property def titular(self): return self.__titular @titular.setter def titular(self, name): if isinstance(name, str): self.__titular = name @property def idNumero(self): return self.__id @property def valorTotal(self): return self.__saldo + self.__limite conta1 = Conta('Felipe', 4000, 10000) conta2 = Conta('Camila', 7000, 25000) # print(conta1.__dict__) somaSaldos = conta1.saldo + conta2.saldo # Perceba que, para os getters, não é necessário parênteses. print(f'Soma dos saldos: {somaSaldos}'); print() print(f'Limite de {conta1.titular}: R${conta1.limite}.00') print(f'Limite de {conta2.titular}: R${conta2.limite}.00') print(f'Valor total Conta 1: {conta1.valorTotal}') print(f'Valor total Conta 2: {conta2.valorTotal}'); print() print(conta1.titular) print(conta2.titular) conta3 = Conta('Alguma Pessoa', '3000', '9000') print(f'Total: {conta3.saldo + conta3.limite}')
d1fd9c0eb3419d14efc2d6ea85e8e9e59960c5cc
syurskyi/Algorithms_and_Data_Structure
/Python for Data Structures Algorithms/template/13 Stacks Queues and Deques/Stacks, Queues, and Deques Interview Problems/SOLUTIONS/Balanced Parentheses Check - SOLUTION.py
2,891
4.0625
4
# # Balanced Parentheses Check - SOLUTION # # Problem Statement # # Given a string of opening and closing parentheses, check whether its balanced. We have 3 types of parentheses: # # round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesnt contain any other # # character than these, no spaces words or numbers. As a reminder, balanced parentheses require every opening # # parenthesis to be closed in the reverse order opened. For example ([]) is balanced but ([)] is not. # # # # You can assume the input string has no spaces. # # Solution # # # # This is a very common interview question and is one of the main ways to check your knowledge of using Stacks! # # We will start our solution logic as such: # # First we will scan the string from left to right, and every time we see an opening parenthesis we push it to a stack, # # because we want the last opening parenthesis to be closed first. (Remember the FILO structure of a stack!) # # # # Then, when we see a closing parenthesis we check whether the last opened one is the corresponding closing match, # # by popping an element from the stack. If its a valid match, then we proceed forward, if not return false. # # Or if the stack is empty we also return false, because there is no opening parenthesis associated with this closing # # one. In the end, we also check whether the stack is empty. If so, we return true, otherwise return false because # # there were some opened parenthesis that were not closed. # # # # Here's an example solution: # # ___ balance_check s # # Check is even number of brackets # __ l.. ? % 2 !_ 0 # r_ F.. # # # Set of opening brackets # opening _ s.. '([{' # # # Matching Pairs # matches _ s..([('(', ')'), ('[', ']'), ('{', '}')]) # # # Use a list as a "Stack" # stack _ # list # # # Check every parenthesis in string # ___ paren __ s # # # If its an opening, append it to list # __ ? __ o.. # ?.a.. ? # # ____ # # # Check that there are parentheses in Stack # __ l..(?) __ 0 # r_ F.. # # # Check the last open parenthesis # last_open _ ?.p.. # # # Check if it has a closing match # __ ? ? n.. __ ? # r_ F.. # # r_ l.. ? __ 0 # # # balance_check('[]') # # True # # balance_check('[](){([[[]]])}') # # True # # balance_check('()(){]}') # # False # # # Test Your Solution # """ # RUN THIS CELL TO TEST YOUR SOLUTION # """ # from nose.tools import assert_equal # # # c_ TestBalanceCheck o.. # # ___ test sol # assert_equal(sol('[](){([[[]]])}('), F..) # assert_equal(sol('[{{{(())}}}]((()))'), T..) # assert_equal(sol('[[[]])]'), F..) # print 'ALL TEST CASES PASSED' # # # # Run Tests # # t _ TestBalanceCheck() # t.test(balance_check)
a7123a74bb59f8fc006abe5444112cafb7f45101
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/ryxshr002/question2.py
654
3.859375
4
"""Shriya Roy 8 May 2014 counting program""" def pair(n,i): if len(n)==0:#checks if length is 0 return print("Number of pairs:",i) if len(n)==1:#checks if length is 1 return print("Number of pairs:",i) else: if n[0]==n[1]:#checks if the first two are identical i+=1 return pair(n[2:],i)#increasing increments of 2 else: return pair(n[2:],i) n=input("Enter a message:\n") pair(n,0)
29255977c6f2067cfc9275a1dacf9564f0ae9805
artificialfintelligence/letter-boxed-game-solver
/src/word.py
275
3.6875
4
from typing import NamedTuple, Set class Word(NamedTuple): text: str unique_letters: Set[str] num_unique_letters: int @staticmethod def create(text: str): unique_letters = set(text) return Word(text, unique_letters, len(unique_letters))
7813529a051b6cf9256a2ab26dcf5bd3762bae9d
Kanishk9/OpenSourceLabs
/Lab3/open1.py
138
3.640625
4
str1 = "Hello World" frequency = {} for i in str1: if i in frequency: frequency[i] += 1 else: frequency[i] = 1 print (frequency)
f93bec1f86741577030f6556eb9d5935f24f5eb1
qiannn/leetcode
/Binary Tree Postorder Traversal/Binary Tree Postorder Traversal.py
595
3.890625
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def postorderTraversal(self, root): list = [] self.traversal(root, list) return list def traversal(self, root, list): if root == None: return self.traversal(root.left, list) self.traversal(root.right, list) list.append(root.val) def main(): solution = Solution() node1 = TreeNode(1) node2 = TreeNode(2) node3 = TreeNode(3) node1.left = node2 node2.left = node3 print solution.postorderTraversal(node1) if __name__ == '__main__': main()
95909e1b94d0e460981515f5ece9ae983ccd2a91
Crafty-Star/Anish-Sarkar-Graphic-Studio
/Python Starfield Assignment/ScalingLineStarfield.py
2,246
3.96875
4
from tkinter import * import math, time, random def convertRGBToHex(r,g,b): return "#{0:02x}{1:02x}{2:02x}".format(r,g,b) # Define the behavior of a line segment class Line: def __init__(self, canvas, x, y, dx, dy, color = "yellow"): self.canvas = canvas # The center of the line, so you can scale it later about that point self.x = x self.y = y # How much it moves. Used to draw the initial line as well self.dx = dx self.dy = dy # This draws the line in the direction that it is moving self.line = self.canvas.create_line(x-dx/2, y-dy/2, x+dx/2, y+dy/2, fill = color, width = random.randint(1,4)) def move(self): # Move the line the correct amount self.x += self.dx self.y += self.dy self.canvas.move(self.line, self.dx, self.dy) # Make the line longer as it moves towards the edges of the screen self.canvas.scale(self.line, self.x, self.y, 1.1, 1.1) mousex = 450 mousey = 450 root = Tk() c = Canvas(root, width = 900, height = 900, bg = "black") c.pack() planets = [] def mainloop(): global planets angle = 0 while angle < 6.28: scale = random.uniform(20,30) dx = math.cos(angle) * scale dy = math.sin(angle) * scale angle += 0.03 if random.randint(1,2) == 1: color = "white" p = Line(c, mousex + dx, mousey + dy, dx, dy, color) planets.append(p) for p in planets: p.move() if p.x > 800 or p.x < 100 or p.y >800 or p.y <100: c.itemconfig(p.line, fill = convertRGBToHex(137,207,240)) elif p.x > 700 or p.x < 200 or p.y >700 or p.y <200: c.itemconfig(p.line, fill = convertRGBToHex(15,82,186)) elif p.x > 600 or p.x < 300 or p.y >600 or p.y <300: c.itemconfig(p.line, fill = convertRGBToHex(137,207,240)) elif p.x > 500 or p.x < 400 or p.y >500 or p.y <400: c.itemconfig(p.line, fill = convertRGBToHex(176,223,229)) if p.x > 900 or p.y > 900 or p.x < 0 or p.y < 0: c.delete(p.line) planets.remove(p) root.after(1, mainloop) mainloop()
80f45d8284bbc67dc219c85c6fd68fa93ce75af2
jcohen66/python-sorting
/recursion/towers_of_hanoi.py
413
3.75
4
def towers_of_hanoi(n, source, dest, aux): print(f"n {n} source {source} dest {dest} aux {aux}") if n == 1: print(f"Move disk 1 from source {source} to destination {dest}") return towers_of_hanoi(n-1, source, aux, dest) print(f"Move disk {n} from source {source} to destination {dest}") towers_of_hanoi(n-1, aux, dest, source) # driver n = 4 towers_of_hanoi(n, 'A', 'B', 'C')
ec4777248a57910bba407212cdd202e1b65d2adb
tssutha/Learnpy
/test.py
1,160
3.5
4
import math import time l = list() def reverse(ls): #l = list() print ls l.append(ls[len(ls)-1]) print l if(len(ls)>1): reverse(ls[:-1]) else: return l; ls = [1,2,3] def reverse2(ls): if len(ls)>1: return reverse2(ls[1:]).append(ls[0]) else: return ls #print reverse2(ls) ls = [2, [5,False,[7,False,False]],[9,False,False]] lastIndex = 0 def issqu(ls, N): global lastIndex i = lastIndex print i ln = len(ls) while(i < ln and ln >1): element = ls[i] if element != 'Fizz' : if element**2 == N : lastIndex = i return True i = i +1 return False def fizz(N): ls = [] lastFizz = 0 for i in range(N): if N >= lastFizz: if issqu(ls, i+1) == True : ls.append('Fizz') lastFizz = (math.sqrt(i+1) + 1)**2 else: ls.append(i+1) else: ls.append(i+1) return ls def fizz1(N): ls = [] lastFizz = 0 for i in range(N): if issqu(ls, i+1) == True : ls.append('Fizz') else: ls.append(i+1) return ls start = time.time() #print fizz(100) end = time.time() print end - start start = time.time() print fizz1(100) end = time.time() print end - start
f89da34f751c98fc63617e23f88d28ef11aac458
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/8 Problems on bits and masking/12_OFF_SpecifiedBit/Demo.py
420
3.6875
4
''' Write a program which accept one number and position from user and off that bit. Return modified number IP: 1840 (11100110000) iPos = 5 OP: 1824 (11100100000) ''' def OffBit(no,pos): mask = ~(1 << (pos - 1)); return (no & mask); def main(): no = int(input("Enter number: ")); pos = int(input("Enter position: ")); result = OffBit(no,pos); print(result); if __name__ == "__main__": main();
8e9f883f532052194319a0a01dd59468602d12ea
1914866205/python
/pythontest/day04-18-151-04.py
110
3.546875
4
def multi(*num): result=1 for i in num: result*=i return result print(multi(1,2,3,4,5))
4e09e60c9b598b2e6ca1a45f14af3c80c656298d
Halal375657/Graph-Theory
/PrimsMST.py
1,619
3.984375
4
# # Prim's Algorithm # Book:- Introduction to Algorithms # O(E log V) # from heapq import heappush, heappop, heapify class Graph: def __init__(self, n): self.n = n self.graph = [{} for _ in range(n)] def addEdges(self, u, v, w): self.graph[u][v] = w # As undirected. self.graph[v][u] = w def primMST(self, src): setMST = [False]*self.n Q = [(0, 0, src)] lookup = set() A = [] while Q: w, _, u = heappop(Q) for v in self.graph[u]: if setMST[v] == False: heappush(Q, (self.graph[u][v], u, v)) if Q: w, u, v = Q[0][0], Q[0][1], Q[0][2] if v in lookup: continue lookup.add(v) setMST[u] = True A.append((u,v, w)) return A if __name__ == "__main__": g = Graph(5) edges = ((1, 2, 5), (1, 3, 2), (2, 3, 1), (2, 4, 2), (3, 4, 3) ) for (u, v, w) in edges: g.addEdges(u, v, w) A = g.primMST(1) print("============Before prim's MST============") print("u - v -> Weight") totalCost = 0 for (u, v, w) in edges: totalCost += w print(u,"-",v,"->",w) print("Total Cost is:", totalCost) print("\n\n============After prim's MST============") print("u - v -> Weight") totalCost = 0 for (u, v, w) in A: totalCost += w print(u,"-",v,"->",w) print("Total Cost is:", totalCost)
4a710ffeeaeb8bedfd140d78fab583133701aeef
ithangarajan/HackerRank
/Grading Students
436
3.59375
4
#!/bin/python3 import sys def solve(grades): answer=[] for x in grades: if x > 37: if x%5 == 3: x=x+2 if x%5 == 4: x=x+1 answer.append(x) return answer n = int(input().strip()) grades = [] grades_i = 0 for grades_i in range(n): grades_t = int(input().strip()) grades.append(grades_t) result = solve(grades) print ("\n".join(map(str, result)))
8086a7615c470e5c7131dc76e81c05f7fa4008c9
simpleman19/patterns_project
/walker.py
1,151
3.84375
4
from random import choice import pickle class Walker: """ Generates random walks """ def __init__(self, num_points=5000): """ Initialize attributes for a walk """ self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): """ Calculate the points in the walk """ while len(self.x_values) < self.num_points: x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) x_step = x_direction * x_distance y_direction = choice([1, -1]) y_distance = choice([0, 1, 2, 3, 4]) y_step = y_direction * y_distance if x_step == 0 and y_step == 0: continue next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y) def create_memento(self): return pickle.dumps(vars(self)) def set_memento(self, memento): previous_state = pickle.loads(memento) vars(self).clear() vars(self).update(previous_state)
8485cdfb5d873234977a828369a817b6a55fd883
alperkarasuer/Project-Euler
/Q10.py
361
4
4
def isPrime(n): if (n <= 1): return False if (n <= 3): return True if (n % 2 == 0 or n % 3 == 0): return False i = 5 while (i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True primes = [x for x in range(1,int(2e6)) if isPrime(x)] print(sum(primes))
f6dbc52885bf60408c175a019a6e82d82a683292
mikej803/digitalcrafts-2021
/week2notes/oppLab.py
3,953
3.921875
4
# # # # DIRs # # # chris = { # # # "firstName": "Chris", # # # "lastName": "Owens", # # # "greeting": greeting # # # } # # # matt = { # # # "firstName": "Matt", # # # "lastName": "Fisher", # # # "greeting": greeting # # # } # # # print(chris["firstName"], chris["lastName"]) # # # chris["greeting"]("Veronica") # # # class Dir: # # # def greeting(self): # # # print('hello world') # # # chris = DIR() # # # matt = DIR() # # # def greeting(name): # # # print(f"hello {name}") # # # mike = {} # # # class Student: # # # def __init__(self, fName, lName): # # # self.firstname = fName # # # self.lastName = lName # # # print(f'Hello {fName}{lName}') # # # def greeting(self, name): # # # print(f'hello {name}') # # # mike = Student("Jake ", "Green ") # # # jake = Student("Mike ", "Williams ") # # # greeting = ("Hello ") # # class Student: # # def __init__(self, fName, lName): # # self.firstname = fName # # self.lastName = lName # # print(f'{self.firstname} Say whats up to {self.firstname}') # # def greeting(self, name): # # print(f'{self.firstname} says hello, by the way {name}') # # # class Campus: # # # def __init__(self) # # jake = Student("Mike ", "Williams ") # # mike = Student("Jake ", "Green ") # # # greeting = ("Hello ") # # mike.greeting("Jake") # # jake.greeting("Mike") # # # mike.firstname("Jake") # # # jake.firstname("Mike") # # # carol = Student() # # # john = Student() # # # jake = Student() # # # mike.greeting('john') # # # victoria.greeting('jake') # # # carol.greeting('mike') # # # john.greeting('victoria') # # # jake.greeting('carol') # # # Students # # # mike = { # # # "firstName": "Mike", # # # "lastName": "Williams", # # # "greeting": greeting # # # } # # # victoria = { # # # "firstName": "Jake", # # # "lastName": "Green", # # # "greeting": greeting # # # } # # notes # def incrementCount(): # global count = 0 # count += 1 # return count # result = incrementCount() # print(result) # result = incrementCount() # r2 = increment() # print(result) # class Counter(): # def __init__(self): # self.count = 0 # def increment(self): # self.count += 1 # return self.count # a = 5 # count1 = Counter() # print(count1.increment()) # print(count1.increment()) # print(count1.increment()) # print(count1.increment()) # print(count1.increment()) # print("instance variable for count 1: ", count1.count) # count2 = Counter() # print("count2: ", count2.increment()) # class Button(): # def __init__(self, color, height, width): # self.count = 0 # self.color = color # self.height = height # self.width = width # def click(self): # self.count += 1 # navButton = Button('green', '100px', '200px') # helpButton = Button('yellow', '50px', '25px') # navButton.click() # navButton.click() # navButton.click() # navButton.click() # print(f'nav: {navButton.count} help: {helpButton.count}') # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # helpButton.click() # print(f'nav: {navButton.count} help: {helpButton.count}') class Button(): FontWeight = 'bold' FontColor = 'red' def __init__(self, color, height, width): self.count = 0 self.color = color self.height = height self.width = width def click(self): self.count: += 1 @classmethod def popUp(cls): print('popups are so annoying') navButton = Button('green', '100px', '200px') helpButton = Button('yellow', '50px', '25px') Button.FontWeight = "33" print(Button.FontWeight)
8e0c4ec65d65c3d28be6facf64fe8820a5075700
snehask7/AI-Lab
/A5-Polygon/Polygons.py
7,171
3.515625
4
import random import math import itertools import heapdict import heapq from collections import deque class Polygon: def __init__(self, vertices): self.vertices = vertices def check_inside(self, x, y): equation_values = [] direction=0 for i in range(len(self.vertices)): if(i == len(self.vertices)-1): # line connecting last and first vertex x1, y1 = self.vertices[len( self.vertices)-1].x, self.vertices[len(self.vertices)-1].y x2, y2 = self.vertices[0].x, self.vertices[0].y else: x1, y1 = self.vertices[i].x, self.vertices[i].y x2, y2 = self.vertices[i+1].x, self.vertices[i+1].y equation_values.append((-(y2-y1)*x) + ((x2 - x1)*y) + (-(-(y2-y1)*x1 + (x2 - x1)*y1))) left=True right=True for x in equation_values: #right if x>0: continue else: right=False break for x in equation_values: #left if x<0: continue else: left=False break return left or right class Vertex: def __init__(self, x, y): self.x = x self.y = y self.parent = None self.g = 0 # g(n) value def __eq__(self, v2): if (self.x == v2.x and self.y == v2.y): return True return False def dist(self, v2): a = abs(self.x - v2.x) b = abs(self.y - v2.y) # root of a square plus b square return math.sqrt(math.pow(a, 2) + math.pow(b, 2)) def __str__(self): return str(self.x) + str(self.y) def __hash__(self): return hash(str(self)) class Edge: def __init__(self, v1, v2): # stores 2 ends of lines self.x1 = v1.x self.y1 = v1.y self.x2 = v2.x self.y2 = v2.y def get_y(self, x): m = (self.y2 - self.y1) / (self.x2 - self.x1) y = m * (x-self.x1) + self.y1 # y=mx+c return y def check_inside(self, polygon): # go point by point on line and check if inside polygon if (self.x1 != self.x2): # not vertical line for x in gen_spaces(min(self.x1, self.x2), max(self.x2, self.x1) , 0.001): y = self.get_y(x) if (polygon.check_inside(x, y)): return True return False else: # vertical line for y in gen_spaces(min(self.y1, self.y2), max(self.y1, self.y2), 0.001): if (polygon.check_inside(self.x1, y)): return True return False def gen_spaces(start, end, step): # to generate steps as decimals if step !=0: no_spaces = int(abs(start-end) / step) return itertools.islice(itertools.count(start, step), no_spaces) class Env: def __init__(self, polygons, start_point, goal_point): self.polygons = polygons self.start = start_point self.goal = goal_point self.states = [] for i in polygons: for j in i.vertices: self.states.append(j) self.states.append(goal_point) def check_inside(self, line): for polygon in self.polygons: if (line.check_inside(polygon)): return True return False def getNextStates(self, current): next_states = [] for state in self.states: if state != current: line = Edge(current, state) if not self.check_inside(line): next_states.append(state) return next_states def heuristic(state,goal): return goal.dist(state) def path(state,env): path_list=[] depth=state.g while depth>0: path_list.append([state.x,state.y]) state=state.parent depth-=1 path_list.append([env.start.x,env.start.y]) path_list.reverse() return path_list def BFS(env): #uninformed initial=env.start goal=env.goal frontier = deque([]) failure = None explored = set() explored.add(initial) frontier.append([(initial.x, initial.y)]) initial.g = 0 if(initial==goal): return initial while len(frontier) != 0: path = frontier.popleft() node = path[-1] node = Vertex(node[0], node[1]) for neighbor in env.getNextStates(node): newlist = list(path) neighbor.g = node.g + 1 neighbor.parent=node if(neighbor==goal): goallist = list(newlist) goallist.append((neighbor.x, neighbor.y)) return goallist if neighbor not in explored: explored.add(neighbor) newlist.append((neighbor.x, neighbor.y)) frontier.append(newlist) def GreedyBFS(env): initial=env.start goal=env.goal frontier = heapdict.heapdict() failure = None explored = set() frontier[initial] = heuristic(initial,goal) initial.g = 0 while len(frontier) != 0: node = frontier.popitem()[0] if(node==goal): return node explored.add(node) for neighbor in env.getNextStates(node): neighbor.parent=node neighbor.g = node.g + 1 found = 0 if neighbor not in explored and neighbor not in frontier.keys(): #not in frontier or explored frontier[neighbor]= heuristic(neighbor,goal) return failure def AStar(env): initial=env.start goal=env.goal frontier = heapdict.heapdict() failure = None explored = set() frontier[initial] = heuristic(initial,goal) while len(frontier) != 0: node = frontier.popitem()[0] if(node==goal): return node explored.add(node) for neighbor in env.getNextStates(node): neighbor.parent=node neighbor.g = node.g+1 new_cost = heuristic(neighbor,goal)+neighbor.g if neighbor not in explored and neighbor not in frontier.keys(): #not in frontier or explored frontier[neighbor] = new_cost elif neighbor in frontier.keys() and frontier[neighbor] > new_cost: #already in frontier but with a higher cost frontier[neighbor] = new_cost #replacing cost with the lower cost return failure p1=Polygon([Vertex(1,1),Vertex(1,3),Vertex(5,3),Vertex(5,1)]) p2=Polygon([Vertex(3,4),Vertex(4,4),Vertex(3.5,7)]) p3=Polygon([Vertex(2, 4),Vertex(1, 4.5),Vertex(0.75, 7),Vertex(1.5, 9),Vertex(2.3,6.5)]) p4=Polygon([Vertex(6,4),Vertex(6,9),Vertex(8,9),Vertex(8,4)]) p5=Polygon([Vertex(6,1),Vertex(6,3),Vertex(8,2)]) env=Env([p1,p2,p3,p4,p5],Vertex(0,0),Vertex(10,10)) print('A STAR') point=AStar(env) final_path=path(point,env) print(final_path) print('GREEDY BFS') point=GreedyBFS(env) final_path=path(point,env) print(final_path) print('BFS') final_path=BFS(env) print(final_path) """ OUTPUT A STAR [[0, 0], [6, 1], [6, 9], [10, 10]] GREEDY BFS [[0, 0], [6, 1], [6, 9], [10, 10]] BFS [(0, 0), (1, 3), (8, 4), (10, 10)] """
b564cc1af09eb0c618da6652b6b1be38521d3c0d
gauravmalaviya143/loop
/nestedwhileloop.py
146
3.9375
4
i = 1 while i<=3: print("hello", end="") j = 1 while j<=2: print("gaurav", end="") j+=1 i+=1 print()
52bf3af5514b7e7dad54e8f44163764fcd798148
1642195610/backup_data
/data_zgd/python进阶/10.20/test.py
1,676
3.75
4
from typing import List from randomList import randomList def sort(nums: List[int]) -> List[int]: # 冒泡排序法 if len(nums) <= 1: return nums for i in range(len(nums) - 1): f = 1 for j in range(len(nums) - 1 - i): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] \ = nums[j + 1], nums[j] f = 0 if f == 1: break print(f"第{i + 1}轮排序结果: {nums}") return nums if __name__ == '__main__': list = randomList.randomList(10) print(f"冒泡原始数据: {list}") result = sort(list) print(f"冒泡排序数据: {result}") print() def sort1(nums: List[int]) -> List[int]: if len(nums) <= 1: return nums for i in range(len(nums) - 1): maxindex = i f = 1 for j in range(i + 1, len(nums)): if nums[maxindex] > nums[j]: maxindex = j f = 0 if f: continue if maxindex != i: nums[i], nums[maxindex] = nums[maxindex], nums[i] print(f"第{i + 1}轮排序结果: {nums}") return nums if __name__ == '__main__': list = randomList.randomList(10) print(f"选择原始数据: {list}") result1 = sort1(list) print(f"选择排序数据: {result1}") def two_sum(nums: List[int], target: int): dict1 = {} for i in range(len(nums)): left = target - nums[i] if left in dict1: return [dict1[left], i] else: dict1[nums[i]] = i if __name__ == '__main__': list = [2, 3, 7, 9] result = two_sum(list, 9) print(result)
a24401cd68510151aafcaed9f4bb03b1fb393572
lordgrenville/project_euler
/prob_9.py
500
3.625
4
import time start = time.time() squares = [] triplets = [] i = 1 while i**2 < 1000000: squares.append(i**2) i += 1 for a in squares: for b in squares: for c in squares: if a + b == c: triplets.append(tuple([a, b, c])) for a in triplets: if sum([i**0.5 for i in a]) == 1000: winner = [i**0.5 for i in a] print(winner) print(winner[0] * winner[1] * winner[2]) end = time.time() print('total running time is ', end - start)
cd85fd0ccd1bc652e615e9c00990ab5b4ab2b47c
prasertcbs/python_tutorial
/src/area.py
313
3.84375
4
def rectangle(w, h): # dynamic typing # code block area = w * h return area def triangle(w, h): # area = .5 * w * h return .5 * w * h # main entry point w = int(input("width = ")) # string '5' "5" h = int(input("height = ")) # "3" # print(rectangle(w, h)) print(triangle(w,h))
ba8dfd448cba8be6215e9649262225c334540c7c
poding/poding.github.io
/01_python/chapter12/ex12_03.py
1,157
3.546875
4
# 랜덤 모듈 import random for i in range(5): print(random.randint(1, 10)) # 1~10까지 정수 for i in range(5): print(random.randrange(1, 10)) # 1~9까지 정수 for i in range(5): print(random.uniform(1, 10)) # 1~10까지 실수 # 시퀀스에서 랜덤한 요소 선택 두가지 예제 food = ["짜장면", "짬뽕", "탕수육", "군만두"] print(random.choice(food)) i = random.randrange(len(food)) print(food[i]) # 시퀀스 내용 랜덤하게 섞기 print(food) random.shuffle(food) print(food) # 시퀀스에서 랜덤한 갯수의 요소 뽑기 print(random.sample(food, 2)) nums = random.sample(range(1, 46), 6) # 로또 nums.sort() print(nums) # sys 모듈 (읽기 전용) import sys print("버전: ", sys.version) print("플랫폼: ", sys.platform) print("바이트 순서: ", sys.byteorder) print("모듈 경로: ") for i in range(len(sys.path)): print(sys.path[i], end="\n") # for path in sys.path: # print(path) # sys.exit(0) # 위에껀 변수 이건 함수, 프로그램 강제 종료 # sys.exit(-1) # 종료 코드 -1 # 명령형 인수 print(sys.argv) # [파일경로, 인자1, 인자2, ..)
755837253137d808215f206c3fc8e815670739a3
marcyheld/SI507
/lab-11-assignment-marcyheld/sample6.py
1,820
3.546875
4
# Change Frame seconds and make movements smoothly #required import pygame pygame.init() #create a surface gameDisplay = pygame.display.set_mode((800,600)) #initialize with a tuple #lets add a title, aka "caption" pygame.display.set_caption("Frame per seconds") pygame.display.update() #only updates portion specified #create colors white = (255,255,255) black = (0,0,0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) #position vars x_pos = 0 y_pos = 0 x_delta = 0 y_delta = 0 clock = pygame.time.Clock() def redraw(): gameDisplay.fill(white) gameDisplay.fill(blue, rect=[50,50, 20,20]) pygame.draw.circle(gameDisplay, red, (50,100), 20, 0) pygame.draw.lines(gameDisplay, red, False, [(100,100), (150,200), (200,100)], 1) # Creating a string object. f = pygame.font.Font(None, 25) # Rendering this string object. t = f.render('Sample Text', False, black) # Displaying this text on the window. gameDisplay.blit(t, (400,300)) gameExit = False while not gameExit: # Drawing objects and filling out background color redraw() for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: x_delta=0 y_delta=0 # Changing delta value to move the object automatically if event.key == pygame.K_LEFT: x_delta -= 10 if event.key == pygame.K_RIGHT: x_delta += 10 if event.key == pygame.K_UP: y_delta -= 10 if event.key == pygame.K_DOWN: y_delta += 10 # Keep changing x and y position based on the delta value until you put another keyboard input x_pos += x_delta y_pos += y_delta gameDisplay.fill(blue, rect=[x_pos,y_pos, 20,20]) pygame.display.update() # Setting frame seconds. You can change the number to make the game faster or slower. clock.tick(10) #required pygame.quit() quit() #exits python
d97e33eb8e9f23a26fd317eb7e196716613baec9
kirti167/FOOD-RECIPE-APP-in-python-using-tkinter-
/chilipotato.py
2,329
3.65625
4
import tkinter as tk from tkinter import * from PIL import ImageTk, Image root=tk.Toplevel() root.geometry("1400x700+0+0") root.config(bg='white') canvas = Canvas(root, width =500, height=500) canvas.place(x=0,y=0,relheight=1,relwidth=1) img = ImageTk.PhotoImage(file="chili1.jpg") canvas.create_image(1400,37,anchor=NW ,image=img) label=Label(root,text="CHILLI POTATO",font="Helvetica 15 bold",pady=3,padx=3,bd=2,fg='white',bg='black',relief=RAISED) label.place(x=0,y=2,relwidth=1) t=tk.Text(root,bg='white',fg='black',font="Helvetica 15 bold") t.place(x=2,y=37,height=900,width=800) quote=""" RECIPE OF CHILLI POTATO Step 1 Add potatoes in a bowl. Add corn flour, salt, and white pepper powder. Mix well and set aside for twenty minutes. Step 2 Heat two tablespoons oil in a non stick pan. Add onion roundels and sauté for two minutes or until pink. Add garlic, garlic paste and sauté for half minute. Step 3 Heat oil in a kadai. Deep fry the potatoes till crisp. Drain on an absorbent paper and add to the onion-garlic mixture. Step 4 Add green chillies, soy sauce and MSG and mix well. Check the seasonings. Add vinegar and mix well.Serve hot. """ t.insert(tk.END,quote) t.config(state="disabled") t1=tk.Text(root,bg='white',fg='black',font="Helvetica 11 bold") t1.place(x=803,y=37,height=204,width=600) quote1=""" ABOUT THE DISH: A hugely popular Chinese dish, Honey Chill Potato is juicy, crunchy and full of flavour snack that you just cannot resist. A delicious pick for kids, the great taste of honey chilli potatoes can be brought home in a few easy steps. Try this recipe and you'll never head to those street stalls again! """ t1.insert(tk.END,quote1) t1.config(state="disabled") t2=tk.Text(root,bg='white',fg='black',font="Helvetica 14 bold") t2.place(x=803,y=238,height=600,width=730) quote2=""" INGREADIENTS: -Potatoes cut into fingers 5 medium -Cornflour/ corn starch 3 tablespoon -Salt to taste -White pepper powder a pinch -Oil 2 tbsps + to deep fry -Onions cut 2 medium -Garlic finely chopped 1/2 tablespoon -Garlic paste 1/2 tablespoon -Green chillies slit 4 -Soy sauce 2 teaspoon -MSG optional a pinch -Vinegar 1 teaspoon """ t2.insert(tk.END,quote2) t2.config(state="disabled") tk.mainloop()
17dd496940fea0f52b43219da94fe13099c16b16
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/3418.py
1,209
3.796875
4
def checkTidy(numLst): lastDigit = 0 for digit in numLst: if digit < lastDigit: return False lastDigit = digit return True def makeList(num): numStr = str(num) numLst = [] for digit in numStr: numLst.append(int(digit)) return numLst def makeNewNum(numLst): if numLst[0] == 0: numLst = numLst[1:] # delete leading 0, if it's there return int(''.join(str(i) for i in numLst)) # convert numLst back to int # use for large input sizes (recursion) def getLastTidyNum(n): numLst = makeList(n) if checkTidy(numLst): return n else: #not tidy yet for index, digit in enumerate(numLst): nextDigit = numLst[index+1] if digit > nextDigit: numLst[index] -= 1 for indexOfFollowingDigit in xrange(index+1, len(numLst)): numLst[indexOfFollowingDigit] = 9 break newN = makeNewNum(numLst) return getLastTidyNum(newN) t = int(input()) for i in range(1, t + 1): n = int(input()) lastTidyNum = getLastTidyNum(n) print("Case #{}: {}".format(i, lastTidyNum))
853c4784126c5e253c7a6897fad66a02d75b998d
bobkey/python_learn
/untitled.py
280
3.671875
4
import os def get_file_names(path_name): print path_name file_names = os.listdir(path_name) for name in file_names: if os.path.isdir(name): get_file_names(os.path.abspath(name)) else: print name get_file_names(os.getcwd())
471df938b153c94d08d054c75ee55c6eced4208e
ReCir0/UCU_Programming
/Lab3/series.py
289
3.890625
4
num_check = int(input()) a = 1 b = 2 for i in range(num_check): if i == 0: print(a, "/", b, sep = "", end = "") elif i % 2 != 0: print(" - ", a, "/", b, sep = "", end = "") else: print(" + ", a, "/", b, sep = "", end = "") a += 2 b += 2 print()
f44548304bbc86ccf40883534a901210f933c6f4
Ayushrestha05/HackerRank-Python
/Triangle_Quest_2.py
216
3.859375
4
## You are given a positive integer N. ## Your task is to print a palindromic triangle of size N if __name__ == "__main__": for i in range(1, int(input()) + 1): print(int(10 ** i / 9) * int(10 ** i / 9))
590935d4f552690e09fb61e25da08a4c57befcf9
Woosiq92/Pythonworkspace
/5_list.py
1,124
4.15625
4
#리스트 subway1 = 10 subway2 = 20 subway3 = 30 subway = [10, 20, 30] print(subway) subway = ["유재석", "조세호", "박명수"] print(subway) #조세호가 몇번 째 칸에 타고 있는가? print(subway.index("조세호")) # 하하씨가 다음 정류장에 탐 subway.append("하하") # 항상 맨뒤에 삽입 print(subway) # 정형돈씨를 유재석과 조세호 사이에 태워봄 subway.insert(1, "정형돈") print(subway) # 지하철에 있는 사람이 한명씩 내림 print(subway.pop()) print(subway) print(subway.pop()) print(subway) print(subway.pop()) print(subway) # 같은 이름의 사람이 몇 명 있는지 확인하기 subway.append("유재석") print(subway) print(subway.count("유재석")) # 정렬도 할 수 있음 num_list = [ 5, 4, 3, 2, 1] num_list.sort() print(num_list) # 뒤집기 num_list.reverse() print(num_list) # 모두 지우기 num_list.clear() print(num_list) # 다양한 자료형 함께 사용 num_list = [5, 4, 3, 2, 1] mix_list = ["조세호", 20, True] print(mix_list) #리스트 확장( 병합) num_list.extend(mix_list) print(num_list)
f4358439104ee24ff38e044d19ce1159e2fec608
aj3x/PythonPawnAI
/AlphaBeta.py
3,353
3.625
4
import PWND import MiniMax DEPTH_LIMIT = 5 PAWN_VALUE = 20 THREAT_VALUE = 5 transpositionTable = dict() def alphabeta(node): MiniMax.argMax() MiniMax.argMin() def alphaMini(node,depth = 0,end = False): """ :param node: a Game object responding to the following methods: str(): return a unique string describing the state of the game (for use in hash table) isTerminal(): checks if the game is at a terminal state utility(): successors(): returns a list of all legal game states that extend this one by one move in this version, the list consists of a move,state pair isMinNode(): returns True if the node represents a state in which Min is to move isMaxNode(): returns True if the node represents a state in which Max is to move :return: a pair, u,m consisting of the minimax utility, and a move that obtains it """ depth+=1 s= str(node) if (s in transpositionTable): if(transpositionTable[s][1] != False) : return transpositionTable[s] if node.isTerminal(): u = node.utility() m = None elif depth > DEPTH_LIMIT: u = boardValue(node) m = False else: #print(depth) vs = [(alphaMini(c,depth)[0],m) for (m,c) in node.successors()] # strip off the move returned by minimax! if node.isMaxNode(): u,m = MiniMax.argmax(vs) elif node.isMinNode(): u,m = MiniMax.argmin(vs) else: print("Something went horribly wrong") return None transpositionTable[s] = u,m # store the move and the utility in the tpt #depth = 0 return u,m def hasMove(pawn,node): for z in range(-1,2): if node.legalMove(pawn,z): return True return False def boardValue(node): """ Takes a board and evaluates what it's worth "param node" """ b = dict() w = dict() threat = 0 kills = 0 for x in range(0,PWND.WIDTH): for y in range(0,PWND.HEIGHT): t = node.getPawn(x,y) if(t!=None): if (hasMove(t,node) & t.isColor(node.whoseTurn)):#check if it's a move from winning bs = node bs = bs.move(t,0)[1] if bs.winFor(t.color): return 100 for z in range(-1,2): if((z!=0) & (node.legalMove(t,z))):#can kill kills += PAWN_VALUE*node.intPlayer(node.whoseTurn) m = node.movePos(t,z) if(node.inBounds(m)): if t.color == PWND.WHITE: if str(m) in w: zzz =0 else: w[str(m)] = True threat+=THREAT_VALUE else: if str(m) in b: zzz = 0 else: b[str(m)] = True threat-=THREAT_VALUE pawns = (node.count(PWND.WHITE)-node.count(PWND.BLACK))*PAWN_VALUE #for y in range(0,PWND.HEIGHT): # for x in range(0,PWND.WIDTH): #print(b) #print(w) return pawns+threat+kills
32e6a41777d482af04e300856b5a0a7373adba35
hcxie20/Algorithm
/033_search_rotated_sorted_array.py
834
3.59375
4
# [4, 5, 6, 7, 0, 1, 2, 3] # nums[mid] 与target 是否在同一侧(递增数列) # 是则用target比 # 否则用inf, -inf比 # [4, 5, 6, 7, 0, 1, 2, 3], mid = 3, # target = 5, 同一侧, num = 7 # target = 0, 不同侧,num = -inf class Solution: def search(self, nums, target): l = 0 r = len(nums) - 1 while l <= r: mid = (l + r) // 2 if (nums[mid] < nums[0]) == (target < nums[0]): num = nums[mid] else: if target < nums[0]: num = float("-inf") else: num = float("inf") if num < target: l = mid + 1 elif num > target: r = mid - 1 else: return mid return -1
804b26ef93087df59af4aab0a3cfe0f7a747057e
rec/dedupe
/old/old/file_length.py
965
3.6875
4
import collections import os import sys def count_filename_lengths(*roots): counter = collections.Counter() for root in roots: root = os.path.abspath(os.path.expanduser(root)) for dirpath, _, filenames in os.walk(root): for f in filenames: filename = os.path.join(dirpath, f) counter.update({len(filename): 1}) return counter MESSAGE = """ Number of files = {number_of_files} Number of name characters = {number_of_name_characters} Mean file name length = {mean} """ if __name__ == '__main__': counter = count_filename_lengths(*sys.argv[1:]) print('Most common file lengths:', *counter.most_common(20)) number_of_files = sum(counter.values()) number_of_name_characters = sum(k * v for k, v in counter.items()) mean = number_of_name_characters / number_of_files print(MESSAGE.format(**locals())) if False: print(*sorted(counter.items()), sep='\n')
f20e6e580800eb466a1d2607d5eb8a22c89dc7e8
joshmreesjones/algorithms
/book-problems/clrs/2/2.1-2.py
449
4.0625
4
# 2.1-2 # Rewrite the INSERTION-SORT procedure to sort into nonincreasing instead of nondecreasing order. def insertion_sort_descending(array): for j in range(0, len(array)): data = array[j] i = j - 1 while i >= 0 and data > array[i]: array[i + 1] = array[i] i -= 1 array[i + 1] = data A = [31, 41, 59, 26, 41, 58] insertion_sort_descending(A) print(A) # prints [59, 58, 41, 41, 31, 26]
2f3cca57b8047a14d6786c3b3c88640e05833c98
MatheusFidelisPE/ProgramasPython
/exercicioscursoemvideo/ex004.py
380
4.09375
4
analise=input('Digite algo para caracteliza-lo:') espaco=analise.isspace() print('A string é composta só por espaço--->', espaco) decimal=analise.isdecimal() print('A string é um decimal--->',decimal) maiusculas=analise.isupper() print('A string esta em maiuscula--->', maiusculas) capitalizada=analise.istitle() print('A string esta capitalizada--->{}'.format(capitalizada))
c47b8d567c062d1499d482615835f736455241f4
Arjune-Ram-Kumar-M-Github/FreeCodeCamp.org-Dynamic-Programming--Algorithmic-Problems-Coding-Challenges-Python-Solutions
/Dyanamic_Recursion_Bestsum.py
751
3.65625
4
# Time Complexity - O(m*n) # Space Complexity - O(m) def bestSum(targetNumber,numbers,memo={}): if targetNumber in memo: return memo[targetNumber] if targetNumber == 0: return [] if targetNumber < 0: return None shortestCombination = None for i in numbers: remainder = targetNumber - i combination = bestSum(remainder,numbers) if combination != None: combination.append(i) if (shortestCombination == None) or (len(shortestCombination) > len(combination)): shortestCombination = combination memo[targetNumber] = shortestCombination return shortestCombination print(bestSum(100,[5,3,4,7]))
0e2972971cf99869562af6632f79f59fc6e05cf1
DSM9606/Martin.Rocks.Paper.Excercise
/game.py
2,549
4.21875
4
# game.py import random import os import dotenv dotenv.load_dotenv() PLAYER_NAME = os.getenv("PLAYER_NAME") print(" ") print(" ") print(" ") print(" ") print("Player ", PLAYER_NAME," WELCOME TO Rock, Paper, Scissors, Shoot!") print(" ") print(" ") print(" ") print(" ") user_choice = input("Please choose one of 'rock', 'paper', 'scissors' : ") print(" ") print(" ") print(" ") print(" ") print(PLAYER_NAME, "'s Choice: ", user_choice) print(" ") print(" ") print(" ") print(" ") if (user_choice == "rock") or (user_choice == "paper") or (user_choice == "scissors"): print(PLAYER_NAME, "It looks like your choice,",user_choice,", is a valid choice!! SO LETS KEEP ON GOING!!") else: print(PLAYER_NAME, "INVALID CHOICE PLEASE PLAY AGAIN AND REMEMBER THE INPUTS ARE CASE SENSITIVE!!") exit() print(" ") print(" ") print(" ") print(" ") valid_options = ("rock", "paper", "scissors") computer_choice = random.choice(valid_options) print("Computer Choice: ", computer_choice) # Notes # because we are using the " or " operator in line 9 if any of the conditions are true the whole statement will be true # if we use the " and " operator in line 9, ALL of the statements will need to be true to yield a true output # one = sign means you are assigning a value # two == signs mean that you are asking if one equals the other with a true or false output print(" ") print(" ") print(" ") print(" ") if computer_choice == user_choice: print(PLAYER_NAME, "It's a Tie!!, What a Coincidence!!") elif computer_choice == "rock" and user_choice == "paper": print(PLAYER_NAME, "Congratulations You Won!! , Paper Covers Rock!! ") elif computer_choice == "rock" and user_choice == "scissors": print(PLAYER_NAME, "OH NO THE COMPUTER WON THIS ROUND!! - Rock Crushes Scissors!!") elif computer_choice == "paper" and user_choice == "rock": print(PLAYER_NAME, "OH NO THE COMPUTER WON THIS ROUND!! - Paper covers Rock") elif computer_choice == "paper" and user_choice == "scissors": print(PLAYER_NAME, "Congratulations You Won!! , Scissors cut Paper!! ") elif computer_choice == "scissors" and user_choice == "paper": print(PLAYER_NAME, "OH NO THE COMPUTER WON THIS ROUND!! - Scissors cut Paper!! " ) elif computer_choice == "scissors" and user_choice == "rock": print(PLAYER_NAME, "Congratulations You Won!! , Rock Crushes Scissors!! ") print(" ") print(" ") print(" ") print(" ") print(PLAYER_NAME, "THIS IS THE END OF OUR GAME!! THANK YOU FOR PLAYING, PLEASE PLAY AGAIN!!") print(" ") print(" ") print(" ")
34aac1c327b05e1889f0acfd76b03dc8db17774c
hyeon21-p/python
/Pycharm/HelloPycharm/sequence.py
533
3.875
4
string = "Hello World" list = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] tuple = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd') print(string[0]) print(list[0]) print(tuple[0]) print(string[0:5]) print(list[0:5]) print(tuple[0:5]) for i in string: print(i) string1 = "Hello World" string2 = ", Python" print(string1 + string2) #len: 길이 출력 print(len(string1 + string2)) #반복문 등에서 사용 가능 list = [1,2,3,4,5] print(4 in list) #True if 3 in list: print("3을 포함하고 있습니다.")
2d8c21dde3f4673450e59847d5e20231a5013005
cannium/leetcode
/valid-palindrome.py
445
3.796875
4
class Solution: # @param s, a string # @return a boolean def isPalindrome(self, s): s = ''.join([l if l.isalpha() or l.isdigit() else '' for l in s.lower()]) for i in range(0, (len(s)+1)/2): if s[i] != s[len(s)-1-i]: return False return True t1 = Solution() print t1.isPalindrome("A man, a plan, a canal: Panama") print t1.isPalindrome("race a car") print t1.isPalindrome('1a2')
a767a6b151d5318b77815e3616c517a5c57baba0
ysandeep999/fads-nltk-villy-2014
/fads 2104/test.py
329
3.734375
4
def achr(sents): x = "" for word in sents: x = x + "".join(word[-1]) return x.lower() def main(): txt = ["RANDOM", "ACESS", "MEMORY"] outp = achr(txt).lower() print(outp) main()
e61e9280dc9ad6e8bb9c161e2b0d0a768404e0c1
mjgutierrezo/MCOC-Nivelaci-n-
/23082019/001224.py
575
3.765625
4
# -*- coding: utf-8 -*- """ Ejercicio propuesto """ from numpy import * #001224 given_list = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7] #se quiere obtener la suma de sólo los números negativos de la lista total = 0 i = 0 while i < len(given_list): #primera condición: que el índice pertenezca a la lista if given_list[i] < 0: #que elemento sea negativo total += given_list[i] #suma acumulada i += 1 #modificar variable estudiada en el ciclo para continuar print (total) #retorna la suma total de elementos que cumplían condición
01eaa7031e0725f595519adf6ea4d592f67b690e
gtang31/algorithms
/tree/heap.py
3,548
4.1875
4
""" Implementation of min/max heap from a List. A heap is essentially a binary tree where the root node is either the min/max value in the tree. Heaps are usually used for priority queues where access to min/max is O(1) """ __author__ = 'Gary Tang' class Heap(): def __init__(self, from_list, type='min'): """ @param from_list: list[int]. List to turn into a heap @param type: string. Option to specify heap type """ if len(from_list) <= 1: return from_list if type.lower() in ('min', 'max'): self._type = type.lower() else: print('>>> Defaulting to min heap.') self._type = type self._construct(from_list) def _construct(self, from_list): """ Construct heap from a list. We can use some arithmetic to """ self._heap_list = [0] for idx, i in enumerate(from_list): self.insert(i) def insert(self, key): """ insert key into end of heap. Maintain heap integrity by "bubbling" it up into its correct position in the heap. """ self._heap_list.append(key) idx = len(self._heap_list)-1 while idx > 1: # compare current node to its parent if (self._heap_list[idx] < self._heap_list[idx//2]) and (self._type == 'min'): self._heap_list[idx], self._heap_list[idx//2] = self._heap_list[idx//2], self._heap_list[idx] elif (self._heap_list[idx] > self._heap_list[idx//2]) and (self._type == 'max'): self._heap_list[idx], self._heap_list[idx//2] = self._heap_list[idx//2], self._heap_list[idx] else: # no swaps needed return idx //= 2 def extract(self): """ Remove root from heap. And then re-org heap integrity @return: Int. Either smallest/largest of the heap. """ # swap last element with root self._heap_list[1], self._heap_list[-1] = self._heap_list[-1], self._heap_list[1] root = self._heap_list.pop() idx = 1 # bubble the new root down to its proper position in the heap while idx < len(self._heap_list)-1: # -2 due to 0th element being a filler value if idx*2 > len(self._heap_list): return root child_idx = self._get_child(idx) if (self._type == 'min' and self._heap_list[idx] >= self._heap_list[child_idx]) or (self._type == 'max' and self._heap_list[idx] <= self._heap_list[child_idx]): self._heap_list[idx], self._heap_list[child_idx] = self._heap_list[child_idx], self._heap_list[idx] idx = child_idx return root def _get_child(self, parent_idx): """ helper function that compares child keys and return the index of the min/max """ if parent_idx*2 == len(self._heap_list)-1: return parent_idx*2 else: if self._type == 'min': # return idx of smallest child if self._heap_list[parent_idx*2] <= self._heap_list[parent_idx*2+1]: return parent_idx*2 else: return parent_idx*2+1 elif self._type == 'max': # return idx of largest child if self._heap_list[parent_idx*2] > self._heap_list[parent_idx*2+1]: return parent_idx*2 else: return parent_idx*2+1
79ccf1726b75dd59bfc9d1b088266136f92b7718
Bit4z/python
/new_python/abc.py
156
3.84375
4
def fun(a,b): return a+b n=int(input("enter the first value=")) m=int(input("enter the second value=")) c=fun(n,m) print("the sum of value=",c)
e8059bbb5394ec7ed9fec0bd5e37d414e1121d4f
chenshanghao/LeetCode_learning
/Problem_314/learning_solution.py
1,123
3.875
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ from collections import deque from collections import defaultdict class Solution: """ @param root: the root of tree @return: the vertical order traversal """ def verticalOrder(self, root): # write your code here res = [] if not root: return res dic_Pos_List = defaultdict(list) leftMost, rightMost = 0, 0 queue = deque() queue.append((root, 0)) while queue: node, pos = queue.popleft() dic_Pos_List[pos].append(node.val) if node.left: queue.append((node.left, pos-1)) leftMost = min(leftMost, pos-1) if node.right: queue.append((node.right, pos+1)) rightMost = max(rightMost, pos+1) for pos in range(leftMost, rightMost+1): res.append(dic_Pos_List[pos]) return res
4efacd1075e46c954a54a79cff2ba17ca92aed26
jclavelli89/The-Tech-Academy-Course-Work
/Python/sorting_algorithms.py
9,119
3.953125
4
# Bubblesort ''' def bubblesort(alist): for passnum in range(len(alist) -1, 0, -1): for i in range(passnum): if alist[i] > alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = [67, 45, 2, 13, 1, 998] bubblesort(alist) print(alist) # I want to explain this so I can prove that I understand it: ''' ''' In the global framework are alist and bubblesort(alist). Inside of bubblesort you have a for loop where passnum iterates through the length of alist, which goes from 0 - 5, as there are 6 elements in alist. There is n - 1 pairs of items that need to be compared in order to sort the list since one of these elements will be comparing and it will not compare to itself, it will compare n - 1 times until the largest number in the list is sorted into its proper place. So, you take passnum in range(len(alist) -1, 0, 01): This means that the list begins at -1 of its total, which is 5 elements, because it will sort through 5/6 of the elements to sort the largest out. This will step at -1, because each time an element is properly sorted you will no longer need to sort through that element and there is one less pair to compare. It stops at 0 when there are no longer comparisons needed to be made. Then, for i in range(passnum): i represents the number being compared to the next number In this case the first number is 67 and it is being compared to 45. If in this scenario i is greater than i + 1 (+ 1 meaning + 1 position) which is 45 in this list, then the 67 moves on to compare itself to the next element. Then temp is equal to alist[i] , in this case during the first pass through, is 67. alist[i] becomes equal to alist[i + 1] and moves into that position, while alist[i+1] which in this case is 45 becomes equal to temp which is i and thus the first element in the list, effectively moving 67 into position 1 and 45 into position 0. The nested for loop then continues and i ''' ''' # Selection Sort def selectionSort(alist): for fillslot in range(len(alist)-1,0,-1): positionOfMax=0 for location in range(1,fillslot+1): if alist[location]>alist[positionOfMax]: positionOfMax = location temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp alist = [67, 45, 2, 13, 1, 998] selectionSort(alist) print(alist) # I want to explain this so I can prove that I understand it: ''' ''' In the global framework is alist and selectionsort(alist). Next a For Loop is created so that we can begin checking each position in alist. Then we define positionofMax and set it to position 0. Then we create a nested For Loop that begins with location at position 1 and is always just ahead of postionofMax, then a conditional expression states that if alist[location] is > than alist[positionOfMax] than positionOfMax becomes equal to location, which puts positionOfMax into the next position in the list. If this is true: Then a temp variable is created that is equal to alist[fillslot] which is set equal to alist[positionofmax], this puts alist[filsslot] into temp and alist[positionofmax] into the fillslot position], ultimately switching to the next position in the list. If false it moves to the next postion to then compare positionOfMax to fillslot+1. This Nested For Loop continues until the largest number is moved to the end of the list, triggering the next move in the original for loop which continues until all numebrs are sorted. This differs from a bubbleSort because bubbleSort only passes through two positions then starts again, continually restarting after two positions are switched. The Selectsion Sort moves the largest number to the end on the first pass through, and then on and on until the list is properly sorted. ''' ''' # The insertion Sort def insertionSort(alist): for index in range(1, len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position - 1 alist[position]=currentvalue alist = [67, 45, 2, 13, 1, 998] insertionSort(alist) print(alist) # I want to explain this so I can prove that I understand it: ''' ''' We begin by putting alist and insertionSort(alist) in the global framework below the insertionSort function. Defining inserionSort(alist): For index in range(1, len(alist)): means index begins at position 1, as position 0 is assumed to equal itself. currentvalue = alist[index] so begins the loop at the value of position 1, 45. Currentvalue is 45. position is then set equal to index, which is 1 for position 1. Then a nested while loop states that while this condition is met, postion>0 and alist[position-1] > currentValue alist[position] alist[position-1] making position = position -1 which then when the loop runs again the condition is no longer met, thus you go to the next code which sets postion (now 0) to currentvalue, 26, putting 45 which is less than 67 making them swap positions and you move on to the next position in index in the for loop. Anytime the next index is greater than the preceding one the For Loop continues, once it does not it kicks in the while loop again which, when position dwindles down and finds the proper place for the element. ''' ''' # The shell sort def shellSort(alist): sublistcount = len(alist)//2 while sublistcount > 0: for startposition in range(sublistcount): gapInsertionSort(alist,startposition,sublistcount) print("After increments of size", sublistcount, "The list is", alist) sublistcount = sublistcount // 2 def gapInsertionSort(alist, start, gap): for i in range(start+gap, len(alist), gap): currentvalue = alist[i] position = i while position>=gap and alist[position-gap]>currentvalue: alist[position]=alist[position-gap] position = position-gap alist[position]=currentvalue alist = [67, 45, 2, 13, 1, 998] shellSort(alist) print(alist) # I want to explain this so I can prove that I understand it: ''' ''' You start off by writing alist and shellSort(alist) in your global framework. Eventually gapInsertionSort will also be global. You define a variable within shellSort called sublistcount = len(alist)//2 which divides the length by 2 but doesn't leave a float, only an int. The while loop kicks in as long as sublist count is > 0. Your range is now 3, you utliize the gapInsertionSort function which is: for i in range(start+gap which is the step, then len(alist) and the gap which is = to sublistcount). Then they are compared again to one another in the nested while loop, swapping their positions based on the conditions in the loop. ''' ''' # The Merge Sort def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",alist) alist = [67, 45, 2, 13, 1, 998] mergeSort(alist) print(alist) # I want to explain this so I can prove that I understand it: ''' ''' alist and mergeSort(alist) are in the global framewotk. mergeSort starts by printing "Splitting " and interpolating alist. Then it splits the halves in two and continues until all values are seperated. They all become split into individual elements and then as they merge they sort into proper size order. ''' # The Quick Sort def quickSort(alist): quickSortHelper(alist,0,len(alist)-1) def quickSortHelper(alist,first,last): if first<last: splitpoint = partition(alist,first,last) quickSortHelper(alist,first,splitpoint-1) quickSortHelper(alist,splitpoint+1,last) def partition(alist,first,last): pivotvalue = alist[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and alist[leftmark] <= pivotvalue: leftmark = leftmark + 1 while alist[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: done = True else: temp = alist[leftmark] alist[leftmark] = alist[rightmark] alist[rightmark] = temp temp = alist[first] alist[first] = alist[rightmark] alist[rightmark] = temp return rightmark alist = [67, 45, 2, 13, 1, 998] quickSort(alist) print(alist)
b8252a68dcee907495057b7aa601f4925efd75dd
NoTyOuRDevil/phone-number-detail
/phonenum.py
843
3.90625
4
import phonenumbers from phonenumbers import carrier, geocoder, timezone mobileNo = input("Enter your number: ") print(''' AVAILABEL COUNTRIES FOR THIS APPLICATION INDIA, AMERICA, SRI LANKA ''') cn = input("Enter your country name: ") country_name = cn.upper() if country_name == "INDIA": mobileNo = "+91" + mobileNo if country_name == "AMERICA": mobileNo = "+1" + mobileNo if country_name == "SRI LANKA": mobileNo = "94" + mobileNo mobileNo = phonenumbers.parse(mobileNo) print(timezone.time_zones_for_number(mobileNo)) print(carrier.name_for_number(mobileNo, "en")) print(geocoder.description_for_number(mobileNo, "en")) print('Valid Mobile number: ',phonenumbers.is_valid_number(mobileNo)) print("Checking possibility for number: ", phonenumbers.is_possible_number(mobileNo))
004b22a73911c8045f7df5d3a548b2162b88b0bd
petiatodorova/PythonFundamentals
/exam_preparation/task_2.py
1,528
3.671875
4
first_list = list(map(int, input().split())) command = input() results = [] while not command == "END": nums = first_list commands_line = command.split() if len(commands_line) == 3 and commands_line[0] == "multiply": # OK if not commands_line[1].isdigit(): new = [] n = int(commands_line[2]) for el in nums: for m in range(n): new.append(el) results.extend(new) else: # OK element = int(commands_line[1]) n = int(commands_line[2]) new = [] for el in nums: if el == element: new.append(el * n) results.extend(new) elif len(commands_line) == 2: # OK if commands_line[0] == "contains": num_to_check = int(commands_line[1]) if nums.__contains__(num_to_check): results.append("True") else: results.append("False") elif commands_line[0] == "add": if commands_line[1].isdigit(): # OK results.append(commands_line[1]) else: '''{add} {n} – you should add n, where n could be a single integer OR another list of integers (if n is a list it would be separated by ‘,’)''' results.extend(commands_line[1].split(",")) command = input() print(results) for el in results: print(el, end=" ")
835915e21e79f5c923b4eb97780f4f3b605e7729
JonCanales/PyGame-Car-App
/border.py
4,183
3.75
4
#Here in this file we are able to create a border that if crossed the game will crash. #Also holding down the left and right keys will keep on moving instead of just pressing it once at a time like the display.py program. import pygame import time import random pygame.font.init() pygame.init() #Here we created our constants we dont intend to change display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) #This variable tells where the cars edges will be. The location #just means the top left pixel of the car. This tells the right side as well. car_width = 73 ############################################################################ gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('A bit Racey') clock = pygame.time.Clock() carImg = pygame.image.load('racecar.png') #Takes x and Y starting points,wifth and height variables and a color def things(thingx,thingy,thingw,thingh,color): #Then draws the polygon. The parameters are where,what color,and x and y locations pygame.draw.rect(gameDisplay,color,[thingx,thingy,thingw,thingh]) def car(x,y): gameDisplay.blit(carImg,(x,y)) def text_objects(text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() #Made own function to display text onto screen. #Defines Text and Rectangle that will encompass it.Centers the text.THen blits onto surface. Then updates it. def message_display(text): largeText = pygame.font.Font('freesansbold.ttf',115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(1) game_loop() def crash(): message_display('You Crashed') def game_loop(): x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 ###### #Starting position is random if its in x range between 0 and width of display thing_startx = random.randrange(0, display_width) #starting position for starty. GIves player time to get situated before it comes into view thing_starty = -600 #Object Speed(How many pixels at a time it will move). 7 pixels it will move. thing_speed = 7 #Blocks width and height thing_width = 100 thing_height = 100 ###### gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 if event.key == pygame.K_RIGHT: x_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change gameDisplay.fill(white) things(thing_startx,thing_starty,thing_width,thing_height,black) thing_starty += thing_speed car(x,y) #The logic for whether or not the car has crossed any boundaries left or right. if x > display_width - car_width or x < 0: crash() #WHen thingy's location is greater then the display hight it will create another block if thing_starty > display_height: #Reassign a yvalue to the block where we use 0 -thing_height. thing_starty = 0 - thing_height #Refine the x-position of the block with a range between 0 and entire width of display thing_startx = random.randrange(0,display_width) if y < thing_starty + display_height: print('y crossover') if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx+thing_width: print('x crossover') crash() pygame.display.update() clock.tick(60) #Runs Gameloop and once its done it will run the pygame.quit and crash and quit the game. game_loop()
15fb5b8e2b792bdef30e541372a2eeef84bfb19b
SharonGoldi/graph-algorithms
/Graph.py
3,259
3.640625
4
from collections import defaultdict # a general class for a directed graph class Graph: def __init__(self, num_of_vertex): self.V = num_of_vertex self.graph = defaultdict(list) self.weights = defaultdict(list) self.positive_w = True # add edge into the graph def add_edge(self, s, d, w=1): self.graph[s].append(d) self.weights[s,d].append(w) if w < 0 and self.positive_w: self.positive_w = False # transpose the edge matrix def transpose(self): g = Graph(self.V) for i in self.graph: for j in self.graph[i]: g.add_edge(j, i) return g # the recursive dfs inner func def __dfs(self, d, visited, vertex_ordered_i, vertex_ordered_f, print_forest): visited[d] = True vertex_ordered_i.append(d) for u in self.graph[d]: if not visited[u]: if print_forest: print(d, '->', u, ' ') self.__dfs(u, visited) vertex_ordered_f.append(d) return vertex_ordered_i, vertex_ordered_f # returns the vertex in the dfs order, if wanted prints the dfs forest def dfs(self, d=0, print_forest=True): visited = [False] * self.V vertex_ordered_i = [] vertex_ordered_f = [] self.__dfs(d, visited, vertex_ordered_i, vertex_ordered_f, print_forest) return vertex_ordered_i, vertex_ordered_f # returns the vertex in the bfs order, if wanted prints the bfs tree def bfs(self, d, print_tree): visited = [False] * self.V queue = [] vertex_ordered = [] visited[d] = True queue.append(d) vertex_ordered.append(d) while queue: u = queue.pop() vertex_ordered.append(u) for v in self.graph[u]: if not visited[v]: queue.append(v) visited[v] = True if print_tree: print(u, '->', v, ' ') return vertex_ordered # returns the scc, if wanted, prints the SCC - O(V+E) def scc(self, print_scc=True): scc = [] dfs_order_i, dfs_order_f = self.dfs(0) g_transpose = self.transpose(0) visited = [False] * self.V while dfs_order_f: u = dfs_order_f.pop() if not visited[u]: i, f = g_transpose.__dfs(u, visited, [], [], print_scc) if print_scc: print("/") scc.append(f) return scc # returns the MST calced by Prim's algorithm, if wanted, prints it def mst_Prim(self): pass # returns the MST calced by Kruskal's algorithm, if wanted, prints it def mst_Kruskal(self): pass # returns the shortest path from u to v and its weight calced using Dijkstra, if wanted, prints it def shortest_path_Dijkstra(self, u, v): pass # returns the shortest path from u to v and its weight calced by Bellman Ford, if wanted, prints it def shortest_path_Bellman_Ford(self, u, v): pass # returns a matrix of all pairs shortest paths calced by Johnson algorithm def apsp(self): pass
8c08c2e75da73309653061f89531a34c2b225ade
Eduardo-Goulart/SistemasOperacionais_TempoReal
/Threads/Threads.py
1,461
3.65625
4
from threading import Thread, Lock import time import sys class Trehdis ( Thread ): def __init__(self, id, func, rep = 1 ): Thread.__init__(self) self.mutex = Lock() self.rep = rep self.id = id self.f = func def run (self): num_cycles = self.rep num = 0 self.time_begin = time.time() for i in range(num_cycles): with self.mutex: result = self.f( num ) sys.stdout.write( "Thread %s : %d \n" %( self.id, result ) ) num += 1 self.time_finished = time.time() self.time_accumulated = (self.time_finished - self.time_begin) # Importante para não acessar arquivos compartilhados with self.mutex: sys.stdout.write("Finalizados os ciclos da thread: %s -> Tempo %2.5f \n" %(self.id, self.time_accumulated) ) # Criamos a função que será usada na Thread def dobro ( num ): return 2*num # Numero de threads que serão usadas NUM_THREADS = 500 # Função main para teste if __name__ == "__main__": threads = [] for i in range(NUM_THREADS): t = Trehdis("["+str(i)+"]", dobro, 10 ) t.start() threads.append(t) media = 0 val = [] for t in threads: t.join() val.append(t.time_accumulated) media = sum(val)/NUM_THREADS print("Jitter médio das threads = " + str(media) )
711b47daf5f8754aeb709bb9803307a7f946c87f
candyer/leetcode
/May LeetCoding Challenge/04_findComplement.py
1,126
3.640625
4
# https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3319/ # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), # and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), # and its complement is 0. So you need to output 0. # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/ def findComplement(num: int) -> int: if num == 0: return 1 return pow(2, (num.bit_length())) - 1 - num assert(findComplement(0) == 1) assert(findComplement(1) == 0) assert(findComplement(3) == 0) assert(findComplement(6) == 1) assert(findComplement(13) == 2)
fc234eeb4f0be781b39e6d126bbaf96a08914b44
metallic-tiger/StudenPython
/2.像界面tkinter学习/控件/1.windown窗口.py
757
3.8125
4
#!/usr/bin/python3 # -*- coding: UTF-8 -*- #1.引入Tk模块 import tkinter #建立窗口类 windown=tkinter.Tk() windown.title('显示在窗口上的标题') windown.geometry('600x400')#窗口的长和宽 windown.attributes('-alpha',0.9)#设置窗口透明度为50% 似乎无效 def command(): windown.quit()#退出消息循环 按钮=tkinter.Button(windown,text="按钮上显示的文字:退出",command =command) 按钮.place(x=200,y=200) #显示窗口以及在这个上面的控件 #进入消息循环 消息循环只会执行设置好的消息内容 #例如 按钮的点击等等 windown.mainloop() windown.destroy()#销毁窗口 #点击 x 标示退出也算退出消息循环 print('退出窗口之后执行的语句')
384bc953ac14ed476e7a1fe552583462bb883e5f
ricardoquesada/aiamsori
/gamelib/waypointing.py
6,088
3.5
4
""" Waypointing doing: un poco de test heuristicos para debugear. considerando mejorar algunas cosas, hay partes bastante brute force """ ##FLOYD'S ALGORITHM (int **m, int size) ##{ ## int i,j,k; ## for ( k = 0; k < size; k++ ) ## for ( i = 0; i < size; i++ ) ## for ( j = 0; j < size; j++ ) ## if ( m[i][k] + m[k][j] < m[i][j] ) ## m[i][j] = m[i][k] + m[k][j]; ##} import math from cocos.euclid import Vector2 as V2 bignum = 1.0e+40 class WaypointNav: def __init__(self,points,fn_visibles): """ points: waypoints; all points in the map should have at least one waypoint in sight fn_visibles(a,b) True if point b is visible from point a Interfase Stateless: .get_dest(a,b): give a good intermediate point for going from a to b warn: it is better to use the voucher interfase InterfaseVoucher: ( talk to the voucher object to navigate ) CreateVoucherChase( chaser_actor, chaser_pos_getter, target_actor, target_pos_getter ) CreateVoucherMoveTo( actor, actor_pos_getter, target_point) Later crowding info can be available. """ self.fn_visibles = fn_visibles self.points = [V2(x,y) for x,y in points] self.min_dist = {} self.adj = [] # adj[i] -> list of nodes directly reacheables from i self._init_min_dist() self._floyd() def _init_min_dist(self): """ builds the graph, joining those points with clear line of sight calcs the 1 step distance for each pair (bignum if not in sight) """ points = self.points n = len(points) fn = self.fn_visibles m = self.min_dist for j in xrange(n): adj_j = [] for i in xrange(n): if i==j: m[i,j]=0 continue ix0, jx0 = i,j if fn(points[i],points[j]): ix1, jx1 = i,j assert((points[ix0]==points[ix1]) and (points[jx0]==points[jx1])) m[i,j] = abs(points[i]-points[j]) adj_j.append(i) else: m[i,j] = bignum self.adj.append(adj_j) def _floyd(self): """ knowing the distance between adjacents, the Floyd-Warshalls algo calcs the min distance between any two pair of nodes. O(n^3) """ n = len(self.points) m = self.min_dist for k in xrange(n): for i in xrange(n): for j in xrange(n): if ( m[i,k] + m[k,j] < m[i,j] ): m[i,j] = m[i,k] + m[k,j] def _next_waypoint(self,i,j): """ returns the next index in a minimal path from i to j , i if i==j """ if i==j: return i dmin = self.min_dist[i,j] for k in self.adj[i]: # the first that allow min dist is as good as anyother if abs(dmin-(abs(self.points[i]-self.points[k])+self.min_dist[k,j]))<1.0e-4: return k #must not get there #assert(0) #TODO: remove for release return i def get_near_wps(self,a): if not isinstance(a,V2): a = V2(a[0],a[1]) #get 3 ( if posible ) waypoints near a points = self.points lia = [(abs(a-p),i) for i,p in enumerate(points)] lia.sort() cnt = 0; candidates_a = [] for d,i in lia: if self.fn_visibles(a, points[i]): candidates_a.append(i) cnt += 1 if cnt>=1: break return candidates_a if not len(candidates_a): #print '*** WARNING: no waypoint near', a return a def best_pair(self, a, candidates_a, b, candidates_b): paths = [] for i in candidates_a: for j in candidates_b: kpath = (abs(a-self.points[i])+self.min_dist[i,j]+abs(self.points[j]-b), i,j) paths.append(kpath) paths.sort() d, i, j = paths[0] return d, i, j def get_path(self, a, b): a = self.points.index(a) b = self.points.index(b) return self.get_path_indexed(self, a, b) def get_path_indexed(self, a, b): path = [] path.append(a) while 1: a = self._next_waypoint(a,b) path.append(a) if a == b: break return path def get_dest(self, a, b): """ for direct use without voucher, inneficient. returns a point visible from a, in a good (short) route to b Basically will head to b if visible or to a waypoint in a minimal path from waypoint A near a to Waypoint B near b """ if not isinstance(a,V2): a = V2(a[0],a[1]) if not isinstance(b,V2): b = V2(b[0],b[1]) if self.fn_visibles(a,b): return b points = self.points #get 3 ( if posible ) waypoints near a candidates_a = self.get_near_wps(a) if not len(candidates_a): # print '*** WARNING: no waypoint near SOURCE', a return b #get 3 ( if posible ) waypoints near b candidates_b = self.get_near_wps(b) if not len(candidates_b): # print '*** WARNING: no waypoint near GOAL', b return b #choose the best combo d, i, j = self.best_pair( a, candidates_a, b, candidates_b) #advance in the waypoint route to b while waypoint is visible steps = 0 while 1: steps += 1 last_visible = i i = self._next_waypoint(i,j) if not self.fn_visibles(a,points[i]): break if i == j: break if steps > 10: break return points[last_visible]
df758878ad57a52d3decf4e39ca4ba08a427e229
krishnayash-T/Hacker-Rank
/Hacker Rank Solutions/Python/if-else.py
294
3.8125
4
if __name__ == '__main__': n = int(raw_input()) my_str="Weird" my_str2="Not Weird" if n%2==0: if 2<=n<=5: print(my_str2) if 6<=n<=20: print(my_str) if n>20: print(my_str2) else: print(my_str)
9a709b41c614f2b36cc4a628777eeaf16d96c365
campoloj/SoftwareDevelopment2016
/14/dealer/traitcard.py
5,038
3.640625
4
from globals import * class TraitCard(object): """ Represents a TraitCard of the Evolution game """ def __init__(self, trait, food_points=False): """ Craates a TraitCard :param trait: String representing the name of the TraitCard :param food_points: Integer representing the food points of the TraitCard :return: a TraitCard object """ self.trait = trait self.food_points = food_points def __eq__(self, other): return all([isinstance(other, TraitCard), self.trait == other.trait, self.food_points == other.food_points]) def __ne__(self, other): return not self.__eq__(other) def convert_to_json(self): """ Converts this TraitCard into a JSON Trait or SpeciesCard :return: a JSON Trait or SpeciesCard as specified by the data definitions at http://www.ccs.neu.edu/home/matthias/4500-s16/5.html and http://www.ccs.neu.edu/home/matthias/4500-s16/8.html, respectively. """ self.validate_attributes() return self.trait if self.food_points is False else [self.food_points, self.trait] @classmethod def validate_all_unique(cls, list_of_traitcard, total_deck): """ Validates the uniqueness of all TraitCards in the given list. :param list_of_traitcard: a list of TraitCard objects to be validated :param total_deck: a list of TraitCards representing all valid card possibilities :raise ValueError if duplicate cards exist """ for card in list_of_traitcard: card.validate_unique(total_deck) def validate_unique(self, total_deck): """ Validates this TraitCard by checking that it exists in the given deck of possible cards :param total_deck: a list of TraitCards representing all valid card possibilities :raise ValueError if card is not valid / a duplicate """ if self.food_points is not False: total_deck.remove(self) @classmethod def validate_all_attributes(cls, list_of_traitcard): """ Validates the attributes of all TraitCards in the given list :param list_of_traitcard: a list of TraitCard objects to be validated :raise AssertionError if any card attributes are out of bounds """ for card in list_of_traitcard: card.validate_attributes() def validate_attributes(self): """ Validates the attributes of this TraitCard :raise AssertionError if attributes are out of game bounds """ assert(isinstance(self.trait, basestring) and self.trait in TRAITS_LIST) if self.food_points is not False: assert(isinstance(self.food_points, int) and (CARN_FOOD_MIN <= self.food_points <= CARN_FOOD_MAX if self.trait == CARNIVORE else HERB_FOOD_MIN <= self.food_points <= HERB_FOOD_MAX)) def trait_to_json(self): """ Converts a TraitCard into a JSON Trait or SpeciesCard :param trait_card: a TraitCard object :return: a JSON Trait or SpeciesCard as specified by the data definitions at http://www.ccs.neu.edu/home/matthias/4500-s16/5.html and http://www.ccs.neu.edu/home/matthias/4500-s16/8.html, respectively. """ return '[%s, %d]' % (self.trait, self.food_points) @classmethod def show_all_changes(cls, traitcards_before, traitcards_after): """ Creates a string representation of the changed attributes between a list of TraitCards before and after an imperative function is called on it. :param traitcards_before: List of TraitCard before modification :param traitcards_after: List of TraitCard after modification :return: String of attribute changes, or "" if unchanged. """ if len(traitcards_before) < len(traitcards_after): new_cards = [CARD_TEMPLATE % (card.trait, card.food_points) for card in traitcards_after if card not in traitcards_before] return "new cards: %s" % ", ".join(new_cards) elif len(traitcards_before) > len(traitcards_after): removed_cards = [CARD_TEMPLATE % (card.trait, card.food_points) for card in traitcards_before if card not in traitcards_after] return "removed cards: %s" % ", ".join(removed_cards) else: changed_cards = [] for i in range(len(traitcards_before)): before, after = (traitcards_before[i], traitcards_after[i]) if before != after: changed_cards.append(CHANGE_TEMPLATE % (str(i), CARD_TEMPLATE % (before.trait, before.food_points), CARD_TEMPLATE % (after.trait, after.food_points))) return ", ".join(changed_cards) if changed_cards else ""
642909f7dc7cb10cf8b457f94a2ad85c1e67efc3
ummelen22/sudoku_solver
/src/solve_sudoku.py
2,989
3.96875
4
""" Solver for sudoku puzzels """ SUDOKU = [ [1, 0, 0, 0, 0, 0, 0, 0, 6], # . y [0, 0, 6, 0, 2, 0, 7, 0, 0], # .------------------> [7, 8, 9, 4, 5, 0, 1, 0, 3], # | [0, 0, 0, 8, 0, 7, 0, 0, 4], # | [0, 0, 0, 0, 3, 0, 0, 0, 0], # | [0, 9, 0, 0, 0, 4, 2, 0, 1], # x| [3, 1, 2, 9, 7, 0, 0, 4, 0], # | [0, 4, 0, 0, 1, 2, 0, 7, 8], # | [9, 0, 8, 0, 0, 0, 0, 0, 0], # V ] def is_valid(sudoku, x, y, number): """ Returns whether the provided number and location are a valid combination for the sudoku """ if sudoku[x][y] not in range(10): raise ValueError( f"The current value at [{x}, {y}] is {sudoku[x][y]}, which does not lay within the allowed sudoku values of 1-9" ) if number not in range(1, 10): raise ValueError(f"The suggested number {number} does not lay within the allowed sudoku values of 1-9") if sudoku[x][y] != 0: if sudoku[x][y] == number: return True else: return False # Check whether the number exists in the row if number in sudoku[x]: return False # Check whether the number exists in the column if number in [row[y] for row in sudoku]: return False # Check whether the number exists in the box search_range = dict() search_range['x'] = [(x // 3) * 3 + i for i in range(3)] search_range['y'] = [(y // 3) * 3 + i for i in range(3)] for search_x in search_range['x']: for search_y in search_range['y']: if sudoku[search_x][search_y] == number: return False return True def find_empty_cell(grid): """ Returns the first empty cell it finds in a 2D grid """ for x in range(len(grid)): for y in range(len(grid[0])): if grid[x][y] == 0: return x, y return None def _solve_sudoku(sudoku): """ Solver for sudoku's """ empty_cell = find_empty_cell(sudoku) if not empty_cell: return True x, y = empty_cell for number in range(1, 10): if is_valid(sudoku, x, y, number): sudoku[x][y] = number if _solve_sudoku(sudoku): return True sudoku[x][y] = 0 return False def print_sudoku_human_readable(sudoku): """ Prints the sudoku in a pretty fashion such that it is human readable """ sudoku_readable = [] horizontal = "+ - - - + - - - + - - - +" sudoku_readable.append(horizontal) for n, row in enumerate(sudoku): row_string_list = [str(num) for num in row] for i in [0, 4, 8, 12]: row_string_list.insert(i, "|") sudoku_readable.append(" ".join(row_string_list)) if n in [2, 5, 8]: sudoku_readable.append(horizontal) for row in sudoku_readable: print(row) if __name__ == "__main__": print_sudoku_human_readable(SUDOKU) _solve_sudoku(SUDOKU) print("-"*50) print_sudoku_human_readable(SUDOKU)
de499f4cb5c36d322c899ac2765fd4b4a2952ee1
mapleinsss/python-basic
/chapter4-流程控制/demo04-断言.py
310
4.25
4
''' 断言如果为 True 继续执行,否则抛出 AssertionError 其实等于 if 条件为 False: 抛出 AssertionError 错误 ''' s_age = input('请输入年龄:') age = int(s_age) assert 20 < age < 80 print('年龄在20到80之间') # 输入不在区间的数, AssertionError assert 20 < age < 80
b86dc033a4dab1dece11da3da88d5abcde1c5322
gaurav-singh-au16/Online-Judges
/Leet_Code_problems/1313.decompress_run_length.py
1,261
4.09375
4
""" 1313. Decompress Run-Length Encoded List Easy 357 690 Add to List Share We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Example 1: Input: nums = [1,2,3,4] Output: [2,4,4,4] Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. Example 2: Input: nums = [1,1,2,3] Output: [1,3,3] Constraints: 2 <= nums.length <= 100 nums.length % 2 == 0 1 <= nums[i] <= 100 Accepted 104,023 Submissions 121,953 """ def decompressRLElist(nums): n = len(nums) p1 = 0 p2 = 1 res = [] while p2 < n: while nums[p1] > 0: res.append(nums[p2]) nums[p1] -= 1 p1 += 2 p2 += 2 return res if __name__ == "__main__": nums = [1,2,3,4] print(decompressRLElist(nums))
913d93e2704c13b200ae984eab6f468f3706444e
scott75219/Python-Test
/problem.py
4,602
4.15625
4
# Python Test # You are given a matrix with m rows and n columns of cells, each of which # contains either 1 or 0. Two cells are said to be connected if they are # adjacent to each other horizontally, vertically, or diagonally. The connected # and filled (i.e. cells that contain a 1) cells form a region. There may be # several regions in the matrix. Find the number of cells in the largest region # in the matrix. # Input Format # There will be three parts of the input: # The first line will contain m, the number of rows in the matrix. # The second line will contain n, the number of columns in the matrix. # This will be followed by the matrix grid: the list of numbers that make up the matrix. # Output Format # Print the length of the largest region in the given matrix. # Constraints # 0<m<10 # 0<n<10 # Sample Input: # 4 # 4 # 1 1 0 0 # 0 1 1 0 # 0 0 1 0 # 1 0 0 0 # Sample Output: # 5 # Explanation # X X 0 0 # 0 X X 0 # 0 0 X 0 # 1 0 0 0 # The X characters indicate the largest connected component, as per the given # definition. There are five cells in this component. # Task: # Write the complete program to find the number of cells in the largest region. # You will need to read from stdin for the input and write to stdout for the output # If you are unfamiliar with what that means: # raw_input is a function that reads from stdin # print statements write to stdout # You are not required to use raw_input or print statements, but it is the # simplest and most common way to read and write to stdin/out # The test cases are located in the test-cases directory. # run-tests.py is not part of your test. It is simply a convenience program # that will test your code against all the test cases, one after another, and # then tell you whether it passed or failed, and what the expected and actual # outputs are. You may review and modify run-tests.py as much as you want, but # it will not score or lose you any points # Included in the top level directory are four "hard" test cases that are # square grids of side lengths 10, 25, 50, 100, and 1000 cells. These were # randomly generated using generate-hard-test-case.py, and they do not come # with an expected output. You may generate test cases of various dimensions # using generate-test-case.py, but the ability of your algorithm to solve extra # test cases you've created will not be considered in our evaluation of this # test. Your algorithm should be able to find a correct solution in a timely # manner up to the 100x100 grid. The 1000x1000 grid is "Extra Credit", as it # were. If you work out an algorithm that can solve the 1000x1000 grid, but it # takes more than 10 seconds to do so, please note that in a comment and let us # know when you e-mail us your finished product. All other test cases should # take your algorithm no more than 3 seconds. # Finally, you may not use third party libraries to complete this test. You # may only use the libraries available on a fresh Python 2.7 install. I doubt # you will need to use any libraries at all as this is just an algorithmic # challenge. import sys from sys import stdin from sys import stdout from StringIO import StringIO from array import array import pdb max=0 counter = 0 m = int(raw_input()) n = int(raw_input()) matrix =[] visted=[[None for x in range(n)] for y in range(m)] #initiaizing m x n array directions = [(0, 1), (0, -1), (1, 0),(1, 1),(1, -1),(-1, 0), (-1, 1), (-1, -1)] #Assigning what directions to go to for i in range(m): for j in range(n): visted[i][j]=0 #assigning all locations to visit to 0 for i in range(m): matrix.append(map(int, stdin.readline().strip().split(' '))) #Storing reference matrix by reading line by line and splitting by ' ' ##Find max area function########################################################################################## def Find(matrix, visted, x, y): global counter global max if x<0 or x>=m or y<0 or y>=n or visted[x][y] == 1 or matrix[x][y] == 0: #Checking to see if gone beyond constraints of matrix, if it has already been visted or if the current location is 0 return counter += 1 if counter > max: #Checking to see if the current counter is larger then the max, if so max= current counter max=counter visted[x][y] = matrix[x][y] for dir in directions: Find(matrix, visted, x+dir[0], y+dir[1]) ################################################################################################################### for i in range(m): for j in range(m): Find(matrix, visted, i, j) counter = 0 print max
2f10b1b8449d25bf6186a791d1de189a0a5af377
juffalow/advent-of-code
/2021/1/second_solution.py
354
3.5
4
import sys currentTriplet = [] increasesCount = 0 for line in sys.stdin: if len(currentTriplet) < 3: currentTriplet.append(int(line)) continue first = currentTriplet.pop(0) if sum(currentTriplet) + int(line) > sum(currentTriplet) + first: increasesCount += 1 currentTriplet.append(int(line)) print(increasesCount)
84b4c9f854c576fc1d0f42031922e0a1aa8cbb7f
andreplacet/reinforcement-python-tasks-functions
/exe11.py
189
3.765625
4
# Exercicio 11 from random import shuffle def embaralha(nome): a = list(nome) shuffle(a) a = ''.join(a) print(a.lower()) nome = input('Digite algo: ') embaralha(nome)
c670053a345fdc66c6c47f599f371fd1142018c7
openturns/openturns.github.io
/openturns/master/_downloads/ba246a25b1216656698aa5118fef31ef/plot_kolmogorov_distribution.py
5,619
4.03125
4
""" The Kolmogorov-Smirnov distribution =================================== """ # %% # %% # In this example, we draw the Kolmogorov-Smirnov distribution for a sample size 10. We want to test the hypothesis that this sample has the `Uniform(0,1)` distribution. The K.S. distribution is first plot in the case where the parameters of the Uniform distribution are known. Then we plot the distribution when the parameters of the Uniform distribution are estimated from the sample. # # *Reference* : Hovhannes Keutelian, "The Kolmogorov-Smirnov test when parameters are estimated from data", 30 April 1991, Fermilab # # There is a sign error in the paper; the equation: # ``` # D[i]=max(abs(S+step),D[i]) # ``` # must be replaced with # ``` # D[i]=max(abs(S-step),D[i]) # ``` # %% import openturns as ot import openturns.viewer as viewer from matplotlib import pylab as plt ot.Log.Show(ot.Log.NONE) # %% x=[0.9374, 0.7629, 0.4771, 0.5111, 0.8701, 0.0684, 0.7375, 0.5615, 0.2835, 0.2508] sample=ot.Sample([[xi] for xi in x]) # %% samplesize = sample.getSize() samplesize # %% # Plot the empirical distribution function. # %% graph = ot.UserDefined(sample).drawCDF() graph.setLegends(["Sample"]) curve = ot.Curve([0,1],[0,1]) curve.setLegend("Uniform") graph.add(curve) graph.setXTitle("X") graph.setTitle("Cumulated distribution function") view = viewer.View(graph) # %% # The computeKSStatisticsIndex function computes the Kolmogorov-Smirnov distance between the sample and the distribution. The following function is for teaching purposes only: use `FittingTest` for real applications. # %% def computeKSStatistics(sample,distribution): sample = sample.sort() n = sample.getSize() D = 0. index = -1 D_previous = 0. for i in range(n): F = distribution.computeCDF(sample[i]) Fminus = F - float(i)/n Fplus = float(i+1)/n - F D = max(Fminus,Fplus,D) if (D > D_previous): index = i D_previous = D return D # %% dist = ot.Uniform(0,1) dist # %% computeKSStatistics(sample,dist) # %% # The following function generates a sample of K.S. distances when the tested distribution is the `Uniform(0,1)` distribution. # %% def generateKSSampleKnownParameters(nrepeat,samplesize): """ nrepeat : Number of repetitions, size of the table samplesize : the size of each sample to generate from the Uniform distribution """ dist = ot.Uniform(0,1) D = ot.Sample(nrepeat,1) for i in range(nrepeat): sample = dist.getSample(samplesize) D[i,0] = computeKSStatistics(sample,dist) return D # %% # Generate a sample of KS distances. # %% nrepeat = 10000 # Size of the KS distances sample sampleD = generateKSSampleKnownParameters(nrepeat,samplesize) # %% # Compute exact Kolmogorov CDF. # %% def pKolmogorovPy(x): y=ot.DistFunc_pKolmogorov(samplesize,x[0]) return [y] # %% pKolmogorov = ot.PythonFunction(1,1,pKolmogorovPy) # %% def dKolmogorov(x,samplesize): """ Compute Kolmogorov PDF for given x. x : an array, the points where the PDF must be evaluated samplesize : the size of the sample Reference Numerical Derivatives in Scilab, Michael Baudin, May 2009 """ n=x.getSize() y=ot.Sample(n,1) for i in range(n): y[i,0] = pKolmogorov.gradient(x[i])[0,0] return y # %% def linearSample(xmin,xmax,npoints): '''Returns a sample created from a regular grid from xmin to xmax with npoints points.''' step = (xmax-xmin)/(npoints-1) rg = ot.RegularGrid(xmin, step, npoints) vertices = rg.getVertices() return vertices # %% n = 1000 # Number of points in the plot s = linearSample(0.001,0.999,n) y = dKolmogorov(s,samplesize) # %% curve = ot.Curve(s,y) curve.setLegend("Exact distribution") graph = ot.HistogramFactory().build(sampleD).drawPDF() graph.setLegends(["Empirical distribution"]) graph.add(curve) graph.setTitle("Kolmogorov-Smirnov distribution (known parameters)") graph.setXTitle("KS-Statistics") view = viewer.View(graph) # %% # Known parameters versus estimated parameters # -------------------------------------------- # %% # The following function generates a sample of K.S. distances when the tested distribution is the `Uniform(a,b)` distribution, where the `a` and `b` parameters are estimated from the sample. # %% def generateKSSampleEstimatedParameters(nrepeat,samplesize): """ nrepeat : Number of repetitions, size of the table samplesize : the size of each sample to generate from the Uniform distribution """ distfactory = ot.UniformFactory() refdist = ot.Uniform(0,1) D = ot.Sample(nrepeat,1) for i in range(nrepeat): sample = refdist.getSample(samplesize) trialdist = distfactory.build(sample) D[i,0] = computeKSStatistics(sample,trialdist) return D # %% # Generate a sample of KS distances. # %% sampleDP = generateKSSampleEstimatedParameters(nrepeat,samplesize) # %% graph = ot.KernelSmoothing().build(sampleD).drawPDF() graph.setLegends(["Known parameters"]) graphP = ot.KernelSmoothing().build(sampleDP).drawPDF() graphP.setLegends(["Estimated parameters"]) graphP.setColors(["blue"]) graph.add(graphP) graph.setTitle("Kolmogorov-Smirnov distribution") graph.setXTitle("KS-Statistics") view = viewer.View(graph) plt.show() # %% # We see that the distribution of the KS distances when the parameters are estimated is shifted towards the left: smaller distances occur more often. This is a consequence of the fact that the estimated parameters tend to make the estimated distribution closer to the empirical sample.
c86f7526ea58a0d3469781a9cecf2e3d4585bb2d
dreamroshan/Python-1
/1.Arrays/07.Longest_Peak.py
2,022
4.15625
4
''' LONGEST PEAK PROBLEM STATEMENT: Write a function that takes array of integers and returns the length of the longest peak in the array. A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip(the highest value in the peak) at which point they become strictly decreasing.At least three integers are required to form a peak. For Example,the integers 1,4,10,2 form a peak,but the integers 4,0,10 don't and neither do the integers 1,2,2,0. Similarly,the integers 1,2,3 don't form a peak because there aren't any strictly decreasing integers after the 3. Sample Input : array = [1,2,3,4,0,10,6,5,-1,-3,2,3] Sample Output : 6 // 0,10,6,5,-1,-3 ''' def longestPeak(array): longestPeakLen = 0 i = 1 while i < len(array) - 1: isPeak = array[i - 1] < array[i] > array[i + 1] if not isPeak: i += 1 continue leftIdx = i - 2 while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]: leftIdx -= 1 rightIdx = i + 2 while rightIdx < len(array) and array[rightIdx - 1] > array[rightIdx]: rightIdx += 1 currentPeakLen = rightIdx - leftIdx - 1 longestPeakLen = max(longestPeakLen, currentPeakLen) i = rightIdx return longestPeakLen # My solution small def longestpeak(arr): i = 1 peak_index = [] longest_peak = 0 for i in range(1,len(arr)-1): ispeak = arr[i-1] < arr[i] > arr[i+1] if ispeak: peak_index.append(i) for i in peak_index: k,j=i,i left_count,right_count = 0,0 while(k!= 0 and arr[k] > arr[k-1]): k -= 1 left_count += 1 while(j!=len(arr)-1 and arr[j] > arr[j+1]): j +=1 right_count += 1 curr_peak_len = left_count+right_count+1 longest_peak=max(curr_peak_len,longest_peak) return longest_peak print(longestpeak([1,2,3,5,4]))
4264beb57a2d6d23edd036bc7dfeb389333d862d
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/web-dev-notes-resource-site/2-content/ciriculumn/week-17/python/my-intro-BG/2/Module11WritingFiles.py
302
3.734375
4
fileName = "demo.txt" WRITE = "w" APPEND = "a" data = input("Please enter file info") file = open(fileName, mode=WRITE) file.write(data) file.close() # file = open(fileName, mode = WRITE) # file.write('Susan, 29\n') # file.write('Christopher, 31') # file.close() print("File written successfully")
e4027bbc8947faba24aab7180e3de4f643d524f9
Impact-coder/hackerrank-problem-solving-solution
/Apple and Orange.py
1,335
4.09375
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countApplesAndOranges' function below. # # The function accepts following parameters: # 1. INTEGER s # 2. INTEGER t # 3. INTEGER a # 4. INTEGER b # 5. INTEGER_ARRAY apples # 6. INTEGER_ARRAY oranges # def countApplesAndOranges(s, t, a, b, apples, oranges): # Write your code here app = 0 ora =0 for i in range(0,len(apples)): dis = a+apples[i] if dis>=s and dis<=t: app +=1 for i in range(0,len(oranges)): dis = b+oranges[i] if dis>=s and dis<=t: ora +=1 print(app) print(ora) if __name__ == '__main__': first_multiple_input = input().rstrip().split() s = int(first_multiple_input[0]) t = int(first_multiple_input[1]) second_multiple_input = input().rstrip().split() a = int(second_multiple_input[0]) b = int(second_multiple_input[1]) third_multiple_input = input().rstrip().split() m = int(third_multiple_input[0]) n = int(third_multiple_input[1]) apples = list(map(int, input().rstrip().split())) oranges = list(map(int, input().rstrip().split())) countApplesAndOranges(s, t, a, b, apples, oranges)
bdf8b347fc5946c94aecd5a5386423dd6110275d
Katsura47/Euler
/problem_21(amicable).py
596
3.734375
4
def prime(num): i = 2 total = 0 while num/2 > i > 1: if num%i == 0: return False i += 1 return True def sum_of_divisors(num): i = 1 total = 0 while i <= num / 2: if num%i == 0: total += i i += 1 return total def amicable(num): cevap = sum_of_divisors(num) cevap_1 = sum_of_divisors(cevap) if cevap_1 == num and cevap != num: return True else: return False print(amicable(10000)) i = 1 total = 0 while i < 10000: if amicable(i): total += i i += 1 print(total)
37a693255016fa276cbaa05a04e27054fa528fd0
Thyrvald/SimplePasswordDatabase
/encrypting.py
2,585
3.921875
4
def encrypt(string_to_encrypt): encrypted_string = '' encrypting_table = create_encrypting_table() string_with_code_word = create_string_with_code_word(string_to_encrypt) for i in range(len(string_to_encrypt)): for encrypted_alphabet in encrypting_table: if encrypted_alphabet[0] == string_to_encrypt[i]: for letter in encrypting_table[0]: if letter == string_with_code_word[i]: letter_index = encrypting_table[0].index(letter) encrypted_string += encrypted_alphabet[letter_index] return encrypted_string def decrypt(string_to_decrypt): decrypted_string = '' encrypting_table = create_encrypting_table() string_with_code_word = create_string_with_code_word(string_to_decrypt) for i in range(len(string_to_decrypt)): for encrypted_alphabet in encrypting_table: if encrypted_alphabet[0] == string_with_code_word[i]: for letter in encrypted_alphabet: if letter == string_to_decrypt[i]: letter_index = encrypted_alphabet.index(letter) decrypted_string += encrypting_table[0][letter_index] return decrypted_string def encrypt_file(file_name): with open(file_name, 'r+') as f: content = '' for l in f: line = l.strip('\n') content += encrypt(line) + '\n' with open(file_name, 'w') as f: f.write(content) def decrypt_file(file_name): with open(file_name) as f: content = '' for l in f: line = l.strip('\n') content += decrypt(line) + '\n' with open(file_name, 'w') as f: f.write(content) def clear_file(file_name): with open(file_name, 'w') as f: f.write('') def create_string_with_code_word(string_to_encrypt): code_word = 'vigenere' string_with_code_word = '' while len(string_with_code_word) < len(string_to_encrypt): string_with_code_word += code_word if len(string_with_code_word) > len(string_to_encrypt): string_with_code_word = string_with_code_word[:len(string_to_encrypt)] return string_with_code_word def create_encrypting_table(): list_of_alphabets = [] for i in range(0, 91): alphabet = [] for j in range(0, 91): if j + i + 32 < 123: alphabet.append(chr(j + i + 32)) else: alphabet.append(chr(j + i - 59)) list_of_alphabets.append(alphabet) return list_of_alphabets
2fdd514c907469add9b232232d3a5865ba7bbe22
NixonThuo/ParcticeRepo
/rough_copy.py
382
3.75
4
def sum_large(numbers): if len(numbers) > 1: numbers.sort() new_list = [] new_list.append(numbers[0] + numbers[-1]) numbers.pop(0) numbers.pop(-1) return new_list.append(sum_large(numbers)) else: return new_list print sum_large([1, 2, 5, 9, 7, 6]) """ numbers = [1, 2, 5, 9, 7, 6] numbers.pop(-1) print numbers """
38432e4efd68ff6732061eb132040382bfce0d5c
tlambrou/Data-Structures
/source/sort.py
4,267
4.0625
4
#!python from binarysearchtree import BinarySearchTree, TreeMap def bubble_sort(array): # O(n^2-n) in_order = False # O(1) while in_order is False: # O(n) in_order = True # O(1) for i in range(0, len(array) - 1): # O(n) if array[i] > array[i + 1]: # O(1) array[i], array[i + 1] = array[i + 1], array[i] # O(1) in_order = False # O(1) return array # O(1) def selection_sort(array): # O(n^2) for i in range(0, len(array) - 1): # O(n) running_smallest = i # O(1) for k in range(i, len(array)): # O(n/2) if array[k] < array[running_smallest]: # O(1) running_smallest = k # O(1) array[i], array[running_smallest] = array[running_smallest], array[i] # O(1) return array # O(1) def insertion_sort(array): # O(n*log(n)) for i in range(1, len(array)): # O(n) index = i # O(1) while array[index] < array[index - 1] and index != 0: # O(log(n)) array[index], array[index - 1] = array[index - 1], array[index] # O(1) index -= 1 # O(1) return array # O(1) def tree_sort(array): tree = BinarySearchTree(array) # O(n*log(n)) return tree.items_in_order() def counting_sort(array): treemap = TreeMap(array) return treemap.get_in_order_list() def merge(list1, list2): index1 = 0 index2 = 0 result = [] while len(result) is not (len(list1) + len(list2)): # Check to see if we have finished sorting the first list if index1 == len(list1): for i in range(index2, len(list2)): result.append(list2[i]) # Check to see if we have finished sorting the second list elif index2 == len(list2): for i in range(index1, len(list1)): result.append(list1[i]) else: # Append the smaller element of each list if list1[index1] <= list2[index2]: result.append(list1[index1]) index1 += 1 elif list1[index1] > list2[index2]: result.append(list2[index2]) index2 += 1 return result def merge_sort_nonrecursive(items): midpoint = len(items) / 2 list1 = items[:midpoint] list2 = items[midpoint:] list1 = tree_sort(list1) list2 = counting_sort(list2) return merge(list1, list2) def merge_sort_recursive(items): # Check to see if the list is of length 1 if len(items) <= 1: # Base case # Return the input as-is (it's already sorted!) return items else: # 1. Divide: split input into two sublists of half size midpoint = len(items) / 2 temp1 = items[:midpoint] temp2 = items[midpoint:] # 2. Conquer: sort sublists recursively sorted1 = merge_sort_recursive(temp1) sorted2 = merge_sort_recursive(temp2) # 3. Combine: merge two sorted sublists # This is where the magic happens! merged = merge(sorted1, sorted2) return merged def partition(items): # Three-way partition scheme print("Entered partition") n = len(items) - 1 pivot = median([items[0], items[len(items)/2], items[n]]) i = 0 j = 0 while j <= n: print(i, j, n, pivot) print(items) if items[j] < pivot: items[i], items[j] = items[j], items[i] i += 1 j += 1 elif items[j] > pivot: items[j], items[n] = items[n], items[j] n -= 1 else: j += 1 lower = items[:n] if items[:n] is not None else [] upper = items[n:] if items[n:] is not None else [] return (lower, upper) def quick_sort(items): print("Entered quick_sort") if len(items) < 2: return items else: result = partition(items) if result[0] != None: lower = quick_sort(result[0]) print(lower) if result[1] != None: upper = quick_sort(result[1]) print(upper) return lower.extend(upper) def median(items): sorts = sorted(items) length = len(sorts) if not length % 2: return (sorts[length / 2] + sorts[length / 2 - 1]) / 2.0 return sorts[length / 2]
fc3eb7d06f934c1f93b19db73581d846182079c5
jamalzkhan/idapi
/IDAPICoursework02.py
10,316
3.546875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Coursework in Python from IDAPICourseworkLibrary import * from numpy import * import pydot # # Coursework 1 begins here # # Function to compute the prior distribution of the variable root from the data set def Prior(theData, root, noStates): prior = zeros((noStates[root]), float ) dataSize = len(theData) for i in theData: prior[i[root]] += 1/float(dataSize) return prior # Function to compute a CPT with parent node varP and xchild node varC from the data array # it is assumed that the states are designated by consecutive integers starting with 0 def CPT(theData, varC, varP, noStates): cPT = zeros((noStates[varC], noStates[varP]), float ) cAcc = zeros((noStates[varC]), float ) pAcc = zeros((noStates[varP]), float ) cAndPAcc = zeros((noStates[varC], noStates[varP]), float ) for i in theData: cAndPAcc[i[varC]][i[varP]] += 1 pAcc[i[varP]] += 1 for i in range(0, len(cPT)): for j in range(0, len(cPT[i])): cPT[i][j] = cAndPAcc[i][j] / pAcc[j] return cPT # Function to calculate the joint probability table of two variables in the data set def JPT(theData, varRow, varCol, noStates): jPT = zeros((noStates[varRow], noStates[varCol]), float ) for i in theData: jPT[i[varRow]][i[varCol]] += 1/float(len(theData)) return jPT # # Function to convert a joint probability table to a conditional probability table def JPT2CPT(aJPT): aJPT = aJPT.transpose() for i in aJPT: i /= sum(i) return aJPT.transpose() # Function to query a naive Bayesian network def Query(theQuery, naiveBayes): rootPdf = zeros((naiveBayes[0].shape[0]), float) prior = naiveBayes[0] childNodes = naiveBayes[1:] for i in range(0, len(rootPdf)): rootPdf[i] = prior[i] for j in range(0, len(theQuery)): childNode = childNodes[j] rootPdf[i] = rootPdf[i] * childNode[theQuery[j],i] total = sum(rootPdf) for i in range(0, len(rootPdf)): rootPdf[i] = rootPdf[i]/total return rootPdf def createNaiveBayes(theData, noStates, prior): childCPT = createChildCPT(theData, noStates) return [prior] + childCPT def createChildCPT(theData, noStates): cpt = [] for i in range(1, 6): cpt.append(CPT(theData, i, 0, noStates)) return cpt # End of Coursework 1 # # Coursework 2 begins here # # Calculate the mutual information from the joint probability table of two variables def MutualInformation(jP): mi=0.0 for i in range(0, len(jP)): for j in range(0, len(jP[i])): if jP[i][j] == 0.0: continue Pd = jP[i][j] temp = log2(Pd/(sum(jP[i])*sum(jP.transpose()[j]))) mi += Pd*temp return mi # # construct a dependency matrix for all the variables def DependencyMatrix(theData, noVariables, noStates): MIMatrix = zeros((noVariables,noVariables)) for i in range(0, len(MIMatrix)): for j in range(0, len(MIMatrix[i])): jpt = JPT(theData, i, j, noStates) MIMatrix[i][j] = MutualInformation(jpt) # Coursework 2 task 2 should be inserted here # end of coursework 2 task 2 return MIMatrix # Function to compute an ordered list of dependencies def DependencyList(depMatrix): depList=[] # Coursework 2 task 3 should be inserted here for i in range(0, len(depMatrix)): for j in range(i+1, len(depMatrix[i])): depList.append((depMatrix[i][j], i, j)) # end of coursework 2 task 3 depList = sorted(depList, reverse=True) return array(depList) # # Functions implementing the spanning tree algorithm # Coursework 2 task 4 def generateGraph(spanningTree, noVariables): graph = {} for (x, i, j) in spanningTree: if not i in graph: graph[i] = [] graph[i].append(j) else: graph[i].append(j) if not j in graph: graph[j] = [] graph[j].append(i) else: graph[j].append(i) for i in range(0, noVariables): if not i in graph: graph[i] = [] return graph def bfs(x, graph): visited = {} xSet = [] q = [] q.append(x) visited[x] = True while q: y = q.pop() for i in graph[y]: if not i in visited: xSet.append(i) q.append(i) visited[i] = True return set(xSet) def SpanningTreeAlgorithm(depList, noVariables): spanningTree = [] for (x, i, j) in depList: g = generateGraph(spanningTree, noVariables) setI = bfs(i, g) setJ = bfs(j, g) if not setJ.intersection(setI): spanningTree.append((x, i, j)) return array(spanningTree) def makeName(number): return str(int(number)) def createGraph(spanningTree, noVariables): g = pydot.Dot(graph_type='graph') for i in range(0, noVariables): g.add_node(pydot.Node(makeName(i))) for (x, i, j) in spanningTree: g.add_edge(pydot.Edge(makeName(i), makeName(j)))#, label=str(x))) return g # # End of coursework 2 # # Coursework 3 begins here # # Function to compute a CPT with multiple parents from he data set # it is assumed that the states are designated by consecutive integers starting with 0 def CPT_2(theData, child, parent1, parent2, noStates): cPT = zeros([noStates[child],noStates[parent1],noStates[parent2]], float ) # Coursework 3 task 1 should be inserted here # End of Coursework 3 task 1 return cPT # # Definition of a Bayesian Network def ExampleBayesianNetwork(theData, noStates): arcList = [[0],[1],[2,0],[3,2,1],[4,3],[5,3]] cpt0 = Prior(theData, 0, noStates) cpt1 = Prior(theData, 1, noStates) cpt2 = CPT(theData, 2, 0, noStates) cpt3 = CPT_2(theData, 3, 2, 1, noStates) cpt4 = CPT(theData, 4, 3, noStates) cpt5 = CPT(theData, 5, 3, noStates) cptList = [cpt0, cpt1, cpt2, cpt3, cpt4, cpt5] return arcList, cptList # Coursework 3 task 2 begins here # end of coursework 3 task 2 # # Function to calculate the MDL size of a Bayesian Network def MDLSize(arcList, cptList, noDataPoints, noStates): mdlSize = 0.0 # Coursework 3 task 3 begins here # Coursework 3 task 3 ends here return mdlSize # # Function to calculate the joint probability of a single data point in a Network def JointProbability(dataPoint, arcList, cptList): jP = 1.0 # Coursework 3 task 4 begins here # Coursework 3 task 4 ends here return jP # # Function to calculate the MDLAccuracy from a data set def MDLAccuracy(theData, arcList, cptList): mdlAccuracy=0 # Coursework 3 task 5 begins here # Coursework 3 task 5 ends here return mdlAccuracy # # End of coursework 2 # # Coursework 3 begins here # def Mean(theData): realData = theData.astype(float) noVariables=theData.shape[1] mean = [] # Coursework 4 task 1 begins here # Coursework 4 task 1 ends here return array(mean) def Covariance(theData): realData = theData.astype(float) noVariables=theData.shape[1] covar = zeros((noVariables, noVariables), float) # Coursework 4 task 2 begins here # Coursework 4 task 2 ends here return covar def CreateEigenfaceFiles(theBasis): adummystatement = 0 #delete this when you do the coursework # Coursework 4 task 3 begins here # Coursework 4 task 3 ends here def ProjectFace(theBasis, theMean, theFaceImage): magnitudes = [] # Coursework 4 task 4 begins here # Coursework 4 task 4 ends here return array(magnitudes) def CreatePartialReconstructions(aBasis, aMean, componentMags): adummystatement = 0 #delete this when you do the coursework # Coursework 4 task 5 begins here # Coursework 4 task 5 ends here def PrincipalComponents(theData): orthoPhi = [] # Coursework 4 task 3 begins here # The first part is almost identical to the above Covariance function, but because the # data has so many variables you need to use the Kohonen Lowe method described in lecture 15 # The output should be a list of the principal components normalised and sorted in descending # order of their eignevalues magnitudes # Coursework 4 task 6 ends here return array(orthoPhi) # # main program part for Coursework 1 # def coursework1(): noVariables, noRoots, noStates, noDataPoints, datain = ReadFile("Neurones.txt") theData = array(datain) AppendString("results.txt","Coursework One Results: Jamal Khan - jzk09") AppendString("results.txt","") #blank line AppendString("results.txt","The prior probability distribution of node 0:") prior = Prior(theData, 0, noStates) AppendList("results.txt", prior) AppendString("results.txt","The conditional probability matrix P (2|0) calculated from the data:") cpt = CPT(theData, 2,0, noStates) AppendArray("results.txt", cpt) AppendString("results.txt","The joint probability matrix P (2&0) calculated from the data:") jpt = JPT(theData, 2, 0, noStates) AppendArray("results.txt", jpt) AppendString("results.txt","The conditional probability matrix P (2|0) calculated from the joint probability matrix P (2&0):") jpt2cpt = JPT2CPT(jpt) AppendArray("results.txt", jpt2cpt) AppendString("results.txt","The results of queries [4,0,0,0,5] and [6, 5, 2, 5, 5] respectively on the naive network:") naiveBayes = createNaiveBayes(theData, noStates, prior) queryA = Query([4,0,0,0,5], naiveBayes) AppendList("results.txt", queryA) queryB = Query([6,5,2,5,5], naiveBayes) AppendList("results.txt", queryB) def coursework2(): noVariables, noRoots, noStates, noDataPoints, datain = ReadFile("HepatitisC.txt") theData = array(datain) AppendString("results.txt","Coursework Two Results: Jamal Khan - jzk09") AppendString("results.txt","") #blank line AppendString("results.txt","The dependency matrix for HepatitisC data set:") dm = DependencyMatrix(theData, noVariables, noStates) AppendArray("results.txt", dm) AppendString("results.txt","The dependency list for HepatitisC data set:") dl = DependencyList(dm) AppendArray("results.txt", dl) AppendString("results.txt","The nodes for the spanning tree are: ") st = SpanningTreeAlgorithm(dl, noVariables) AppendArray("results.txt", st) g = createGraph(st, noVariables) g.write_png('spanning_tree.png') if __name__ == "__main__": coursework2()
b35c4a4c0565ae4d21de1dc3c0506c09352eb649
koyasu221b/lintcode
/rotated_sorted_array/recover-rotated-sorted-array/solution.py
618
3.625
4
class Solution: """ @param nums: The rotated sorted array @return: nothing """ def recoverRotatedSortedArray(self, nums): # write your code here for index in range(len(nums)-1): if nums[index] > nums[index+1]: self.reverse(nums, 0, index) self.reverse(nums, index+1, len(nums)-1) self.reverse(nums, 0, len(nums)-1) def reverse(self, nums, start, end): while start < end: tmp = nums[start] nums[start] = nums[end] nums[end] = tmp start +=1 end -=1
b0482f8a47e4be852c00b6aa4aac206536ecb65d
shauravmahmud/100DaysOfCode
/Day 016 Object Orientated Programming/main.py
2,832
4.25
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } resources = { "water": 300, "milk": 200, "coffee": 100, } profit = 0 def enough_resources(order_ingredients): """"True or False if enough ingredients""" is_enough = True for item in order_ingredients: if order_ingredients[item] >= resources[item]: print(f"Sorry there is not enough {item}.") is_enough = False return True def coins(): print("Please insert your coins.") """Total value of coins""" total = int(input("How many quarters?")) * 0.25 total = total + int(input("How many dimes?")) * 0.1 total = total + int(input("How many nickles?")) * 0.05 total = total + int(input("How many pennies?")) * 0.01 return total def transaction(money_in, drink_cost): """"True when payment is enough, or False when not enough""" if money_in >= drink_cost: change = round((money_in - drink_cost), 2) # 2 decimal places print(f'your change is £{change}') global profit #Global scope needed profit = profit + drink_cost return True else: print("That's not enough money!") return False def make_coffee(drink_name, order_ingredients): for item in order_ingredients: resources[item] -= order_ingredients[item] print(f"Here is your {drink_name}") # Ask what drink the user would like. switched_on = True profit = 0 while switched_on: # While True keep running this statement choice = input(f"What drink would you like? espresso,latte or cappuccino?\n") if choice == "report": """Generate report""" water = int(resources["water"]) milk = int(resources["milk"]) coffee = int(resources["coffee"]) print(f' Water left: {water}ml') print(f' Milk left: {milk}ml') print(f' Coffee left: {coffee}grams') print(f' profit: £{profit}') elif choice == "off".lower(): switched_on = False # Turn off the Coffee Machine by entering off to the prompt. # Check resources are sufficient else: drink = MENU[choice] #print(drink) # This is a dictionary of the components of the drink which will be passed in the function if enough_resources(drink["ingredients"]): payment = coins() if transaction(payment, drink["cost"]): make_coffee(choice, drink["ingredients"])
6d533411183326e3ee2e610f4bebf43d3a51bb6a
Don-George-Thayyil/algorithms
/set_adt.py
835
3.84375
4
class SetADT: def __init__(self): self._set = list() def __length__(self): return len(self._set) def __contain__(self,value): return value in self._set def add(self,element): if element not in self._set: self._set.append(element) else: raise "Element is a duplicate" def remove(self,element): if element in self._set: self._set.remove(element) else: raise "Didn't find the element" def __eq__(self, setB): if len(self._set) != len(setB): return False else: return check(self,setB) def check(self,setB): for element in self._set: if element in setB: return True else: return False
f7dc60055181b6c97dd393f2785e241fa6947a55
AlexNilbak/Task_6
/Task_6.py
1,454
3.859375
4
try: file = open("data.txt", "r") except: print("Cannot open file\n") exit() def Read_int(filename): f=0 z=0 x='0' while (x!=' ') and (x!=''): x=filename.read(1) if (x==' ' or x=='') and (f!=0): return z if (x=='') and (f==0): return 'end' elif (x!=' '): try: x=int(x) z=z*10+x if (f==0): f+=1 except: if (x!=' ') and (x!=''): print("Wrong data\n") exit() c=None while (c==None): c=Read_int(file) if (c=='end'): print("Empty file\n") exit() e=None while (e==None): e=Read_int(file) if (e=='end'): print("There is no increasing sections\n") exit() f=1 max=1 if (e>c): f=2 c=None while(c!='end'): while (c==None): c=Read_int(file) if (c!=None) and (c!='end'): if (c>e): f+=1 elif (f>max): max=f f=1 e=c if (c!='end'): c=None if (f>max): max=f if (max==1): print("There is no increasing sections\n") else: print("Maximum length of the increasing section is {}".format(max)) file.close()