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
f5525de60ee896adde7ce25763cdef9cad71efe1
haihala/FSM
/backend/UI.py
963
3.578125
4
""" UI is a parent class to UIs that cli uses. """ from abc import abstractmethod from .action_tree import ActionTree class UI(): """ Parent for cli and possible later graphical UI. """ def __init__(self, *args): self.running = True self.args = args @abstractmethod def tick(self): """ Called repeatedly until self.running is False """ pass class Cli(UI): """ Implementation of the UI interface defined above. """ def __init__(self, *args): super().__init__(self) self.output = "" self.action_tree = ActionTree() def tick(self): print(self.output) # Formated user input fui = self.format(input(">")) self.output = self.action_tree.call(fui) def format(self, to_format): """ Used to format users' inputs in such a form where it can be parsed. """ return to_format.split()
fff9ffb1bddd3c768f9d64a19a0cf92f433f11f5
Md-Monirul-Islam/Python-code
/Python-book-OOP/Method overloading-bangla bool-2.py
227
3.8125
4
class My_num: def __init__(self,value): self.__value = value def __int__(self): return self.__value def __add__(self, other): return self.__value+int(other)*int(other) a=2 b=3 c=a+b print(c)
fe42375fa9fcaeec7e8a2172f84685ca69bdf88b
deekshithanand/PythonExcercises
/pg6.py
469
4.03125
4
''' Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 ''' ip=input() lcount=dcount=0 for i in ip.split(): for j in i: if j.isdigit(): dcount+=1 elif j.isalpha(): lcount+=1 else: pass print(f'LETTERS:{lcount}\nDIGITS:{dcount}')
1b0524cb770c5cc380bd0534fa10edbd62d0ea74
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_53/516.py
621
3.640625
4
#!/usr/bin/python n = 2 k = 3 def solve(n, k): """docstring for solve""" on = (2 ** n) - 1 nk = k % (2 ** n) if nk == on: return "ON" else: return "OFF" def main(): """docstring for main""" input = open("problem") ilines = [l.strip() for l in input.readlines()] num_tests = int(ilines[0], 0) line_num = 1 for test in xrange(num_tests): line = ilines[line_num] line_num = line_num + 1 (n, k) = [int(x, 0) for x in line.split()] print "Case #%d: %s" % (test + 1, solve(n, k)) if __name__ == '__main__': main()
bb2dda37d10cb92e1458a3e83dba7b4282b6eb8b
tthompson-thb/ssw567-HW-01
/classifyTrianglewithUnittest.py
1,418
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Tonya Thompson - SSW567-NBA Assignment - HW 01: Testing triangle classification 02/12/21: Attemp at unit testing """ import unittest try: def classify_triangle(side1, side2, side3): if side1 == side2 == side3: #print("\nEquilateral Triangle") return ('Equilateral Triangle') elif ((side1**2 + side2**2) == side3**2): #print("\nRight Triangle") return('Right Triangle') elif side1==side2 or side2==side3 or side3==side1: #print("Isosceles Triangle") return('Isosceles Triangle') else: #print("Scalene Triangle") return('Scalene Triangle') # side1,side2,side3 = map(int,input("Enter three sides of an triangle: ").split()) # classify_triangle(side1,side2,side3) except ValueError as err: print("ERROR: " +str(err)) class TestTriangle(unittest.TestCase): def test1(self): #print("\nEquilateral Triangle") self.assertEqual(classify_triangle(1,1,1),'Equilateral Triangle','1,1,1 is a Equilateral triangle') #print("\nRight Triangle") self.assertEqual(classify_triangle(3,4,5),'Right Triangle','3,4,5 is a Right triangle') self.assertEqual(classify_triangle(3,5,5),'Isosceles Triangle','3,5,5 is a Isosceles triangle') if __name__ == '__main__': unittest.main()
22dbe7082f001979122470792716b40aabd2f9dc
MartinPons/BookingAnalysis
/rearrangements.py
2,816
3.65625
4
import pandas as pd from BookingData import Booking def get_stay_df(df, group_vars = None, status = None): """Transforms a DataFrame with booking information to a stay date DataFrame. Each row has to include infthe basic info for it to be converted in a Booking object Args: df (DataFrame): DataFrame with booking information group_vars (list): additional vars from df to be include in the output status (list): booking status to include in DataFrame (by default includes every estatus) Returns: DataFrame: a DataFrame where each booking has been extended into one row for every stay day """ # initiates list of DataFrames to save extended booking DataFrames bookings_list = [] # transforms each row in the DataFrame into a extended booking DataFrame for row in range(df.shape[0]): booking = Booking(df.iloc[row]) # checks status filter if status is not None and booking.status not in status: next else: # appends extended booking df to booking_list bookings_list.append(booking.expand(group_vars = group_vars)) bookings_df = pd.concat(bookings_list, axis = 0) return bookings_df def group_stay_df(df, freq = "1D", group_vars = None, status = None): """Aggregates DataFrame with enough info to create a Booking class from each row, into an aggregated version of a stay date DataFrame, with aggregated revenue, roomnights and ADR, with additional levels of aggregation at user discretion Args: df (DataFrame): DataFrame with info enough to create Booking objects from its rows freq (str): date frequency from wich the aggregation will be performed group_vars (list): other columns in the DataFrame for additional levels of aggregation status (list): booking status to include in DataFrame (by default includes every estatus) Returns: DataFrame: a DataFrame with aggregated adr, roomnights and revenue """ # transforms df into a stay date DataFrame bookings_df = get_stay_df(df, group_vars = group_vars, status = status) # creates list with all levels of aggregation including date aggregation grouping_list = [pd.Grouper(key = 'stay_date', freq = freq)] if group_vars is not None: grouping_list.extend(group_vars) # aggregates df daily_df = bookings_df.groupby(grouping_list).agg( roomnights = ('roomnights', 'sum'), revenue = ('adr', 'sum'))\ .reset_index() # computes DataFrame afterwards because it's a ratio daily_df['adr'] = daily_df['revenue'] / daily_df['roomnights'] return daily_df
d053662c9a5f3c9e2db3390b057ca57fa3883fd4
basakrajarshi/LC
/Top Int Ques/020_valid_parentheses.py
1,337
3.859375
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if s == "": return True # ------------- # USING A STACK # ------------- open_brackets = ["[", "{", "("] close_brackets = ["]", "}", ")"] # Initiate an epmty stack st = [] # Iterate through each element in the string for ch in s: # If the element is in open_brackets if ch in open_brackets: # Add it to the stack st.append(ch) # If the element is in close_brackets elif ch in close_brackets: # Find the index of the element in close_brackets ind = close_brackets.index(ch) # If stack is not empty and element at same index in open_brackets is the same element at the bottom of the stack if ((len(st) > 0) and (open_brackets[ind] == st[-1])): # Remove the last element from the stack st.pop() else: return False # If the stack is empty if len(st) == 0: # Return True return True else: return False
a5bd31f6fa37b0eb3b8ed67180f11cd3d908da23
sean578/advent_of_code
/2019/day_6_part_2.py
1,990
4.0625
4
def get_pairs_into_dict(debug=False, debug_array = None): orbit_dict = {} if debug: for line in debug_array: a, b = line.split(')') if b not in orbit_dict.keys(): orbit_dict[b] = a else: print('Duplicate orbit found') else: for line in open('day_6.txt').readlines(): a, b = line.strip().split(')') if b not in orbit_dict.keys(): orbit_dict[b] = a else: print('Duplicate orbit found') return orbit_dict # Simple input shown in question, distance between you and santa = 4 debug_array = [ 'COM)B', 'B)C', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)YOU', 'I)SAN' ] def find_distance_to_com_recursive(planet, orbit_dict, dist=0): """ Recursive version of function used for part a """ new_planet = orbit_dict[planet] if new_planet == 'COM': return dist + 1 else: dist = find_distance_to_com_recursive(new_planet, orbit_dict, dist+1) return dist def get_list_of_orbits_to_com(planet, orbit_dict): orbit_list = [planet] p = planet done = False while not done: p = orbit_dict[p] orbit_list.append(p) if p == 'COM': done = True return orbit_list # Get in form, b orbits a --> [b] = a orbit_dict = get_pairs_into_dict(debug=False, debug_array=debug_array) # Get path through orbits to com for both you and santa you_orbits = get_list_of_orbits_to_com('YOU', orbit_dict) san_orbits = get_list_of_orbits_to_com('SAN', orbit_dict) # Find the first intersection in these paths intersections = set(you_orbits).intersection(san_orbits) # Calc the distance between you and santa via the intersection and find the min min_distance = min([you_orbits.index(x) + san_orbits.index(x) - 2 for x in intersections]) print('Min distance between you and santa =', min_distance)
3d8096c4129e3aaa4df6624bbacc83ec92cc74f7
ktp-forked-repos/py-algorithms
/py_algorithms/data_structures/__init__.py
3,556
3.59375
4
__all__ = [ 'new_deque', 'Deque', 'new_queue', 'Queue', 'new_stack', 'Stack', 'new_heap', 'Heap', 'new_max_heap', 'new_min_heap', 'new_priority_queue', 'PriorityQueue', 'new_suffix_array', 'new_tree_node', 'TreeNode', ] from typing import Any from typing import Callable from typing import List from typing import TypeVar from .deque import Deque from .doubly_linked_list_deque import DoublyLinkedListDeque from .heap import Heap from .max_heap import MaxHeap from .min_heap import MinHeap from .priority_queue import PriorityQueue from .queue import Queue from .stack import Stack from .suffix_array import SuffixArray from .tree_node import TreeNode T = TypeVar('T') def new_deque(collection: List[Any] = ()) -> Deque: """ Generic Dequeue, doubly linked list based implementation :param collection: List[Any] :return: Deque """ return DoublyLinkedListDeque(collection) def new_queue(collection: List[T] = ()) -> Queue[T]: """ Generic Queue, using Deque underneath :param collection: List[T] :return: Queue """ return Queue[T](collection) def new_stack(collection: List[T] = ()) -> Stack[T]: """ Generic Stack, using Deque underneath :param collection: List[T] :return: Stack """ return Stack[T](collection) def new_heap(comparator_f2: Callable[[Any, Any], bool], xs: List[Any] = ()) -> Heap: """ Fibonacci Heap Factory method to construct generic heap :param comparator_f2: a morphism to apply in order to compare heap entries :param List[T] xs: a list of initial isomorphic values to populate heap :return: pointer to Heap interface Example of a generic Max heap >>> max_heap = new_heap(lambda x, y: (x > y) - (x < y) == 1) >>> max_heap.push('Kelly', 1) >>> max_heap.push('Ryan', 7) >>> max_heap.next_key #=> 'Ryan' >>> max_heap.pop() #=> 7 """ return Heap(comparator_f2, xs) def new_max_heap(xs: List[Any] = ()) -> Heap: """ MAX Heap (Fibonacci Heap engine) :param xs: optional collection of initial values :return: an interface to Heap """ return MaxHeap(xs) def new_min_heap(xs: List[Any] = ()) -> Heap: """ MAX Heap (Fibonacci Heap engine) :param xs: optional collection of initial values :return: an interface to Heap """ return MinHeap(xs) def new_priority_queue(queue_vector_f2: Callable[[Any, Any], bool]) -> PriorityQueue: """ MAX Priority Queue (Fibonacci Heap engine) >>> from py_algorithms.data_structures import new_priority_queue >>> >>> pq = new_priority_queue(lambda x, y: (x > y) - (x < y) == 1) >>> pq.push('Important', 10) >>> pq.push('Not So Important', -2) >>> pq.pop() #=> 'Important' :param queue_vector_f2: a functor defining queue order :return: a PriorityQueue interface """ return PriorityQueue(queue_vector_f2) def new_suffix_array(string: str) -> SuffixArray: """ >>> from py_algorithms.data_structures import new_suffix_array >>> >>> ds = new_suffix_array('python') >>> ds.is_sub_str('py') #=> True >>> ds.is_sub_str('on') #=> True >>> ds.is_sub_str('ton') #=> True >>> ds.is_sub_str('blah') #=> False :param string: a subject for detection :return: SuffixArray interface """ return SuffixArray(string) def new_tree_node(element, left=None, right=None): return TreeNode(element=element, left=left, right=right)
f503a76cf01ef51bc080e7b543fc1ed792585945
yongseongCho/python_201911
/day_10/class_10.py
2,234
3.5625
4
# -*- coding: utf-8 -*- class Animal : def __init__(self, name, age, color) : self.name = name self.age = age self.color = color def showInfo(self) : print(f'name : {self.name}') print(f'age : {self.age}') print(f'color : {self.color}') # 생성자 재정의(오버라이딩)를 통한 # 상속 문법 구현 class Dog (Animal) : def __init__(self, name, age, color, power) : # 자식클래스에서 부모클래스의 생성자를 # 사용하지 않고 새롭게 생성자를 정의하는 경우 # 부모클래스의 생성자를 명시적으로 호출하여 # 부모클래스의 인스턴스 변수들이 올바르게 # 생성될 수 있도록 해야합니다. self.power = power # super() 함수는 부모클래스에 접근하기 위한 # 참조값을 반환하는 함수 # 1. 부모 클래스의 생성자 호출 # 2. 오버라이딩된 부모클래스의 메소드 호출 super().__init__(name, age, color) # 부모클래스로부터 물려받은 showInfo 메소드는 # power 값을 출력할 수 없음 # 이러한 경우 부모클래스를 새롭게 재정의하여 # 사용할 수 있습니다. (메소드 오버라이딩) # 메소드 오버라이딩을 구현하면 부모의 메소드는 # 무시되고 오버라이딩된 자식클래스의 메소드가 # 호출됩니다. def showInfo(self) : # super()를 사용하여 부모클래스의 # 오버라이딩된 메소드를 호출할 수 있습니다. super().showInfo() print(f'power : {self.power}') class Cat (Animal) : def __init__(self, name, age, color, speed) : super().__init__(name, age, color) self.speed = speed def showInfo(self) : super().showInfo() print(f'speed : {self.speed}') d = Dog('바둑이', 10, '흰색', '무는힘이 아주 강해요...') c = Cat('나비', 3, '검은색', '너무 빨라서 잡을수가 없어요...') d.showInfo() c.showInfo()
d7d3cd44bfe75129f2b58a153087016a0faedc53
youjin9209/2016_embeded_raspberry-pi
/pythonBasic/break_letter.py
158
4.125
4
break_letter = input("break letter: ") for letter in "python": if letter == break_letter: break print(letter) else: print("all letter print completed")
c357db2ed020c6ccc8a56f4fa258d3cff1020062
hyosung11/PycharmProjects
/modules/randomgame.py
635
3.96875
4
from random import randint import sys # generate a number between 1~10 answer = randint(int(sys.argv[1]), int(sys.argv[2])) while True: try: # input from user? guess = int(input('Guess a number from 1 ~ 10 ')) # check that input is a number 1~10 if guess > 0 < 11: # check if number is the right guess. Otherwise ask again. if guess == answer: print('Wow, great guess. You\'re right!') break else: print('Out of range. Try again please') except ValueError: print('Please enter a number') continue
95e3e3f022c9202b5fae722d3a1c8075093e2284
tpusmb/lei-ihm_video_mapping
/datas/models/Player.py
1,397
3.953125
4
class Player: """ Player Model, which represents the user of our system Example: >>> p = Player() >>> assert p.name == "LEI" >>> assert p.level == 0 >>> assert p.xp == 0 >>> assert p.total_xp_needed_for_next_level() == 30 XP is retained through level up >>> p.xp += 50 >>> assert p.level == 1 >>> assert p.xp == 20 >>> assert p.total_xp_needed_for_next_level() == 40 multiple level up in a single time is supported >>> p.xp += 100 >>> assert p.level == 3 >>> assert p.xp == 30 >>> assert p.total_xp_needed_for_next_level() == 60 """ MIN_XP_LEVEL_1 = 30 STEP_LEVEL = 10 # used to calculate xp necessary needed for each level def __init__(self, name: str = "LEI"): self.name = name self.level = 0 self.xp = 0 @property def xp(self): return self.__xp @xp.setter def xp(self, value: int): """ Set the player xp, and raise the level of the player when the XP is satisfied :param value: The xp value :return: player's xp """ self.__xp = value while self.xp >= self.total_xp_needed_for_next_level(): self.__xp = self.xp - self.total_xp_needed_for_next_level() self.level += 1 def total_xp_needed_for_next_level(self): return self.MIN_XP_LEVEL_1 + self.STEP_LEVEL * self.level
ccc1d2915391662c013013b2b5ef92296c54b235
here0009/LeetCode
/Python/1653_MinimumDeletionstoMakeStringBalanced.py
2,075
3.984375
4
""" You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. Example 1: Input: s = "aababbab" Output: 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb"). Example 2: Input: s = "bbaaaaabb" Output: 2 Explanation: The only solution is to delete the first two characters. Constraints: 1 <= s.length <= 105 s[i] is 'a' or 'b'​​. """ class Solution: def minimumDeletions(self, s: str) -> int: """ wronag answer """ first_b = s.find('b') last_a = s.rfind('a') a, b = 0, 0 for i,v in enumerate(s): if v == 'a' and i > first_b: a += 1 elif v == 'b' and i < last_a: b += 1 print(first_b, last_a, a, b) return min(a, b) class Solution: def minimumDeletions(self, s: str) -> int: """ max length of string can be made by deletion """ pre, a, b = 0, 0, 0 for letter in s: if letter == 'a': a += 1 elif letter == 'b': b += 1 if a >= b: pre += a a = 0 b = 0 return len(s) - (pre + max(a, b)) class Solution: def minimumDeletions(self, s: str) -> int: a, b = 0, 0 for c in s: if c == 'a': a += 1 else: a = min(a, b) b += 1 return min(a, b) S = Solution() s = "aababbab" print(S.minimumDeletions(s)) s = "bbaaaaabb" print(S.minimumDeletions(s)) s = "ababaaaabbbbbaaababbbbbbaaabbaababbabbbbaabbbbaabbabbabaabbbababaa" print(S.minimumDeletions(s)) # 输出: # 28 # 预期: # 25
b2c6835595f629bba3d6f59879d00c8948006522
tvarol/leetcode_solutions
/sortColors/sortColors.py
1,332
4.03125
4
#Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. #Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. #Note: You are not suppose to use the library's sort function for this problem. # https://leetcode.com/problems/sort-colors/discuss/26481/Python-O(n)-1-pass-in-place-solution-with-explanation # Beats 78% of submissions, 37 ms class Solution: def sortColors(self,nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ r = 0 #index of red w = 0 # index of white b = len(nums)-1 # index of blue while w <= b: if nums[w] == 0: nums[r], nums[w] = nums[w], nums[r] w += 1 r += 1 elif nums[w] == 1: w += 1 else: nums[w], nums[b] = nums[b], nums[w] b -= 1 nums = [2,0,2,1,1,0] mySol = Solution() mySol.sortColors(nums) print(nums) """ # Beats 8%, 57 ms for idx in range(1, len(nums)): while idx > 0 and nums[idx-1] > nums[idx]: nums[idx-1], nums[idx] = nums[idx], nums[idx-1] idx -= 1 """
41927b68035e1582b7ab573feae937be9b34b6bb
jmelton15/Python-Console-BlackJack
/BlackJackMain.py
6,089
3.59375
4
import random import blackjackMoney import CardDeck import colorama from colorama import Fore, Back, Style ready = '' playing = True def hit_or_stand(): go = '' try: go = input("Would you like to Hit or Stand?") except: print("Your response must be h,s,hit, or stand. Please try again!") else: if go.upper() == "H" or go.upper() == "HIT": return True else: return False def replay(): replay = '' if blackjackMoney.chipless(playerChips.total): print("You Lost All Your Chips. GAME OVER!") return False else: try: replay = input("\nWould You like to play again?!") except: print("Your response must be y, n, yes, or no. Please try again") else: if replay.upper() == "Y" or replay.upper() == "YES": print('\n'*100) return True else: print("Thanks For Playing! .. Game Has Ended") return False print("Welcome to BlackJack!") playerChips = blackjackMoney.Chips() while True: try: ready = input("\nAre you ready to play?!") except: print("Your response must be y, n, yes, or no. Please try again") continue else: if ready.upper() == 'Y' or ready.upper() == 'YES': gameInSession = True if ready.upper() == 'N' or ready.upper() == 'NO': print("Game Ended by User") gameInSession = False else: gameInSession = True while gameInSession: #global playerChips # Here we create chips object for player and take the bet for the hand aceCount = 0 blackjackMoney.bet(playerChips) # Here we create the hand objects for player and computer # We start the hit stand process liveGame = CardDeck.Hand() liveGame.deal() CardDeck.show_some_cards(liveGame.playerHand,liveGame.computerHand) liveGame.add_player_hand(liveGame.playerHand) liveGame.add_computer_hand(liveGame.computerHand) print(Fore.BLACK + Back.WHITE) print("Your Current Hand Value is: {} ".format(liveGame.initialPlayerHandValue)) print(Style.RESET_ALL) if liveGame.pAces > 0 and aceCount == 0: liveGame.adjust_for_player_ace(liveGame.playerRunningTotal,liveGame.pAces) aceCount += 1 if liveGame.initialPlayerHandValue == 21: blackjackMoney.player_blackjack(liveGame.playerHand,liveGame.computerHand,playerChips) print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False elif liveGame.initialPlayerHandValue != 21 and liveGame.initialCompHandValue == 21: blackjackMoney.dealer_blackjack(liveGame.playerHand,liveGame.computerHand,playerChips) print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False else: while hit_or_stand(): liveGame.hit(liveGame.playerHand) CardDeck.show_some_cards(liveGame.playerHand,liveGame.computerHand) liveGame.add_player_hand(liveGame.playerHand) liveGame.adjust_for_player_ace(liveGame.playerRunningTotal,liveGame.pAces) if liveGame.playerRunningTotal > 21: print(Fore.BLACK + Back.WHITE) print("Your Hand Value {} is over 21. ".format(liveGame.playerRunningTotal)) print(Style.RESET_ALL) blackjackMoney.player_busts(liveGame.playerHand,liveGame.computerHand,playerChips) print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False break else: #print("Your Hand Value is: {}".format(liveGame.playerRunningTotal)) continue if gameInSession == False: break CardDeck.show_all_cards(liveGame.playerHand,liveGame.computerHand) print(Fore.BLACK + Back.WHITE) print("\nDealer's Current Hand Value is: {} ".format(liveGame.initialCompHandValue)) print(Style.RESET_ALL) while liveGame.compRunningTotal < 17: liveGame.hit(liveGame.computerHand) CardDeck.show_all_cards(liveGame.playerHand,liveGame.computerHand) liveGame.add_computer_hand(liveGame.computerHand) print(Fore.BLACK + Back.WHITE) print("\nDealer's New Hand Value is: {} ".format(liveGame.compRunningTotal)) print(Style.RESET_ALL) if liveGame.compRunningTotal > 21: print(Fore.BLACK + Back.WHITE) blackjackMoney.dealer_busts(liveGame.playerHand,liveGame.computerHand,playerChips) print(Style.RESET_ALL) print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False break if liveGame.compRunningTotal > liveGame.playerRunningTotal and liveGame.initialCompHandValue != 21: print(Fore.BLACK + Back.WHITE) print("Dealer's Hand Value is: {} and Your Hand Value is: {} ".format(liveGame.compRunningTotal,liveGame.playerRunningTotal)) print(Style.RESET_ALL) blackjackMoney.dealer_wins(liveGame.playerHand,liveGame.computerHand,playerChips) print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False break if liveGame.playerRunningTotal > liveGame.compRunningTotal and liveGame.initialPlayerHandValue != 21: print(Fore.BLACK + Back.WHITE) print("Dealer's Hand Value is: {} and Your Hand Value is: {} ".format(liveGame.compRunningTotal,liveGame.playerRunningTotal)) print(Style.RESET_ALL) blackjackMoney.player_wins(liveGame.playerHand,liveGame.computerHand,playerChips) print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False break if liveGame.compRunningTotal == liveGame.playerRunningTotal: print(Fore.BLACK + Back.WHITE) print("Dealer's Hand Value is: {} and Your Hand Value is: {} ".format(liveGame.compRunningTotal,liveGame.playerRunningTotal)) print(Style.RESET_ALL) blackjackMoney.push(liveGame.playerHand,liveGame.computerHand) print("Your chip count is:",str(playerChips.total)) gameInSession = False break else: print(Style.BRIGHT + "Your chip count is now:",str(playerChips.total)) gameInSession = False break if not replay(): print("Thanks For Playing! ... You Have Left The Table") break
986c1086c526df8f0cd5f4921f1091b35c5a4453
xiaotuzixuedaima/PythonProgramDucat
/PythonPrograms/python_program/perfect_square_and_sum_all_digit_less10.py
435
4
4
#102. Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10 list=[] n= int(input("enter the lower limit:")) m= int(input("enter the upper limit:")) i=1 while i < m+1: # i is greater than upper limit +1 times . n=i*i # find the perfect square in lower limit to upper limit in range. i = i + 1 print(n) list.append(n) print(list)
b35f905625c4d8d91260229269452b5f9ad0d472
kuige-whu/python-
/python_work/data_structure_and_algorithm/hackerrank/counting_valleys.py
938
3.734375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # author : frontier8186 time: 2019/11/5 16:01 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): s_num = [] for i in range(n): if s[i:i + 1] == 'U': if i == 0: s_num.append(1) else: s_num.append(s_num[i - 1] + 1) else: # 'D' if i == 0: s_num.append(-1) else: s_num.append(s_num[i - 1] - 1) count = 0 for i in range(len(s_num)): if i > 0: if s_num[i] == 0 and s_num[i - 1] == -1: count = count + 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() result = countingValleys(n, s) fptr.write(str(result) + '\n') fptr.close()
08d3a78f5035b95bb7ea3eddf6dba74f2eb1a588
zhoushujian001/homework
/python一些小代码/猜拳.py
738
3.59375
4
import random while True: num = int(input('欢迎参加 剪刀,石头,布 猜拳游戏\n您的对手已准备,剪刀输入1,石头输入2,布输入3\n请问您要出什么(退出请输入4)')) if num in [1,2,3]: answer=random.randint(1,3) if num==answer: print('两边猜的一样呢,真遗憾,对方出的是%d'%answer) elif (num==3 and answer==2) or (num==2 and answer==1) or(num==1 and answer==3): print('真厉害,您赢了这一局,对方出的是%d'%answer) else: print('sorry,您输了,下次再继续努力,对方出的是%d'%answer) elif num==4: break else: print('输入错误,只能输入1234哟')
639369aa54266ad1c191c35e82492f6e290053e3
yunjipark0623/python_2018
/06/gugudan.py
329
3.96875
4
## 변수 선언 부분 i, k, guguLine = 0, 0, "" ## 메인(main) 코드 부분 for i in range(2, 10): guguLine = guguLine + ("# %d단 # " %i) print(guguLine) for i in range(1, 10) : guguLine = "" for k in range(2, 10) : guguLine = guguLine + str("%2d X%2d = %2d " % (k, i, k *i)) print(guguLine)
8478241f34025631de334b6eb09dc5c494be85e9
prasadnaidu1/kv-rao
/polimarphism/operator overloding.py
287
3.640625
4
class operator: def __init__(self,name,pages): self.name=name self.pages=pages def __add__(self,other): print(self.name+other.name) print(self.pages+other.pages) #calling block o1=operator("python",100) o2=operator("adv python",20) print(o1+o2)
e434fe0be53f62eab4e41078d149a9fdc04845d2
Hilldrupca/LeetCode
/python/Top Interview Questions - Medium/Array and Strings/longestpalindromesubstring.py
941
3.859375
4
class Solution: def longestPalindrome(self, s: str) -> str: ''' Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first aphabetically will be returned. Example: longestPalindrome('babad') -> 'aba' longestPalindrome('cddb') -> 'bb' ''' longest = '' for i in range(len(s)): center = self._expand(i, i, s) mirror = self._expand(i, i+1, s) longest = max(center, mirror, longest, key=len) return longest def _expand(self, left: int, right: int, s: str): ''' Helper function to expand from center indices. ''' while left > -1 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left+1:right]
a3274656b13e5e5ff9b9c45d6c44ced0800999d7
TheDarktor/Ex-Python
/ex021.py
601
4.125
4
# ALGORITIMO QUE RECEBE O NOME DE UMA PESSOA E RETORNA AS SEGUINTES INFORMAÇÕES: # Nome com todas as letras maiúsculas e minúsculas. # Quantas letras tem o nome completo (sem considerar os espaços) # Quantas letras tem o primeiro nome. nome = str(input('Digite seu nome completo: ')).strip() print('Seu nome em maiúsculo é: {}'.format(nome.upper())) print('Seu nome em minúsculo é: {}'.format(nome.lower())) print('Seu nome possui {} letras'.format(len(nome) - nome.count(' '))) nome_split = nome.split() print('Seu primeiro nome possui {} letras'.format(len(nome_split[0])))
b448008dcec180654421e24c0134dbee474d5d93
budavariam/advent_of_code
/2020/21_2/solution.py
2,262
3.65625
4
""" Advent of code 2020 day 21/2 """ import math from os import path import re from collections import defaultdict class AllergenAssessment(object): def __init__(self, data): self.lines, self.allergenes, self.ingredients = data def solve(self): mapping = {} while len(mapping) < len(self.allergenes): for name, appearance in self.allergenes.items(): possible_ingredients = self.ingredients for location in appearance: possible_ingredients = possible_ingredients.intersection( self.lines[location]["ingredients"]) if len(possible_ingredients) == 1: # save result mapping[name] = list(possible_ingredients)[0] # clear from ingredient list for index, line in enumerate(self.lines): new_ingredients = line["ingredients"].difference( set(list(possible_ingredients))) self.lines[index]["ingredients"] = new_ingredients return ",".join([val for _, val in sorted(mapping.items())]) ALLERGEN_PARSER = re.compile(r'^(.*) \(contains (.*)\)$') def preprocess(raw_data): processed_data = raw_data.split("\n") result = [] all_ingredients = set() allergen_locations = defaultdict(set) for index, line in enumerate(processed_data): match = ALLERGEN_PARSER.match(line) ingredients = set(match.group(1).split(" ")) all_ingredients = all_ingredients.union(ingredients) allergens = set(match.group(2).split(", ")) for alg in allergens: allergen_locations[alg] = allergen_locations[alg].union( set([index])) result.append({ "ingredients": ingredients, "allergens": allergens, }) return result, allergen_locations, all_ingredients def solution(raw_data): """ Solution to the problem """ data = preprocess(raw_data) solver = AllergenAssessment(data) return solver.solve() if __name__ == "__main__": with(open(path.join(path.dirname(__file__), 'input.txt'), 'r')) as input_file: print(solution(input_file.read()))
5013dd18822f296e1d1da4fb5ff34f463176569b
Vekselsvip/HW-Python
/homework5.8.py
157
3.6875
4
a = [1, 2, 3, 4] b = [5, 4, 7, 8] c = [9, 10, 11, 12] d = [13, 14, 15, 16] matrix = a, b, c, d x = 0 for i in matrix: x += len(i) print(matrix) print(x)
e0940199096a20d7ace0bc7b4991076de47be294
MarcelArthur/leetcode_collection
/Greedy/860_Lemonade_Change.py
507
3.6875
4
#!python3 # Best Solution class Solution: def lemonadeChange(self, bills: List[int]) -> bool: # Time O(N) one loop five = ten = 0 for b in bills: if b == 5: five += 1 elif b == 10: five -= 1 ten += 1 elif ten > 0: ten -= 1 five -= 1 else: five -= 3 if five < 0: return False return True
b3af271bb29c33e75332f3ef3c1f735f774ecb7a
prafful/python_feb2020
/24_inheritance.py
822
3.921875
4
class Employee: def __init__(self, fname, lname): print("In Employee Constructor!") self.fname = fname self.lname = lname def getFname(self): return self.fname def getLname(self): return self.lname def getEmployeeDetails(self): print("In getEmployeeDetails of Employee!") class FullStackEngineer(Employee): def __init__(self, fname, lname, tech): self.tech = tech super().__init__(fname, lname) def getEmployeeDetails(self): return "Name: " + self.fname + " " + self.lname + "\n" + "Technology: " + self.tech fse1 = FullStackEngineer("O", "BB", "Java") print(fse1.getEmployeeDetails()) print(fse1.getFname()) print(fse1.getLname()) emp1 = Employee("Yuko", "San") emp1.getEmployeeDetails()
709779669418a19b281a860830d9d87e7db15e8d
syves/algorithms
/recursive_choc.py
722
3.8125
4
# ::num_choc //[int], int=>int def num_choc(dollars, cost, wrappers_required, wrappers): if dollars >= cost: return (1 + num_choc(dollars - cost, cost, wrappers_required, wrappers + 1)) elif wrappers >= wrappers_required: return 1 + (wrappers - wrappers_required) + num_choc(dollars, cost, wrappers_required, wrappers - wrappers_required) else: #wrappers < wrappers required return 0 def main(): T = int(raw_input()) triplets = [map(int, raw_input().split(' ')) for i in range(0, T)] print '\n'.join([str(num_choc(dollars, cost, wrappers_required, 0)) for dollars, cost, wrappers_required in triplets]) if __name__ == '__main__': main()
a97c0a7f2c94c8f561d3581d391a7f25ca86e903
chao-yuan-cy/DataStrucures
/DS3_BaseStructures/lesson3_queue.py
6,187
4.3125
4
''' 队列:是一系列有顺序的元素的集合,新元素加入在队列的一端,这一端叫做'队尾(rear)' 以有元素的移除发生在队列的另一端,叫做'队首(front)',当以元素被加入到队列之后, 他就从队尾向队首前进,直到他成为下一个即将被移除队列的元素 先进先出(FIFO):最新被加入的元素处于对尾,在队列中停留最长时间的元素处于队首 ----------------------------------- rear front ----------------------------------- 抽象数据类型(ADT): Queue() 创建一个空队列对象,无需参数,返回空的队列 enqueue(item) 将数据项添加到队尾,无返回值 dequeue() 从队首移出数据项,无需参数,返回值为队首数据项 isEmpty() 是否队列为空,无需参数,返回值为布尔值 size() 返回队列中的数据项的个数,无需参数 用python list实现队列 队尾在列表0的位置 enqueue insert() dequeue pop() ''' # class Queue(): # def __init__(self): # self.items = [] # def enqueue(self,item): # self.items.insert(0,item) # def dequeue(self): # return self.items.pop() # def isEmoty(self): # return self.items == [] # def size(self): # return len(self.items) # q = Queue() # q.enqueue(4) # q.enqueue('dog') # q.enqueue(True) # print(q.size()) # print(q.isEmoty()) # print(q.dequeue()) # q = Queue() # q.enqueue('hello') # q.enqueue('dog') # q.enqueue(3) # q.dequeue() ''' 马铃薯游戏,20s中结束,物品在谁手里,谁将被淘汰 选定一个人作为开始的人经过num个人后,将此人淘汰 ''' from pythonds.basic.queue import Queue name_list = ['红','明','强','丽','马','王','赵','三','四','五','啦'] num = 7 def send_flower(name_list,num): q = Queue() for name in name_list: q.enqueue(name) while q.size() > 1: for i in range(num): q.enqueue(q.dequeue()) n = q.dequeue() print(n) return q.dequeue() send_flower(name_list,num) ''' 模拟打印机 平均每天任意一个小时大约有10个学生在实验室里,在这一小时中 通常每人发起2次打印任务,每个打印任务的页数从1到20页不等,实验室中 的打印机比较老旧,如果以草稿模式打印,每分钟可以打印10页,打印机可以转换成 较高品质的打印模式,但每分钟只能打印5页,较慢的打印速度可能会使学生等待太长时间, 应该采取哪种打印模式 学生(等待时间+打印时间) 打印任务(打印任务队列) 打印机(状态:打印中,空闲) 1-20不等,随机数模拟 总共 10*2 =20 次打印任务,平均每3分钟产生一个打印任务 在3分钟内的任意一秒产生一个打印任务的概率是:task/180, 随机数模拟,如果生成随机数是180,就可以认为生成了一个任务 过程: 1.创建一个打印任务队列,每个任务在生成时被赋予了一个'时间戳' 2.一个小时中的每一秒(currentSecond)都需要判断: (1).是否有新的打印任务生成,如果有,把他加入打印队列, (2).如果打印机空闲并且队列不为空: 从队列中拿出一个任务交给打印机 从加入打印机时间 - 加入对列时间 = 等待时间 将该任务的等待时间加入到一个列表中,方便后续时候,计算总的学生打印花费时间 基于打印的页数的随机数,求出需要多长时间打印 3.打印机工作中,那对于打印机而言,就是工作一秒;对于打印任务而言,离打印结束又近了一秒 4.打印任务完成,剩余时间为0,打印机进入空闲状态 python实现: 1.三个对象:打印机(Printer) 打印任务(Task) 打印队列(PrintQueue) 2.Printer需要实时监测是否正在执行打印任务,判断自己处于空闲还是打印中的状态 设置是打印草稿还是打印高品质的 如果打印中,需要结合随机的打印的页数,计算打印的时间 打印结束后,将打印机状态设置为空闲 ''' import random from pythonds.basic.queue import Queue class Printer: def __init__(self,ppm): # 设置打印的速率 self.pagerate = ppm self.currentTask = None # 打印机当前任务的剩余时间 self.timeRemaining = 0 # 内部任务需要的时间计算函数 def tick(self): if self.currentTask != None: self.timeRemaining = self.timeRemaining - 1 if self.timeRemaining <=0: self.currentTask = None # 切换打印机状态 def is_busy(self): if self.currentTask != None: return True else: return False def startNew(self,newTask): self.currentTask = newTask self.timeRemaining = newTask.getPages()*60/self.pagerate class Task: def __init__(self,time): self.timestamp = time self.pages = random.randrange(1,21) def getStamp(self): return self.timestamp def getPages(self): return self.pages def waitTime(self,currenttime): return currenttime - self.timestamp def main(numSeconds,pagesPerMinute): labPrinter = Printer(pagesPerMinute) printQueue = Queue() watingtimes = [] for currentSeconds in range(numSeconds): if newPrintTask(): task = Task(currentSeconds) printQueue.enqueue(task) if(not labPrinter.is_busy()) and (not printQueue.isEmpty()): nexttask = printQueue.dequeue() watingtimes.append(nexttask.waitTime(currentSeconds)) labPrinter.startNew(nexttask) labPrinter.tick() averageWait = sum(watingtimes)/len(watingtimes) print('平均等待%6.2f秒 还剩%3d任务'%(averageWait,printQueue.size())) def newPrintTask(): num = random.randrange(1,181) if num == 180: return True else: return False for i in range(10): main(3600,5) ''' 1.学生数变为20 2.不局限在一个小时之内 '''
95459a6354f4c8641e2287b0ce97a5ae8ed87ad1
abdullahcheema63/itc_assignments
/i160033_assignment1/i160033_assignment1_question6.py
187
3.703125
4
#question_6 count=5 while count>0: space=count while space>0: print " ", space-=1 print count, print "\n", #print ((" "*count)+str(count)) count-=1
a84225c3220e3cc74ba9eb22329fca4eb591245e
etwit/LearnPy
/Day3/ex10.py
1,019
3.734375
4
#!/usr/bin/env python #_*_coding:utf-8_*_ ''' Created on 2017年7月21日 @author: Ethan Wong ''' #三元运算和lambda表达式 temp = None if 1>3: temp = 'gt' else: temp = 'lt' print temp result = 'gt' if 1>3 else 'lt' print result #lambda表达式 def foo(x,y): return x+y print foo(4,10) #智能调用一次 函数简单不会经常被调用 temp = lambda x,y,z:x+y*z print temp(4,4,5) #内置函数 a = [] #help(a) #传的是key print dir() #传的是key和value print vars() #查看变量类型 print type(a) #reload()会重新载入一次函数 t1 = 123 t2 = 124 print id(t1) print id(t2) print abs(-9) print bool(-1) #分页显示 取余数取商 #除数除以被除数等于商 print divmod(9, 3) #指数 print pow(2, 11) #所有都是真才是真0是假 print all([1,2,3,0]) #如果有一个是真即是真 print any([1,0,0,0]) print bool('') print bool(None) #字母数字转换 print chr(69) print ord('A') #十进制 十六进制 二进制 print hex(2000) print bin(2000) print oct(2)
ecfa72e8bb480c7caaf3977d1852e723858d0c02
dhitalsangharsha/GroupA-Baic
/question16.py
315
3.828125
4
'''16) Convert the code snippet given below to list comprehension to get the exact result. my_list = [] for x in [20, 40, 60]: for y in [2, 4, 6]: my_list.append(x * y) print(my_list) # Output: [40, 80, 120, 80, 160, 240, 120, 240, 360]''' x=[20,40,60] y=[2,4,6] my_list=[i*j for i in x for j in y] print(my_list)
e0cf291af346f5509ca3464e2a8520b3998080be
MilanDonhowe/AoC2019
/day3/ww3.py
2,261
3.921875
4
# Day 3: let's get this bread 🍞 import pprint def manhattan_distance(pos): return abs(pos[0]) + abs(pos[1]) def generate_vertices(pathstr, return_list=False): steps = pathstr.split(",") vertices = set() list_option = [] # x, y this_x = 0 this_y = 0 for step in steps: change_magnitude = int(step[1:]) for i in range(change_magnitude): if (step[0] == 'D'): this_y -= 1 elif (step[0] == 'U'): this_y += 1 elif (step[0] == 'L'): this_x -= 1 elif (step[0] == 'R'): this_x += 1 vertices.add((this_x, this_y)) list_option.append((this_x, this_y)) if (return_list == True): return list_option else: return vertices # Reading the actual input pathways = [] with open("input.txt", "r") as file: pathways = file.readlines() vertex_list_one = generate_vertices(pathways[0]) vertex_list_two = generate_vertices(pathways[1]) #vertex_list_one = generate_vertices("R75,D30,R83,U83,L12,D49,R71,U7,L72") #vertex_list_two = generate_vertices("U62,R66,U55,R34,D71,R55,D58,R83") distances = [] for point in vertex_list_two: if (point in vertex_list_one): distances.append(manhattan_distance(point)) print(f"the minimum distance is {min(distances)}") # part 2 finding the number of steps involved #list_one = generate_vertices("R75,D30,R83,U83,L12,D49,R71,U7,L72", True) #list_two = generate_vertices("U62,R66,U55,R34,D71,R55,D58,R83", True) list_one = generate_vertices(pathways[0], True) list_two = generate_vertices(pathways[1], True) paces_list_one = 0 intersects_one = {} for pos in list_one: paces_list_one += 1 if (pos in vertex_list_two): intersects_one[pos] = paces_list_one paces_list_two = 0 intersects_two = {} for pos in list_two: paces_list_two += 1 if (pos in vertex_list_one): intersects_two[pos] = paces_list_two steps_taken = set() for key, value in intersects_one.items(): this_step = value + intersects_two[key] steps_taken.add(this_step) print(f"the minimum number of steps required is {min(steps_taken)}")
83767cb2796f1fd41f1dbb203ca48cf121144434
shreyansh-tyagi/leetcode-problem
/integer replacement.py
838
4.25
4
''' Given a positive integer n, you can apply one of the following operations: If n is even, replace n with n / 2. If n is odd, replace n with either n + 1 or n - 1. Return the minimum number of operations needed for n to become 1. Example 1: Input: n = 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: n = 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 Example 3: Input: n = 4 Output: 2 Constraints: 1 <= n <= 231 - 1 ''' class Solution: def integerReplacement(self, n: int) -> int: c=0 while n>1: if n%2==0: n=n/2 c=c+1 else: if n==3 or n%4==1: n=n-1 c=c+1 else: n=n+1 c=c+1 return c
f0acb9b80b78f3ff92889ea8bf66a215593523df
brpadilha/exercicioscursoemvideo
/Desafios/Desafio 017.py
205
3.8125
4
#achar hipotenusa from math import sqrt,hypot op=float(input('Cateto oposto: ')) ad=float(input('Cateto adjacente: ')) #hip= sqrt(op**2+ad**2) hip=hypot(op,ad) print('Hipotenusa = {}' .format(hip))
fd54e4dc2b235f3c7bc976f74335d424eb58cd34
dallasmcgroarty/python
/DataStructures_Algorithms/linked_list_problems.py
1,843
4.0625
4
# function to check for a cycle in a linked list # the node class defined below: class Node(object): def __init__(self, value): self.value = value self.next = None def cycle_check(node): temp = node while(temp): if temp.next == node: return True else: temp = temp.next return False a = Node(1) b = Node(2) c = Node(3) d = Node(4) a.next = b b.next = c c.next = a # cycle created for testing print('cycle in linked list => ', cycle_check(a)) def print_list(head): temp = head while(temp): print(temp.value, end=' ') temp = temp.next print() a2 = Node(1) b2 = Node(2) c2 = Node(3) d2 = Node(4) e2 = Node(5) a2.next = b2 b2.next = c2 c2.next = d2 d2.next = e2 # reverse a linked list def reverse_list(head): current = head prev = None next = None while current: next = current.next current.next = prev prev = current current = next return prev reverse_list(a2) print(d2.next.value) print(c2.next.value) print(b2.next.value) reverse_list(e2) # print the length of the linked list/number of nodes in the list def list_size(head): temp = head count = 0 while(temp): count += 1 temp = temp.next return count print('size of list => ', list_size(a2)) # function thate takes a head node and an integer n and returns the # nth to last node in the linked list def nth_last_node(n, head): temp = head count = 0 while(temp): count += 1 temp = temp.next if n > count: raise LookupError('Error: n greater than length of list') target = count - n nth = head while(nth and target > 0): nth = nth.next target -= 1 return nth print_list(a2) nth_node = nth_last_node(3, a2) print(nth_node.value)
d4b303a89a076ff3791850b1ca1039855dee44e6
Ashish-012/Competitive-Coding
/linkedlist/deleteNode.py
922
4
4
''' If the head is `None` return. Setup two pointers, one pointing to the previous node and one to the current node and one variable counting the positions. Traverse till we reach the end of the list or the position. After that check if we reach the position or not, if not then the position does not exists in the list. Check if the position is 0, if it is then just point head to the `current.next`. Otherwise point prev.next to the current.next and set current to `None`. ''' def deleteNode(head, position): if not head: return head current = head prev = None pos = 0 while current and pos != position: prev = current current = current.next pos += 1 if pos!= position: return head elif pos == 0: head = current.next current = None else: prev.next = current.next current = None return head
1c7b1d661fa37200a80eca2770a9370767d16850
hector-cortez/python_examples
/ej019.py
304
3.828125
4
# -*- coding: utf-8 -*- ''' @author: Hector Cortez Calcular el factorial de un número N por sumas sucesivas, desplegar el resultado. ''' n = int(input("Introduzca un número: ")) f = 1 sf = 0 for ca in range(1, n + 1, 1): for cs in range(1, ca +1, 1): sf = sf + f f = sf sf = 0 print n, f
9053ae9fb05feb4046a9b002d63561e051d3aeda
Bjarkis/School_assignments
/max_int.py
477
4.46875
4
num_int = int(input("Input a number: ")) # Do not change this line # Fill in the missing code #The program should ask the user for positive integers and and then print the highest one out #If a negative integer it put in the program quits max_int = 0 #it needs to hold on to the largest int while num_int >= 0: if max_int < num_int: max_int = num_int num_int = int(input("Input a number: ")) print("The maximum is", max_int) # Do not change this line
a36c2bf8e14e07b4b0d3bc49c449ca3478877ba0
WorkWithSoham/Eel-Python-Sudoku
/Backend/OnlyPythonGenSolve.py
804
3.796875
4
import Sudoku_generator import Sudoku_solver def printPuzzle(string, SudokuPuzzle): print(string) for grid in SudokuPuzzle: print(grid) print("\n\n") if __name__ == '__main__': loop = True while loop: Difficulty = int(input("Enter difficulty level from 1 to 5, with 5 being most difficult: ")) if 0 < Difficulty < 6: loop = False diff = { 1: 23, 2: 22, 3: 19, 4: 18, 5: 17, } SudokuPuzzle = Sudoku_generator.generateSudoku(diff[Difficulty]) printPuzzle('The Puzzle', SudokuPuzzle) # Sudoku_solver.solveSudoku(SudokuPuzzle) # printPuzzle('The Solution', SudokuPuzzle) SudokuPuzzle = Sudoku_solver.ReturnableSudoku(SudokuPuzzle) printPuzzle('The Solution', SudokuPuzzle)
73155475c33a8d7b73408c7572f67c6b9de4977e
michaelRobinson84/Assignment2
/prac_02/files.py
596
3.75
4
# Program 1 name = input("Please enter your name: " ) out_file = open("name.txt", "w") out_file.write(name) out_file.close() # Program 2 in_file = open("name.txt", "r") name = in_file.read() print("Your name is", name) in_file.close() # Program 3 in_file = open("numbers.txt", "r") first_num = int(in_file.readline()) second_num = int(in_file.readline()) result = first_num + second_num print(result) in_file.close() # Program 4 running_total = 0 in_file = open("numbers.txt", "r") for line in in_file: running_total = running_total + int(line) print(running_total) in_file.close()
d45818a6ad143c1768f9b84c5b521afd64ae8c9d
laszewsk/cloudmesh
/cloudmesh/util/menu.py
1,275
3.84375
4
'''Ascii menu class''' def ascii_menu(title=None, menu_list=None): ''' creates a simple ASCII menu from a list of tuples containing a label and a functions refernec. The function should not use parameters. :param title: the title of the menu :param menu_list: an array of tuples [('label', f1), ...] ''' if not title: title = "Menu" n = len(menu_list) def display(): index = 1 print print title print len(title) * "=" print for (label, function) in menu_list: print " {0} - {1}".format(index, label) index += 1 print " q - quit" print print display() while True: result = input("Select between {0} - {1}: ".format(1, n)) print "<{0}>".format(result) if result == "q": break else: try: result = int(result) - 1 if result > 0 and result < n: (label, f) = menu_list[result] print "EXECUTING:", label, f.__name__ f() else: print "ERROR: wrong selection" except Exception, e: print "ERROR: ", e display()
e2b5b0bcd58d35bccc9f5968236c75411fc23622
bproetto92/midterm
/Q3.py
751
3.90625
4
# # QUESTION 3 # import os import pandas csv_filepath = "albums.csv" csv_data = pandas.read_csv(csv_filepath) print("------------------") print("PROCESSING SONG DATA FROM CSV...", csv_filepath) print("CSV FILE EXISTS?", os.path.exists(csv_filepath)) #> should be True, otherwise run the preceding setup code cell (one time only) print("------------------") print(csv_filepath) print(csv_data) # todo: import csv module or pandas package here! # # PART A # # todo: write some Python code here to answer the question! # # PART B # # todo: write some Python code here to answer the question! # # PART C # # todo: write some Python code here to answer the question! # # PART D # # todo: write some Python code here to answer the question!
efde7c9000ab9c0c88b9ce9891afb5f31a9977b1
bridgidrankin/Easter-Sunday-Calculator
/easter_sunday_calculator.py
1,210
4.21875
4
#!/usr/bin/env python3 def calcEasterSunday(year): #perform Easter calculation D = year - 1900 R = D % 19 P = (7 * R + 1) // 19 S = (11 * R + 4 - P) % 29 Q = D // 4 T = (D + Q + 31 - S) % 7 result = 25 - S - T if result > 0: month = "April" day = str(result) date = day + ' ' + month return date elif result <= 0: month = "March" day = str(31 + result) date = day + ' ' + month return date def main(): #display a welcome message print("THE EASTER SUNDAY CALCULATOR : ") print("==============================") print("Enter a negative value to quit") print("==============================") print() while True: # get input from the user year = int(input("Enter year:\t\t")) if year < 0: break else: date = calcEasterSunday(year) print() print("(Western) Easter Sunday is " + date + ", " + str(year)) print() print() print("Bye...") if __name__ == "__main__": main()
cb7ee0e90771d70e649a95186c5b6893550ba290
SimonLundell/Udacity
/Intro to Self-Driving Cars/Vehicle motion and control/Lesson_1/Understanding the Derivative.py
17,102
4.375
4
#!/usr/bin/env python # coding: utf-8 # # Understanding the Derivative # # You just saw these three statements. # # > 1. **Velocity** is the instantaneous rate of change of **position** # > 2. **Velocity** is the slope of the tangent line of **position** # > 3. **Velocity** is the derivative of **position** # # But there's another, more formal (and mathematical) definition of the derivative that you're going to explore in this notebook as you build an intuitive understanding for what a derivative is. # # ## BEFORE YOU CONTINUE # This notebook is a long one and it really requires focus and attention to be useful. Before you continue, make sure that: # # 1. You have **at least 30 minutes** of time to spend here. # 2. You have the mental energy to read through math and some (occasionally) complex code. # # ----- # ## Formal definition of the derivative # # The **derivative of $f(t)$ with respect to t** is the function $\dot{f}(t)$ ("f dot of t") and is defined as # # $$\dot{f}(t) = \lim_{\Delta t \to 0} \frac{f(t+\Delta t) - f(t)}{\Delta t}$$ # # You should read this equation as follows: # # *"F dot of t is equal to the limit as delta t goes to zero of F of t plus delta t minus F of t all over delta t"* # ## Outline # In this notebook we are going to unpack this definition by walking through a series of activities that will end with us defining a python function called `approximate_derivative`. This function will look very similar to the math shown above. # # A rough outline of how we'll get there: # # 1. **Discrete vs Continuous Motion** - A quick reminder of the difference between **discrete** and **continuous** motion and some practice defining continuous functions in code. # # 2. **Plotting continuous functions** - This is where you'll see `plot_continuous_function` which is a function that takes **another function** as an input. # # 3. **Finding derivatives "by hand"** - Here you'll find the **velocity** of an object *at a particular time* by zooming in on its **position vs time** graph and finding the slope. # # 4. **Finding derivatives algorithmically** - Here you'll use a function to reproduce the steps you just did "by hand". # # 5. **OPTIONAL: Finding the full derivative** - In steps 3 and 4 you actually found the derivative of a function *at a particular time*, here you'll see how you can get the derivative of a function for **all** times at once. Be warned - the code gets a little weird here. # # ----- # ## 1 - Discrete vs Continuous Motion # # The data we deal with in a self driving car comes to us discretely. That is, it only comes to us at certain timestamps. For example, we might get a position measurement at timestamp `t=352.396` and the next position measurement at timestamp `t=352.411`. But what happened in between those two measurements? Did the vehicle **not have a position** at, for example, `t=352.400`? # # Of course not! # # > Even though the position data we measure comes to us **discretely**, we know that the actual motion of the vehicle is **continuous**. # # Let's say I start moving forwards from `x=0` at `t=0` with a speed of $2 m/s$. At t=1, x will be 2 and at t=4, x will be 8. I can plot my position at 1 second intervals as follows: # In[1]: from matplotlib import pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') t = [0,1,2,3,4] x = [0,2,4,6,8] plt.scatter(t,x) plt.show() # This graph above is a **discrete** picture of motion. And this graph came from two Python **lists**... # # But what about the underlying **continuous** motion? We can represent this motion with a function $f$ like this: # # $$f(t)=2t$$ # # # How can we represent that in code? # # A list won't do! We need to define (surprise, surprise) a function! # In[2]: def position(time): return 2*time print("at t =", 0, "position is", position(0)) print("at t =", 1, "position is", position(1)) print("at t =", 2, "position is", position(2)) print("at t =", 3, "position is", position(3)) print("at t =", 4, "position is", position(4)) # That looks right (and it matches our data from above). Plus it can be used to get the position of the vehicle in between "sensor measurements!" # In[3]: print("at t =", 2.2351, "position is", position(2.2351)) # This `position(time)` function is a continuous function of time. When you see $f(t)$ in the formal definition of the derivative you should think of something like this. # ----- # ## 2 - Plotting Continuous Functions # # Now that we have a continuous function, how do we plot it?? # # We're going to use `numpy` and a function called `linspace` to help us out. First let me demonstrate plotting our position function for times between 0 and 4. # In[4]: # Demonstration of continuous plotting import numpy as np t = np.linspace(0, 4) x = position(t) plt.plot(t, x) plt.show() # #### EXERCISE - create and plot a continuous function of time # **Write a function, `position_b(time)` that represents the following motion:** # # $$f(t)=-4.9t^2 + 30t$$ # # **then plot the function from t = 0 to t = 6.12** # In[14]: # EXERCISE def position_b(time): return -4.9 * time ** 2 + 30 * time t = np.linspace(0, 6.12) x = position_b(t) print(t) plt.plot(t, x) plt.show() # don't forget to plot this function from t=0 to t=6.12 # Solution is below. # In[ ]: # # # # Spoiler alert! Solution below! # # # # In[7]: def position_b(time): return -4.9 * time ** 2 + 30 * time t = np.linspace(0, 6.12) z = position_b(t) plt.plot(t, z) plt.show() # **Fun fact (maybe)** # # There's a reason I used the variable `z` in my plotting code. `z` is typically used to represent distance above the ground and the function you just plotted actually represents the height of a ball thrown upwards with an initial velocity of $30 m/s$. As you can see the ball reaches its maximum height about 3 seconds after being thrown. # ### 2.1 - Generalize our plotting code # I don't want to have to keep copy and pasting plotting code so I'm just going to write a function... # In[15]: def plot_continuous_function(function, t_min, t_max): t = np.linspace(t_min, t_max) x = function(t) plt.plot(t,x) # In[16]: plot_continuous_function(position_b, 0, 6.12) plt.show() # Take a look at `plot_continuous_function`. # # Notice anything weird about it? # # This function actually *takes another function as input*. This is a perfectly valid thing to do in Python, but I know the first time I saw code like this I found it pretty hard to wrap my head around what was going on. # # Just wait until a bit later in this notebook when you'll see a function that actually `return`s another function! # # For now, let me show you other ways you can use `plot_continuous_function`. # In[17]: def constant_position_motion(time): position = 20 return position + 0*time def constant_velocity_motion(time): velocity = 10 return velocity * time def constant_acceleration_motion(time): acceleration = 9.8 return acceleration / 2 * time ** 2 plot_continuous_function(constant_position_motion, 0, 20) plt.show() # In[18]: # position vs time # with constant VELOCITY motion plot_continuous_function(constant_velocity_motion, 0, 20) plt.show() # In[19]: # position vs time # with constant ACCELERATION motion plot_continuous_function(constant_acceleration_motion, 0, 20) plt.show() # ---- # ## 3 - Find derivative "by hand" *at a specific point* # # Let's go back to the ball-thrown-in-air example from before and see if we can find the **velocity** of the ball at various times. Remember, the graph looked like this: # In[20]: plt.title("Position vs Time for ball thrown upwards") plt.ylabel("Position above ground (meters)") plt.xlabel("Time (seconds)") plot_continuous_function(position_b,0,6.12) plt.show() # Now I would like to know the **velocity** of the ball at t=2 seconds. # # > GOAL - Find the velocity of the ball at t=2 seconds # # And remember, **velocity is the derivative of position**, which means **velocity is the slope of the tangent line of position** # # Well we have the position vs time graph... now we just need to find the slope of the tangent line to that graph AT t=2. # # One way to do that is to just zoom in on the graph until it starts to look straight. I can do that by changing the `t_min` and `t_max` that I pass into `plot_continuous_function`. # #### EXERCISE - "Linearize" a function by zooming in # # The code below allows you to adjust a single parameter `DELTA_T` in order to control how zoomed in you are. # # Read through and run the code to get a sense for how it works. # # Then you should adjust `DELTA_T` until the graph looks like a straight line. Start by trying `DELTA_T = 3.0`, then `DELTA_T = 2.5`, then `2.0` etc... # # The "formal definition of the derivative" had a part that said: # # $$\lim_{\Delta t \to 0}$$ # # This activity is an exploration of why "taking delta t to zero" makes sense. # In[23]: DELTA_T = 10 # you don't need to touch the code below t_min = 2 - (DELTA_T / 2) t_max = 2 + (DELTA_T / 2) plt.title("Position vs Time for ball thrown upwards") plt.ylabel("Position above ground (meters)") plt.xlabel("Time (seconds)") plot_continuous_function(position_b, t_min, t_max) plt.show() # With `DELTA_T = 0.06` (try it) the graph looks like this: # # ![](https://d17h27t6h515a5.cloudfront.net/topher/2017/December/5a31a625_linearized/linearized.png) # # which looks PRETTY straight to me. Since we've zoomed in SO much the graph looks like a straight line. # # The tangent line to this graph (at t=2) will have to have a slope that's REALLY close to the slope of *this* linear approximation. # # So what's the slope of this line? # # $$\text{slope}=\frac{\text{vertical change in graph}}{\text{horizontal change in graph}}$$ # # or, another way to say that: # # $$\text{slope}=\frac{\Delta z}{\Delta t}$$ # **Vertical change** # # The position has a value of about **40.08** (just less than 40.1) at the beginning and increases to about **40.71** at the end. So the vertical change is # # $$\Delta z = 40.71 - 40.08 = 0.63 \text{ meters}$$ # **Horizontal change** # # The horizontal change is just $\Delta t$, which in this case is 0.06 seconds. # # **Slope** # # $$\text{slope} = \frac{0.63 \text{ meters}}{0.06 \text{ seconds}} = 10.5 \text{ meters per second}$$ # ---- # ## 4 - Finding derivatives algorithmically *at a certain point* # # Why would we calculate the vertical change by looking at a graph? Let's just get the EXACT change numerically. # # The change in position for the zoomed in graph (which shows values from $t = 1.97$ to $t = 2.03$ is given mathematically as: # # $$\Delta z = f(2.03) - f(1.97)$$ # # And we can calculate this in code as well! # In[24]: DELTA_Z = position_b(2.03) - position_b(1.97) DELTA_T = 0.06 SLOPE = DELTA_Z / DELTA_T print("the graph goes from", position_b(1.97), "at t=1.97") print("to", position_b(2.03), "at t=2.03") print("which is a delta z of", DELTA_Z) print() print("This gives a slope of", SLOPE) # Using the **exact** values of the function gives us a more accurate value for the slope (and therefore the velocity of the ball). But now it looks like we've answered our question: # # > The velocity of the ball at $t=2$ is **10.4 meters per second** # #### EXERCISE - Find the speed of the ball at t = 3.45 # # Use a sequence of steps similar to what we just did for $t=2$ to find the velocity of the ball at $t=3.45$ # In[31]: # Your code here! delta_z = position_b(3.46) - position_b(3.44) delta_t = 0.02 slope = delta_z / delta_t print(slope) # In[ ]: # # # # Spoiler alert! Solution below! # # # # # In[26]: # SOLUTION - FIRST ATTEMPT # 1. set some relevant parameters TIME = 3.45 DELTA_T = 0.02 # 2. The "window" should extend 0.01 to the left and # 0.01 to the right of the target TIME t_min = TIME - (DELTA_T / 2) t_max = TIME + (DELTA_T / 2) # 3. calculate the value of the function at the left and # right edges of our "window" z_at_t_min = position_b(t_min) z_at_t_max = position_b(t_max) # 4. calculate vertical change delta_z = z_at_t_max - z_at_t_min # 5. calculate slope slope = delta_z / DELTA_T print("speed is",slope, "m/s at t =", TIME) # You can see my solution above. This code *approximates* the derivative of our position_b function at the time $t=3.45$. # # With a bit of modification we could make this into a function that approximates the derivative of **any** function at **any** time! # In[27]: # SOLUTION - second (better) version def approximate_derivative(f, t): # 1. Set delta_t. Note that I've made it REALLY small. delta_t = 0.00001 # 2. calculate the vertical change of the function # NOTE that the "window" is not centered on our # target time anymore. This shouldn't be a problem # if delta_t is small enough. vertical_change = f(t + delta_t) - f(t) # 3. return the slope return vertical_change / delta_t deriv_at_3_point_45 = approximate_derivative(position_b, 3.45) print("The derivative at t = 3.45 is", deriv_at_3_point_45) # Let's connect the code in the function above to the mathematical definition of the derivative... # # > The **derivative of $f(t)$ with respect to t** is the function $\dot{f}(t)$ and is defined as # # > $$\dot{f}(t) = \lim_{\Delta t \to 0} \frac{f(t+\Delta t) - f(t)}{\Delta t}$$ # # 1. As you can see, I made `delta_t` very small (0.00001) so as to approximate "the limit as $\Delta t$ goes to 0". Why not just set `delta_t = 0.0`? Go ahead! Try it in function above. See what happens when you try to run it :) # # 2. The vertical change of the function at time `t` is calculated in the exact same way that the mathematical definition prescribes. # # 3. The slope is calculated identically as well. # ---- # ## 5 - OPTIONAL: Finding the "full" derivative # # The `approximate_derivative` function is good because it works for ANY function at ANY point. But I want to know the derivative of ANY function at **EVERY** point. # # > GOAL - I want a function that takes a continuous function as input and produces ANOTHER continuous function as output. The output function should be the derivative of the input function. # In[32]: # These four lines of code do exactly what we wanted! # There is a good chance that this will be the # hardest-to-understand code you see in this whole # Nanodegree, so don't worry if you're confused. def get_derivative(f): def f_dot(t): return approximate_derivative(f,t) return f_dot # After reading (and running) the code above, try running the code cells below to see why this function is useful... # In[33]: # plot 1 - a reminder of what our position function looks like. # Remember, this is a plot of vertical POSITION vs TIME # for a ball that was thrown upwards. plt.title("Position vs Time for ball thrown upwards") plt.ylabel("Position above ground (meters)") plt.xlabel("Time (seconds)") plot_continuous_function(position_b, 0, 6.12) plt.show() # In[34]: # plot 2 - a plot of VELOCITY vs TIME for the same ball! Note # how the ball begins with a large positive velocity (since # it's moving upwards) and ends with a large negative # velocity (downwards motion right before it hits the ground) velocity_b = get_derivative(position_b) plot_continuous_function(velocity_b, 0, 6.12) plt.show() # In[35]: # plot 3 - a plot of ACCELERATION vs TIME for the same ball. # Note that the acceleration is a constant value # of -9.8 m/s/s. That's because gravity always causes # objects to accelerate DOWNWARDS at that rate. acceleration_b = get_derivative(velocity_b) plt.ylim([-11, -9]) plot_continuous_function(acceleration_b, 0, 6.12) plt.show() # In[36]: # plot 4 - All 3 plots at once! plot_continuous_function(position_b, 0, 6.12) plot_continuous_function(velocity_b, 0, 6.12) plot_continuous_function(acceleration_b, 0, 6.12) plt.show() # Now that you've seen what `get_derivative` can do for us, let's try to understand how it works... # # ```python # def get_derivative(f): # def f_dot(t): # return approximate_derivative(f,t) # return f_dot # ``` # # Let's go line by line. # # 1. `def get_derivative(f):` The important thing to note here is that this function only takes ONE input and that input is a function `f`. # # 2. `def f_dot(t):` Here we define a new function INSIDE `get_derivative`. And note that THIS function only takes a single input `t`. # # 3. `return approximate_derivative(f,t)` Here we define the behavior of `f_dot` **when called with some time `t`**. And what we want it to do is to approximate the derivative of the function `f` at time `t`. # # 4. `return f_dot` Here we return the function that we just defined! Weird, but reasonable if you think about it. Now, if you think about the `get_derivative` functions overall role, it's this: take a function as input and produce another function (which is the derivative) as output. #
d46f3a2abef1c0c945840a22f13b85135a8d9fc8
PiyushMishra318/Programs
/Python/Knapsack.py
429
3.765625
4
max_weight=int(input("Enter the maximum weight the burgalur can carry:")) n=int(input("Enter the no. of items in the house:")) value=[] weight=[] for i in range(0,n): a=int(input()); value.append(a); b=int(input()); weight.append(b); while(i<n): maxim=max(value); if(value[i]==maxim): if(weight[i]<=max_weight): totalcost=value[i] value.pop(i) n=n-1; print(totalcost)
e013bb9696774beb815997ceadd8915113cf0e45
devhliu/arterial_vessel_measures
/utils/search_utils.py
3,932
3.671875
4
import os from pathlib import Path import pandas as pd # finds files(used to find error_files) and gives a dictionary as output # this function is used only for manual error preparation def find_error_file(directory, file="001.nii", search="string"): """ finds files(used to find error_files) and gives a dictionary as output Args: directory: directory in which error nifti files are located file: specify file type using a string, for example "nii" search: search string should also be included in the file name Returns: """ file_list = [] suffix = [] for x, y, z in (os.walk(directory)): for item in z: if file in item and search in item: image_to_find = os.path.join(x, item) file_list.append(image_to_find) suffix.append(item) error_suffix_dict = dict(zip(file_list, suffix)) print("This is error suffix dict", error_suffix_dict) return error_suffix_dict def find_list_to_evaluate(directory, file="001.nii"): """ Finds files in a "directory" with the "file" name. returns a list of the folder names in the previous directory. For example for path root/patient/E1/segmentation.nii.gz the folder_name gives E1 which is the error string. See code documentation for details. Args: directory: the folder containing the segmentations should be given as the "directory" argument file: file name of the segmentation nifti Returns: a list of folder names containing the files. """ segmentation_strings = [] for x, y, z in (os.walk(directory)): for item in z: if file in item: image_to_evaluate = os.path.join(x, item) # first leaves out(cuts) the filename of the path then cut = Path(image_to_evaluate).parent # gets the last element after / folder_name = os.path.basename(cut) segmentation_strings.append(folder_name) print("....Getting segmentation paths to compare with ground_truth") return segmentation_strings # In this code it is used to get all the csv files in the evaluation folder def find_file(directory, file="001.nii", search="string"): """ finds list of files in a directory with file extension containing the search string Args: directory: directory to search file: specify file type using a string, for example "nii" search: search string should be in the file name Returns: list of matching files """ file_list = [] for x, y, z in (os.walk(directory)): for item in z: if file in item and search in item: image_to_find = os.path.join(x, item) file_list.append(image_to_find) return file_list # gets all the values of a metric (for example DICE) for every segmentation # and makes a dictionary with error name and metric value def find_metric_to_dict(list_of_csv_files, metric="DICE"): metric_value_list = [] tree_names = [] for path in list_of_csv_files: # gets the error name from the file name of the csv # to create a list(later to zip the to lists to create a dictionary) file_with_extension = os.path.basename(path) file_without_extension = os.path.splitext(file_with_extension)[0] tree_names.append(file_without_extension) # reads csv into dataframe metricsdataframe = pd.read_csv(path) # extracts from the csv the value of the metric metric_value = metricsdataframe.at[0, metric] metric_value_list.append(metric_value) # dictionary_of_a_metric contains all the values of one particular metric # # for the segmentations that are simulated in this run dictionary_of_a_metric = dict(zip(tree_names, metric_value_list)) return dictionary_of_a_metric
b714da7b9acfe90347b87becb7d3174e48248bd2
vishaalgc/codes
/Array/kadane.py
421
3.6875
4
def maxSubArray( nums): """ :type nums: List[int] :rtype: int """ max_ending_here = 0 max_so_far = 0 for i in nums: max_ending_here += i if max_ending_here < 0: max_ending_here = 0 max_so_far = max(max_so_far, max_ending_here) if max_so_far == 0: return max(nums) return max_so_far A = [-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(A))
071e2fdace928eee78cd0b23ca6e69906a369d3b
Danielwong6325/ICTPRG-Python
/week11/question6.py
1,020
3.953125
4
def Getpasswordfromuser(): SpecialSym =['$', '@', '#', '%','!','*','?','/','-','^','&'] while True: try: pas = str(input("Please enter your password")) for i in len(pas): if pas.upper <1: raise ValueError("You need at least one uppercase letter") if pas.lower <1: raise ValueError("You need at least one lowercase letter") if len(i) <7: raise ValueError("You need to have a longer password") if pas == ("Password"): raise ValueError("The password word should not contain the word ""password") if not any(SpecialSym in pas): raise ValueError("Password should have at least one of the symbols $@#") else: print("You have a valid password") return pas except ValueError as err: print(err) Getpasswordfromuser()
93e0b55bf6a69dcb828dc3fba3b24315c11ea724
Aniketthani/Python-Tkinter-Tutorial-With-Begginer-Level-Projects
/32flashcard.py
8,112
3.65625
4
from tkinter import * from PIL import ImageTk,Image from random import randint, shuffle root=Tk() root.title("Flashcard App By Aniket Thani") root.geometry("700x700") root.config(bg="orange") #functions def random_image(): #list of state names global our_states our_states = ['chhattisgarh', 'madhya_pradesh', 'karnataka', 'tamil_nadu', 'gujarat', 'harayana', 'rajasthan', 'delhi', 'maharashtra', 'bihar'] #generate random integer global rnum rnum = randint(0, len(our_states)-1) global state state = "states/"+our_states[rnum]+".jpg" #display image of state global state_img state_img = ImageTk.PhotoImage(Image.open(state)) global img_label img_label = Label(states_frame, image=state_img) img_label.pack() def check_answer(): value=answer.get().lower() value=value.replace(" ","_") if our_states[rnum]==value: response.config(text="Correct!! " + our_states[rnum].replace("_"," ").title()) else: response.config(text="Incorrect!! " + our_states[rnum].replace("_"," ").title()) answer.delete(0,"end") img_label.destroy() random_image() def states(): hide_all_frames() states_frame.pack() states_frame.focus_set() #create next state button next_button=Button(states_frame,text=" >> ",padx=10,pady=7,command=states) next_button.pack(pady=5) #create answer input box global answer answer=Entry(states_frame,font=("Helvetica",20),bd=3) answer.pack(pady=5) #create submit button submit=Button(states_frame,text="Submit",pady=5,command=check_answer) submit.pack() #create response label global response response=Label(states_frame,text="",font=("Helvetica",16),bg="orange") response.pack() random_image() def state_capitals(): hide_all_frames() state_capitals_frame.pack(fill=BOTH,expand=1) label=Label(state_capitals_frame,text="Capitals").pack(pady=5) #selecting random states and capitals count =1 global answer_list answer_list=[] global ranum global state_list state_list = ['chhattisgarh', 'madhya_pradesh', 'karnataka', 'tamil_nadu','gujarat', 'harayana', 'rajasthan', 'delhi', 'maharashtra', 'bihar'] global capitals capitals=['raipur','bhopal','bangalore','chennai','gandhinagar','chandigarh','jaipur','delhi','mumbai','patna'] while count<4: if count==1: ranum=randint(0,len(state_list)-1) global answer_state answer_state=state_list[ranum] global answer_capital answer_capital=capitals[ranum] else: ranum=randint(0,len(state_list)-1) answer_list.append(capitals[ranum]) state_list.remove(state_list[ranum]) capitals.remove(capitals[ranum]) count+=1 #shuffle the answer list shuffle(answer_list) #var for radio button global user_selection user_selection=StringVar() user_selection.set("0") #create a pass button pass_button=Button(state_capitals_frame,text=" >> " , font=("Helvetica",14),command=state_capitals).pack(pady=5) #create radio buttons radio1=Radiobutton(state_capitals_frame,text=answer_list[0],variable=user_selection,value='0',tristatevalue=4,bg="orange") radio2=Radiobutton(state_capitals_frame,text=answer_list[1],variable=user_selection,value='1',tristatevalue=4,bg="orange") radio3 = Radiobutton(state_capitals_frame, text=answer_list[2], variable=user_selection, value='2',tristatevalue=4,bg="orange") radio1.pack(pady=5) radio2.pack(pady=5) radio3.pack(pady=5) submit=Button(state_capitals_frame,text="Submit",command=capital_check).pack(pady=5) #response label global response_label response_label=Label(state_capitals_frame,text="",font=("Helvetica",15),bg="orange") response_label.pack(pady=5) # putting image on screen global state_path global img global label_img state_path="states/"+answer_state+".jpg" img=ImageTk.PhotoImage(Image.open(state_path)) label_img=Label(state_capitals_frame,image=img).pack() def capital_check(): if answer_list[int(user_selection.get())]==answer_capital: response="Correct !! " else: response="Incorrect !! " answer_capital_copy=answer_capital state_capitals() response_label.config(text=response + answer_capital_copy + " was the right answer") def hide_all_frames(): #loop through and destroy children widgets in frames for widget in states_frame.winfo_children(): widget.destroy() for widget in state_capitals_frame.winfo_children(): widget.destroy() for widget in math_addition_frame.winfo_children(): widget.destroy() # hiding frames states_frame.pack_forget() state_capitals_frame.pack_forget() math_addition_frame.pack_forget() #creating math addition function def add(): hide_all_frames() math_addition_frame.pack(fill="both",expand=1) math_addition_label=Label(math_addition_frame,text="Additon Flashcard",font=("Helvetica",15)).pack(pady=10) #frame for displaying images pic_frame=Frame(math_addition_frame,height=500,width=500,bg="orange") pic_frame.pack() global num_1 global num_2 num_1=randint(1,10) num_2=randint(1,10) #path to image global path1 global path2 path1="numbers/"+str(num_1) + ".jpg" path2="numbers/"+str(num_2) + ".jpg" #images global img_1 global img_2 img_1=ImageTk.PhotoImage(Image.open(path1)) img_2=ImageTk.PhotoImage(Image.open(path2)) #labels global num_1_label global num_2_label num_1_label=Label(pic_frame,image=img_1,height=300,width=250).grid(row=0,column=0) num_2_label=Label(pic_frame,image=img_2,height=300,width=250).grid(row=0,column=2) sign_label = Label(pic_frame, text=" + ",font=("Helvetica",30),bg="orange").grid(row=0, column=1) #answer input box global answer_box answer_box=Entry(math_addition_frame,font=("Helvetica",20),bd=3) answer_box.pack(pady=30) submit_button=Button(math_addition_frame,text="submit",command=addition_check).pack(pady=15) global output_label output_label=Label(math_addition_frame,text="",font=("Helvetica",16),bg="orange") output_label.pack(pady=10) answer_box.focus_set() def addition_check(): ans=num_1+num_2 if(str(ans)==str(answer_box.get())): response="Correct!! The Value of Sum was "+str(ans) else: response="Incorrect!! The Value of Sum was "+str(ans) add() output_label.config(text=response) def event_bind(event): #checking if states_frame is packed on screen or not if states_frame.winfo_manager(): # calling the check answer function check_answer() if state_capitals_frame.winfo_manager(): capital_check() if math_addition_frame.winfo_manager(): addition_check() #binding return key for submit root.bind("<Return>", event_bind) #creating menu my_menu=Menu(root) root.config(menu=my_menu) #create geography menu items states_menu=Menu(my_menu) my_menu.add_cascade(label="Geography",menu=states_menu) states_menu.add_command(label="States",command=states) states_menu.add_separator() states_menu.add_command(label="State Capitals",command=state_capitals) states_menu.add_command(label="Exit",command=root.quit) #creating math menu math_menu=Menu(my_menu) my_menu.add_cascade(label="Math",menu=math_menu) math_menu.add_command(label="Addition",command=add) #creating Frames states_frame=Frame(root,height=700,width=700,bg="orange") state_capitals_frame=Frame(root,height=700,width=700,bg="orange") math_addition_frame=Frame(root,height=700,width=700,bg="orange") root.mainloop()
815d1c457f96c17f89899f1085def24a07f767c0
anaswara-97/python_project
/flow_of_control/looping/even_btw_range.py
277
4.1875
4
min=int(input("Enter minimum limit : ")) max=int(input("Enter maximum limit : ")) print("even numbers between",min,"and",max,"are :") # for i in range(min,max+1): # if(i%2==0): # print(i) #while using i=min while(i<max+1): if(i%2==0): print(i) i+=1
d71bc7c9cd312bd8edfb5b63c5e52cb4c1220559
kingwangz/python
/king26.py
494
3.609375
4
fdict = dict((['x', 1], ['y', 2])) print(fdict) ddict = {}.fromkeys(('x', 'y'), (-1, -2)) print(ddict) print(ddict.keys()) print('y' in ddict.keys()) print(hash('x')) s = set('cheeseshop') print(s) t = frozenset('bookshop') print(t) myTuple = (123, 'xyz', 0, 45.67) legends = {('Poe', 'author'): (1809, 1849, 1976), ('Gaudi', 'architect'): (1852, 1906, 1987), ('Freud', 'psychoanalyst'): (1856, 1939, 1990)} i = iter(legends) for k in list(legends): print(next(i)) print(legends)
c8d8dc910aac2a8db2ee3fdfc300f60d8658dfaa
bodsul/code2040-challenge
/challenge.py
3,408
3.8125
4
#import library for making HTTP requests import requests #import library for converting python objects to JSON format import json #import object from library to convert ISO date to python date format import dateutil.parser as parser #import object from library to add dates in python format from datetime import timedelta #initialize parameters email = "sule1@illinois.edu" github = "https://github.com/bodsul/code2040-challenge" url = "http://challenge.code2040.org/api/register" input = {"email": email, "github": github} #convert input to JSON format json_input = json.dumps(input) #use post method of request library to make request value = requests.post(url, data = json_input) #print and save returned object print "returned value is: ", value.text my_return = value.json() #extract string from returned dict my_token = my_return.values()[0] json_token = json.dumps({"token": my_token}) #I.Reverse a string #initialize url to get string url = "http://challenge.code2040.org/api/getstring" value = requests.post(url, data = json_token) my_string = value.json() my_string_value = my_string.values()[0] #reverse string using standard python method my_string_reversed = my_string_value[::-1] #return reversed string json_answer = json.dumps({"token": my_token, "string": my_string_reversed}) url = "http://challenge.code2040.org/api/validatestring" value = requests.post(url, data = json_answer) #print result print value.text #II. needle in a haystack url = "http://challenge.code2040.org/api/haystack" value = requests.post(url, data = json_token) my_dict = value.json() my_dict_value = my_dict.values()[0] my_needle = my_dict_value['needle'] my_array = my_dict_value['haystack'] #initilize counter for position j = 0 #for loop to find position of needle in haystack for j in range(0, len(my_array)): if(my_array[j] == my_needle): break j+=1 #return answer json_answer = json.dumps({"token": my_token, "needle": j}) url = "http://challenge.code2040.org/api/validateneedle" value = requests.post(url, data = json_answer) #print result print value.text #III. Prefix problem url = "http://challenge.code2040.org/api/prefix" value = requests.post(url, data = json_token) my_dict = value.json() my_dict_value = my_dict.values()[0] my_string = my_dict_value['prefix'] my_array = my_dict_value['array'] my_array_answer =[] for entry in my_array: #append entry that doesnot start with my_string to my_array_answer if not entry.startswith(my_string): my_array_answer.append(entry) url = "http://challenge.code2040.org/api/validateprefix" json_answer = json.dumps({"token": my_token, "array": my_array_answer}) value = requests.post(url, data = json_answer) #print result print value.text #IV. The dating game url = "http://challenge.code2040.org/api/time" value = requests.post(url, data = json_token) my_dict = value.json() my_dict_value = my_dict.values()[0] my_isodate = my_dict_value["datestamp"] my_interval = my_dict_value["interval"] #convert date to python format my_pdate = parser.parse(my_isodate) #add date to interval in seconds my_pdate += timedelta(seconds = my_interval) #convert date to iso format my_newdate = my_pdate.isoformat() json_answer = json.dumps({"token": my_token, "datestamp": my_newdate}) url = "http://challenge.code2040.org/api/validatetime" value = requests.post(url, data = json_answer) #print result print value.text
b92e50b0a0c20a19b71e18500dea4612363e3dda
jossefaz/python_test_automation
/_1_basics/tests/test_main.py
318
3.703125
4
from ..app.main import add def test_add_num(): assert add(1,2) == 3 def test_add_str(): assert add("hello ", "world") == "hello world" class TestMain: def test_add_num(self): raise assert add(1, 2) == 3 def test_add_str(self): assert add("hello ", "world") == "hello world"
226c25531b4b79451cfdf69647c22dfa54c9ab07
jieer-ma/algorithm_practice
/max_string.py
1,092
3.890625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: MSJ # date: 2021/3/11 # desc:计算字符串或列表中每个字符出现的次数,并打印出现次数最多的字符 def calc_max_string(str): # 将字符串转化成列表 str_list = list(str) # 定义一个空字典,用来存储 字符: 出现次数 str_dict = {} # 遍历列表(字符串) for x in str_list: # 如果该字符没有在字典中出现过,则赋值为1,否则在原来基础上+1 if str_dict.get(x) is None: str_dict[x] = 1 else: str_dict[x] = str_dict[x] + 1 # 输出 { 字符:出现次数 } print(str_dict) # 找出字典中的 max(values) max_str = max(str_dict.values()) # 遍历字典 for k,v in str_dict.items(): # 如果 values = max,打印该字符及出现次数 if v == max_str: print('出现次数最多的字符是:', k, ',一共出现了', v, '次') else: continue if __name__ == '__main__': calc_max_string('asdfghjkliiuytreqasdccvv')
439c5270cc6c81e4bbde866a26d2bfcbf2325007
devak23/python
/other_progs/sorting.py
768
4.3125
4
#!/usr/bin/python # An implementation of the quick sort algorithm from enum import Enum class Order(Enum): ASCENDING = 1 DESCENDING = 2 def quicksort(collection, order): "Quicksort over a list-like sequence" if len(collection) == 0: return collection pivot = collection[0] small = quicksort([f for f in collection if f < pivot], order) large = quicksort([f for f in collection if f > pivot], order) return (large + [pivot] + small) if order == Order.DESCENDING else (small + [pivot] + large) if __name__ == '__main__': colleagues = ['Guru', 'Avinash', 'Ashwani', 'Tejas', 'Abhay', 'Srini', 'Rakshapal', 'Suhas', 'Lokesh'] sorted_colleagues = quicksort(colleagues, Order.ASCENDING) print(sorted_colleagues)
c6f5cb86c18f49889926147e51e947ee969e1533
theMonarK/Snake2p
/mCase.py
1,170
3.640625
4
# -*- coding: cp1252 -*- #Module case #Constructeur def creer(etat) : assert type(etat) is str entier=0 if etat == "rien": entier=0 elif etat == "vide": entier=1 elif etat == "bonbon": entier=2 elif etat == "snake1": entier=3 elif etat == "snake2": entier=4 return entier #Accesseur def getCase(x): '''(case)''' assert type(x) is int etat="bug" if x==0: etat="rien" elif x==1: etat="vide" elif x==2: etat="bonbon" elif x==3: etat="snake1" elif x==4: etat="snake2" return etat def setCase(etat): '''etat''' assert type(etat) is str entier = 0 if etat == "rien": entier=0 elif etat == "vide": entier=1 elif etat == "bonbon": entier=2 elif etat == "snake1": entier = 3 elif etat == "snake2": entier = 4 #print entier return entier def getCaseX(x, etat): '''(case, etat)''' assert type(x) is int assert type(etat) is str return getCase(x)== etat
94e7c649d370b33515a8c9b6e8fb9a3017bde8f5
Dino-Dan/PassManager
/PassManager.py
5,466
4.1875
4
import os class PassManager(): '''(None) -> None This is a class that will manage passwords by storing them in a text file. They will be in a format that follows this: WEBSITE:[USERNAME, PASSWORD] This will also be able to read the passwords within the text file and output them if the user so wishes. This can also delete passwords and change stored passwords ''' def __init__(self): ''' (None) -> None Check if the directory has a text file, if not, create one ''' # Check the current directory to check if there already is a # text file within that you can use. If there isn't then create one files = filter(os.path.isfile, os.listdir(os.curdir)) if("passfile.txt" not in files): file = open("passfile.txt" , "w") file.close() self.file_name = "passfile.txt" def save(self, website, username, password): ''' This functions will save the given website's username and password into a text file ''' # Create a file variable file = open(self.file_name, "a") # Add the website and it's information to the text file file.write(website + "[" + username + "," + password + "]\n") # Close the file file.close() def read(self, website): ''' This function will read the website's username and password from a text file ''' # Create a output and create a local variable for file and a # variable to check if the website has any information saved file = open(self.file_name, "r") output = website + "'s login information:" found = False # Loop through the text file to find the website's information for line in file: # Find the index of the brackets open_brkt = line.find("[") close_brkt = line.find("]") if(line[:open_brkt] == website): # We found the website's login information found = True # Get the information from the line and split # it into an array for referencing info = line[open_brkt + 1:close_brkt] info = info.split(",") # Add the information including user friendly output output += ("\nUsername: " + info[0] + "\nPassword: " + info[1]) # If we can not find the website's information, tell the user if(not found): raise InvalidLookupError("Not a saved webstie") # Give the appropriate output and close the file print(output) file.close() def delete(self, website): ''' This function will go through and find the saved website data and delete it ''' # Create a file variable, a seek variable, and read all the lines try: website_info = self._delete_helper(website) except InvalidLookupError as error: print(error.args) if(not_needed == "Not Found"): print(website + "'s information doesn't exist") else: print(website + "'s data has been removed!") def changePass(self, website, newpassword): ''' This function will go through the text file and change the website's password to a new password ''' # Delete previous save, but retain the username try: website_info = self._delete_helper(website) except InvalidLookupError as error: print(error.args) username = website_info[website_info.find("[") + 1: website_info.find(",")] # Resave the information with the newpassword self.save(website, username, newpassword) def changeUser(self, website, newusername): ''' This function will go through the text file and change the website's username to a new username ''' # Delete previous save, but retain the password try: website_info = self._delete_helper(website) except InvalidLookupError as error: print(error.args) password = website_info[website_info.find(",") + 1: website_info.find("]")] # Resave the information with the newusername self.save(website, newusername, password) def getAll(self): ''' This function will output all of the saved usernames and passwords beside their respective website names ''' file = open(self.file_name, "r") for line in file: open_brkt = line.find("[") print(line[:open_brkt]) def _delete_helper(self, website): ''' Helper function that deletes and returns the website's info ''' # Create a file variable, a seek variable, and read all the lines file = open(self.file_name, "r+") website_info = "" found = False lines = file.readlines() file.seek(0) # Look for the website's data for line in lines: # If the line is not the website to be removed, add it to the file open_brkt = line.find("[") if website != (line[:open_brkt]): file.write(line) else: website_info = line found = True # Truncate and close the file file.truncate() file.close() if(not found): raise InvalidLookupError("Not a saved website") return line class InvalidLookupError(LookupError): def __init__(self, arg): self.args = arg
30c11a5cddec6270eaa71709cdc84d31222c17b7
Chris0089/adaline-single-modular
/perceptron.py
17,636
3.8125
4
''' Neuronal Networks Algorithm Neuron availables: Perceptron Adaline Activation functions available: step logistic Training methods available: feedforward backpropagation ''' import sys import random import numpy as np import pylab import matplotlib.pyplot as plt from itertools import chain from user_data import * import time LIMIT_TOP = 1 LIMIT_BOTTOM = -1 ERROR101= "Error 101: No inputs found for a neuron." ERROR102 = "Error 102: Too many input list for a neuron." ERROR103 = "Error 103: Not especified activation function." class Neuron: def __init__(self, inputs, af, bias): self.inputData = None self.inputQuantity = None self.combinationOfInputs = None self.weightData = None self.output = None self.summation = None self.v = None self.activationFunction = af self.bias = bias self.set_inputs(inputs) self.obtain_inputs_info() self.generate_random_values() self.calculate_output() def set_inputs(self, inputs): if isinstance(inputs, list): self.inputData = [] self.inputData = inputs.copy() else: self.inputData = inputs def obtain_inputs_info(self): if isinstance(self.inputData, list): if isinstance(self.inputData[0], list): if isinstance(self.inputData[0][0], list): sys.exit(ERROR102) else: self.inputQuantity = len(self.inputData[0]) self.combinationOfInputs = len(self.inputData) else: self.inputQuantity = len(self.inputData) self.combinationOfInputs = 1 else: self.inputQuantity = 1 self.combinationOfInputs = 1 def generate_random_values(self): if self.inputQuantity > 1: self.weightData = [] for eachInput in range(0,self.inputQuantity): self.weightData.append(random.uniform(LIMIT_BOTTOM, LIMIT_TOP)) elif self.inputQuantity == 1: self.weightData = random.uniform(LIMIT_BOTTOM, LIMIT_TOP) else: sys.exit(ERROR101) def activation_function(self, value): if self.activationFunction == "step": if value <= 0: output = 0 else: output = 1 return output elif self.activationFunction == "logistic": output = 1 / (1 + np.exp(value * -1)) return output else: sys.exit(ERROR103) def calculate_output(self): if self.combinationOfInputs == 1: self.summation = 0 self.v = 0 if self.inputQuantity > 1: for quantity in range(0, self.inputQuantity): self.summation += self.inputData[quantity] * self.weightData[quantity] else: self.summation = self.inputData * self.weightData self.v = self.summation + self.bias self.output = self.activation_function(self.v) else: self.summation = [] self.v = [] self.output = [] for combination in range (0, self.combinationOfInputs): self.summation.append(0) for quantity in range(0, self.inputQuantity): self.summation[combination] += self.inputData[combination][quantity] * self.weightData[quantity] self.v.append(0) self.v[combination] = self.summation[combination] + self.bias self.output.append(self.activation_function(self.v[combination])) #print("Weight = " + str(self.weightData)) #print("Bias = " + str(self.bias)) class Layer: def __init__(self, inputData, desiredData, actFunc, trainingMtd, neurons): self.bias = None self.neurons = [] self.inputData = inputData.copy() self.outputData = None self.outputTransformed = [] self.desiredOutput = desiredData.copy() self.activationFunction = actFunc self.training = trainingMtd self.neuronsQty = neurons self.generate_rand_bias() self.create_neurons() self.error = [] def generate_rand_bias(self): self.bias = random.uniform(LIMIT_BOTTOM, LIMIT_TOP) def create_neurons(self): for neuron in range(0, self.neuronsQty): self.neurons.append(Neuron(self.inputData, self.activationFunction, self.bias )) self.outputData = self.neurons[neuron].output.copy() self.calculate_output() def calculate_output(self): if self.neuronsQty == 1: self.neurons[0].calculate_output() self.outputData = self.neurons[0].output.copy() elif self.neuronsQty > 1 : for neuron in range(0, len(self.neurons)): self.neurons[neuron].calculate_output() outputArray = [] print(self.neurons) for val in range(0, len(self.neurons[0].inputData)): outputArray.append([]) for neuron in range(0, self.neuronsQty): outputArray[val].append(self.neurons[neuron].output[val]) self.outputData = outputArray.copy() print("data beach") print(self.outputData) def training_step(self): for neuron in range(0, self.neuronsQty): for out in range(0, len(self.desiredOutput)): error = 0.0 error = self.desiredOutput[out] - self.outputData[out] if error != 0: self.bias = self.bias + (ETA * error) self.neurons[neuron].bias = self.bias for inputValue in range(0, len(self.inputData[0])): self.neurons[neuron].weightData[inputValue] = self.neurons[neuron].weightData[inputValue] + (ETA * error * self.inputData[out][inputValue]) def training_logistic(self): for neuron in range(0, self.neuronsQty): for out in range(0, len(self.desiredOutput)): error = 0.0 error = self.desiredOutput[out] - self.outputData[out] if abs(error) > MAXERROR: self.bias = self.bias + (ETA * error * self.outputData[out] * (1-self.outputData[out])) self.neurons[neuron].bias = self.bias for inputValue in range(0, len(self.inputData[0])): self.neurons[neuron].weightData[inputValue] = self.neurons[neuron].weightData[inputValue] + (ETA * error * self.inputData[out][inputValue] * self.outputData[out] * (1-self.outputData[out])) def training_logistic_multi(self): for neuron in range(0, self.neuronsQty): for out in range(0, len(self.desiredOutput)): self.bias = self.bias + (ETA * self.error[out] * self.outputData[out][neuron] * (1-self.outputData[out][neuron])) self.neurons[neuron].bias = self.bias for inputValue in range(0, len(self.inputData[0])): self.errorBS = [] self.errorBS.append([]) self.errorBS[0].append(self.error[0]) self.errorBS[0].append(self.error[1]) self.errorBS.append([]) self.errorBS[1].append(self.error[2]) self.errorBS[1].append(self.error[3]) self.neurons[neuron].weightData[inputValue] = self.neurons[neuron].weightData[inputValue] + (ETA * self.errorBS[neuron][inputValue] * self.inputData[out][inputValue] * self.outputData[neuron][inputValue] * (1-self.outputData[neuron][inputValue])) def updateError(self, error): self.error = [] self.error = error.copy() def updateInputs(self, inputData): self.inputData = [] self.inputData = inputData.copy() class NeuronalNetwork: def __init__(self, inputData, desiredData, eta, layersQty, neuronsQty, typeNetwork="other", training = "NA", logicGate="NA"): self.train= training self.finalOutput = [] self.finalWeights = [] self.iteration = 0 self.inputData = inputData.copy() self.desiredOutput = [] self.desiredOutput = desiredData.copy() self.eta = eta self.layers = [] self.layersQty = layersQty self.neuronsQty = neuronsQty self.typeNetwork = typeNetwork self.w1 = None self.w2 = None self.bias = None self.logicGate = logicGate self.mainAlgorithm() self.globalError = [] def isDesiredOutput(self): if self.typeNetwork == "perceptron": if self.desiredOutput == self.finalOutput: return True else: return False elif self.typeNetwork == "adaline" or self.typeNetwork == "multilayer": for val in range(0, len(self.desiredOutput)): error = abs(self.desiredOutput[val] - self.finalOutput[val]) if error > MAXERROR: return False return True def calculateGlobalError(self): self.globalError = [] for val in range(0, len(self.desiredOutput)): self.globalError.append(self.desiredOutput[val] - self.finalOutput[val]) def mainAlgorithm(self): if self.typeNetwork == "perceptron": iteration = 0 layer = Layer(self.inputData, self.desiredOutput, "step", "fastforwarding", 1) while not self.isDesiredOutput(): iteration += 1 print( "Ciclo: " + str(iteration) ) layer.training_step() layer.calculate_output() self.finalOutput = layer.outputData.copy() print(self.finalOutput) print(self.desiredOutput[0]) self.iteration = iteration self.w1 = layer.neurons[0].weightData[0] self.w2 = layer.neurons[0].weightData[1] self.bias = layer.bias print("finished!!!!!!!!") if self.train == "NA": self.printPlot(layer.neurons[0].weightData[0], layer.neurons[0].weightData[1], layer.neurons[0].bias) if self.typeNetwork == "multi": iteration = 0 layer = Layer(self.inputData, self.desiredOutput, "step", "fastforwarding", 1) while not self.isDesiredOutput(): iteration += 1 print( "Ciclo: " + str(iteration) ) layer.training_step() layer.calculate_output() self.finalOutput = layer.outputData.copy() print(self.finalOutput) print(self.desiredOutput[0]) self.iteration = iteration if self.typeNetwork == "adaline": iteration = 0 layer = Layer(self.inputData, self.desiredOutput, "logistic", "fastforwarding", 1) self.finalOutput = layer.outputData.copy() while not self.isDesiredOutput(): iteration += 1 print( "Ciclo: " + str(iteration) ) layer.training_logistic() layer.calculate_output() self.finalOutput = layer.outputData.copy() print(self.finalOutput) print(self.desiredOutput[0]) self.iteration = iteration self.w1 = layer.neurons[0].weightData[0] self.w2 = layer.neurons[0].weightData[1] self.bias = layer.bias print("finished!!!!!!!!") if self.train == "NA": self.printPlot(layer.neurons[0].weightData[0], layer.neurons[0].weightData[1], layer.neurons[0].bias) if self.typeNetwork == "multilayer": iteration = 0 innerLayer = Layer(self.inputData, self.desiredOutput, "logistic", "fastforwarding", 2) lastLayer = Layer(innerLayer.outputData, self.desiredOutput, "logistic", "fastforwarding", 1) self.finalOutput = lastLayer.outputData.copy() while not self.isDesiredOutput(): #time.sleep(.001) iteration += 1 print( "Ciclo: " + str(iteration) ) print("Inner Neuron 1:" + str(innerLayer.neurons[0].weightData)) print("Inner Neuron 2:" + str(innerLayer.neurons[1].weightData)) print("Last Neuron:" + str(lastLayer.neurons[0].weightData)) self.calculateGlobalError() print("Global error:" + str(self.globalError)) innerLayer.updateError(self.globalError) innerLayer.training_logistic_multi() innerLayer.calculate_output() lastLayer.updateInputs(innerLayer.outputData) lastLayer.training_logistic() lastLayer.calculate_output() self.finalOutput = lastLayer.outputData.copy() self.iteration = iteration print("finished!!!!!!!!") def printPlot(self, w1, w2, bias): minX = min(chain.from_iterable(self.inputData)) - 2 maxX = max(chain.from_iterable(self.inputData)) + 2 x = np.linspace(minX, maxX, 4) formulaPlot = (-1 * bias / w2) - (w1 / w2 * x) if self.desiredOutput[0] == 0: plt.plot(0,0, 'x', color = 'red') else: plt.plot(0,0, 'ro', color = 'green') if self.desiredOutput[1] == 0: plt.plot(0,1, 'x', color = 'red') else: plt.plot(0,1, 'ro', color = 'green') if self.desiredOutput[2] == 0: plt.plot(1,0, 'x', color = 'red') else: plt.plot(1,0, 'ro', color = 'green') if self.desiredOutput[3] == 0 : plt.plot(1,1, 'x', color = 'red') else: plt.plot(1,1, 'ro', color = 'green') plt.suptitle(str(self.typeNetwork) + " " +str(self.logicGate)+ " " + str(self.iteration) + " iteraciones.") pylab.plot(x, formulaPlot, color = "blue") pylab.show() xorMulti = NeuronalNetwork(INPUTDATA, [0,1,0,0], ETA, LAYERS, NEURONS, "perceptron", "multi" ) xorMulti2 = NeuronalNetwork(INPUTDATA, [0,0,1,0], ETA, LAYERS, NEURONS, "perceptron", "multi" ) xnorMulti = NeuronalNetwork(INPUTDATA, [0,0,0,1], ETA, LAYERS, NEURONS, "perceptron", "multi" ) xnorMulti2 = NeuronalNetwork(INPUTDATA, [1,0,0,0], ETA, LAYERS, NEURONS, "perceptron", "multi" ) xorBack = NeuronalNetwork(INPUTDATA, [0,1,0,0], ETA, LAYERS, NEURONS, "adaline", "backpropagation" ) xorBack2 = NeuronalNetwork(INPUTDATA, [0,0,1,0], ETA, LAYERS, NEURONS, "adaline", "backpropagation" ) xnorBack = NeuronalNetwork(INPUTDATA, [1,0,0,0], ETA, LAYERS, NEURONS, "adaline", "backpropagation" ) xnorBack2 = NeuronalNetwork(INPUTDATA, [0,0,0,1], ETA, LAYERS, NEURONS, "adaline", "backpropagation" ) def XNORPlot(title, w1, w2, bias, w3, w4, bias2 ): minX = min(chain.from_iterable(INPUTDATA)) - 2 maxX = max(chain.from_iterable(INPUTDATA)) + 2 x = np.linspace(minX, maxX, 4) formulaPlot1 = (-1 * bias / w2) - (w1 / w2 * x) formulaPlot2 = (-1 * bias2 / w4) - (w3 / w4 * x) plt.plot(0,0, 'ro', color = 'green') plt.plot(0,1, 'x', color = 'red') plt.plot(1,0, 'x', color = 'red') plt.plot(1,1, 'ro', color = 'green') plt.suptitle(str(title)) pylab.plot(x, formulaPlot1, color = "blue") pylab.plot(x, formulaPlot2, color = "blue") pylab.show() def XORPlot(title, w1, w2, bias, w3, w4, bias2 ): minX = min(chain.from_iterable(INPUTDATA)) - 2 maxX = max(chain.from_iterable(INPUTDATA)) + 2 x = np.linspace(minX, maxX, 4) formulaPlot1 = (-1 * bias / w2) - (w1 / w2 * x) formulaPlot2 = (-1 * bias2 / w4) - (w3 / w4 * x) plt.plot(0,0, 'x', color = 'red') plt.plot(0,1, 'ro', color = 'green') plt.plot(1,0, 'ro', color = 'green') plt.plot(1,1, 'x', color = 'red') plt.suptitle(str(title)) pylab.plot(x, formulaPlot1, color = "blue") pylab.plot(x, formulaPlot2, color = "blue") pylab.show() perceptronAND = NeuronalNetwork(INPUTDATA, [0,0,0,1], ETA, LAYERS, NEURONS, "perceptron", "NA", "AND" ) adalineAND = NeuronalNetwork(INPUTDATA, [0,0,0,1], ETA, LAYERS, NEURONS, "adaline", "NA", "AND" ) perceptronOR = NeuronalNetwork(INPUTDATA, [0,1,1,1], ETA, LAYERS, NEURONS, "perceptron", "NA", "OR" ) adalineOR = NeuronalNetwork(INPUTDATA, [0,1,1,1], ETA, LAYERS, NEURONS, "adaline", "NA", "OR" ) perceptronNAND = NeuronalNetwork(INPUTDATA, [1,1,1,0], ETA, LAYERS, NEURONS, "perceptron", "NA", "NAND" ) adalinenAND = NeuronalNetwork(INPUTDATA, [1,1,1,0], ETA, LAYERS, NEURONS, "adaline", "NA", "NAND" ) perceptronNOR = NeuronalNetwork(INPUTDATA, [1,0,0,0], ETA, LAYERS, NEURONS, "perceptron", "NA", "NOR" ) adalineNOR = NeuronalNetwork(INPUTDATA, [1,0,0,0], ETA, LAYERS, NEURONS, "adaline", "NA", "NOR" ) XORPlot("Multilayer XOR", xorMulti.w1, xorMulti.w2, xorMulti.bias, xorMulti2.w1, xorMulti2.w2, xorMulti2.bias) XNORPlot("Multilayer XNOR", xnorMulti.w1, xnorMulti.w2, xnorMulti.bias, xnorMulti2.w1, xnorMulti2.w2, xnorMulti2.bias) XORPlot("Backpropagation XOR", xorBack.w1, xorBack.w2, xorBack.bias, xorBack2.w1, xorBack2.w2, xorBack2.bias) XNORPlot("Backpropagation XNOR", xnorBack.w1, xnorBack.w2, xnorBack.bias, xnorBack2.w1, xnorBack2.w2, xnorBack2.bias)
d402eb159e0d2fc5557077a39a0e910eb1dd3504
jose-carlos-code/CursoEmvideo-python
/exercícios/EX_CursoEmVideo/ex022.py
407
3.859375
4
nome = str(input('qual o seu nome completo?: ')).strip() print('analisando o seu nome... ') print('o seu nome em maiusculas e {}'.format(nome.upper())) print('o seu nome em minusculas e {}'.format(nome.lower())) print('seu nome tem um total de {} letras'.format(len(nome) - nome.count(' '))) dividido = nome.split() print('seu primeiro nome é {}, e ele tem {} letras'.format(dividido[0], len(dividido[0])))
66bfc88e0b5a80940ffa717bb3870b57cabc400b
SMcDick/BookPriceAnalyst
/example.py
756
3.65625
4
from selenium import webdriver from bs4 import BeautifulSoup #example of finding the price of a book driver=webdriver.PhantomJS(executable_path='/Users/jameszheng/GitProj/BookPriceAnalyst/phantomjs'); driver.get('http://bookscouter.com/prices.php?isbn=9780132139311&searchbutton=Sell'); html = driver.page_source; soup = BeautifulSoup(html, "html.parser") mydivs = soup.findAll("div", class_="offer") print driver.current_url companyDiv = mydivs[0].findAll("div", class_="column-1") priceDiv = mydivs[0].findAll("div", class_="column-6") #extract the string company = str(companyDiv[0].text).strip() price = str(priceDiv[0].findAll("div", class_="book-price-normal")[0].text).strip() #remove dollar sign price = float(price[1:]) print company print price
c63cc95cc0244f27e0cc70fd46e651c7f2f4ae83
wangbo-android/python
/Python参考手册4/chapter3/ch3.py
460
3.9375
4
def compare(a, b): if a is b: print("a is b") elif a == b: print('a == b') elif type(a) is type(b): print('type a is type b') l1 = list() l2 = l1 compare(l1, l2) print(dir(l1)) l3 = ['hello', 'world'] l4 = l3.copy() l5 = l3[:] del l4[1] print(l3) print(l4) print(l5) print(list({'name': 'wangbo', 'age': 30}.keys())) print(list({'name': 'wangbo', 'age': 30}.values())) print((type('hello world') is type(12))) print(isinstance('helloworld', str))
61beaf6ddc778d8b44333e96d8f46bcab9c2ca97
aaronfox/LeetCode-Work
/MeetingRoomsII.py
2,706
3.875
4
# URL: https://www.lintcode.com/problem/meeting-rooms-ii # Meeting Rooms II # Given an array of meeting time intervals consisting of start and end times # [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. def getMeetingRooms(times): # Sort separately created start and end times arrays. Then use two pointers. # If start time comes first, then a meeting has started and we need another room # If end time comes first, that means one meeting ended so we need one less room # Max number of rooms at any one time is the answer # O(nlog(n)) time complexity for sorting # O(n) space complexity for storing times in separate arrays startTimes = [x[0] for x in times] endTimes = [x[1] for x in times] startTimes = sorted(startTimes) endTimes = sorted(endTimes) print(startTimes) print(endTimes) i = 0 j = 0 currRooms = 0 rooms = 0 while i < len(times): # If start time is less than current end time, # then other meeting still occurring and we need another room if startTimes[i] < endTimes[j]: currRooms += 1 rooms = max(rooms, currRooms) i += 1 # If start time greater than end time, then other meeting is # over and we can decrement number of current rooms being used else: currRooms -= 1 j += 1 return rooms # This time, use min heap on time intervals sorted by start time # If the starting time of current interval is less than current min_heap # then push end of current interval end time to heap since we must add another room # Else, pop the current meeting as it has ended. The end result is the length # of the min heap since it will still contain the remaining min number of conference # rooms needed import heapq def getMeetingRooms2(times): if not times: return 0 times = sorted(times, key=lambda x: x[0]) # Only need end times in heap min_heap= [times[0][1]] # Start from second time interval for i in range(1, len(times)): interval = times[i] if interval[0] < min_heap[0]: heapq.heappush(min_heap, interval[1]) else: # Add interval end to min heap but pop top as well heapq.heappushpop(min_heap, interval[1]) return len(min_heap) intervals1 = [(0, 30), (5, 10), (15, 20)] print(getMeetingRooms2(intervals1)) print(getMeetingRooms2(intervals1) == 2) # Explanation: # We need two meeting rooms # room1: (0, 30) # room2: (5, 10), (15, 20) intervals2 = [(2, 7)] print(getMeetingRooms2(intervals2)) print(getMeetingRooms2(intervals2) == 1) # Explanation: # Only need one meeting room
e42a2a16261c919901dbd4a6b97f7eb3e6293586
Valen558/gao
/generator.py
404
4
4
#generator that uses yield def wordGenerator(): n=-1 allWords=['tea','table','go','speak','swim','jump','Earth','fly','plane','study','girl','boy','student'] while(True): n+=1 if(n<len(allWords)): yield allWords[n] else: raise StopIteration() wordGeneratorInstance=wordGenerator() next(wordGeneratorInstance) next(wordGeneratorInstance)
50d6ed7304d7c7814456b2ec448b689a56409cc1
zsmountain/lintcode
/python/interval_array_matrix/64_merge_sorted_array.py
1,201
4.375
4
''' Given two sorted integer arrays A and B, merge B into A as one sorted array. You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. Example A = [1, 2, 3, empty, empty], B = [4, 5] After merge, A will be filled as [1, 2, 3, 4, 5] ''' class Solution: """ @param: A: sorted integer array A which has m elements, but size of A is m+n @param: m: An integer @param: B: sorted integer array B which has n elements @param: n: An integer @return: nothing """ def mergeSortedArray(self, A, m, B, n): # write your code here i = m + n - 1 m -= 1 n -= 1 while m >= 0 and n >= 0: if A[m] > B[n]: A[i] = A[m] m -= 1 else: A[i] = B[n] n -= 1 i -= 1 while m >= 0: A[i] = A[m] m -= 1 i -= 1 while n >= 0: A[i] = B[n] n -= 1 i -= 1 s = Solution() A = [1, 2, 3, 0, 0] B = [4, 5] s.mergeSortedArray(A, 3, B, 2) print(A)
bfa6ef82ed7e1f9db2e74bab27fef8677d22c509
stefanverhoeff/leetcode
/is_palindrome.py
956
3.890625
4
import re class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) < 2: return True # Ignore case s = s.lower() # Strip non-alpha numerics from the string s = re.sub(r'[^a-z0-9]', '', s) # compare chars both sides start = 0 end = len(s) - 1 while start < end: if s[start] != s[end]: return False start += 1 end -= 1 # If they meet at the end, it's a palindrome return True sol = Solution() test_cases = [ 'lala', 'laal', '', '0P', '505', 'ohhiqihho', 'A man, a plan, a canal: Panama' ] for test in test_cases: result = sol.isPalindrome(test) print(test, result)
53433f98d50292faf01ed0c8244b50626421c86a
arvindkg/Machine-Learning
/Classification-ForestCoverType-RandomForest/Classification-ForestCoverType-RandomForest.py
1,202
3.5625
4
# ------------------------------------------------ # Classification of Forest Cover Type Using Random Forests Algorithm # # Data Source: https://archive.ics.uci.edu/ml/datasets/covertype # # Author: Arvind Kumar # Email: arvindk.cse@gmail.com #------------------------------------------------- import pandas as pd from sklearn import ensemble from sklearn.model_selection import train_test_split from sklearn import metrics # Load the training and test data sets data = pd.read_csv('./UCI_covtype.data', header=None) # Analyze the data #data.describe() print(data.shape) # Create numpy arrays for use with scikit-learn train_X = data.iloc[:, :-1] train_y = data.iloc[:, 54:55] # Split the training set into training and validation sets X_train,X_test,y_train,y_test = train_test_split(train_X,train_y,test_size=0.2) # Train and predict with the random forest classifier rf_classifier = ensemble.RandomForestClassifier() # train rf_classifier rf_classifier.fit(X_train,y_train.values.ravel()) # predict using trained rf_classifier y_rf = rf_classifier.predict(X_test) print("============RandomForestClassifier Accuracy: ") print( metrics.accuracy_score(y_test,y_rf) )
b8e53d65674188feea0828c73211948ab211de8a
brookeclouston/CISC499
/initialization.py
4,466
3.84375
4
""" This script creates an initial population of candidate timetables. Each timetable will be represented as an array of values. Each value will represent a timeslot/room pairing for one of the courses to be timetabled. Input values will include the number of courses, number of entries in the timeslot/room grid, and population size. Return value will be list of the following: [0] - Population. List of candidate solutions. Each candidate solution is a dict, with key=course name and value=dict (keys: time, room, prof; values: assigned timeslot index, assigned room index, assigned prof index). e.g. for popsize = 5: """ import numpy from numpy.random import seed from numpy.random import randint import config import operator from operator import getitem import random # Remove the comment from the line below to make sure the 'random' # numbers are generated the same each time by fixing the seed. # seed(1) def init(popsize): """ Function: init Creates initial population: times and rooms assigned randomly, profs read from configuration file :param popsize: Size of initial population :returns: List containing initial population of candidate solutions (dictionary) """ courses = config.config_courses() rooms = config.config_rooms() profs = config.config_profs() times = config.config_times() profcourses = config.config_profcourselinks() population = [] while popsize != 0: candidate = {} courses = config.config_courses() # reinitialize time_room_slots = [] roomindex = 0 # Create list of tuples for each possible time/room slot option. # 3-tuple contains room index, time index, room capacity # e.g. (0,1,75) means room[0], time[1], room capacity = 75. for x, val in rooms.items(): for y in range(len(times)): time_room_slots.append((roomindex,y,val['Capacity'])) roomindex += 1 # loop through the courses, assign largest first for x in range(len(courses)): # find the next course to schedule this_course = next_tourn_schedule(courses) timeslot = "" room = "" room, timeslot, del_slot = schedule_it(this_course, courses, time_room_slots) time_room_slots.remove((room, timeslot, del_slot)) prof = "" # Find instructor for each course for item in profcourses: if item['Course'] == this_course: prof = item['Prof'] candidate[this_course] = {"room": room, "time": timeslot, "prof": prof} del courses[this_course] candidate["Fitness"] = 0 population.append(candidate) popsize -= 1 return [population, courses, rooms, profs, times] def next_to_schedule(course_list): """ Function: next_to_schedule Takes a list of courses, finds the one with highest enrolment. :param course_list: List of courses, each is a dictionary :returns: One course entry from the list. """ return max(course_list, key=lambda v: course_list[v]['Enrolment']) def next_tourn_schedule(course_list): """ Function: next_tourn_schedule Variation of next_to_schedule. Takes a list of courses, finds the top X with highest enrolment Selects one of the top X at random and returns that as the next course to be scheduled. :param course_list: List of courses, each is a dictionary :returns: One course entry from the list. """ tourn_set = dict(sorted(course_list.items(), key=lambda item: item[1]['Enrolment'])[-5:]) win_course, enrol = random.choice(list(tourn_set.items())) return win_course def schedule_it(course_tbs, course_list, slot_list): """ Function: schedule_it Schedules a single course. Takes a course name (as an index from a list of courses), schedules it to the first available room that has sufficient capacity to meet the course enrolment. :param course_tbs: Course 'to be scheduled'. Integer index referring to course_list :param course_list: List of courses, each is a dictionary :param slot_list: List of slots which a given course can be scheduled. Each slot is a tuple :returns: A slot from a list of slot options """ for slot in slot_list: if slot[2] > course_list[course_tbs]['Enrolment']: return slot
483e663109c2e43b9d15237711ff8eafae68e621
suntyneu/test
/test/输入一个字符串打印其中所有数字的和.py
166
3.578125
4
str = input() index = 0 sum = 0 while index < len(str): if str[index] >= "0" and str[index] <= "9": sum = sum + int(str[index]) index += 1 print(sum)
798dcb961584951bfc047e07ff1a770cc5d4bfe2
lamceol/python
/score.py
407
4.03125
4
# # Script for checking the score of a grade # Robert Lambe # # Get input inp = raw_input("Enter Score: ") score = float(inp) # Calculate score if score < 0 : print "Error1" quit() elif score > 1 : print "Error2" quit() elif score >= 0.9 : print "A" elif score >= 0.8 : print "B" elif score >= 0.7 : print "C" elif score >= 0.6 : print "D" elif score < 0.6 : print "F"
56ece4cad55fc5c0569e6ed4a9efce58fb92cae0
brpadilha/PythonPractice
/AprovedOrNot.py
275
4.09375
4
#a program that reads the note of a studend and if is greater than 6, returns approved else desapproved. def consult(n): if n >= 6: print ('Approved') else: print ('Desapproved') note = int(input("What is the note of the student: ")) consult(note)
70196d1c97f5973e09cbe4fe46d3f084fdde6ddf
ameyalaad/2048
/Game.py
6,927
4.03125
4
from Storage import Storage from Move import Move import os class Game: """ The class that keeps track of a Game session Each game is represented by a Storage class object """ def __init__(self): self.max_score = 0 self.storage = None def new_game(self): """ Starts a new game by creating a Storage object and generates 2 random tiles """ self.storage = Storage() # Generate two initial tiles self.storage.generate_update() self.storage.generate_update() # Clean the screen os.system('cls' if os.name == 'nt' else 'clear') print("Initializing Board....") self.storage.show_current_state() print() def interactive(self): """ Used to start a user-controlled interactive loop This uses the getchar module """ self.game_running = True while self.game_running: print("Do a move: ", ["w", "a", "s", "d", "n", "u"]) print(f"Anything else exits...\nScore = {self.storage.get_score()}, High Score = {self.max_score}") # fetch the possible outcomes before hand scores = self.storage.generate_moves() score_val = -1 self.storage.show_states() move = getch() # set the current state based on user input if move == b'w': if scores[0] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(0)) score_val = scores[0] elif move == b'a': if scores[1] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(1)) score_val = scores[1] elif move == b"s": if scores[2] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(2)) score_val = scores[2] elif move == b"d": if scores[3] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(3)) score_val = scores[3] elif move == b"n": self.new_game() elif move == b"u": try: prev_state, prev_score = self.storage.pop_previous_state() self.storage.set_state(prev_state) self.storage.set_score(prev_score) except IndexError as error: print("No previous state available. Do a move to undo") else: self.game_running = False print("Exiting...") break os.system('cls' if os.name == 'nt' else 'clear') if score_val == -1: print(f"No changes, try another move") else: self.storage.generate_update() new_score = self.storage.get_score() + score_val self.storage.set_score(new_score) if new_score > self.max_score: self.max_score = new_score if self.check_game_over() != 0: # TODO : Implement endgame print("Press 'n' for a new game, Anything else to exit") move = getch() if move == b'n': self.new_game() else: self.game_running = False break def check_game_over(self): return self.storage.check_game_over() def get_sum(self): return self.storage.get_sum_tiles() def get_max_tiles(self): return self.storage.get_max_tiles() def get_max_tiles_attainable(self): return self.storage.get_max_tiles_attainable() # The following methods may be used by an AI agent to manipulate the Game def play_move(self, move): # fetch the possible outcomes before hand scores = self.storage.generate_moves() score_val = -1 if move == 'up': if scores[0] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(0)) score_val = scores[0] elif move == 'left': if scores[1] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(1)) score_val = scores[1] elif move == 'down': if scores[2] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(2)) score_val = scores[2] elif move == 'right': if scores[3] != -1: self.storage.push_previous_state(self.storage.get_state(), self.storage.get_score()) self.storage.set_state(self.storage.get_move_state(3)) score_val = scores[3] elif move == 'undo': prev_state, prev_score = self.storage.pop_previous_state() self.storage.set_state(prev_state) self.storage.set_score(prev_score) if score_val != -1: self.storage.generate_update() new_score = self.storage.get_score() + score_val self.storage.set_score(new_score) if new_score > self.max_score: self.max_score = new_score print(f"Move: {move}") self.storage.show_current_state() print(f"Sum = {self.get_sum()}, Max attainable tile = {self.get_max_tiles_attainable()}") print("*************************************************************************") def _find_getch(): """ Gets a single character from the screen Used while a user is playing the Game """ try: import termios except ImportError: # Non-POSIX. Return msvcrt's (Windows') getch. import msvcrt return msvcrt.getch # POSIX system. Create and return a getch that manipulates the tty. import sys import tty def _getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch return _getch getch = _find_getch()
12b35199553afa6ad379198820c63ff8b0e2e6c2
JmcRobbie/novaRoverDemos
/nova_rover_demos/utils/python_benchmarking/lib/module.py
1,644
4.46875
4
# The following codes for sorting algorithms are taken from GeekforGeeks # (https://www.geeksforgeeks.org/) # SAMPLE CODE # YOU CAN DELETE THIS # Function to do insertion sort def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n-1): # range(n) also work but outer loop will repeat one time more than needed. # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Implementation of Selection sort def selectionSort(arr): # Traverse through all array elements for i in range(len(arr)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(arr)): if arr[min_idx] > arr[j]: min_idx = j # Swap the found minimum element with # the first element arr[i], arr[min_idx] = arr[min_idx], arr[i]
7e583113833f6adbbde9d50f391376a86a4ab58f
paolithiago/python_DSA
/VermaiorvalornnaLista_Reduce_Lambda.py
396
3.75
4
from functools import reduce #Cria uma lista lista= [1,16,2,444,69,8,4,36,54,87] print(lista) #gera um for para imprimir a lista #for i in lista: # print(i) #agora gerar um reduce para verificar o maior valor da lista sendo que o lambda ira para uma variavel chlista = lambda a , b: a if (a > b) else b type(chlista) print("Valor maior:") teste=reduce(chlista,lista) print(teste)
c16fe0870e7e9f81761d4b25892c1915a3603788
mohitgureja/DSA_Nanodegree-Python
/Project_1-Unscramble computer science problems/Task4.py
1,291
4.28125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv def get_telemarketers(remove_set,calls_list): number_set = set() for number in calls_list: if(number[0] not in remove_set): number_set.add(number[0]) return number_set def get_removable_telemarketers(texts_list,calls_list): number_set = set() for number in texts_list: number_set.add(number[0]) number_set.add(number[1]) for number in calls_list: number_set.add(number[1]) return number_set with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) number_set = get_telemarketers(get_removable_telemarketers(texts,calls),calls) print ("These numbers could be telemarketers: ") for number in sorted(number_set): print (number) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """
a7d27d04180c0c01c9ef5a6bde71266409cd531c
avin2003/ASlevel
/hollow.py
258
3.953125
4
size = int(input("Input number of rows:")) for row in range(1,(size+1)): for col in range(1,(2*size)): if row== size or row+col== size+1 or col-row== size-1: print("A",end = "") else: print(end=" ") print()
86a3cb2e6f694acefcd7ebbe6456dc716ad29ea2
vaibhavd2103/GitHubMini
/Python/palindrome.py
298
3.703125
4
def isPalindrome(num): return str(num) == str(num)[::-1] def largest(min, max): z = 0 for i in range(max, min, -1): for j in range(max, min, -1): if isPalindrome(i*j): if i*j > z: z = i*j return z print(largest(100, 999))
ed80455e7d05ea88690b53af1ed111c65218a980
nichollasong/Python-
/Chatbot/Chatbot.py
3,061
3.984375
4
print("Hello") response = raw_input("\nWhat is your name ?\n ") print("\nHello " + response + ". How are you feeling?\n ") import random moods1 = ["bad", "not great", "horrible", "not too bad"] responses1 = ["\nOh cheer up, I'm sure you'll be just fine\n "] moods2 = ["ok", "good", "great", "amazing", "fantastic"] responses2 = ["\nGlad to hear!\n", "\nI'm happy to hear that\n"] question = ["how are you?","how are you doing?"] responses3 = ["\nOkay\n","\nNot too bad\n", "\nI'm fine\n"] while True: userInput = raw_input() if userInput in moods1: random_response = random.choice(responses1) print(random_response) elif userInput in moods2: random_response = random.choice(responses2) print(random_response) elif userInput in question: random_response = random.choice(responses3) print(random_response) else: print("\nWould you like to know some random facts?\n") break answer = ["yes", "go on", "why not"] facts = ["\nBanging your head against a wall burns 150 calories an hour\n", "\nPteronophobia is the fear of being tickled by feathers\n", "\nA flock of crows is known as a murder\n", "\nThe first man to urinate on the moon was Buzz Aldrin, shortly after stepping onto the lunar surface\n", "\nThe top of the Eiffel Tower leans away from the sun, as the metal facing the sun heats up and expands. It can move as much as 7 inches\n", "\nYou are 1% shorter in the evening than in the morning\n", "\nMost dust particles in your house are made from dead skin\n", "\nA man from Britain changed his name to Tim Pppppppppprice to make it harder for telemarketers to pronounce\n", "\nThe word gorilla is derived from a Greek word meaning, A tribe of hairy women\n", "\nThe average person spends 6 months of their lifetime waiting on a red light to turn green\n", "\nBy law a pregnant woman can pee anywhere she wants to in Britain even if she chooses in a police officers helmets\n", "\nHuman saliva has a boiling point three times that of regular water\n", "\nIf you consistently fart for 6 years & 9 months, enough gas is produced to create the energy of an atomic bomb\n", "\nFacebook, Skype and Twitter are all banned in China\n", "\nArtist Salvador Dali would often get out of paying for drinks and meals by drawing on the cheques, making them priceless works of art and therefore un-cashable.\n"] while True: userInput = raw_input() if userInput in answer: random_response = random.choice(facts) print(random_response + "\nAnother one?\n") else: print("\nNice talking to you, goodbyeeeeeeeeeee\n")
17de8bf3f3b6f898225ef2e4d32391340e0b57c1
dipanbhusal/Python_practice_programs
/ques4.py
536
4.21875
4
# 4. Write a Python program to get a single string from two given strings, separated # by a space and swap the first two characters of each string. def string_swap(string1, string2): modified_str1 = string2[0:2]+string1[2:] modified_str2 = string1[0:2] + string2[2:] result = modified_str1 + ' ' + modified_str2 return result if __name__=="__main__": test_string1 = input('Enter the first string: ') test_string2 = input('Enter the second string: ') res = string_swap(test_string1, test_string2) print(res)
1503cf36b31931b5fdc27a3044fa06ba096fcf10
dlefcoe/daily-questions
/contiguousSum.py
1,069
4.28125
4
''' This problem was asked by Lyft. Given a list of integers and a number K, return which contiguous elements of the list sum to K. For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9. ''' def contigElem(intList, sumReq): ''' takes a list and searches contiuous elements until k is found. intList: type=list, list of integers sumReq: type=integer, the resultant sum that user requires returns: a list representing the contiguous string. ''' miniList = [] for i, v in enumerate(intList): for j in intList[i:]: miniList.append(j) if sum(miniList) == k: return miniList elif sum(miniList) > k: # too large, empty the minilist miniList.clear() break else: # k not reached continue return 'no contiguous list found' intList = [1, 2, 3, 4, 5] k = 12 answer = contigElem(intList, k) print(answer)
fe0333281e247a5aba14247c93f39ebd50e8963c
g10guang/offerSword
/app/tree/median.py
2,727
3.796875
4
# -*- coding: utf-8 -*- # author: Xiguang Liu<g10guang@foxmail.com> # 2018-05-05 16:59 # 题目描述:https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?tpId=13&tqId=11216&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking class Solution: """ 每次取中位数时候就重新排序 """ def __init__(self): self.container = [] def Insert(self, num): self.container.append(num) def GetMedian(self): t = sorted(self.container) self.container = t if len(t) % 2 == 0: # python2 中 int / int == int # python3 中 int / int == float return (t[len(t) // 2] + t[len(t) // 2 - 1]) / float(2) return t[len(t) // 2] from heapq import heappush, heappop class Solution2: """ 维护两个堆,其中一个为 left 大根堆,另一个 right 最小根堆 将小于中值的都插入到 left 中,将所有大于中值的都插入到 right 中 这样就可以以最快的速度取到中值,以计算中位数 因为所有元素都有可能成为中位数,因为后面的输入还不清楚,所以需要保存所有的元素 由于 python 堆为小顶堆,而在本算法中需要用到大顶堆,借助一个小技巧,将大顶堆中的所有元素取相反数 """ def __init__(self): self.left = [] self.right = [] self.elemNum = 0 def Insert(self, num): if len(self.right) == 0 or num > self.right[0]: heappush(self.right, num) else: # 取反 num heappush(self.left, -num) # 调整两个堆,目的 -1 <= len(self.left) - len(self.right) <= 1 while len(self.left) - len(self.right) > 1: elem = -heappop(self.left) heappush(self.right, elem) while len(self.right) - len(self.left) > 1: elem = heappop(self.right) heappush(self.left, -elem) def GetMedian(self): if len(self.left) == len(self.right): if len(self.left) == 0: return 0 return (-self.left[0] + self.right[0]) / 2.0 elif len(self.left) > len(self.right): return -self.left[0] else: return self.right[0] import unittest class TestCase(unittest.TestCase): def setUp(self): self.s = Solution2() def test_1(self): data = [5, 2, 3, 4, 1, 6, 7, 0, 8] median = [5, 3.5, 3, 3.5, 3, 3.5, 4, 3.5, 4] for i, x in enumerate(data): self.s.Insert(x) r = self.s.GetMedian() self.assertEqual(median[i], r) # r = self.s.GetMedian() # self.assertEqual(4, r)
3362c4d866825394bef76541b33e6ceade012bdd
Kashif1Naqvi/Python-Algorithums-the-Basics
/unorder_list_searching.py
196
3.75
4
items = [1,2,3,4,5,6,7,8,9,11] def find_items(item,itemslist): for i in range(0,len(items)): if item == itemslist[i]: return i return None print(find_items(11,items)) # output: 9
96faf832fe2dc14ab3046933631618b5c06410ea
dylanbr0wn/ProjectGames
/db_init.py
860
3.546875
4
""" Initialize SQLite database. Should only be called when one doesn't already exist """ import sys import os import sqlite3 def init(dbname): """ Initialize database with name dbname """ assert dbname is not None # Connect & get db cursor conn = sqlite3.connect(dbname) curs = conn.cursor() # Double check tables don't already exist, quit if so tab = curs.execute ("SELECT * FROM sqlite_master WHERE type='table' AND name='polls_game'").fetchall() if len(tab) > 0: print("table games exists in current directory.") print("Please delete ", dbname, " before running this script.") sys.exit(0) # Create tables print("Initialize with Django") def drop_database(dbname): assert 'test' in dbname # dont delete prod data! try: os.remove(dbname) except OSError: pass
ba3e900a96147d3a735f9f64cb12973d805358b0
djinn00/CryptoScripts
/caesar.py
632
4.0625
4
#!/usr/bin/env python3 from sys import argv, exit import string def caesar(s, n): letters = string.ascii_uppercase out = "" for c in s: if c in letters: i = letters.index(c) ni = int((i + (n % len(letters))) % len(letters)) out += letters[ni] else: out += c return out if __name__ == '__main__': if len(argv) != 3: print('Usage: %s [input string] [key (as integer)]' % argv[0]) exit(1) try: print(caesar(argv[1].upper(), int(argv[2]))) except ValueError: print('Key must be an integer.') exit(1)
f9ad5f4af65e603c0dda41b6f8ad011f3ae002dd
improvbutterfly/twilioquest-exercises
/python/fizzbuzz.py
278
3.546875
4
import sys for i in range(len(sys.argv)): if i > 0: if (int(sys.argv[i]) % 3 == 0) and (int(sys.argv[i]) % 5 == 0): print("fizzbuzz") elif int(sys.argv[i]) % 3 == 0: print("fizz") elif int(sys.argv[i]) % 5 == 0: print("buzz") else: print(int(sys.argv[i]))
d1b2484512d0b7ab51f40b6a48746d9c7422b330
kaci65/Nichola_Lacey_Python_By_Example_BOOK
/Maths/divide.py
294
4.21875
4
#!/usr/bin/python3 """Use whole number division and remainder""" import math num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) div = num1 // num2 rem = num1 % num2 print("{:d} divided by {:d} is {:d} with {:d} remaining".format( num1, num2, div, rem))
f69988ac1d9596891def606b4f44101230d068e0
hankerkuo/PythonPractice
/Introduction and Basic data types/Runner-Up Score.py
471
3.6875
4
#Problem:https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem print(dir(list)) Score_Number = int(input()) Score_List = list(map(int,input().split(' '))) RunnerUp = int() Score_List.sort() if Score_List[0] == Score_List[Score_Number-1]: print("ERROR : All the scores are same") for i in range(Score_Number-1,0,-1): if Score_List[i-1]<Score_List[i]: RunnerUp = Score_List[i-1] print(RunnerUp) break #DEF sort
733d9c50a5e8e2d062c8f57a22544016932274ce
pauldubois98/MathematicalPaper_ModularForms
/SpeedComparison/SparsePython.py
810
3.796875
4
def delta(LENGTH): f = [] indice = 1 i = 1 while indice < LENGTH: f.append(indice) i += 2 indice = i**2 return (f, LENGTH) def square(form): f_sq = [] f = form[0] for n in f: if 2*n-1 <= form[1]: f_sq.append(2*n-1) return (f_sq, form[1]) if __name__=='__main__': #setting maxi = 6 print("Heating up...") import timeit, time time.sleep(0.5) #heatup delta(100) square(delta(100)) print("Hot !") print('[', end='') for l in range(maxi): L = 10**l print(timeit.timeit(lambda: delta(L)), end=', ') print(']') print('[', end='') for l in range(maxi): L = 10**l print(timeit.timeit(lambda: square(delta(L))), end=', ') print(']')
2149775bc373e37b82201b10a08a5a6433c87ad4
zlc1994/Google-Foorbar
/string_cleaning.py
2,605
4.0625
4
""" String cleaning =============== Your spy, Beta Rabbit, has managed to infiltrate a lab of mad scientists who are turning rabbits into zombies. He sends a text transmission to you, but it is intercepted by a pirate, who jumbles the message by repeatedly inserting the same word into the text some number of times. At each step, he might have inserted the word anywhere, including at the start or end, or even into a copy of the word he inserted in a previous step. By offering the pirate a dubloon, you get him to tell you what that word was. A few bottles of rum later, he also tells you that the original text was the shortest possible string formed by repeated removals of that word, and that the text was actually the lexicographically earliest string from all the possible shortest candidates. Using this information, can you work out what message your spy originally sent? For example, if the final chunk of text was "lolol," and the inserted word was "lol," the shortest possible strings are "ol" (remove "lol" from the beginning) and "lo" (remove "lol" from the end). The original text therefore must have been "lo," the lexicographically earliest string. Write a function called answer(chunk, word) that returns the shortest, lexicographically earliest string that can be formed by removing occurrences of word from chunk. Keep in mind that the occurrences may be nested, and that removing one occurrence might result in another. For example, removing "ab" from "aabb" results in another "ab" that was not originally present. Also keep in mind that your spy's original message might have been an empty string. chunk and word will only consist of lowercase letters [a-z]. chunk will have no more than 20 characters. word will have at least one character, and no more than the number of characters in chunk. """ def cut(string, start, length): """remove a substring with a certain start index and length""" return string[:start]+string[start+length:] def clean(chunk, word, start): """remove all occurrence word in chunk at the start index""" index = chunk.find(word, start) while index != -1 and start < len(word): chunk = cut(chunk, index, len(word)) index = chunk.find(word) return chunk def answer(chunk, word): """do clean method with all the subsequences, and return the lexicographically earliest string """ result = [] for start in range(len(chunk)-len(word)): string = clean(chunk, word, start) if string != chunk: result.append(string) return sorted(result)[0]
e20e80a8cb0f4ed881e0a2a3e2ff9cc00cc6ce55
bagorbenko/home-tasks
/jug_problem.py
3,045
4.125
4
print('Наполнить сосуд A (A+).\n Наполнить сосуд B (B+).') print('Вылить воду из сосуда A (A-).\n Вылить воду из сосуда B (B-).') print('Перелить воду из сосуда A в сосуд B (A-B).\n Перелить воду из сосуда B в сосуд A (B-A).') print('Для завершения работы введите "Выход").') A = input('Введите объем большего ведра А: ') B = input('Введите объем ведра В: ') rez = input('Введите расчитываемый объем: ') while not A.isdigit() or not B.isdigit() or not rez.isdigit(): A = input('Введите объем большего ведра А: ') B = input('Введите объем ведра В: ') rez = input('Введите расчитываемый объем: ') print('Вводите только числовые параметры') print("Начинайте переливание") A1 = 0 #литраж воды между операциями B1 = 0 if A == B: print('Решений не существует') quit('Попробуйте заново') if rez > A and rez > B: print('Решений не существует ') quit('Попробуйте заново') counter = 0 while A1 != rez and B1 != rez: a = input('Введите операцию ') counter += 1 if a == 'A-' and A1 >= 0: A1 = 0 print('Количество воды в ведре А - ' + str(A1) + ' Количество воды в ведре B - '+str(B1)) elif a == 'A+' and A1 <= A: A1 = A print('Количество воды в ведре А - ' + str(A1) + ' Количество воды в ведре B - ' + str(B1)) elif a == 'B-' and B1 >= 0: B1 = 0 print('Количество воды в ведре А - ' + str(A1) + ' Количество воды в ведре B - ' + str(B1)) elif a == 'B+' and B1 <= B: B1 = B print('Количество воды в ведре А - ' + str(A1) + ' Количество воды в ведре B - ' + str(B1)) elif a == 'B-A': if A1+B1 > A: B1 = (B1 + A1) - A A1 = A else: A1 = A1 + B1 B1 = 0 print('Количество воды в ведре А - ' + str(A1) + ' Количество воды в ведре B - ' + str(B1)) elif a == 'A-B': if A1 + B1 > B: A1 = A1 - (B-B1) B1 = B else: B1 = B1 + A1 A1 = 0 print('Количество воды в ведре А - ' + str(A1) + ' Количество воды в ведре B - ' + str(B1)) elif a == 'Выход': print('Вы вышли из задачи') break else: print('В ведре A - ' + str(rez1) + ' литров воды') print('Количество совершенных операций - ', str(counter))
7a7d84894d31742cd6d3dc5e1985b95dc88e73a2
anjanasrinivas/Intuit-Coding-Challenge-
/problem_1.py
298
3.625
4
lst = [1,10,5,63,29,71,10,12,44,29,10,-1] def sorted_list(lst): for i in range (len(lst)): for j in range (len(lst)-1-i): if lst[j] > lst[j+1]: lst [j], lst[j+1] = lst[j+1], lst[j] sorted_list(lst) print(lst) #Using python built in feature to sort def sort(lst): lst.sort()
146747c4c52d3d59074a6809ed53b6128fdba1a7
furyjack/Connect4
/game.py
3,278
3.609375
4
from board import Board from node import Node from copy import deepcopy from tree_render import create_graph from random import shuffle class Game: def __init__(self): self.has_ended = False self.current_state = Board() #assuming game starts with the player self.turn = 0 def play(self): self.turn = int(input("Who would start?\n")) while not self.has_ended : if self.turn == 0: self.player_move() else: self.comp_move() self.current_state.print_board() if self.turn == 1: print("Player won!") else: print("Computer won!") def player_move(self): try: r, c = input('Enter row, col\n').split(',') r = int(r) c = int(c) except: return self.player_move() if (r,c) not in self.current_state.valid_moves: print("please enter a valid move") return self.player_move() if self.current_state.place(self.turn, r, c) == 1: self.has_ended = True self.turn = 1 def comp_move(self): #calculate best move and play #max depth 5 moves r,c = self.minmax() if self.current_state.place(self.turn, r, c) == 1: self.has_ended = True self.turn = 0 def _minmax(self, node): if node.depth >= 8 or (node.lastmove and (node.board.check_win(0, node.lastmove[0], node.lastmove[1]) == 1 or node.board.check_win(1, node.lastmove[0], node.lastmove[1]) == 1)): node.val = node.evaluate() node.alpha = node.val node.beta = node.val node.isimp = True return node scores = {} moves = list(node.board.valid_moves) shuffle(moves) for i, move in enumerate(moves): nboard = deepcopy(node.board) didwin = nboard.place(node.chance, move[0], move[1]) child_chance = (node.chance + 1) % 2 child_node = Node(node.depth + 1, child_chance, nboard, 4000 if child_chance == 0 else -4000, move) child_node.alpha = node.alpha child_node.beta = node.beta self._minmax(child_node) node.children.append(child_node) # minimize if node.chance == 0: node.val = min(node.val, child_node.val) node.beta = min(node.beta, node.val) if node.alpha >= node.beta: child_node.isimp = True return child_node else: node.val = max(node.val, child_node.val) node.alpha = max(node.alpha, node.val) if node.alpha >= node.beta: child_node.isimp = True return child_node if child_node.val not in scores: scores[child_node.val] = i node.children[scores[node.val]].isimp = True return node.children[scores[node.val]] def minmax(self): root = Node(0, 1, self.current_state, -4000) bestchild = self._minmax(root) root.isimp = True create_graph(root) return bestchild.lastmove obj = Game() obj.play()
e3f47696dd48aa98ba8260e2ed68923ff5d6b2e3
byunwonju/2020_programming
/prob101.py~ prob130.py/prob 115.py
418
3.828125
4
#사용자로부터 하나의 값을 입력받은 후 해당 값에 20을 뺀 값을 출력하라. 단 값의 범위는 0~255이다. 0보다 작은 값이되는 경우 0을 출력해야 한다. a= int(input("값을 입력하세요.:") if(a>=0 and a<=255): a=(a-20) if (a<=255): print("0") else: print(a) else: print("0-255 사이의 값을 입력하세요.")
95f7acb5e03b1d0d1d66266238bcadd0c969b98c
ObinnaEE/Programming-Applications-Course-Spring-2016
/Week 1/PlotHW1.py
936
3.5
4
#import numpy and matlibplots module #generate array of x values from 0 to 6pi #calculate y values for sin wave #calculate y values for cosine wave #plot x and y values for both functions #set dashed line for sine wave and solide line for cosine wave #add legend #leave comment here with your information #Name: #Date: #import numpy and matlibplots module import matplotlib.pyplot as plt import numpy as np import pylab as pl #generate array of x values from 0 to 6pi #calculate y values for sin wave #calculate y values for cosine wave # #plot x and y values for both functions #set dashed line for sine wave and solide line for cosine wave #add legend #leave comment here with your information #Name: Obinna Okonkwo #Date: 1/17/2016 x = np.linspace(0, 2*3.14, 101) y1 = np.sin(x) y2 = np.cos(x) plt.legend(['Sin = Red, Cos = Blue'], loc='right', shadow=True) plt.plot(x, y1, x, y2) plt.title("Obi's Graph") plt.show()
d01285162112d08887ec9c5adb3daa92a3b67597
LucasPires50/jogo_memoria
/jogos.py
501
3.71875
4
import forca import adivinhacao def escolha_jogo(): print("*********************************") print("*********Escolha um jogo!********") print("*********************************") print("(1)Forca (2)Adivinhação") jogo = int(input("Qual jogo?")) if (jogo == 1): print("Jogo da Forca") forca.jogar_forca() elif(jogo == 2): print("Jogo da Adivinhação") adivinhacao.jogar_adivinhacao() if(__name__ == "__main__"): escolha_jogo()
223560954afb6b5c4ead7f7de81a2270df5b625f
vashistak/Basic-Python-Codes
/Basic Python Codes/nanodegrexample.py
200
3.546875
4
def mystery(N): s = [] while N > 0: s.append(N % 3) N = N / 3 buf = "" while len(s) > 0: buf += str(s.pop()) return buf print mystery(50)
7593e3eeade2c8c2a00cdafbb48fa79a98f6282b
gitbot41/sunny-side-up
/src/Baseline/Bayes/feature_extractors.py
1,935
3.75
4
''' The file is a collection of functions that take in a sentence string as input, and output a set of features related to that sentence Output of each function is of the following format: {feature_1, feature_2, ... , feature_n} ''' from nltk import word_tokenize from nltk.corpus import stopwords as stpwrds stopwords = stpwrds.words('english') def word_feats(sentence, tokenizer=word_tokenize, remove_stopwords=False, stemmer=None, all_lower_case=False): ''' Takes in a sentence returns the words and/or punctuation in that sentence as the features (depending on chosen tokenizer) @Arguments: sentence -- Chosen sentence to tokenize, type(sentence) = String tokenizer (optional) -- Function of type nlkt.tokenize to be used for breaking apart the sentence string. Standard tokenizer splits on whitespace and removes punctuation remove_stopwords (optional) -- if true, all stopwords in sentence will not be included as features. Currently only for English text. Value is initially false stemmer (optional) -- Function of type nltk.stem to be used for stemming word features. @Return: List of features of the following form: {word_1: True, word_2: True, ... , word_n: True} ''' features = dict() for word in tokenizer(sentence): # Removes word from features if in nlkt.corpus.stopwords('english') if remove_stopwords: if word.lower() in stopwords: continue # Changes all word features to lower case if ture if all_lower_case: word = word.lower() # Stems all word features with chosen stemmer function if not None if stemmer: word = stemmer(word) features[word] = True return features
aad2b9686d74cdb756eb0df236c7d8922a1bfa8f
ParthRoot/Basic-Python-Programms
/Ways to remove i’th character from string.py
238
3.921875
4
# Programme by parth.py # Ways to remove i’th character from string def remove(str,j): for i in range(0,len(str)): if i != j: print(str[i], end="") a = "APPLE" b = remove(a, 2) """ Output: APLE """
f307f5835b24fda917ce719f768474c154fe7f2c
Wambuilucy/CompetitiveProgramming
/Project Euler/ProjectEuler6.py
801
3.96875
4
#! /usr/bin/env python ''' Project Euler 6 (https://projecteuler.net/problem=6) Sum Square Difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. ''' def sum_of_squares(n): res = 0 for i in range(1, n + 1): res += i ** 2 return res def square_of_sum(n): res = 0 for i in range(1, n + 1): res += i return res ** 2 print(square_of_sum(100) - sum_of_squares(100))
a832e86bba417951a64dc96e76afd57e234b1402
NikolasMatias/urionlinejudge-exercises
/Iniciante/Python/exercises from 2001 to 2600/exercise_2146.py
114
3.5
4
while True: try: number = int(input()) print(str(number-1)) except EOFError: break