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
51d6d7e809e0ac1577f68cb27cb5aef4dd2ac7d5
yoskovia/python_uat
/notebooks/src/Python Basics.py
2,484
4.5
4
#!/usr/bin/env python # coding: utf-8 # # Python Basics # # This notebook contains examples of basic Python syntax. # # ### Topics # - Getting Help # - Basic Operations # - Lists # - Functions # In[ ]: # Click this cell, and then click the "Run" button above to execute the code within print('Hello world!') # ## Getting Help # - `help(str)` will print out the help page for an object # - `type(variable)` will show the type of a `variable` # - `dir(variable)` will show you the things you can do with `variable` # In[ ]: my_name = 'Anthony' # What is the type of my_name? type(my_name) # In[ ]: # What operations can I perform on my_name? dir(my_name) # In[ ]: # upper looks interesting, I'd like to read more about it. help(my_name.upper) # In[ ]: my_name.upper() # In[ ]: my_name # In[ ]: help(my_name.isupper) # In[ ]: my_name.isupper() # In[ ]: '32'.zfill(5) # In[ ]: foo = 1 foo.zfill(2) # In[ ]: str(foo).zfill(2) # In[ ]: int('01') # ### Python is a case sensitive language, so the following will not work. # In[ ]: print(My_name) # ## Operations - Python As A Calculator # In[ ]: print(15 + 100) print(15 - 100) print(15 * 100) print(15 ** 2) print(15 // 3) print((15 / 15) ** 2) print(15 % 2) # Mod # ## Lists # In[ ]: fruits = ['apples', 'oranges'] fruits # In[ ]: for fruit in fruits: print('I like ' + fruit) # Lists can contain different types # In[ ]: another_list = ['name', 500] # In[ ]: another_list # In[ ]: fruits[0] # In[ ]: fruits[1] # In[ ]: len(fruits) # ## Doing something to each element of a list # In[ ]: [name.upper() for name in ['anthony', 'mittens']] # ## Functions # In[ ]: def add_them(a, b): print(f'a = {a}, b = {b}') return a + b add_them(1, 3) # In[ ]: # Can also explicitly specify the arguments add_them(a=1, b=3) # In[ ]: # If you explictly specify the arguments, the order does not matter add_them(b=3, a=1) # In[ ]: def add_them(a, b): """ Add two numbers. a (int): First number b (int): Second number Example usage: add_two(1, 2) >>> 3 """ return a + b # In[ ]: add_them(1, 2) # In[ ]: print(add_them.__doc__) # In[ ]: help(add_them) # ### Caution! # In[ ]: def this_shouldnt_work(foo): # The variable asdf doesn't exist, but we will not see an error when we define the function print(asdf) # In[ ]: this_shouldnt_work(1)
700977eac87b6d1d82716fc43a2f9ba2f3293ca8
jonmagnus/IN3110
/assignment6/visualize.py
4,039
3.703125
4
''' Display the predictions of classifier. ''' import matplotlib.pyplot as plt import pandas as pd import numpy as np import os from data import plot_with_columns from data import get_split_table, get_labels from fitting import fit def visualize_confidence(classifier, table, col1, col2, ax=None, **kwargs): ''' Draw a contour in the prediction area for the classifier given two features to predict on. :param classifier: Trained classifier to visualize predictions of. :param table: The full table to get the range of possible values to predict on. :param col1: The first column name. :param col2: The second column name. :param ax: The canvas to draw on. :return: The modified canvas. ''' if ax is None: # Generate a new canvas if none was provided. ax = plt.subplot(1,1,1) x_values = table[col1] y_values = table[col2] x_min = np.min(x_values) - 1 x_max = np.max(x_values) + 1 y_min = np.min(y_values) - 1 y_max = np.max(y_values) + 1 h = .2 x = np.arange(x_min, x_max, h) y = np.arange(y_min, y_max, h) xx, yy = np.meshgrid(x, y) xy_foldout = np.c_[xx.ravel(), yy.ravel()] if hasattr(classifier, 'decision_function'): Z = classifier.decision_function(xy_foldout) else: Z = classifier.predict_proba(xy_foldout)[:, 1] Z = Z.reshape(xx.shape) ax.contourf(xx, yy, Z, colors=['#ff000080','#0000ff80'], levels=1, **kwargs) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) return ax def handle_image_generation(classifier, feature_set, imagepath, title=''): ''' Train a classifier and return it's scores on the train and test split. Save a contour image of it's predictions if it is only trained on two features. :param classifier: A string or object describing a classifier. :param feature_set: A list of column names describing the feature set to train the model on. :param imagepath: The path to store the contour plot. :param title: The title of the plot with scores. :return: The train and test scores for the classifier. ''' train_table, test_table = get_split_table() train_labels, test_labels = get_labels(train_table, test_table) classifier = fit(classifier, feature_set, train_table) train_score = classifier.score(train_table[feature_set], train_labels) test_score = classifier.score(test_table[feature_set], test_labels) if (len(feature_set) == 2): fig = plt.figure() ax = visualize_confidence(classifier, train_table, *feature_set) plot_with_columns(train_table, *feature_set, ax=ax, marker='+', label='train') plot_with_columns(test_table, *feature_set, ax=ax, label='test') ax.legend() try: ax.set_title(title.format(train_score=train_score, test_score=test_score)) except ValueError: ax.set_title(title) fig.savefig(imagepath) return train_score, test_score if __name__=='__main__': from data import get_numerical_columns from fitting import classifier_map train_table, test_table = get_split_table() train_labels, test_labels = get_labels(train_table, test_table) feature_options = get_numerical_columns() feature_set = np.random.choice(feature_options, size=2) fig = plt.figure() classifier_name = np.random.choice(list(classifier_map.keys())) classifier = fit(classifier_name, feature_set, train_table) train_score = classifier.score(train_table[feature_set], train_labels) test_score = classifier.score(test_table[feature_set], test_labels) ax = visualize_confidence(classifier, train_table, *feature_set) plot_with_columns( train_table, *feature_set, ax=ax, marker='+', label='train', ) plot_with_columns(test_table, *feature_set, ax=ax, label='test') ax.set_title(f'{classifier_name}: Test {test_score:.5f} Train {train_score:.5f}') ax.legend() plt.show()
db82c6951e52f364893ee8575bbd2af211d094a6
Huijuan2015/leetcode_Python_2019
/355. Design Twitter.py
2,110
3.890625
4
class Twitter(object): def __init__(self): """ Initialize your data structure here. """ import collections self.follower = collections.defaultdict(set) self.tweets = collections.defaultdict(list) self.timer = 0 def postTweet(self, userId, tweetId): """ Compose a new tweet. :type userId: int :type tweetId: int :rtype: None """ self.tweets[userId].append((self.timer, tweetId)) self.timer -= 1 def getNewsFeed(self, userId): """ Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. :type userId: int :rtype: List[int] """ tweets = self.tweets[userId][:] res = [] # print self.tweets[userId], tweets, self.follower[userId] for p in self.follower[userId]: if p != userId: tweets.extend(self.tweets[p]) heapq.heapify(tweets) while tweets and len(res) < 10: res.append(heapq.heappop(tweets)[1]) return res def follow(self, followerId, followeeId): """ Follower follows a followee. If the operation is invalid, it should be a no-op. :type followerId: int :type followeeId: int :rtype: None """ self.follower[followerId].add(followeeId) def unfollow(self, followerId, followeeId): """ Follower unfollows a followee. If the operation is invalid, it should be a no-op. :type followerId: int :type followeeId: int :rtype: None """ if followeeId in self.follower[followerId]: self.follower[followerId].remove(followeeId) # Your Twitter object will be instantiated and called as such: # obj = Twitter() # obj.postTweet(userId,tweetId) # param_2 = obj.getNewsFeed(userId) # obj.follow(followerId,followeeId) # obj.unfollow(followerId,followeeId)
51af00325626738a46a5aee2dad846984e3e5271
mdebowska/Gra_w_Pana
/src/GameClass.py
4,354
3.828125
4
from src import CardClass class Game: def __init__(self): self.stack = [] self.players = [] self.restart() def __repr__(self): """ Wyświetla karty ze stosu :return: """ return 'gra0: '+','.join( [card.__repr__() for card in self.stack] ) def restart(self): """ resetuje ustawienia - nadaje początkowe :return: """ self.players = [] CardClass.restart_cards() def add_to_stack(self, cards, player): """ Połóż karty na stos i odejmij z ręki gracza :return: """ print('Hand: ', player.hand) for card in cards: print('card: ', card) self.stack.append(card) player.hand.remove(card) player.layed_card.append(card) def take_from_stack(self, number_of_cards, player): """ Zabierz karty ze stosu i daj je graczowi :return: """ print(number_of_cards) print(self.stack[len(self.stack)-1]) for i in range(number_of_cards): if len(self.stack) == 1: break card = self.stack[len(self.stack)-1] player.hand.append(card) self.stack.remove(card) def add_player(self, player): """ Dodaj gracza do gry :return: """ self.players.append(player) def add_players(self, players): """ Dodaj graczy z listy (players) do gry (do self.players) :return: """ for player in players: self.players.append(player) def take_cards_start(self): """ losuje karty dla gracza :return: """ if self.players: for player in self.players: for i in range(1, int((24/len(self.players))+1)): player.take_card() def find_active_player(self): """ Znajduje aktywnego gracza :return: object type Person """ for player in self.players: if player.active == 1: return player def swich_active_person(self, next_label = 0): """ Zmień aktywnego gracza na kolejnego lub poprzedniego :return: """ current_active = self.find_active_player() current_active.active = 0 if next_label: #jeśli ostatnie było "zakończ" (tzn poprzedni gacz rzucił karty na stos) to sprawdź czy to było wino if self.stack[len(self.stack)-1].color != 'w': id_next_active = (self.players.index(current_active)+1)%len(self.players) #bierze indeks kolejnego gracza self.players[id_next_active].active = 1 else: id_prev_active = (self.players.index(current_active)-1)%len(self.players) #bierze indeks poprzedniego gracza self.players[id_prev_active].active = 1 else: id_next_active = (self.players.index(current_active) + 1) % len(self.players) # bierze indeks kolejnego gracza self.players[id_next_active].active = 1 def check_if_good_to_add(self, cards): """ Funkcja sprawdza, czy wybrane karty nadają się do zagrania :return bool """ if len(cards) != 1 and len(cards) != 3 and len(cards) != 4: #bierzemy pod uwagę zagranie tylko 1, 3 lub 4 kartami # print('nie jest 1 ani 3 ani 4', len(cards)) return False elif len(cards) == 3 or len(cards) == 4: # jeśli więcej niż 1, to sprawdź czy mają tę samą wartość for i in range(len(cards)-1): if cards[i].value != cards[i+1].value: # print('nie jest takie samo') return False if cards[0].value < self.stack[len(self.stack)-1].value: # sprawdź, czy karta nie jest słabsza niż ostatnia na stosie # print('Nie jest rowna lub większa') return False return True def find_player_with_9s(self): """ Funkcja znajdująca rozpoczynającego gracza :return: player """ for player in self.players: for card in player.hand: if card.value == 9 and card.color == 's': return player
affe24da0f780822a8031dd251401d54be6dd757
Frankiee/leetcode
/archived/string/1784_check_if_binary_string_has_at_most_one_segment of Ones.py
848
3.96875
4
# [Archived] # https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/ # 1784. Check if Binary String Has at Most One Segment of Ones # History: # 1. # Apr 10, 2021 # Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. # Otherwise, return false. # # # # Example 1: # # Input: s = "1001" # Output: false # Explanation: The ones do not form a contiguous segment. # Example 2: # # Input: s = "110" # Output: true # # # Constraints: # # 1 <= s.length <= 100 # s[i] is either '0' or '1'. # s[0] is '1'. class Solution(object): def checkOnesSegment(self, s): """ :type s: str :rtype: bool """ for i in range(1, len(s)): if s[i] == '1' and s[i-1] == '0': return False return True
f47544f7d05bf415364282f1b7a66fa0cfd2b9cc
number23/iLibrary
/pyLib/_date.py
1,294
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __all__ = [ 'prev_month', 'next_month', 'get_Monday' ] from datetime import timedelta def prev_month(d): """Calculate the first day of the previous month for a given date. >>> prev_month(date(2004, 8, 1)) datetime.date(2004, 7, 1) >>> prev_month(date(2004, 8, 31)) datetime.date(2004, 7, 1) >>> prev_month(date(2004, 12, 15)) datetime.date(2004, 11, 1) >>> prev_month(date(2005, 1, 28)) datetime.date(2004, 12, 1) """ return (d.replace(day=1) - timedelta(1)).replace(day=1) def next_month(d): """Calculate the first day of the next month for a given date. >>> next_month(date(2004, 8, 1)) datetime.date(2004, 9, 1) >>> next_month(date(2004, 8, 31)) datetime.date(2004, 9, 1) >>> next_month(date(2004, 12, 15)) datetime.date(2005, 1, 1) >>> next_month(date(2004, 2, 28)) datetime.date(2004, 3, 1) >>> next_month(date(2004, 2, 29)) datetime.date(2004, 3, 1) >>> next_month(date(2005, 2, 28)) datetime.date(2005, 3, 1) """ return (d.replace(day=28) + timedelta(7)).replace(day=1) def get_Monday(d): return d + timedelta(days=-d.weekday())
dc12be306513bde65bf03b921c5d99531090fc29
BbillahrariBBr/python
/Book1/10-13-18-4-prime-1.py
491
4.21875
4
def is_prime1(n): if n<2: return False prime = True for x in range(2, n): if n%x == 0: print(n, "is divisable by: ",x) prime = False return prime while True: number = input("Please enter a number enter (0 for exit):") number = int(number) if number == 0: break prime = is_prime1(number) if prime is True: print(number, " is prime number") else: print(number, " is not a prime")
69390dd009e5305d8ed06c01b8624fb8e42e7d29
abdlhhelal/automate-the-boring-stuff-with-python-answers
/Chapter7/RegStrip.py
551
3.625
4
import re def regStrip(*String): try: if String[1]!=True: StripChar=String[1] except: StripChar='\s' StripRegex = re.compile(r'^[%s]*((\w|\W)*?)[%s]*$'%(StripChar,StripChar)) try: StrippedString=StripRegex.search(String[0]).group(1) return StrippedString except: return String[0] String=',,,,, ,, , , A 4s rsrsr sAIt''sWorking,,,,,,,,A4srs,A' Stripped1=regStrip(String,'A, 4rs') Stripped2=String.strip('A, 4rs') print(Stripped1) print(Stripped2) print(Stripped1==Stripped2)
711c775990736bd586f39f82bda381f943066558
stefanVanEchtelt/blok_1_opdrachten_prog
/Control Structures/2. If with 2 boolean operators.py
172
3.703125
4
age = eval(input('Geef je leeftijd: ')) hasPassport = str(input('Nederlands paspoort: ')) if (age >= 18) & hasPassport == 'ja': print('Gefeliciteerd, je mag stemmen!')
f4f7f785d6cf6317ca93dc440ccae019c2888485
roshan2M/edX--mitX--introduction-to-computer-science-and-programming-with-python
/Week 2/Lecture 3 - Simple Algorithms/Questions/Lec3Problem5b.py
85
3.9375
4
for num in range(10, 0, -2): if (num == 10): print "Hello!" print num
9d4ee9560ba9b87a8bf746c64abfc2837239c4c0
skinder/Algos
/PythonAlgos/Done/Find_Difference.py
1,123
3.796875
4
''' https://leetcode.com/problems/find-the-difference/ Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added. ''' class Solution(object): def findTheDifference(self, s, t): from collections import Counter s_dict = Counter(s) t_dict = Counter(t) for key in t_dict: if key not in s_dict or t_dict[key] != s_dict[key]: return key return None def findTheDifference2(self, s, t): for i in t: if t.count(i) > s.count(i): return i def singleNumber(self, nums): res1 = res2 = 0 for num in nums: res1 = (res1 ^ num) & (~res2) res2 = (res2 ^ num) & (~res1) return res1 a = Solution() print a.findTheDifference("abcd", "abcde") print a.findTheDifference2("abcd", "abcde") print a.singleNumber([2,2,3,2])
8e739e1c7460aa1aa8ae1569936353a43abd0c14
LiangJinYong/PythonRpa
/rpa_basic/desktop/2_mouse_move.py
842
3.5625
4
import pyautogui # 마우스 이동 # pyautogui.moveTo(200, 100) # 지정한 위치(가로 x, 세로 y)로 마우스를 이동 # pyautogui.moveTo(100, 200, duration=5) # 0.25초 동안 100, 200 위치로 이동 # pyautogui.moveTo(100, 100, duration=0.25) # pyautogui.moveTo(200, 200, duration=0.25) # pyautogui.moveTo(300, 300, duration=0.25) # 상대 좌표로 이동 (현재 커서가 있는 위치로 부터) # pyautogui.moveTo(100, 100, duration=0.25) # print(pyautogui.position()) # Point(x, y) # pyautogui.move(100, 100, duration=0.25) # 100, 100 기준으로 +100, +100 -> 200, 200 # print(pyautogui.position()) # Point(x, y) # pyautogui.move(200, 200, duration=0.25) # 200, 200 기준으로 +200, +200 -> 400, 400 # print(pyautogui.position()) # Point(x, y) p = pyautogui.position() print(p[0], p[1]) # x, y print(p.x, p.y) # x, y
1348d67a60332c661887f783248771b3c3774125
daniel-reich/turbo-robot
/biJPWHr486Y4cPLnD_13.py
832
4.28125
4
""" Write a function that divides a list into chunks of size **n** , where **n** is the length of each chunk. ### Examples chunkify([2, 3, 4, 5], 2) ➞ [[2, 3], [4, 5]] chunkify([2, 3, 4, 5, 6], 2) ➞ [[2, 3], [4, 5], [6]] chunkify([2, 3, 4, 5, 6, 7], 3) ➞ [[2, 3, 4], [5, 6, 7]] chunkify([2, 3, 4, 5, 6, 7], 1) ➞ [[2], [3], [4], [5], [6], [7]] chunkify([2, 3, 4, 5, 6, 7], 7) ➞ [[2, 3, 4, 5, 6, 7]] ### Notes * It's O.K. if the last chunk is not completely filled (see example #2). * Integers will always be single-digit. """ def chunkify(lst, size): output=[] i=0 new_list=[] n=0 while i < len(lst): output.append([]) #print(output) for k in range(0,size): if i < len(lst): output[n].append(lst[i]) i+=1 else: break n+=1 return output
cc41e712dcaddc187b319f263ee8e941badfe398
AnTznimalz/python_prepro
/fibooooo.py
311
3.78125
4
def fib(num): '''Func. fib for super speed algorithm for fibo''' fib(num) = fib(2*num)+fib(2*num-1) fib(2*num) = fib(num-1)**2 + fib(num)**2 fib(2*num-1) = (2*fib(num+1)+fib(num))*fib(num) if num == 0 or num == 1: return num else: return fib(num) print(fib(int(input())))
052b8f657b5ed71debf9de708a39fa43f9048dd6
makhmudislamov/leetcode_problems
/book_cci/check_permutation.py
1,380
3.78125
4
""" Chaoter 1, Page 90 given two strings, check if one is a permutation of another """ # questions to ask: # acceptable and optimal time and space # case sensetivity, whitespace, upper, lower cases. Assume case sensetive to whitespace # base case # if lenghts are differetn then return false # approach 1. Time and space - logn logn for sorting two strings >> Time: logn and space 1 # sort the strings and check if they are the same # def is_permutation(str1, str2): # if len(str1) != len(str2): # return False # str1.sort() # str1.sort() # return str1 == str2 # approach 2 = time and space - o(n) and O(n) # create hashmap - char and frequency with first string # go throught the second string # decrement the char value from the hashmap if char exists # if the req value is zero remove the key altogether # if hashmap is empty - return true def is_permutation(str1, str2): if len(str1) != len(str2): return False freq = {} # building dict with str1 for char in str1: if char not in freq: freq[char] = 1 else: freq[char] += 1 for char in str2: if char not in freq: return False else: freq[char] -= 1 if freq[char] == 0: freq.pop(char) return not freq print(is_permutation("doG", "God"))
b736c65837feb958bed1d64662c7ec4f68eff265
DreamingFuture/python-crawler
/视频随堂/18.xpath的使用.py
681
3.578125
4
# 作者 :孔庆杨 # 创建时间 :2019/1/29 14:42 # 文件 :18.xpath的使用.py # IDE :PyCharm '''教程网址: w3shcool''' import requests from lxml import etree from fake_useragent import UserAgent url = 'https://www.qidian.com/rank/yuepiao?chn=21' headers = { "User-Agent": UserAgent().random } response = requests.get(url, headers=headers) e = etree.HTML(response.text) names = e.xpath('//h4/a/text()') author = e.xpath('//p/a[@class="name"]/text()') grope = e.xpath('//p/a[@data-eid="qd_C42"]/text()') done = e.xpath('//p[@class="author"]/span/text()') for index in range(len(names)): print(names[index], author[index])
c76a9467a7de411078b256474d3e7b2250da1cf6
vqpv/stepik-course-58852
/9 Строковый тип данных/9.2 Срезы/6.py
163
3.78125
4
string = input() print(len(string)) print(string * 3) print(string[:1]) print(string[:3]) print(string[-3:]) print(string[::-1]) print(string[1:len(string) - 1])
e9d2d9634ede05e54e21768aaf69f26f12dea34f
apb7/ProjectEuler
/p5.py
198
3.5
4
def is_div(n): for i in range(2,21,1): if n%i!=0: return False return True i=2520 while True: if is_div(i): break i=i+1 print str(i)
9e29f220459cfdfebd5d51709649909b54e0a22f
JSYoo5B/TIL
/PS/BOJ/1874/1874.py
857
3.5
4
#!/usr/bin/env python3 if __name__ == '__main__': cnt = int(input()) sequence = [] for i in range(cnt): num = int(input()) sequence.append(num) # Reverse sequence to avoid popleft operation costs sequence.reverse() operations = ['+'] current = 2 stack = [1] while len(sequence) > 0: top = stack[-1] if len(stack) > 0 else 0 if sequence[-1] > top: stack.append(current) current += 1 operations.append('+') elif sequence[-1] == top: stack.pop() sequence.pop() operations.append('-') else: # Invalid condition, unable to create this sequence operations = None break if operations == None: print('NO') else: print('\n'.join(operations))
2b6a314f7e7ea8b26c44c84db441fa98095e84fc
noveoko/thecalculatorgamesolver
/parse.py
551
3.78125
4
import re def parse_all(string): regex = re.compile(r"((?P<add>\+\d+)|(?P<multiply>x\d+)|(?P<divide>\/\d+)|(?P<balance>\(\d+\))|(?P<subtract>\-\d+)|(?P<remove_digit>\<\<)|(?P<first_digit_to_second>(\d+)\=\>(\d+))|(?P<insert_number>\d))") match = regex.match(string) groups = match.groupdict() return [(a[0],only_numbers(a[1])) for a in groups.items() if a[1] != None][-1] def only_numbers(string): all_nums = [int(a) for a in re.sub('[^0-9]+',",", string).split(",") if a] return all_nums if __name__ == "__main__": pass
09a4ad861fb2764f9793649ca8fe23af9b7e11bd
Misora000/google-foobar
/l3_prepare_the_bunnies_escape.py
8,543
3.90625
4
''' Prepare the Bunnies' Escape =========================== You're awfully close to destroying the LAMBCHOP doomsday device and freeing Commander Lambda's bunny prisoners, but once they're free of the prison blocks, the bunnies are going to need to escape Lambda's space station via the escape pods as quickly as possible. Unfortunately, the halls of the space station are a maze of corridors and dead ends that will be a deathtrap for the escaping bunnies. Fortunately, Commander Lambda has put you in charge of a remodeling project that will give you the opportunity to make things a little easier for the bunnies. Unfortunately (again), you can't just remove all obstacles between the bunnies and the escape pods - at most you can remove one wall per escape pod path, both to maintain structural integrity of the station and to avoid arousing Commander Lambda's suspicions. You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1). Write a function solution(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed. Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit Solution.java Test cases ========== Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Python cases -- Input: solution.solution([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]]) Output: 7 Input: solution.solution([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]) Output: 11 -- Java cases -- Input: Solution.solution({{0, 1, 1, 0}, {0, 0, 0, 1}, {1, 1, 0, 0}, {1, 1, 1, 0}}) Output: 7 Input: Solution.solution({{0, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0}}) Output: 11 Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. ''' def solution(map): # Your code here # 0 for distances without via any wall # 1 for distances with via a wall dst = [[[65535]*len(map[0]) for _ in range(len(map))], [[65535]*len(map[0]) for _ in range(len(map))]] dst[0][0][0] = 1 dst[1][0][0] = 1 # (x, y, wall) que = [] x, y, wall = 0, 0, 0 while True: curr_distance = dst[wall][x][y] # get neighbors of current position. neighbors = get_neighbors(map, x, y) for i in range(len(neighbors)): xn, yn = neighbors[i] # is wall and has passed a wall via_wall = map[xn][yn]+wall if via_wall > 1: continue neighbor_dist = dst[via_wall][xn][yn] if neighbor_dist == 65535: # neighbor has not been visited yet. # update distance map & put the neighbor to queue. dst[via_wall][xn][yn] = curr_distance+1 que.append((xn, yn, via_wall)) elif neighbor_dist > curr_distance+1: # neighbor has been visited but the org distance is longer. # update distance map only because the neighbor must in the # queue and after current position due to its longer dist. dst[via_wall][xn][yn] = curr_distance+1 x, y, wall = pop_min(dst, que) if x == len(map)-1 and y == len(map[0])-1: break return min(dst[0][len(map)-1][len(map[0])-1], dst[1][len(map)-1][len(map[0])-1]) def get_neighbors(map, x, y): n = [] if x > 0: n.append((x-1, y)) if y > 0: n.append((x, y-1)) if x < len(map)-1: n.append((x+1, y)) if y < len(map[0])-1: n.append((x, y+1)) return n def pop_min(dst, que): mini = 0 for i in range(len(que)): x, y, wall = que[i] mx, my, mwall = que[mini] if dst[wall][x][y] < dst[mwall][mx][my]: mini = i return que.pop(mini) def debug(dst): for i in range(len(dst[0])): print(dst[0][i]) print('---------------------------------------------------------------') for i in range(len(dst[1])): print(dst[1][i]) # for i in range(len(dst[0])): # print([1 if dst[0][i][j][1] else 0 for j in range(len(dst[i]))]) # for i in range(len(dst[1])): # print([1 if dst[i][j][1] else 0 for j in range(len(dst[i]))]) print(solution([ [0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0], ])) print(solution([ [0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1], [0, 0, 0, 0, 1, 0], [0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 0], ])) print(solution([ [0, 1, 0, 0], [0, 0, 1, 0], ])) print(solution([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ])) print(solution([ [0, 1], [0, 0], ])) print(solution([ [0, 1], [0, 0], [0, 0], ])) print(solution([ [0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0], [0, 0, 0, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], ])) print(solution([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], ]))
95be0e08e4407fa760ec2f66779789e5fc8a9714
negi317145/python_assignment
/merge1.py
299
3.703125
4
l=[] num1=input('enter first number') num2=input('enter second number') num3=input('enter third number') num4=input('enter forth number') print(l.append(num1)) print(l.append(num2)) print(l.append(num3)) print(l.append(num4)) print(l) a=["google","apple","facebook","microsoft","tesla"] print(l+a)
589946b60871892ebc42ebdb47ec78f6e2cfe08b
Ryann-W/python
/practice.py
9,655
4.125
4
# the practice in py4e.com # here is the question #5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. # Once 'done' is entered, print out the largest and smallest of the numbers. # If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. # Enter 7, 2, bob, 10, and 4 and match the output below. ''' largest = None smallest = None lst = list() while True: try: num = input("Enter a number: ") if num == "done" : break num = int(num) lst.append(num) except ValueError: print("Invalid input") for a in lst: if largest is None or a > largest: largest = a for b in lst: if smallest is None or b < smallest: smallest = b print("Maximum is ", largest) print("Minimum is ", smallest) tot = 0 sum = 0 for i in [5, 4, 3, 2, 1] : tot = tot + 1 sum = sum + i print(tot) print(sum) # the find() method is find the position in a string , position means index in a string for letter in 'banana' : print(letter) # 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: # X-DSPAM-Confidence: 0.8475 # Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. # Do not use the sum() function or a variable named sum in your solution. # You can download the sample data at http://www.py4e.com/code3/mbox-short.txt # when you are testing below enter mbox-short.txt as the file name. fname = input("Enter file name: ") fh = open(fname) total = 0 count = 0 middle = list() final = list() for line in fh: if line.startswith("X-DSPAM-Confidence:"): print(line) middle = line.split() final.append(float(middle[1])) for value in final: total = total + value count = count + 1 average = total / count print("Average spam confidence:",average) print("Done") #8.4 Open the file romeo.txt and read it line by line. # For each line, split the line into a list of words using the split() method. # The program should build a list of words. # For each word on each line check to see if the word is already in the list and if not append it to the list. # When the program completes, sort and print the resulting words in alphabetical order. # You can download the sample data at http://www.py4e.com/code3/romeo.txt fname = input("Enter a file name:") fhand = open(fname) lst = list() count = 0 for line in fhand: line.split() for item in line.split(): lst.append(item) print(list(set(sorted(lst)))) #------------------------------------------------------------------------- # fname = input("Enter file name: ") # if len(fname) < 1 : fname = "mbox-short.txt" fh = open("mbox-short.txt") count = 0 odd = 0 for line in fh: odd = odd + 1 if(line.startswith("From")) and (odd % 2 == 0): print(line.split()[1]) count = count + 1 print("There were", count, "lines in the file with From as the first word") #------------------------------------------------------------------------- handle = open("mbox-short.txt") count = 0 odd = 0 value = 0 lst = list() dt = dict() dt2 = dict() dt3 =dict() for line in handle: odd = odd + 1 if(line.startswith("From")) and (odd % 2 == 0): print(line.split()[1]) lst.append(line.split()[1]) print(lst) for key in lst: dt[key] = dt.get(key,0) + 1 print("method1: ",dt) for key in lst: if key not in dt2: # if the key is not in dictionaries, set the value to 1 dt2[key] = 1 else: dt2[key] = dt2[key] + 1 print("method2: ",dt2) for item,value in dt.items(): print("converse the dic: ",(value,item)) dt3[value] = item # for reverse the key and value in a dict , another shorter method: dt33 = [(value,key) for key,value in dt.items()] # it returns a touple list not a dict print(max(dt3.items())[1],max(dt3)) print("------------------") print("reverse a dict using for loop: ",dt3) print("more efficient method: ", dt33) print("---------------------") #------------------------------------------------------------------------- fh = open("mbox-short.txt") lst = list() for line in fh: if line.startswith("From"): lst.append(line.split(":")[0][-2:]) #print(lst) print(lst) dt = dict() for item in lst: dt[item] = dt.get(item,0) + 1 print(dt) del dt['om'] print(dt) for a,b in sorted(dt.items()): print(a,b) #------------------------------------------------------------------------- ''' ''' import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('data.pr4e.org', 80)) cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode() mysock.send(cmd) while True: data = mysock.recv(512) if len(data) < 1: break print(data.decode(),end='') mysock.close() ''' #------------------------------------------------------------------------- ''' # To run this, download the BeautifulSoup zip file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") # Retrieve all of the anchor tags tags = soup('span') count = 0 total = 0 for tag in tags: # Look at the parts of a tag print('TAG:', tag) print('Contents:',tag.contents[0]) print('Attrs:',tag.attrs) count = count + 1 total = total + int(tag.contents[0]) print("Count",count) print("Sum",total) ''' #------------------------------------------------------------------------- ''' from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") # Retrieve all of the anchor tags tags = soup('span') count = 0 total = 0 for tag in tags: # Look at the parts of a tag # print('TAG:', tag) # print('Contents:',tag.contents[0]) # print('Attrs:',tag.attrs) count = count + 1 total = total + int(tag.contents[0]) print("Count",count) print("Sum",total) ''' #------------------------------------------------------------------------- # To run this, download the BeautifulSoup zip file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file ''' import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE b=0 while b<=6: url = input('Enter - ') html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') # Retrieve all of the anchor tags tags = soup('a') a = 0 lst = list() for tag in tags: a = a + 1 if a <= 18: lst = tag.get('href', None).split(".") aa = lst[-2] bb = aa.split("_")[-1] b = b+1 lst = list() lst.append(bb) print(lst) print(lst[-1]) ''' # To run this, download the BeautifulSoup zip file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file #Find the link at position 3 (the first name is 1). # Follow that link. Repeat this process 4 times. # The answer is the last name that you retrieve. # Sequence of names: Fikret Montgomery Mhairade Butchi Anayah #-------------------------------------------- # this means when u found the name in position 3 and click, then find another name # in position, click it again , and repeat process 4 times import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') # count = int(input('Enter counts - ')) # position = int(input('Enter position - ')) a = 0 b = 0 c = 0 html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') # Retrieve all of the anchor tags tags = soup('a') for tag in tags: a = a + 1 if a == 18: break print(tag.get('href', None)) # for test targetTag = tag.get('href',None) # the target tag we looking for --- in the posiiton 3 # print("target Tag: ", targetTag) while b<6: url = targetTag html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') newTag = soup('a') for tag in newTag: c = c + 1 if c == 18: break print("new name in target tag: ",tag.get('href',None)) targetTag = tag.get('href', None) extraTag = tag.get('href', None).split("_")[-1].split(".")[0] print(extraTag) c = 0 b = b + 1 print("the final name is:",extraTag) ''' this practice including: variables loops def Web List Dict Tuple ... '''
784bcfbf7638136acdb4fb68c9884098800f8c95
SafeeSaif/Personal-Code
/Sum of 0 till 100.py
186
3.53125
4
n = 100 s = 0 counter, z = 1, 1 while counter < n: counter += 1 z = z + counter print (counter) print("Sum of 1 until %d: %d" % (n,z)) placeholder = input("")
60ec7f0cb4ccef8894def44f9d1ff64a12c3261e
poisonivysaur/LOGPROG
/Python Exercises/Day 5/EXERCISE4-Month, Day, Year.py
634
4.125
4
'''Exercise 4 Write a program that will allow the user to enter an 8-digit number to represent a date value (with the format of mmddyyyy). The rst 2 digits of this number represent the month, next 2 digits the day and the last 4 digits represent the year.''' strInput=input('Enter a number: ') n=int(strInput) year=n%10000 year=int(year) day=(n%1000000-n%10000)/10000 day=int(day) month=(n%100000000-n%1000000)/1000000 month=int(month) print('month=',str(month)+',','day=',str(day)+',','year=',year) #Better sol'n would be... year=n%10000 day= n //10000 %10 month=n//1000000 # no need to put int()
80ab76aec811e0e6c19012e5d3e4e897dd4a6a1c
fengyehong123/Python_skill
/03-if条件判断较多的时候的优化.py
2,115
3.71875
4
import random from enum import Enum # 定义一个常量类 class Condition(Enum): A = 1 B = 2 C = 3 D = 4 values = [1, 2, 3, 4] choice = Condition(random.choice(values)) """if choice == Condition.A or choice == Condition.B or choice == Condition.C: print('go to step one') else: print('go to step two') """ # 先判断少的情况,然后判断多的情况 if choice == Condition.D: print("go to step two") else: print("go to step one") print("==================") values = [1, 2, 3, 4] choice = Condition(random.choice(values)) # 优化之前 if choice == Condition.A or choice == Condition.B: print('go to step one') else: print('go to step two') # 第一种优化,把可能的情况放在列表中,判断情况是否在列表中,这种速度最快 options = [Condition.A, Condition.B] if choice in options: print('go to step one') else: print('go to step two') # 第二种优化,把可能的情况放在集合中,这种方式的速度高于直接判断,低于放在列表中 options = {Condition.A, Condition.B} if choice in options: print('go to step one') else: print('go to step two') print("#"*20) # ------------------------------------------------------------------------------ # 直接判断 import time choice = Condition.C start_time = time.time() for i in range(0, 1000000): if choice == Condition.A or choice == Condition.B or choice == Condition.C: pass else: pass end_time = time.time() print(end_time - start_time) # 0.4547841548919678 # 放到列表中 choice = Condition.C start_time = time.time() options = [Condition.A, Condition.B, Condition.C] for i in range(0, 1000000): if choice in options: pass else: pass end_time = time.time() print(end_time - start_time) # 0.09374809265136719 # 放到集合中 import time choice = Condition.C start_time = time.time() options = {Condition.A, Condition.B, Condition.C} for i in range(0, 1000000): if choice in options: pass else: pass end_time = time.time() print(end_time - start_time) # 0.26628756523132324
1853a6b93f34980c11ec98da0a1096d4b10b571c
dacastanogo/holbertonschool-interview
/0x10-rain/0-rain.py
616
3.5625
4
#!/usr/bin/python3 """ Calculates how much water will be retained """ def rain(walls): """ Calculates water retained given width of walls """ if walls is None or len(walls) < 2: return 0 water = 0 n = len(walls) left = [0] * n right = [0] * n left[0] = walls[0] for idx in range(1, n): left[idx] = max(left[idx - 1], walls[idx]) right[n - 1] = walls[n - 1] for idx in range(n - 2, -1, -1): right[idx] = max(right[idx + 1], walls[idx]) for idx in range(0, n): water += min(left[idx], right[idx]) - walls[idx] return water
dcfa51a2ab221533eee590e3c920a24734f6c8c7
huyquangbui/buiquanghuy-fundamental-c4e23
/session4/hw/se1.py
1,701
4.03125
4
sheep1 = [5,7,300,90,24,50,75] print ("Hello here is my flock ") print(sheep1) # # writing a program is very misleading when it is (just) a function # # sheep = sorted(set(sheep1)) # for r in sheep: # count = 0 # for t in sheep: # if r >= t: # count += 1 #if there were 2 sheep with same sizes, doesnt work! # if count == len(sheep): # print("now my biggest sheep has size", r, "let's shear it") # sheep1[sheep1.index(r)]= 8 # big = max(sheep1) sheep1[sheep1.index(big)] = 8 print("after shearing, here is my flock") print(sheep1) print() loop = 1 month = 1 while loop == 1: print("MONTH: ",month) print("one month has passed, now here is my flock") for i in sheep1: num = sheep1.index(i) i += 50 sheep1[num] = i print(sheep1) big = max(sheep1) # sheep = sorted(set(sheep1)) # for i in sheep: # count = 0 # for j in sheep: # if i >= j: # count += 1 #if there were 2 sheep with same sizes, doesnt work! # if count == len(sheep): # print("now my biggest sheep has size", i, "let's shear it") # sheep1[sheep1.index(i)]= 8 choice = input("wanna Shear or Sell? ").lower() if choice == "shear": sheep1[sheep1.index(big)] = 8 print("after shearing, here is my flock") print(sheep1) loop = 1 month += 1 elif choice == "sell": sum = 0 for i in sheep1: sum += i print("my flock has total size of: ",sum) print("i would get",sum,"* 2$ =", sum*2,"$") loop = 0 print()
016ba7b349e7f2008e6f8629f07c547333928fda
gerrycfchang/leetcode-python
/matrix/flodd_fill.py
2,234
4.09375
4
# 733. Flood Fill # # An image is represented by a 2-D array of integers, each integer representing the pixel value of the image # (from 0 to 65535). # # Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, # and a pixel value newColor, # "flood fill" the image.# # # To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of # the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels # (also with the same color as the starting pixel), and so on. # Replace the color of all of the aforementioned pixels with the newColor.# # # At the end, return the modified image. # # Example 1: # Input: # image = [[1,1,1],[1,1,0],[1,0,1]] # sr = 1, sc = 1, newColor = 2 # Output: [[2,2,2],[2,2,0],[2,0,1]] # Explanation: # From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected # by a path of the same color as the starting pixel are colored with the new color. # Note the bottom corner is not colored 2, because it is not 4-directionally connected # to the starting pixel. class Solution(object): def floodFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ m = len(image) n = len(image[0]) visited = [[False for _ in range(n)] for _ in range(m)] self.dfs(sr, sc, image, image[sr][sc], newColor, visited) return image def dfs(self, i, j, image, value, newColor, visited): m, n = len(image), len(image[0]) dirs = [[1,0],[-1,0],[0,1],[0,-1]] if i < 0 or i >= m or j < 0 or j >= n or visited[i][j] or image[i][j] != value: return image[i][j] = newColor visited[i][j] = True ## four directions for _dir in dirs: self.dfs(i+_dir[0], j+_dir[1], image, value, newColor, visited) if __name__ == '__main__': sol = Solution() image = [[1,1,1],[1,1,0],[1,0,1]] res = sol.floodFill(image, 1, 1, 2) exp = [[2,2,2],[2,2,0],[2,0,1]] assert res == exp
6f0122af149b2ac8509a4526ce0a738e86f55703
maxgreat/fileSort
/comicSort.py
1,616
3.53125
4
import glob import sys import os def dirExplore(dirname, extension=''): """ Explore a directory, and the sub directory and return everry file with a given extension """ els = [] for path in glob.glob(dirname+'/*'): if os.path.isdir(path) : print(path, 'is a directory') els += dirExplore(path) elif os.path.isfile(path): if extension in path: els.append(path) return els def isfloat(value): """ Test if the value can be cast to float """ try: float(value) return True except ValueError: return False if __name__ == '__main__': if len(sys.argv) > 1: mainDir = os.path.abspath(sys.argv[1]) else: mainDir = os.path.abspath(os.path.curdir) l = dirExplore(mainDir, extension='.cbr') l += dirExplore(mainDir, extension='.cbz') listSerie = [] for comic in l: name, ext = os.path.splitext(comic.split('/')[-1]) tmp = name.split(' ') date = tmp[0] #verify year if len(date.split('-')) != 2: continue year, month = date.split('-') #extract name of the serie serie = '' i = 1 while i < len(tmp) and not tmp[i].split('.')[0].isdigit(): serie += tmp[i]+' ' i += 1 serie = serie[0:-1] #create the file in the year directory if not os.path.isdir(mainDir+'/'+year): os.mkdir(mainDir+'/'+year) if not os.path.isfile(mainDir+'/'+year+'/'+name+ext): os.link(comic, mainDir+'/'+year+'/'+name+ext) #create the file in the serie directory if not os.path.isdir(mainDir+'/'+serie): os.mkdir(mainDir+'/'+serie) if not os.path.isfile(mainDir+'/'+serie+'/'+name+ext): os.link(comic, mainDir+'/'+serie+'/'+name+ext)
f56cfb8105fc6fbd18fecbc17e16b90ef24d5ea6
activehuahua/python
/pythonProject/exercise/6/6.6.py
543
3.59375
4
import string def myStrip(s): aList1=[] aList2=[] for i in range(len(s)): if s[i].isspace(): continue else: str2=s[i:] break for i in range(-1,-len(str2),-1): if str2[i].isspace(): continue else: if i==-1: str3=str2[:] else: str3=str2[:i+1] break return str3 print(myStrip(' 1 sssss 1 ')) print(myStrip(' 2 sssss 2')) print(myStrip(' 3 ss sss 3 '))
69dab0eaa7321052752be014b79e5c7ec82ed9cd
Tsingzao/MyLeetCode
/Longest Univalue Path.py
832
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 25 21:24:13 2018 @author: Tsingzao """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ self.ret = 0 def dfs(root): if not root: return 0 m, n = dfs(root.left), dfs(root.right) m = m + 1 if root.left and root.left.val == root.val else 0 n = n + 1 if root.right and root.right.val == root.val else 0 self.ret = max(self.ret, m + n) return max(m, n) dfs(root) return self.ret
b9f3f3fe58995a147ad29ae82dd030a57d90db15
itayzaga/matala1
/equations.py
1,152
3.75
4
def exponent (x): n = 1 mone = 1.0 mahane = 1 a = 1 while n <= 150: mone = mone * x mahane = mahane * n a = a + (mone/mahane) n = n + 1 return a def Ln (x): if (x <= 0.0): return 0.0 yi = x - 1.0 while True: yi_1 = yi + 2 * ((x - exponent(yi)) / (x + exponent(yi))) if (yi - yi_1 >= 0): if (yi - yi_1 < 0.000001): break else: if (yi - yi_1 > -0.000001): break yi = yi_1 return yi def XtimesY (x , y): if (x < 0.0): return 0.0 return exponent(y * Ln(x)) def sqrt (x , y): try: return XtimesY (y , (1/x)) except: return 0.0 def calculate (x): return exponent (x) * XtimesY (7.0 , x) * XtimesY (x , -1) * sqrt (x , x) #x = input("give x ") #x = float(x) #calculate (x) #if (x < 0.0): # if (y - int(y) != 0.0): # print (y) # print (int(y)) # print (y - int (y)) # if (((y * 10)/2) - int (((y * 10)/2)) != 0.0): # print ("the answer is complex number") # return 0.0 # else: # return pow # elif ((y/2) - int(y/2) != 0.0): # return -1 * pow # else: # return pow # else: # return pow #y = float(input("give y ")) #pow = sqrt (x , y) #pow = XtimesY(x , y)#print (pow)
60d69b8b0e55fcb31921b44277a120ac02c65a0c
arundeepkakkar/Reeborg
/Step 07.py
999
3.75
4
from library import multi_move, turn_right, turn_back def mov_n_put(count=1): for _ in range(count): move() put() def draw(num): if num: move() turn_left() mov_n_put(5) turn_back() multi_move(5) turn_left() move() else: move() turn_left() mov_n_put(5) turn_right() mov_n_put(2) turn_right() mov_n_put(4) turn_right() mov_n_put() for _ in range(2): turn_left() move() move() draw(1) draw(0) draw(0) draw(1) draw(0) move() ################################################################ # WARNING: Do not change this comment. # Library Code is below. ################################################################ def multi_move(count=1): for _ in range(count): move() def turn_right(): turn_left() turn_left() turn_left() def turn_back(): turn_left() turn_left()
4e793a09b75addab242e2ba21192bae83cad2e2e
aumc-bscs5th/Lab-Submissions
/Lab Test -17 Nov 2017/153174/GuessRandomNumber.py
305
4.09375
4
import random num = random.randint(1,50) while NumGuessed != num : NumGuessed = int(input("Enter a number to guess the computer's random number: ")) if (NumGuessed==num): print("You won, you guess the number, what a LUCK :D ") else: print("Try Again, you can guess it :D ")
843237490efacea3c5c65c35713414bf400ef9d2
huyinhou/leetcode
/path-sum-ii/lcode113.py
1,706
3.625
4
import unittest class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if root is None: return [] remain = sum - root.val retval = [] if root.left is None and root.right is None: # print root.val, remain if remain == 0: return [[root.val,]] return [] # print root, remain if root.left is not None: temp = self.pathSum(root.left, remain) # print temp for v in temp: t = [root.val,] t.extend(v) retval.append(t) if root.right is not None: temp = self.pathSum(root.right, remain) # print temp for v in temp: t = [root.val,] t.extend(v) retval.append(t) return retval def makeTree(vals): nodes = [None]*len(vals) for i in range(len(vals)): nodes[i] = TreeNode(vals[i]) for i in range(len(vals)): l = 2 * i + 1 r = 2 * (i + 1) if l < len(vals): nodes[i].left = nodes[l] if r < len(vals): nodes[i].right =nodes[r] return nodes[0] class TestSolution(unittest.TestCase): def test_1(self): t = makeTree([1, 2, 3, 0, 1, -4, 0, -3, 3, -4]) s = Solution() ret = s.pathSum(t, 0) print ret def main(): unittest.main() if __name__ == '__main__': main()
76f26d3ae6ed244971955001c7784c40c0e51969
felixzhao/WordSegmentation
/MaxWordSegmentation/MaxWordSegmentation.py
1,966
3.765625
4
# -*- coding: cp936 -*- #ƥ䷨зִ, ļΪMaxWordSegmentationTest.py #author #date 2013/3/25 import string import re #ʱļڴlist #:ʵļ, :ʵдʵlist,ʳ def load_dict(filename): f = open(filename,'r').read() maxLen = 1 strList=f.split("\n") #Ѱʳ for i in strList: if len(i)>maxLen: maxLen=len(i) return strList,maxLen; #ִʷ. #:ʱдʵбеʳ, :ִʺб def segmentation(strList,maxLen,sentence): wordList=[] #Ĵб while(len(sentence)>0): word=sentence[0:maxLen] #ÿȡʳĴ meet=False; #λ, жǷҵô while((not meet) and (len(word)>0)): #ڴʱ if(word in strList): wordList.append(word) #ӵб sentence=sentence[len(word):len(sentence)]# meet=True; #ʲڴʱʱ else: #ʳΪ1ʱ, ӵ, ܴλ if(len(word)==1): wordList.append(word) sentence=sentence[len(word):len(sentence)] meet=True; else: #ʳΪ1ʱ, ʳ1(һλ) word=word[0:len(word)-1] return wordList # def main(): strList,maxLen=load_dict('dict.txt') print("ʱʳΪ:",maxLen) # sentence = input('ľӣ') print('ľΪ:',sentence) # sentence='ϣ' print('ľΪ:',sentence) length=len(sentence) print('ľӳ:',length) print("****************ʼ**********************") wordl=segmentation(strList,maxLen,sentence) #ӡִʽ for eachChar in wordl: print(eachChar,end = "/ ") print("")# print("****************!*********************") # if __name__ == '__main__': main()
b79c0e77eff10435ebfffa69029b0b4829964ceb
nahyunsung/python
/qullze02.py
651
3.578125
4
import random as r import tkinter as tk def num(): global q_num as_num = int(a_num.get()) if as_num == q_num: lbl.configure(text = "정답 !!") txtnum.configure(state = 'readonly') elif as_num > q_num: lbl.configure(text = "더작은 수자를 넣어봐!!") else: lbl.configure(text= "더큰 숫자를 넣어봐!!" ) root = tk.Tk() root.geometry("300x300") q_num = r.randint(1,100) a_num = tk.StringVar() print(q_num) lbl = tk.Label(text = "정답은 ???") txtnum = tk.Entry(textvariable = a_num) btn = tk.Button(text="정답", command = num) lbl.pack() txtnum.pack() btn.pack() tk.mainloop()
becf6fdcd8ca5320e1eb57932ca4dee47cea0d21
Ehtesham22/codeforce
/team.py
220
3.59375
4
n = int(input()) count = 0 for x in range(0, n): friend_1, friend_2, friend_3 = [int(x) for x in input().split()] vote = friend_1 + friend_2 + friend_3 if vote >= 2: count += 1 print(count)
cfad42fd8831e2161755765ea45d321c24de7ae9
kangli-bionic/algorithm
/lintcode/374.py
1,291
3.6875
4
""" 374. Spiral Matrix https://www.lintcode.com/problem/spiral-matrix/description?_from=ladder&&fromId=131 BFS """ DIRECTIONS = [ (0, 1), (1, 0), (0, -1), (-1, 0) ] from collections import deque class Solution: """ @param matrix: a matrix of m x n elements @return: an integer list """ def spiralOrder(self, matrix): # write your code here if not matrix or not matrix[0]: return [] res = [] visited = set() q = deque() q.append((0,0,0)) visited.add((0, 0)) while q: f_d_i, f_c_x, f_c_y = q.popleft() res.append(matrix[f_c_x][f_c_y]) for i in range(4): delta_x, delta_y = DIRECTIONS[(f_d_i + i) % 4] nx, ny = f_c_x + delta_x, f_c_y + delta_y if self.is_valid(nx, ny, matrix, visited): visited.add((nx, ny)) q.append(((f_d_i + i) % 4, nx, ny)) break return res def is_valid(self, x, y, matrix, visited): n = len(matrix) m = len(matrix[0]) if not (0 <= x < n and 0 <= y < m): return False if (x, y) in visited: return False return True
ab6057c146a8cd5624d52c58e56870abe87be9a9
dhanashreesshetty/Project-Euler
/Problem 26 Reciprocal cycles/pyprog.py
760
3.84375
4
def checkLength(n): rem=1 i=1 num=1 #number is the dividend and its updated in every loop array=[] #array stores positions of obtained remainders-can be use to check if that remainder had occurred before as well as its position array=array+n*[0] while rem!=0 and i<=n: rem=num%n if array[rem]!=0: #we check if the current remainder was obtained before. If it was, we found a pattern length=i-array[rem] return length num=rem*10 array[rem]=i i+=1 return 0 i=3 maxl=0 #max stores current maximum length while i<1000: temp=checkLength(i) if temp>maxl: maxl=temp num=i #num stores corresponding number i+=1 print(num)
01973cccbbcd3f29b2f0362d0703380888a9603f
MilesBurne/BalloonPopGame
/Projectile_Module.py
3,865
3.90625
4
#Projectile Module by Miles Burne 13/03/19 #projectile class, takes the size for the projectile class Projectile(): #init, takes the surface of the screen, the start position, and the Quadratic class, as well as an optional input of size def __init__(self, surface, pos, Quadratic, size=15): #imports pygame locally import pygame self.pygame = pygame #gets the reference for the quadratic class, which updates the equation from the players input self.Quadratic = Quadratic #adding total game surface which will display image self.gameDisplay = surface #getting size of screen self.display_w, self.display_h = self.pygame.display.Info().current_w, self.pygame.display.Info().current_h #grabbing the image to create first surface self.image = self._load_image() #resizing image to a managable scale self.image = self.pygame.transform.smoothscale(self.image,(size,size)) self.rect = self.image.get_rect() self.rect.centerx, self.rect.centery = pos[0], (-1*self.Quadratic.get_y(pos[0]+10))+((self.display_h/4)*3) #changing position of rect to blit object self.reset_pos = self.rect.topleft #adding the position the image will reset to #used to control when the projectile is moving self.moving = False #first move to display ball def first_move(self): #blits projectile at position 1 self.gameDisplay.blit(self.image, self.reset_pos) #private method to get the image for the projectile surface def _load_image(self): #filename for use in loading filename = "Cannonball.png" #loads file, if fails to load game is quit after displaying an error try: image = self.pygame.image.load(filename) except ImportError: print("Error: File '"+filename+"' is not present") quit() #returning image return(image) #returns current rect def get_rect(self): return(self.rect) #resets the projectile to its starting position def reset(self): #resets the projectile to position 1 self.gameDisplay.blit(self.image, self.reset_pos) #resetting the rect self.rect.centerx, self.rect.centery = self.reset_pos[0], self.reset_pos[1] self.moving = False #move function, uses the quadratic from self.quadratic def move(self,moving=False): self.moving = moving #used to return True if object has moved has_moved = False #controls if the projectile should be moving or not if self.moving == True: #checking if projectile at end of screen or below minimum boundary if self.rect[0]+((self.rect[3]/4)*3) >= self.display_w or self.rect[1] >= (self.display_h*3/4)+(self.rect[3]/2): self.reset() else: #making new positions based of of current position new_x = self.rect.centerx+10 new_y = (-1*self.Quadratic.get_y(self.rect.centerx+10))+((self.display_h/4)*3) #as in pygame top of screen is y = 0, values need to be changed #changes rect, used for detecting collisions self.rect.centerx = new_x self.rect.centery = new_y #blitting image self.gameDisplay.blit(self.image, (self.rect.topleft)) #object has moved therefore True has_moved = True return(has_moved) #if shouldnt be moving else: #blits projectile where it should start self.gameDisplay.blit(self.image, self.reset_pos) return(has_moved)
44a17099e4bec7e03e4e6076384af876a64a40c2
HaraHeique/Jogo-da-vida
/mundo.py
489
3.5
4
# -*- coding: utf-8 -*- def carrega_mundo(arquivo): with open(arquivo, "r") as arq: linhas = arq.readlines() matriz_mundo = [] matriz = [[caractere for caractere in linha[:-1]] for linha in linhas] #Esse condicional serve para quando o arquivo(mundo) não for o arquivo 1, pois os outros arquivos está gerando sempre na última linha... #74 elementos e não 75 if (arquivo != "entrada1.txt") : matriz[len(matriz)-1].append("."); return matriz
32e14893649b922f2e5a92b40f803655e0f99772
urishabh12/practice
/dfs.py
315
3.578125
4
n = int(input()) adjacency = [] visited = [False]*n for i in range(n): adjacency.append(list(map(int, input().split()))) def dfs(at): if visited[at]: return print(at) visited[at] = True neighbours = adjacency[at] for i in neighbours: dfs(i) print("-------------") dfs(0)
8b85a4cc77387a4c66aad4e630c28d2b333bbb82
huynmela/CS161
/Project 6/6a/find_median.py
570
4.34375
4
# Author: Melanie Huynh # Date: 5/6/2020 # Description: This program takes a list of numbers and returns the median of those numbers. def find_median(list): """Returns the median of a list of numbers""" list.sort() # Sorts the lists from low to high length = len(list) # Gets length of the list if length % 2 != 0: # Checks if the total list is odd to apply correct mathematical equation return list[length//2] else: # Otherwise, even lists get applied correct mathematical equation num1 = list[length//2] num2 = list[length//2 -1] return (num1 + num2) / 2
e4f3429003a33bf57389b2709fb9f83800309253
Roger-random/python_tutorials
/flow_control.py
1,523
4.625
5
#!/usr/bin/env python3 ############################################################################# # # Multiple assignments takes everything on left of equal and assigns them # everything on the right, in order. Demonstrated in this Fibonacci while loop def fib(fib_limit): """This is a documentation string (docstring) I should explain my function prints a Fibonacci sequence""" print("Fibonacci up to", fib_limit, end=': ') a,b = 0,1 while b < fib_limit: print(b, end=', ') a,b = b,a+b print('(end)') fib(20) ############################################################################# # if/elif/else x = int(input("Enter an integer:")) if x < 0: print("Negative number") elif x > 0: print("Positive number") else: print("Neither negative nor positive, must be zero!") ############################################################################# # For loops only go over sequences forseq = ["It's", "a", "happy", "day"] for w in forseq: print(w, len(w)) # To make a for loop that looks like other languages for loops, create a range of integers. for i in range(5): #for( int i = 0; i < 5; i++) print(i) for i in range(0, 10, 3): #for (int i = 0; i < 10, i+= 3) print(i) ############################################################################# # Python has 'else' block to run after a successfully completed loop for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, "equals", x, "*", n/x) break; else: print(n, "is a prime number")
60103cf81ef0c5eac9408b436ef66aab19f250aa
jeanDeluge/pythonForEverybody
/Chap6_5.py
338
3.59375
4
#문자열을 저장하는 아래 파이썬 코드에서 find와 문자열 슬라이스를 사용해서 콜론 이후의 문자열을 가져온 다음, #float 함수를 써서 실수로 변환시켜보자. str = 'X=DSPAM-Confidence:0.8475' char = str.find(':') last =str.find("5",char) answer = float(str[char+1:last+1]) print(answer)
9357fe59a0b956edfe980f3d26da609eea0e5ea9
AnjaliMewada12/hackerearth_programs
/The Great Kian.py
1,285
3.515625
4
'''The great Kian is looking for a smart prime minister. He's looking for a guy who can solve the OLP (Old Legendary Problem). OLP is an old problem (obviously) that no one was able to solve it yet (like P=NP). But still, you want to be the prime minister really bad. So here's the problem: Given the sequence a1, a2, ..., an find the three values a1 + a4 + a7 + ..., a2 + a5 + a8 + ... and a3 + a6 + a9 + ... (these summations go on while the indexes are valid). Input The first line of input contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an separated by space (1 ≤ ai ≤ 109). Output Print three values in one line (the answers).''' test=int(input()) l=[int(x) for x in input().split()] flag3=0 k=test sum=0 i=0 if test>=3: while k>0: sum+=l[i] i+=3 k-=3 print(sum,end=" ") k=test-1 sum=0 i=1 while k>0: sum+=l[i] i+=3 k-=3 print(sum,end=" ") k=test-2 sum=0 i=2 while k>0: sum+=l[i] i+=3 k-=3 flag3=1 print(sum,end=" ") else: for item in l: print(item,end=" ") if flag3==0: print("0")
882023cde8bba1262eb818079b322dbde5bff8f1
shivamrai/pycode
/linkedlist.py
2,588
3.71875
4
class Node: def __init__(self,val): self.val = val self.next = None def __repr__(self): return "Node data is = {}".format(self.val) def getval(self): return self.val def setval(self, new_val): """Replace the data with new""" self.val = new_val def getnext(self): """"Return next attribute""" return self.next def setnext(self,new_next): """"new next""" self.next = new_next class SinglyLinkedList: def __init__(self): self.head = None #self.length = 0 def __repr__(self): return "SLL object: head={}".format(self.head) def isEmpty(self): """returns true if linked list is empty""" return self.head is None def addFront(self,val): temp = Node(val) temp.setnext(self.head) self.head = temp def size(self): size = 0 if self.head is None: return size current = self.head while(current): #while there are nodes to count size += 1 #current = current.next current= current.getnext() return size def search(self,searchterm): if self.head is None: return "Linked list is empty, no nodes to search" current = self.head while(current): if(current.getval()==searchterm): return True else: current = current.getnext() return False def remove(self,val): if self.isEmpty(): return "List is empty, nothing to remove" current = self.head previous = None found = False while(not found): if(current.getval()==val): found = True else: if(current.getnext()==None): return "Node not found" else: previous = current current = current.getnext() if(previous is None): self.head = current.getnext() else: previous.setnext(current.getnext()) return found if __name__ == "__main__": # node = Node('apple') # node.getval() # node.setval(7) # node.getval() # node2 = Node('carrot') # node.setnext(node2) # print(node.getnext()) node1 = Node(4) sll = SinglyLinkedList() print(sll.isEmpty()) sll.head = node1 print(sll.isEmpty()) sll.addFront('Barry') print(sll.head) print(sll.size()) print(sll.search('barry'))
27aea80d75d8025f06f0d75b334e213d99cac09b
JoshuaHing/cs2041
/revision/15s2/17.py
498
3.609375
4
#!/usr/bin/python3 import sys, re string1 = sys.argv[1] string2 = sys.argv[2] if (string1 == string2): print(string1) else: match = re.search(r'(.*?)(\d+)(.*)', string1) if match: bef = match.group(1) lower = int(match.group(2)) aft = match.group(3) match = re.search(r'(\d+)', string2) if match: higher = int(match.group(1)) i = lower while (i <= higher): line = bef+str(i)+aft print (line) i += 1
c08e7a8c884a7be016ee2a311b9bf8ae4209ede1
Shafin-Thiyam/Python_prac
/func.py
92
3.578125
4
def greeting(name): print("hello " + name) n=input("Enter your Name") greeting(n)
f35954e4835e906ed9972fa3fb19efa3fd9927cf
alexhla/programming-problems-in-python
/linkedlist_add.py
861
3.71875
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addNumbers(self, l1, l2): carry = 0 head = ListNode(0) # create head node curr = head while l1 != None or l2 != None: v1 = l1.val if l1!=None else 0 v2 = l2.val if l2!=None else 0 n = v1 + v2 + carry carry = 0 if n >= 10: carry = n//10 n %= 10 curr.next = ListNode(n) curr = curr.next l1 = l1.next if l1!=None else l1 l2 = l2.next if l2!=None else l2 if carry > 0: curr.next = ListNode(carry) return head.next obj = Solution() n1 = ListNode(5) n1.next = ListNode(10) n1.next.next = ListNode(20) n2 = ListNode(5) n2.next = ListNode(10) n2.next.next = ListNode(20) ans = obj.addNumbers(n1,n2) print("\nAnswer Is ", end="") while ans != None: print(ans.val, end="") ans = ans.next print("\n")
e0dd4e919c585cf36edd0ea96a9e143e9a801fa1
taoyan/python
/Python学习/day10/json序列化.py
977
3.59375
4
import pickle import json class Student(): def __init__(self,name,age): self.name = name self.age = age s = Student('yant',26) #dumps()方法,返回序列化后的bytes print(pickle.dumps(s)) f = open('student.txt','wb') pickle.dump(s,f) f.close() f = open('student.txt','rb') s2 = pickle.load(f) f.close() print(s2.name,s2.age) #json是个字符串,不是二进制 #对象转json d = dict(name = 'bob',age = 20,score = 90) print(json.dumps(d)) #直接转化报错 # print('student json = ',json.dumps(s)) #可以转换class的__dict__属性,因为是个dict print(json.dumps(s,default=lambda obj:obj.__dict__)) f = open('student2.txt','w') json.dump(s.__dict__,f) f.close() f = open('student2.txt','r') dic = json.load(f) f.close() print(dic,type(dic)) #dict转class def dict2student(d): return Student(d['name'],d['age']) json_str = '{"name":"allen","age":26}' s3 = json.loads(json_str,object_hook = dict2student) print(s3.name,s3.age)
2ac633d31721ae8e8d245d1643bfeb72d1a02b7f
vektorelpython19/pythontemel
/OOP/Inheritance.py
1,383
4.0625
4
# Inheritance class A: def __init__(self): self.__gizli = 1 self.a = "A" def aFonk(self): return 1 class B(A): def __init__(self): super().__init__() self.b = "B" class C(B): def __init__(self): super().__init__() self.c = "C" class D: def __init__(self): self.d = "D" class D_1: def __init__(self): self.d_1 = "D_1" class E(A,D): def __init__(self): # super().__init__() #A A.__init__(self) D.__init__(self) self.e = "E" class F(D,D_1): def __init__(self): D.__init__(self) D_1.__init__(self) self.f = "F" nesneA = A() nesneB = B() nesneC = C() nesneD = D() nesneD_1 = D_1() nesneE = E() nesneF = F() print(type(nesneA)) print(type(nesneB)) print(type(nesneC)) print(type(nesneD)) print(type(nesneD_1)) print(type(nesneE)) print(type(nesneF)) print(isinstance(nesneA,C)) print(isinstance(nesneC,A)) print(issubclass(D_1,C)) print(issubclass(E,D)) # Acaba --------------- # # class A_1: # def __init__(self): # self.a = "A" # class B_1(A_1): # def __init__(self): # super().__init__() # self.b = "B" # class A_1(B_1): # def __init__(self): # super().__init__() # self.c = "C" # nesne1 = A_1() # print(nesne1.a) # print(nesne1.b) # print(nesne1.c)
c881aa3dc9b4f97dc107f67c2b0a45ce93613bed
famaxth/Way-to-Coding
/snakify-problems-python/6/The index of the maximum of a sequence.py
149
3.578125
4
max = 1 i = 1 max_i = 1 a = int(input()) while a != 0: if a > max: max = a max_i = i a = int(input()) i += 1 print(max_i)
9f51d3d9d39fc4425e3b83e13018f13d6b43d376
MontessoriSchool-CS/Intro-Python-2.1-Simple-Maths
/main.py
358
3.625
4
# FORK ME or copy the code! Please don't request edit access. This is the original so it needs to stay undedited for all users. # Task 1 - Add comments to this code to predict what it will do. print(8 + 2) print( 8 - 2) print(8 * 2) print(8 / 2) print(8 // 2) # Task 2 - Write code that calculates and outputs the following numbers: 2001, 1024, 42, 15
4cf0e25d1658afb75acd0d30918a323d10d2a398
Torbacka/adventofcode
/2021/day1/main.py
259
3.53125
4
from utils import * numbers = [int(line) for line in open("input/input.in").readlines()] if __name__ == '__main__': print(sum([int(b) > int(a) for a, b in zip(numbers, input[1:])])) print(sum([int(b) > int(a) for a, b in zip(numbers, input[3:])]))
600c0fd97db4ccf46cb63d96dc0dcaada576f671
Joes-BitGit/Leetcode
/leetcode/num_island.py
1,818
3.765625
4
# DESCRIPTION # Given a 2d grid map of '1's (land) and '0's (water), # count the number of islands. An island is surrounded by water # and is formed by connecting adjacent lands horizontally or vertically. # You may assume all four edges of the grid are all surrounded by water. # EXAMPLE 1: # Input: # 11110 # 11010 # 11000 # 00000 # Output: 1 # EXAMPLE 2: # Input: # 11000 # 11000 # 00100 # 00011 # Output: 3 class Solution: def numIslands(self, grid: List[List[str]]) -> int: ''' Time: O(N^2), we have to dfs each element in the grid Space: O(N), stack frames from dfs at worst point ''' # check if grid exists or if the grid has length 0 if not grid or len(grid) == 0: return 0 # island counter num_islands = 0 # must iterate over every element for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '1': # when an island appears increment the counter num_islands += self.dfs(grid, i , j) return num_islands def dfs(self, grid, i , j): # row goes up # row goes too low # column goes too left # column goes too right # current element has been seen/ ran out of land # exit if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[i]) or grid[i][j] == '0': return 0 # backtracking: set the current element has seen grid[i][j] = '0' # search right self.dfs(grid, i, j + 1) # search left self.dfs(grid, i, j - 1) # search up self.dfs(grid, i + 1, j) # search down self.dfs(grid, i - 1, j) # count the element when it was sent from the main loop return 1
5f69cbc463a59cf9febc23025dcea957834ca17c
Bukio-chan/sotsuken_flask
/calc.py
12,168
3.65625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from matplotlib.image import imread from matplotlib import pyplot import numpy as np import random import operator import pandas as pd import matplotlib.pyplot as plt import string import csv class Attraction: # distance.csvのデータを2次元配列distance_listに格納 with open("static/csv/distance.csv", 'r', encoding="utf-8")as f: reader = csv.reader(f) distance_list = [row for row in reader] def __init__(self, x, y, name, wait_time_list=None, ride_time=None, num=None, now_wait_time=None, url=None): self.x = x self.y = y self.name = name self.wait_time_list = wait_time_list self.ride_time = ride_time self.num = num self.now_wait_time = now_wait_time self.url = url self.scale = 140 / 41.231 # 縮尺 # 距離の計算 def distance(self, attraction): # distance = np.sqrt((self.x - attraction.x) ** 2 + (self.y - attraction.y) ** 2) # 二点間の距離の計算 # distance = float(self.distance_list[self.num][attraction.num]) # 設定した距離データで計算 wonderland_x = 165 wonderland_y = 160 if self.distance_list[self.num][attraction.num] == 'None': distance = np.sqrt((self.x - attraction.x) ** 2 + (self.y - attraction.y) ** 2) * self.scale elif self.num >= 12: distance = float(self.distance_list[self.num][attraction.num]) distance += np.sqrt((self.x - wonderland_x) ** 2 + (self.y - wonderland_y) ** 2) * self.scale elif attraction.num >= 12: distance = float(self.distance_list[self.num][attraction.num]) distance += np.sqrt((wonderland_x - attraction.x) ** 2 + (wonderland_y - attraction.y) ** 2) * self.scale else: distance = float(self.distance_list[self.num][attraction.num]) # 設定した距離データで計算 return distance def __repr__(self): return f'{self.name}' class Calculation: def __init__(self, route, ga): self.route = route self.start_place = ga.start_place self.end_place = ga.end_place self.start_time = ga.start_time self.factor = ga.factor self.walk_speed = 80 # 歩く速さ self._each_wait_time = 0 # 待ち時間list self._each_walk_time = 0 # 徒歩時間list self._time = 0 self._distance = 0 self._fitness = 0 # 徒歩時間の追加 def add_walk_time(self, route): walk_time = [round(self.start_place.distance(route[0]) / self.walk_speed)] # 最初の地点 for i in range(len(route) - 1): # 距離 from_attraction = route[i] to_attraction = route[(i + 1) % len(route)] walk_time.append(round(from_attraction.distance(to_attraction) / self.walk_speed)) walk_time.append(round(self.end_place.distance(route[-1]) / self.walk_speed)) # 最後の地点 return walk_time # 所要時間の合計 def calculate_total_time(self, route): start_time = self.start_time fixed_time = start_time # スタート時間の固定 each_walk_time = self.add_walk_time(route) total_time = 0 flag = True each_wait_time = [] if type(route[0].now_wait_time) == int: # 現在時刻のときの待ち時間 route[0].wait_time_list[start_time] = route[0].now_wait_time for i in range(len(route)): if start_time < 23: total_time += each_walk_time[i] # 徒歩時間 total_time += route[i].ride_time # 乗車時間 each_wait_time.append(route[i].wait_time_list[start_time]) # アトラクション毎の待ち時間 total_time += each_wait_time[i] # 待ち時間の合計 if total_time >= 30: start_time = fixed_time + round(total_time / 30) else: flag = False break total_time += each_walk_time[-1] # 最後のアトラクションからゴール位置までの時間 if flag: return total_time, each_wait_time, each_walk_time else: return total_time * 10000, each_wait_time, each_walk_time @property def time(self): # 時間の計算 if self._time == 0: path_time = self.calculate_total_time(self.route) self._time, self._each_wait_time, self._each_walk_time = path_time return self._time, self._each_wait_time, self._each_walk_time @property def distance(self): # 総距離の計算 if self._distance == 0: path_distance = 0 path_distance += self.start_place.distance(self.route[0]) # 最初の地点 for i in range(len(self.route) - 1): # 距離 from_attraction = self.route[i] to_attraction = self.route[(i + 1) % len(self.route)] path_distance += from_attraction.distance(to_attraction) # どっちか path_distance += self.end_place.distance(self.route[-1]) # 最後の地点 self._distance = path_distance return self._distance @property def time_fitness(self): if self._fitness == 0: self._fitness = 1 / float(self.time[0]) return self._fitness @property def distance_fitness(self): if self._fitness == 0: self._fitness = 1 / float(self.distance) return self._fitness def mutate(individual): # 突然変異 # This has mutation_rate chance of swapping ANY city, instead of having mutation_rate chance of doing # a swap on this given route... for swapped in range(len(individual)): if random.random() < 0.01: # 突然変異率 swap_with = int(random.random() * len(individual)) individual[swapped], individual[swap_with] = individual[swap_with], individual[swapped] return individual def mutate_population(population): mutated_pop = [] for ind in population: mutated = mutate(ind) mutated_pop.append(mutated) return mutated_pop def breed(parent1, parent2): gene_a = int(random.random() * len(parent1)) gene_b = int(random.random() * len(parent2)) start_gene = min(gene_a, gene_b) end_gene = max(gene_a, gene_b) child_p1 = [] for i in range(start_gene, end_gene): child_p1.append(parent1[i]) child_p2 = [item for item in parent2 if item not in child_p1] child = child_p1 + child_p2 return child def mating_pool(population, selection_results): pool = [population[idx] for idx in selection_results] return pool def breed_population(pool, elite_size): children = [] length = len(pool) - elite_size pool = random.sample(pool, len(pool)) for i in range(elite_size): children.append(pool[i]) for i in range(length): child = breed(pool[i], pool[-i - 1]) children.append(child) return children def selection(population_ranked, elite_size): selection_results = [] df = pd.DataFrame(np.array(population_ranked), columns=['Index', 'Fitness']) df['cum_sum'] = df['Fitness'].cumsum() df['cum_perc'] = 100 * df['cum_sum'] / df['Fitness'].sum() for i in range(elite_size): selection_results.append(population_ranked[i][0]) for i in range(len(population_ranked) - elite_size): pick = 100 * random.random() satisfying = df[df['cum_perc'] >= pick] picked_idx = int(satisfying['Index'].iloc[0]) selection_results.append(picked_idx) return selection_results def create_route(attraction_list): route = random.sample(attraction_list, len(attraction_list)) return route def create_initial_population(population_size, attraction_list): population = [] for i in range(population_size): population.append(create_route(attraction_list)) return population class GeneticAlgorithm: def __init__(self, attraction_list, distance_flag, start_place, end_place, start_time, factor): self.attraction_list = attraction_list self.distance_flag = distance_flag self.start_place = start_place self.end_place = end_place self.start_time = start_time self.factor = factor def rank_routes(self, population): fitness_results = {} for i in range(len(population)): calc = Calculation(population[i], self) if self.distance_flag: fitness_results[i] = calc.distance_fitness else: fitness_results[i] = calc.time_fitness return sorted(fitness_results.items(), key=operator.itemgetter(1), reverse=True) def next_generation(self, current_gen, elite_size): pop_ranked = self.rank_routes(current_gen) selection_results = selection(pop_ranked, elite_size) mate_pool = mating_pool(current_gen, selection_results) children = breed_population(mate_pool, elite_size) next_gen = mutate_population(children) return next_gen def plot_route(self, route, title=None): # 表示 img = imread("static/USJ_map.png") # 画像ファイル名のランダム文字列 random_string = ''.join([random.choice(string.ascii_letters + string.digits) for i in range(6)]) img_filename = f"static/result/USJ_route_{random_string}.png" plt.figure() for i in range(len(route)): attraction = route[i] next_attraction = route[(i + 1) % len(route)] bbox_dict = dict(boxstyle='round', facecolor='#00bfff', edgecolor='#0000ff', alpha=0.75, linewidth=2.5, linestyle='-') pyplot.text(attraction.x, attraction.y - 15, i + 1, bbox=bbox_dict) # 番号の表示 plt.scatter(attraction.x, attraction.y, c='red') if i >= len(route) - 1: break plt.plot((attraction.x, next_attraction.x), (attraction.y, next_attraction.y), c='black') if title: plt.title(title, fontname="MS Gothic") # スタート地点・ゴール地点のplot plt.scatter(self.start_place.x, self.start_place.y, c='blue') plt.scatter(self.end_place.x, self.end_place.y, c='blue') plt.plot((self.start_place.x, route[0].x), (self.start_place.y, route[0].y), c='black') plt.plot((self.end_place.x, route[-1].x), (self.end_place.y, route[-1].y), c='black') plt.imshow(img) # plt.show() plt.tick_params(labelbottom=False, labelleft=False, labelright=False, labeltop=False) # ラベル消す plt.tick_params(bottom=False, left=False, right=False, top=False) # ラベル消す # plt.subplots_adjust(left=0, right=0.975, bottom=0.1, top=0.9) # 余白調整 plt.savefig(img_filename, bbox_inches='tight', pad_inches=0) # 画像で保存 return img_filename def solve(self, generation, population_size, elite): pop = create_initial_population(population_size, self.attraction_list) for g in range(generation): pop = self.next_generation(pop, elite) best_route_index = self.rank_routes(pop)[0][0] best_route = pop[best_route_index] calc = Calculation(best_route, self) if self.distance_flag: time_result = calc.time distance_result = round(1 / self.rank_routes(pop)[0][1], 2) else: time_result = calc.time distance_result = round(calc.distance, 2) if not self.distance_flag and time_result[0] > 10000: time_result = 0 return best_route, time_result, distance_result def main(self, generation): population_size = generation elite = int(population_size / 5) best_route = self.solve(generation, population_size, elite) order_result, time_result, distance_result = best_route img_filename = self.plot_route(order_result) return order_result, time_result, distance_result, img_filename
d72b0ff579977b6d6d3384e179d0f422fca1ff19
mukoedo1993/Python_related
/python_official_tutorial/chap5_3/tuple.py
600
4.09375
4
t = 12345, 54321, 'hello!' print(t[0]) print(t) # Tuples may be nested u = t, (1, 2, 3, 4, 5) print(u) # Tuples are immutable: #t[0] = 88888 """ Traceback (most recent call last): File "tuple.py", line 14, in <module> t[0] = 88888 TypeError: 'tuple' object does not support item assignment """ # but they can contain mutable objects v=([1, 2, 3], [3, 2, 1]) print(v) """ (base) zcw@mukoedo1993:~/python_related_clone/Python_related/python_official_tutorial/chap5_3$ python tuple.py 12345 (12345, 54321, 'hello!') ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) ([1, 2, 3], [3, 2, 1]) """
8bec6339bcb2a8ce60a1cb4dbfd4e3d68d117104
cpeixin/leetcode-bbbbrent
/tree/levelOrder.py
1,446
3.921875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2021/4/29 8:05 上午 # @Author : CongPeiXin # @Email : congpeixin@dongqiudi.com # @File : levelOrder.py # @Description:给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 # #   # # 示例: # 二叉树:[3,9,20,null,null,15,7], # # 作者:力扣 (LeetCode) # 链接:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefh1i/ # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def levelOrder(self, root): if not root: return [] res, queue = [], [root] while queue: tmp = [] for i in range(len(queue)): current = queue.pop(0) tmp.append(current.val) if current.left: queue.append(current.left) if current.right: queue.append(current.right) res.append(tmp) return res if __name__ == '__main__': tree_3 = TreeNode(3, TreeNode(5, TreeNode(6), TreeNode(2, TreeNode(7), TreeNode(4))), TreeNode(1, TreeNode(0), TreeNode(8))) result = Solution.levelOrder(tree_3) print(result)
45a5b4a1ed375577bd77af12cced2cece7fa5960
jedzej/tietopythontraining-basic
/students/hyska_monika/lesson_02_flow_control/BishopMoves.py
563
3.796875
4
# The program print that Bishop can move from one field to second field import math v1 = int(input("Put vertical position for 1st field (from 1 to 8): ")) h1 = int(input("Put horizontal position for 1st field(from 1 to 8): ")) v2 = int(input("Put vertical position for 2nd field(from 1 to 8): ")) h2 = int(input("Put horizontal position for 2nd field(from 1 to 8): ")) vector_1 = int(math.fabs(v1 - v2)) vector_2 = int(math.fabs(h1 - h2)) if(vector_1 - vector_2) == 0: value = "YES" else: value = "NO" print("\nOr Bishop can go in one move?:", value)
6469622c5371a5d9c6551ef0e3ceb245b52fca01
ashfaqrehman/calculator
/tests/test_add.py
844
3.515625
4
""" Test the add() function of the calculator """ import pytest #import pdb;pdb.set_trace() from calculator import add def test_two_plus_two(): """ If given 2 and 2 as paramters, 4 should be returned """ assert add(2,2) == 4 def test_three_plus_three(): """ If given 3 and 2 as paramters, 6 should be returned """ assert add(3,3) == 6 def test_no_parameters(): """ IF no params are provided return 0 """ assert add() == 0 def test_one_two_three(): """ Given values 1,2,3 should return 6 """ assert add(1,2,3) == 6 def test_negative_values(): """ Given values -11,-1,22 should return 6 """ assert add(-11,-1,22) == 10 def test_decimal_values(): """ Given 0.1,0.1,0.1 should return 0.3 """ assert add(0.1,0.1,0.1) == pytest.approx(0.3)
0f007964f6d6f037ebcadc88ef781963bb70b027
xpeeperp/Python
/ftp/ftp5.py
5,064
3.640625
4
# !/usr/bin/python # coding:utf-8 # write:JACK # info:ftp example import ftplib, socket, os from time import sleep, ctime def LoginFtp(self): ftps = ftplib.FTP() ftps.connect(self.host, self.port) ftps.login(self.name, self.passwd) # 未进行判断地址输入是否为ip或者域名;可以进行判断是否包含<或者实体符号以及';其他可以忽略 class LoFtp(object): 'this is ftp class example' host = str(raw_input('host,202.101.231.234\n')) if host == '': host = '202.101.231.234' port = raw_input('port,21\n') if not (port.isdigit()): port = 21 name = str(raw_input('name,anonymous\n')) if name == '': name = 'testpython' passwd = str(raw_input('password\n')) if passwd == '': passwd = 'test123@321' \ '' def ZqFtp(self, host, name, passwd, port): self.host = host self.name = name self.passwd = passwd self.port = port def LoginFtp(self): self.ftps = ftplib.FTP() self.ftps.connect(self.host, self.port) self.ftps.login(self.name, self.passwd) self.buffer = 2048 # 设置缓存大小 def ShowFtp(self): self.LoginFtp() self.ftps.dir('/') dirs = str(raw_input('PLEASE INPUT DIR!\n')) print self.ftps.dir(dirs) def UpFtp(self): 'uploads files' self.LoginFtp() self.ftps.set_debuglevel(2) filename = str(raw_input('PLEASE FILE NAME!\n')) file_open = open(filename, 'rb') # 打开文件 可读即可 self.ftps.storbinary('STOR %s' % os.path.basename(filename), file_open, self.buffer) # 上传文件 self.ftps.set_debuglevel(0) file_open.close() def DelFtp(self): 'Delete Files' self.LoginFtp() filename = str(raw_input('PLEASE DELETE FILE NAME!\n')) self.ftps.delete(filename) def RemoveFtp(self): 'Remove File' self.LoginFtp() self.ftps.set_debuglevel(2) # 调试级别,0无任何信息提示 oldfile = str(raw_input('PLEASE OLD FILE NAME!\n')) newfile = str(raw_input('PLEASE NEW FILE NAME!\n')) self.ftps.rename(oldfile, newfile) self.ftps.set_debuglevel(0) def DownFtp(self): 'Download File' self.LoginFtp() self.ftps.set_debuglevel(2) filename = str(raw_input('PLEASE FILE NAME!\n')) file_down = open(filename, 'wb').write self.ftps.retrbinary('STOP %s' % os.path.basename(filename), file_down, self.buffer) self.ftps.set_debuglevel(0) file_down.close() a = LoFtp() print a.ShowFtp() while True: helpn = str(raw_input('Whether to continue to view or exit immediately!(y/n/q)\n')) if (helpn == 'y') or (helpn == 'Y'): dirs = str(raw_input('PLEASE INPUT DIR!\n')) a.ftps.dir(dirs) elif (helpn == 'q') or (helpn == 'Q'): exit() else: break while True: print '上传请选择----1' print '下载请选择----2' print '修改FTP文件名称----3' num = int(raw_input('PLEASE INPUT NUMBER![exit:5]\n')) if num == 1: upf = a.UpFtp() print 'Upfile ok!' elif num == 2: dof = a.DownFtp() print 'Download file ok!' elif num == 3: ref = a.RemoveFtp() print 'Remove file ok!' else: a.ftps.quit() print 'Bingo!' break # login(user='anonymous',passwd='', acct='') 登录到FTP服务器,所有的参数都是可选的 # pwd() 得到当前工作目录 # cwd(path) 把当前工作目录设置为path # dir([path[,...[,cb]]) 显示path目录里的内容,可选的参数cb 是一个回调函数,它会被传给retrlines()方法 # nlst([path[,...]) 与dir()类似,但返回一个文件名的列表,而不是显示这些文件名 # retrlines(cmd [, cb]) 给定FTP 命令(如“RETR filename”),用于下载文本文件。可选的回调函数cb 用于处理文件的每一行 # retrbinary(cmd, cb[,bs=8192[, ra]]) 与retrlines()类似,只是这个指令处理二进制文件。回调函数cb 用于处理每一块(块大小默认为8K)下载的数据。 # storlines(cmd, f) 给定FTP 命令(如“STOR filename”),以上传文本文件。要给定一个文件对象f # storbinary(cmd, f[,bs=8192]) 与storlines()类似,只是这个指令处理二进制文件。要给定一个文件对象f,上传块大小bs 默认为8Kbs=8192]) # rename(old, new) 把远程文件old 改名为new # delete(path) 删除位于path 的远程文件 # mkd(directory) 创建远程目录 # 每个需要输入的地方,需要进行排查检错。仅仅这个功能太小了。不过根据实际情况更改,放在bt里边当个小工具即可 # 有点烂,没有做任何try
787ece1d731649dfe63bb3f58597113eb08a732e
rika/TCC11
/filter/old/animation.py
4,159
3.96875
4
#!/usr/bin/python #-*- coding: utf-8 -*- ''' Animation of tracking data Author: Ricardo Juliano Mesquita Silva Oda <oda.ric@gmail.com> Data: 24/09/11 Filename: simulation.py To run: python simulation.py [FILENAME] [STARTFRAME] [ENDFRAME] The program will run an animation of the tracking data in the interval of frames given as parameters. Input file: The input begins with two integers S T, the number of the starting and ending frame of the experiment. After this there's T-S+1 blocks. Each block starts with an integer N, and the next N following lines have four numbers: S H Y X. S is an integer representing the number of the subject; H is an float for the height of the subject; Y is the coordinate y of the subject; X is the coodinate x of the subject. ''' from Tkinter import * import re, time, sys from model import Model WIDTH = 1007 HEIGHT = 400 OBJ_SIZE = 4 color = [ "black", "red", "blue", "green", "yellow", "brown", "cyan", "grey" ] # Simulation class that stores the objects in a canvas class Simulation: def __init__ (self, canvas): self.canvas = canvas def clear (self): self.canvas.delete(ALL) def add (self, obj): x = obj.cx y = obj.cy ink = color[obj.subject%len(color)] self.canvas.create_rectangle(x-OBJ_SIZE, \ y-OBJ_SIZE, x+OBJ_SIZE, y+OBJ_SIZE, fill=ink) item = self.canvas.create_text(x, y+3*OBJ_SIZE, text=str(obj.subject)+": ("+str(x)+","+str(y)+")") # Stores objects of in a frame class FrameData: def __init__(self, objects): self.objects = objects def get_objects(self): return self.objects # Stores the information (frames and objects) from the input file class Data: def __init__(self, filename): self.frames = [] # Open file and get lines infile = open(sys.argv[1], "r") lines = infile.readlines() infile.close() # Get starting and ending frame numbers s = re.match('(\d+)\s(\d+)$', lines[0]) lines = lines[1:] self.start = int(s.group(1)) self.end = int(s.group(2)) for frame in range(self.start, self.end+1): # n is the number of objects in the frame s = re.search('(\d+)$', lines[0]) lines = lines[1:] n = int(s.group(1)) # Get objects of the frame objects = [] for _i in range(n): s = re.search('(\d+)\s(\d+.?\d*)\s(-?\d+)\s(-?\d+)$', lines[0]) lines = lines[1:] subject = int(s.group(1)) height = float(s.group(2)) cx = int(s.group(3)) cy = int(s.group(4)) objects.append(Model(frame, subject, height, cx, cy)) self.frames.append(FrameData(objects)) def get_objects(self, frame): return self.frames[frame-self.start].get_objects() # Parameters if len(sys.argv) != 4: print "USAGE: python " + sys.argv[0] + " [FILENAME] [START_FRAME] [END_FRAME]" exit(0) start = int(sys.argv[2]) end = int(sys.argv[3]) # Loading data from input file data = Data(sys.argv[1]) if start < data.start or end > data.end or start > end: print "Invalid frame interval" print "This data file can be animated in the interval [", \ data.start,",",data.end,"]" exit(-1) # Setup root = Tk() root.title("Simulation") root.resizable(0, 0) root.geometry("+20+20") frame = Frame(root, bd=5, relief=SUNKEN) frame.pack() canvas = Canvas(frame, width=WIDTH, height=HEIGHT) canvas.pack(side = TOP) frameNumber = StringVar() label = Label(frame, textvariable=frameNumber) label.pack(side = BOTTOM) sim = Simulation(canvas) root.update() # Animation loop try: while (True): for frame in range(start, end+1): frameNumber.set("Frame: "+str(frame)) objects = data.get_objects(frame) sim.clear() for obj in objects: sim.add(obj) root.update() # redraw #time.sleep(1.0/24) sys.stdin.readline() except TclError: pass # to avoid errors when the window is closed
55e38f479e83cc1e37e5ae854f80e7c79add8fa4
melandres8/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,316
4.625
5
#!/usr/bin/python3 """Square class""" class Square(): """__init__ constructor: Runs always when we create a new instance of a class Attributes: attr1 (int): is the size of a square """ def __init__(self, size=0): """ Inicializing my class with Args: size (int): size of a square """ self.__size = size @property def size(self): """Getter, retrieve the size of a square this methods is useful to handle with privacity of our instance""" return self.__size @size.setter def size(self, value): """ Handle the value of a size if is an integer or not Args: size (int): size of a square """ if not isinstance(value, int): raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") self.__size = value def area(self): """Calculating the area of a square""" return int(self.__size) * int(self.__size) def my_print(self): """Printing a Square and validating if the size is 0 or not""" for row in range(self.__size): print('#' * self.__size) if self.__size == 0: print()
ede227bd6cb479c516d598399d0506a025064855
aolbrech/codility-lesson-solutions
/Tasks/Painless_Lesson05_PassingCars/Solution_PassingCars.py
705
3.75
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 nrCarsTravellingEast = 0 for value in A: nrCarsTravellingEast += value nrPassingCars = 0 for value in A: if value == 0: nrPassingCars += nrCarsTravellingEast if nrPassingCars > 1000000000: return -1 else: nrCarsTravellingEast -= 1 return nrPassingCars A = [0, 1, 0, 1, 1] print "The number of pairs of passing cars is:", solution(A) corrAnsw = 5 if solution(A) != corrAnsw: print "WRONG SOLUTION!" else: print "Correct solution found!"
326cf8cc6cbb625f5cf36ff4a836f7ed0337e37d
ravisjoshi/python_snippets
/Strings/NumberOfSegmentsInAString.py
627
4.25
4
""" Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. Please note that the string does not contain any non-printable characters. Input: "Hello, my name is John" / Output: 5 """ class Solution: def countSegments(self, _str): count = 0 prev_char = ' ' for char in _str: if char != ' ' and prev_char == ' ': count += 1 prev_char = char return count if __name__ == '__main__': s =Solution() inputString = "Hello, my name is John" print(s.countSegments(inputString))
0e73e46a6b04bec969f6624b596a7025d25c027a
Gafficus/Delta-Fall-Semester-2014
/CST-186-14FA(Intro Game Prog)/Nathan Gaffney CHapter 4/N.G.Project2.py
209
4.28125
4
#Created by: Nathan Gaffney #14-Sep-2014 #Chapter 4 Project 2 #THis program will reverse a string phrase = raw_input("Enter a phrase: ") strLen = len(phrase) while strLen > 0: print phrase[strLen-1] strLen-=1
89196e1879dc9d6c0c088bd89bf1c734cd60bcdf
oneshan/Leetcode
/accepted/147.insertion-sort-list.py
1,454
3.8125
4
# # [147] Insertion Sort List # # https://leetcode.com/problems/insertion-sort-list # # Medium (32.81%) # Total Accepted: # Total Submissions: # Testcase Example: '[]' # # Sort a linked list using insertion sort. # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None dummy = ListNode(0) curr = dummy while head: if curr and curr.val > head.val: curr = dummy while curr.next and curr.next.val < head.val: curr = curr.next temp = curr.next curr.next = head head = head.next curr.next.next = temp return dummy.next if __name__ == "__main__": try: from utils.ListNode import ListNode, createListNode, printListNode sol = Solution() head = createListNode([1, 3, 2, 4, 5]) printListNode(sol.insertionSortList(head)) head = createListNode([3, 4, 1]) printListNode(sol.insertionSortList(head)) head = createListNode([1, 1]) printListNode(sol.insertionSortList(head)) except Exception as e: print(e)
546d50a0ffc35a2ba9cf50068d0c22ce1411c314
liliankotvan/urionlinejudge
/URI1042.py
205
3.8125
4
x, y, z = raw_input().split(" ") x, y, z = int(x), int(y), int(z) list = [x, y, z] list_sorted = sorted(list) for s in list_sorted: print (s) print ("") for l in list: print (l)
352fac621bb95f9a93a289b4168c906f518be640
ksami/cg3002py
/timer.py
628
3.515625
4
# Timer.py import time # Raises a flag when x seconds are up # params: num of seconds def alarm(x): try: time.sleep(x) print "timer up!!" except KeyboardInterrupt: #Ctrl-C pass # Puts x onto queue q once x seconds are up # params: queue, num of seconds def timer(q, x): try: for i in xrange(1, x+1): time.sleep(1) q.put(i) except KeyboardInterrupt: #Ctrl-C pass # For testing: # Run in command line using # python timer.py 3 if __name__ == '__main__': import sys seconds = int(sys.argv[1]) try: time.sleep(seconds) print "timer up!" except KeyboardInterrupt: #Ctrl-C print "interrupted"
969f9a0d96c66c5ec75e74ae90d628a4b22f0cc6
Donn-Lee/Py-algorithm-leetcode
/algo/20.Valid Parentheses.py
1,611
3.9375
4
''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. ''' class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ #思路:遍历整个string,若出现了一个新的右括号,最近也应该能pop出一个相同的左括号(stack) #方法,两个set,分别存储,{'(','{','{'}和{'()','{}','[]'},每次有一个左括号时存储在list中等待pop #检查三个问题,新出现的右括号应该和左括号相同;新出现右括号时,存储左括号的list应该长度不为零;检查完以后,左括号list长度应该为0 left = set(('{','(','[')) match = set(('[]','{}','()')) stack = list() if len(s) == 0: return True for i in s: if i in left: stack.append(i) else: #新出现右括号时,存储左括号的list应该长度不为零 if len(stack) == 0: return False else: left_pop = stack.pop() #新出现的右括号应该和左括号相同 if left_pop+i not in match: return False #检查完以后,左括号list长度应该为0 return len(stack)== 0 s = Solution() print(s.isValid(']'))
f790e6e4c8ee11f24b50f055e8306d519be2ba51
waynessabros/Linguagem-Python
/script_18.py
379
4.125
4
#listas em python #-*- coding: utf-8 -*- lista = [124,345,72,46,6,7,3,1,7,0] lista.sort()#vai ordenar numericamente do menor ao maior print(lista) lista.sort(reverse=True) #vai ordenar numericamente do maior ao menor print (lista) lista.reverse()#reversão da lista print(lista) lista2 = ["bola", "abacate", "dinheiro"] lista2.sort()#ordena alfabeticamente print(lista2)
cb315996c93f24797d0e2016e26a0c07b8f832f0
TerryRPatterson/PythonHardWay
/ex9.py
517
3.90625
4
# Here's some new strange stuff, remeber type it exactly. #The days of the week days = "Mon Tue Wed Fri Sat Sun" #backslash is the espcace character n incidates a new line months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" #Printing the variables print("Here are the days: ", days) print("Here are the months ",months) #print multiple line with triple quotes print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 line if we want, or 5, or 6. """)
232d26a3ec5d0f9c80c58d9135d2b079e50d3a11
TechGirl254/Training101
/OperatorsBasic.py
219
3.765625
4
modulus =23334 % 8 print(modulus) # Arithmetic # comparison Operators result=2==3 print (result) # equality # inequality results=2!=3 print((results)) # logical operators # AND,OR,NOT res =2 < 3 and 10 <20 print(res)
19b0c4a7a8e248466766b6fdac9bf6977cd391f3
CarlTheUser/PythonPractices
/venv/AreaCalculationOperation.py
2,524
4.03125
4
from abc import ABCMeta, abstractmethod from Operation import Operation import math class AreaCalculationOperation(Operation): __metaclass__ = ABCMeta SQUARE = None RECTANGLE = None TRIANGLE = None CIRCLE = None def __init__(self, name): super().__init__(name) @abstractmethod def calculate_area(self): pass class SquareAreaCalculationOperation(AreaCalculationOperation): def __init__(self): super().__init__("Square Area Calculator") self._side = 0 def calculate_area(self): return self._side * self._side def operate(self): try: self._side = float(input("Enter the square's side length: ")) print("The area of the square is: {}".format(str(self.calculate_area()))) except ValueError: print("Invalid input") class RectangleAreaCalculationOperation(AreaCalculationOperation): def __init__(self): super().__init__("Rectangle Area Calculator") self._width = 0 self._height = 0 def calculate_area(self): return self._width * self._height def operate(self): try: self._width = float(input("Enter the rectangle's width: ")) self._height= float(input("Enter the rectangle's height: ")) print("The area of the rectangle is: {}".format(str(self.calculate_area()))) except ValueError: print("Invalid input") class TriangleAreaCalculationOperation(AreaCalculationOperation): def __init__(self): super().__init__("Triangle Area Calculator") self._base = 0 self._height = 0 def calculate_area(self): return (self._base * self._height) / 2 def operate(self): try: self._base = float(input("Enter the triangle's base length: ")) self._height= float(input("Enter the rectangle's height: ")) print("The area of the triangle is: {}".format(str(self.calculate_area()))) except ValueError: print("Invalid input") class CircleAreaCalculationOperation(AreaCalculationOperation): def __init__(self): super().__init__("Circle Area Calculator") self._radius = 0 def calculate_area(self): return math.pi * (self._radius * self._radius) def operate(self): try: self._radius = float(input("Enter the circle's radius: ")) print("The area of the circle is: {}".format(str(self.calculate_area()))) except ValueError: print("Invalid input") AreaCalculationOperation.SQUARE = SquareAreaCalculationOperation() AreaCalculationOperation.RECTANGLE = RectangleAreaCalculationOperation() AreaCalculationOperation.TRIANGLE = TriangleAreaCalculationOperation() AreaCalculationOperation.CIRCLE = CircleAreaCalculationOperation()
aa8cf5d668f79020c9dfb1124e239a4bf0b116f9
alexmovsesyan/othello
/othello_game_logic.py
15,273
3.96875
4
#othello_game_logic.py #Alexandra Movsesyan #42206297 Black = 1 White = 2 class InvalidMoveError(Exception): ''' Raised whenever an invalid move is made ''' pass class GameOverError(Exception): ''' Raised whenever an attempt is made to make a move after the game is already over ''' pass class Gamestate: def __init__(self,rows:int,columns:int,first_player:str,how_won:str,user_board:[str])->[[str]]: ''' Initializes a Gamestate and based on the user input stores: the board, amount of columns, amount of rows, how the game is won, and first player Also determines opposite player, and creates a winner ''' self._make_board(rows,columns,user_board) self._columns = columns self._rows = rows self._how_won = how_won turn = first_player if turn == 'black': self._turn = Black self._opposite_player = White elif turn == 'white': self._turn = White self._opposite_player = Black self._winner = None def verify_move(self,row:int,col:int)->([[str]],int): ''' Verifies if the moves is valid, then executes move Raises InvalidMoveError if the cell is already occupied, there are no valid mores, or the row or column number do not exist ''' try: if self._check_space_empty(row,col) == False: raise InvalidMoveError() else: self._get_valid_moves() if self._moves == []: raise InvalidMoveError() else: self._make_moves() self._determine_turn() return self._board,self._turn except IndexError: raise InvalidMoveError() def player_scores(self)->(int,int): ''' Based on the cells in the board, determines amount of Black and White cells and returns count ''' self._b_count = 0 self._w_count = 0 for row in self._board: for item in row: if item == 1: self._b_count +=1 elif item == 2: self._w_count +=1 return self._b_count,self._w_count def determine_winner(self)-> None: ''' Checks if there are any more valid moves avaiable If there are, there is not winner If there aren't any valid moves, determines winner based on how the user wanted the game to be won, using the amount of black and white cells ''' if self._determine_if_valid_moves_still_available() == False: b_count, w_count = self.player_scores() if b_count == w_count: winner = 0 elif self._how_won == '>': if b_count > w_count: winner = Black elif w_count > b_count: winner = White elif self._how_won == '<': if b_count > w_count: winner = White elif w_count > b_count: winner = Black else: winner = None self._winner = winner return winner def _make_board(self,rows:int,columns:int,user_board:[[str]])-> None: ''' Makes a board based on user input ''' board = [] for x in range(rows): board.append([]) c = 0 while c < rows: new_row = [] for item in user_board[c]: if item == 'black': new_row.append(Black) elif item == 'white': new_row.append(White) elif item == '.': new_row.append('.') board[c] = new_row c+=1 self._board= board def _find_valid_indexes(self)->[(int,int)]: ''' Searches through the board and findes every blank cell ''' indexes = [] i = 0 while i < self._rows: row = list(enumerate(self._board[i])) c = 0 while c < len(row): if row[c][1]== '.': index = (i,c) indexes.append(index) c+=1 i+=1 self._valid_indexes = indexes def _find_if_valid_moves(self,current_player:int,opposite_player:int)-> None: ''' Determines if any blank cell could be a valid move ''' valid_moves = False i = 0 while i <len(self._valid_indexes): self._row_number = self._valid_indexes[i][0] self._column_number = self._valid_indexes[i][1] self._get_valid_moves() if self._moves != []: valid_moves = True break elif self._moves == []: pass i+=1 return valid_moves def _determine_turn(self)->str: ''' Based on the valid indexes, swithces the current player and opposite player If the opposite player has no valid moves, turn reverts back to current player ''' self._find_valid_indexes() if self._turn == Black: self._turn = White self._opposite_player = Black white_valid_moves = self._find_if_valid_moves(self._turn,self._opposite_player) if white_valid_moves == False: self._turn = Black self._opposite_player = White elif self._turn == White: self._turn = Black self._opposite_player = White black_valid_moves = self._find_if_valid_moves(self._turn,self._opposite_player) if black_valid_moves == False: self._turn = White self._opposite_player = Black return self._turn def _determine_if_valid_moves_still_available(self)->bool: ''' Checks if there are any valid moves still available for both players ''' black_moves = self._find_if_valid_moves(Black,White) white_moves = self._find_if_valid_moves(White,Black) if white_moves == False and black_moves == False: return False def _check_space_empty(self,row:int,column:int)-> bool: ''' Given a cell location, determines if it is empty ''' self._row_number = row-1 self._column_number = column-1 if self._board[self._row_number][self._column_number]== '.': return True else: return False def _get_valid_moves(self)-> [str]: ''' Checks if there are any valid moves in horizontal, vertical, and diagonal direction Creates starting and ending indexes for the cells to flip in that certain valid move ''' valid_moves = [] if self._check_vertical()== True: valid_moves.append('v') self._start_index_v = self._starting_index self._end_index_v = self._ending_index if self._check_horizontal()== True: valid_moves.append('h') self._start_index_h = self._starting_index self._end_index_h = self._ending_index if self._check_diagonal_forward()== True: valid_moves.append('d1') self._start_index_d1 = self._starting_index self._end_index_d1 = self._ending_index if self._check_diagonal_backward()== True: valid_moves.append('d2') self._start_index_d2 = self._starting_index self._end_index_d2 = self._ending_index self._moves = valid_moves def _make_moves(self)-> None: ''' Executes all valid moves ''' if self._winner!= None: raise GamveOverError() for move in self._moves: if move == 'h': board = self._horizontal_move() elif move == 'v': board = self._vertical_move() elif move == 'd1': board = self._diagonal_forwards_move() elif move == 'd2': board = self._diagonal_backwards_move() def _check_if_valid(self)-> None: ''' With a given line(horizontal, vertical, or diagonal) checks if move is valid Immidately becomes invalid if the opposite player doesnt have a cell in that line Finds the instances of the current player in the line and determines the starting and ending indexes of which the cells should be flipped Move is invalid if the opposite player insn't in-between those indexes ''' if self._turn not in self._area_to_check: return False c =0 while c < len(self._area_to_check): if self._area_to_check[c] == self._turn: last_instance = c else: pass c+=1 i =0 while i < len(self._area_to_check): if self._area_to_check[i] == self._turn: first_instance = i break i+=1 if first_instance <self._new_index: trajectory = self._area_to_check[first_instance:(self._new_index+1)] if self._opposite_player in trajectory: self._starting_index = first_instance self._ending_index = self._new_index return True else: return False elif first_instance > self._new_index: trajectory = self._area_to_check[self._new_index:(last_instance+1)] if self._opposite_player in trajectory: self._starting_index = self._new_index self._ending_index = last_instance return True else: return False def _check_horizontal(self)->bool: ''' Finds a horizontal line based on desired cell placement Checks if a horizontal move is valid ''' horizontal = self._board[self._row_number] self._new_index = self._column_number self._area_to_check = horizontal response = self._check_if_valid() return response def _check_vertical(self)-> None: ''' Finds a vertical line based on desired cell placement Checks if a vertical move is valid ''' self._new_index = self._row_number vertical = [] row = 0 while row < len(self._board): vertical.append(self._board[row][self._column_number]) row+=1 self._area_to_check = vertical response = self._check_if_valid() return response def _check_diagonal_forward(self)-> None: ''' Finds a forwards diagonal line based on desired cell placement Checks if a forwards diagonal move is valid ''' self._new_index = self._row_number diagonal1 = self._get_diagonal_forward() self._area_to_check = diagonal1 response = self._check_if_valid() return response def _check_diagonal_backward(self)-> None: ''' Finds a backwards diagonal line based on desired cell placement Checks if a backwards diagonal move is valid ''' self._new_index = self._row_number diagonal2 = self._get_diagonal_backwards() self._area_to_check = diagonal2 response = self._check_if_valid() return response def _get_diagonal_forward(self)->[int,str]: ''' Generates a forwards diagonal line based on desired indexes ''' diagonal = [] row = self._row_number col = self._column_number while row >= 0 and col >= 0: diagonal.append(self._board[row][col]) row-=1 col-=1 diagonal.reverse() row = self._row_number col = self._column_number while row < self._rows-1 and col < self._columns-1: diagonal.append(self._board[row+1][col+1]) row+=1 col+=1 return diagonal def _get_diagonal_backwards(self)->[int,str]: ''' Generates a backwards diagonal line based on desired indexes ''' diagonal = [] row = self._row_number col = self._column_number while row >= 0 and col < self._columns: diagonal.append(self._board[row][col]) row-=1 col+=1 diagonal.reverse() row = self._row_number col = self._column_number while row < self._rows-1 and col >0: diagonal.append(self._board[row+1][col-1]) row+=1 col-=1 return diagonal def _horizontal_move(self)->[[int,str]]: ''' With a starting and ending index, flips all cells in a horizontal line to the current player ''' start = self._start_index_h while start <= self._end_index_h: self._board[self._row_number][start] = self._turn start+=1 return self._board def _vertical_move(self)->[[int,str]]: ''' With a starting and ending index, flips all cells in a vertical line to the current player ''' start = self._start_index_v while start <= self._end_index_v: self._board[start][self._column_number] = self._turn start+=1 return self._board def _diagonal_forwards_move(self)->[[int,str]]: ''' With a starting and ending index, flips all cells in a forwards diagonal line to the current player ''' start = self._start_index_d1 if start == self._row_number: row = start col = self._column_number while row <=self._end_index_d1: self._board[row][col] = self._turn row+=1 col+=1 elif start != self._row_number: row = self._end_index_d1 col =self._column_number while row >=self._start_index_d1: self._board[row][col] = self._turn row-=1 col-=1 return self._board def _diagonal_backwards_move(self)->[[int,str]]: ''' With a starting and ending index, flips all cells in a backwards diagonal line to the current player ''' start = self._start_index_d2 if start == self._row_number: row = start col = self._column_number while row <=self._end_index_d2: self._board[row][col] = self._turn row+=1 col-=1 elif start != self._row_number: row = self._end_index_d2 col =self._column_number while row >=self._start_index_d2 and col<= self._columns-1: self._board[row][col] = self._turn row-=1 col+=1 return self._board
814199dda7f71f5006db447ca1e310adcf7d7c56
timseymore/depths-of-madness
/src/models/enviroment/platform.py
4,762
3.9375
4
import pygame class Platform(pygame.sprite.Sprite): """Platform that floats or moves in the game.""" def __init__(self, x, y, x_speed, y_speed, min_x, max_x, min_y, max_y): """ Constructor Method - x: int : x position of platform - y: int : y position of platform - x_speed: int : speed at which platform moves left/right - y_speed: int : speed at which platform moves up/down - min_x: int : lower x bound - max_x: int : upper x bound - min_y: int : lower y bound - max_y: int : upper y bound """ super().__init__() self.image = pygame.image.load(r'src/graphics/platform.png') self.rect = pygame.rect.Rect((x, y), self.image.get_size()) self.walls = None self.x_speed = x_speed self.y_speed = y_speed self.min_x = min_x self.max_x = max_x self.min_y = min_y self.max_y = max_y def change_bounds(self, min_x, max_x, min_y, max_y): """ Change the upper and lower bounds on x and y - min_x: int : new limit for left directional movement - max_x: int : new limit for right directional movement - min_y: int : new limit for upward directional movement - max_y: int : new limit for downward directional movement """ self.min_x = min_x self.max_x = max_x self.min_y = min_y self.max_y = max_y def change_speed(self, x, y): """ Change the speed of the platform. - x: int : new left/right speed - y: int : new up/down speed """ self.x_speed = x self.y_speed = y def update(self, dt, gravity): """ Update the platform position. - dt: int : delta time - gravity: int : gravity constant """ self.handle_left_right() self.handle_up_down() def handle_left_right(self): """ Handle left and right movement and collisions """ self.move_left_right() self.check_left_right() def move_left_right(self): """ Move platform left and right """ self.rect.x = self.move(self.min_x, self.max_x, self.rect.x, self.x_speed) def check_left_right(self): """ Check for left and right collisions """ # Did this update cause us to hit a wall? block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) for block in block_hit_list: # If we are moving right, set our right side to the left side of block if self.x_speed > 0: self.rect.right = block.rect.left self.x_speed *= -1 else: # Otherwise if we are moving left, do the opposite. self.rect.left = block.rect.right self.x_speed *= -1 def handle_up_down(self): """ Handle the up and down movement of the platform """ self.move_up_down() self.check_up_down() def move_up_down(self): """ Move the platform up and down ignoring any objects """ if self.min_y <= self.rect.y <= self.max_y: self.rect.y += self.y_speed else: self.y_speed *= -1 self.rect.y += self.y_speed def check_up_down(self): """ Change platform direction and position if collision is detected NOTE: position should be reset to just outside of colliding object combined with change in direction, platform will be safe to move next tick """ # Did this update cause us to hit a wall? block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) for block in block_hit_list: # If we are moving down, set our bottom side to the top side of block if self.y_speed < 0: self.rect.bottom = block.rect.top self.y_speed *= -1 else: # Otherwise if we are moving up, do the opposite. self.rect.top = block.rect.bottom self.y_speed *= -1 @staticmethod def move(lower_bound, upper_bound, pos, velocity, vertical=False): """ move platform within given bounds - lower_bound: int : lower limit of movement - upper_bound: int : upper limit of movement - pos: (int, int) : current position - velocity: int : rate of change in position - vertical: bool : True if moving vertically, False by default Return: new position (int, int) """ if lower_bound <= pos <= upper_bound: pos += velocity else: velocity *= -1 if vertical: pos += velocity return pos
d45232f1c2aaaf31531ebcd09a544d410f8c0c00
Yanfreak/datastructurealgorithm
/Chapter7/link.py
18,013
4.0625
4
class Empty(Exception): pass class LinkedStack: """LIFO Stack implementation using a singly linked list for storage.""" # nested _Node class class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = '_element', '_next' # streamline memory usage def __init__(self, element, next): # initialize node's fields self._element = element self._next = next # stack methods def __init__(self): """Create an empty stack.""" self._head = None self._size = 0 def __len__(self): """Return the number of elements in the stack.""" return self._size def is_empty(self): """Return `True` if the stack is empty.""" return self._size == 0 def push(self, e): """Add element `e` to the top of the stack.""" self._head = self._Node(e, self._head) # create and link a new node self._size += 1 def top(self): """ Return (but do not remove) the element at the top of the stack. Raise `Empty` exception if the stack is empty. """ if self.is_empty(): raise Empty('Stack is empty') return self._head._element def pop(self): """ Remove and return the element from the top of the stack (i.e., LIFO). Raise `Empty` exception if the stack is empty. """ if self.is_empty(): raise Empty('Stack is empty') answer = self._head._element self._head = self._head._next self._size -= 1 return answer class LinkedQueue: """FIFO queue implementation using a singly linked list for storage.""" class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = '_element', '_next' # streamline memory usage def __init__(self, element, next): # initialize node's fields self._element = element self._next = next def __init__(self): """Create an empty queue.""" self._head = None self._tail = None self._size = None def __len__(self): return self._size def is_empty(self): return self._size == 0 def first(self): if self.is_empty(): raise Empty('Queue is empty') return self._head._element def dequeue(self): if self.is_empty(): raise Empty('Queue is empty') answer = self._head._next self._size -= 1 if self.is_empty(): self._tail = None return answer def enqueue(self, e): newest = self._Node(e, None) if self.is_empty(): self._head = newest else: self._tail._next = newest self._tail = newest self._size += 1 def rotate(self): if self._size > 0: old_head = self._head self._head = old_head._next self._tail._next = old_head old_head._next = None def concatenate(self, Q2: LinkedQueue): """Takes all elements of LinkedQueue Q2 and appends them to the end of the original queue. The operation should run in O(1) time and should result in Q2 being an empty queue.""" self._tail._next = Q2._head self._tail = Q2._tail Q2._head = None class CircularQueue: """Queue implementation using circularly linked list for storage.""" class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = '_element', '_next' # streamline memory usage def __init__(self, element, next): # initialize node's fields self._element = element self._next = next def __init__(self): """Create an empty queue.""" self._tail = None self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def first(self): if self.is_empty(): raise Empty('Queue is empty') head = self._tail._next return head._element def dequeue(self): if self.is_empty(): raise Empty('Queue is empty') oldhead = self._tail._next if self._size == 1: self._tail = None else: self._tail._next = oldhead._next self._size -= 1 return oldhead._element def enqueue(self, e): newest = self._Node(e, None) if self.is_empty(): newest._next = newest else: newest._next = self._tail._next self._tail = newest self._size += 1 def rotate(self): """Rotate front element to the back of the queue.""" if self._size > 0: self._tail = self._tail._next class _DoublyLinkedBase: """A base class providing a doubly linked list representation.""" class _Node: """Lightweight, nonpublic class for storing a doubly linked node.""" __slots__ = '_element', '_prev', '_next' # streamline memory def __init__(self, element, prev, next): # initialize node's fields self._element = element self._prev = prev self._next = next def __init__(self): """Create an empty list.""" self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def _insert_between(self, e, predecessor, successor): """Add element `e` between two existing nodes and return new node.""" newest = self._Node(e, predecessor, successor) predecessor._next = newest successor._prev = newest self._size += 1 return newest def _delete_node(self, node): """Delete nonsentinel node from the list and return its element.""" predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 element = node._element # wait, i think this is a shallow copy?? node._prev = node._next = node._element = None return element def reverse(self): """Reverse the order of the list, yet without creating or destroying any nodes.""" self._header, self._trailer = self._trailer, self._header self._header._prev, self._header._next = self._header._next, self._header._prev self._trailer._prev, self._trailer._next = self._trailer._prev, self._trailer._next if not self.is_empty(): cursor = self._header._next for _ in range(self._size): cursor._next, cursor._prev = cursor._prev, cursor._next cursor = cursor._next class LinkedDeque(_DoublyLinkedBase): """Double-ended queue implementation based on a doubly linked list.""" def first(self): if self.is_empty(): raise Empty('Deque is empty') return self._header._next._element def last(self): if self.is_empty(): raise Empty('Deuque is empty') return self._trailer._prev._element def insert_first(self, e): """Add an element to the front of the deque.""" self._insert_between(e, self._header, self._header._next) def insert_last(self, e): """Add an element to the back of the deque.""" self._insert_between(e, self._trailer._prev, self._trailer) def delete_first(self): if self.is_empty(): raise Empty('Deque is empty') return self._delete_node(self._header._next) def delete_last(self): if self.is_empty(): raise Empty('Deque is empty') return self._delete_node(self._trailer._prev) class PositionalList(_DoublyLinkedBase): """A sequential container of ellements allowing positional access.""" # nested Position class class Position: """An abstraction representing the location of a single element.""" def __init__(self, container, node): """Constructor should not be invoked by user.""" self._container = container self._node = node def element(self): """Return the element stored at this Position.""" return self._node._element def __eq__(self, other): """Return `True` if other is a Position representing the same location.""" return type(other) is type(self) and other._node is self._node def __ne__(self, other): """Return `True` if other does not represent the same location.""" return not (self == other) # utility method def _validate(self, p): """Return position's node, or raise appropriate error if invalid.""" if not isinstance(p, self.Position): raise TypeError('p must be proper Position type') if p._container is not self: raise ValueError('p does not belong to this container') if p._node._next is None: # convention for deprecated nodes raise ValueError('p is no longer valid') return p._node def _make_position(self, node): """Return Position instance for given node (or `None` if sentinel).""" if node is self._header or node is self._trailer: return None else: return self.Position(self, node) # accessors def first(self): """Return the first Position in the list (or `None` if list is empty).""" return self._make_position(self._header._next) def last(self): """Return the last Position in the list (or `None` if list is empty).""" return self._make_position(self._trailer._prev) def before(self, p): """Return the Position just before Position p (or None if p is first).""" node = self._validate(p) return self._make_position(node._prev) def after(self, p): """Return the Position just after Position p (or None if p is last).""" node = self._validate(p) return self._make_position(node._next) def __iter__(self): """Generate a forward iteration of the elements of the list.""" cursor = self.first() while cursor is not None: yield cursor.element() cursor = self.after(cursor) def __reversed__(self): """Generate a backward iteration of the elements of the list.""" cursor = self.last() while cursor is not None: yield cursor.element() cursor = self.before(cursor) # mutators # overide inherited version to return Position, rather than Node def _insert_between(self, e, predecessor, successor): """Add element between existing nodes and return new Position.""" node = super()._insert_between(e, predecessor, successor) return self._make_position(node) def add_first(self, e): """Insert element `e` at the front of the list and return new Position.""" return self._insert_between(e, self._header, self._header._next) def add_last(self, e): """Insert element `e` at the back of the list and return new Position.""" return self._insert_between(e, self._trailer._prev, self._trailer) def add_before(self, p, e): """Insert element `e` into list before Position p and return new Position.""" original = self._validate(p) return self._insert_between(e, original._prev, original) def add_after(self, p, e): """Insert element e into list after Position p and return new Position.""" original = self._validate(p) return self._insert_between(e, original, original._next) def delete(self, p): """Remove and return the element at Position p.""" original = self._validate(p) return self._delete_node(original) def replace(self, p, e): """Replace the element at Position p with e. Return the element formerly at Position p.""" original = self._validate(p) old_value = original._element original._element = e return old_value def max(self): """Return the maximum element from the instance.""" currentmax = self.first().element node_iter = self.__iter__() for n in node_iter: if n.element > currentmax: currentmax = n.element return currentmax def find(self, e): """returns the position of the (first occurrence of) element e in the list (or None if not found).""" p = self._header._next if p is None: return None elif p._element == e: return self._make_position(p) else: return self.find(e) #def swap(self, p: _Node, q: _Node): # sorting a positional list def insertion_sort(L): """Sort PositionalList of comparable elements into nondecreasing order.""" if len(L) > 1: marker = L.first() while marker != L.last(): pivot = L.after(marker) value = pivot.element() if value > marker.element(): marker = pivot else: walk = marker while walk != L.first() and L.before(walk).element() > value: walk = L.before(walk) L.delete(pivot) L.add_before(walk, value) class FavouritesList: """List of elements ordered from most frequently accessed to least.""" # nested _Item class class _Item: __slots__ = '_value', '_count' def __init__(self, e): self._value = e self._count = 0 # nonpublic utilities def _find_position(self, e): """Search for element e and return its Position (or None if not found).""" walk = self._data.first() while walk is not None and walk.element()._value != e: walk = self._data.after(walk) return walk def _move_up(self, p): """Move item at Position p earlier in the list based on access count.""" if p != self._data.first(): cnt = p.element()._count walk = self._data.before(p) if cnt > walk.element()._count: while (walk != self._data.first() and cnt > self._data.before(walk).element()._count): walk = self._data.before(walk) self._data.add_before(walk, self._data.delete(p)) # public methods def __init__(self): """Create an empty list of favourites.""" self._data = PositionalList() def __len__(self): """Return number of entries on favourites list.""" return len(self._data) def is_empty(self): return len(self._data) == 0 def access(self, e): """Access element e, thereby increasing its access count.""" p = self._find_position(e) # try to locate existing element if p is None: p = self._data.add_last(self._Item(e)) # if new, place at end p.element()._count += 1 # always increment count self._move_up(p) # consider moving forward def remove(self, e): """Remove element e from the list of favorites.""" p = self._find_position(e) if p is not None: self._data.delete(p) def top(self, k): """Generate sequence of top k elements in term of access count.""" if not 1 <= k <= len(self): raise ValueError('Illegal value for k') walk = self._data.first() for _ in range(k): item = walk.element() yield item._value walk = self._data.after(walk) def clear(self): """Returns the list to empty.""" walk = self._data.first() while walk is not None: walk = self._data.after(walk) self._data.delete(self._data.before(walk)) def reset_counts(self): """Rresets all elements’ access counts to zero (while leaving the order of the list unchanged).""" p = self._data.first() while p is not None: p.element()._count = 0 p = self._data.after(p) class FavouritesListMTF(FavouritesList): """List of elements ordered with move-to-front heuristic.""" # we override _move_up to provide move-to-front semantics def _move_up(self, p): """Move accessed item at Position `p` to front of list.""" if p != self._data.first(): self._data.add_first(self._data.delete(p)) # we override top because list is nno longer sorted def top(self, k): """Generate sequence of top `k` elements in terms of access count.""" if not 1<= k <= len(self): raise ValueError('Illegal value for k') # begin by making a copy of the original list temp = PositionalList() for item in self._data: temp.add_last(item) # repeatedly find, report, and remove element with largest count for _ in range(k): # find and report next highest from temp highPos = temp.first() walk = temp.after(highPos) while walk is not None: if walk.element()._count > highPos.element()._count: highPos = walk walk = temp.after(walk) # we have found the element with highest count yield highPos.element().old_value temp.delete(highPos)
3fb3173413fc7e48258a7e965e749704b5f34bf9
mgarchik/P2_SP20
/Labs/hangman.py
3,490
4.34375
4
""" Matthew Garchik Hangman February 2020 """ import random # Hangman game # PSEUDOCODE # setup your game by doing the following # make a word list for your game # grab a random word from your list and store it as a variable # in a loop, do the following # display the hangman using the gallows # display the used letters so the user knows what has been selected # display the length of the word to the user using blank spaces and used letters # prompt the user to guess a letter # don't allow the user to select the same letter twice # if the guess is incorrect increment incorrect_guesses by 1 # if the incorrect_guesses is greater than 8, tell the user they lost and exit the program # if the user gets all the correct letters, tell the user they won # ask if they want to play again gallows = [ ''' +---+ | | | | | | ========= ''', ''' +---+ | | O | | | | ========= ''', ''' +---+ | | O | | | | | ========= ''', ''' +---+ | | O | /| | | | ========= ''', ''' +---+ | | O | /|\ | | | ========= ''', ''' +---+ | | O | /|\ | / | | ========= ''', ''' +---+ | | O | /|\ | / \ | | ========= ''' ] my_word_list = ["delta", "earnings", "beta", "investment", "loss", "interest", "bonds", "yield", "dividend", "option" , "money", "funds", "savings", "retirement", "tax"] def play(): lives_lost = 0 my_word = my_word_list.pop(random.randrange(len(my_word_list))) print(my_word) my_list = [] for i in range(len(my_word)): my_list.append("_") abcs = [chr(x) for x in range(65, 65 + 26)] used_abcs = [] while lives_lost < 6: for i in my_list: print(i, end=" ") print() guess = input("Guess Letter") while guess.upper() in used_abcs: guess = input("You have used that letter, guess again") while guess.upper() not in abcs: guess = input("That is not a letter, guess again") used_abcs.append(guess.upper()) print("Guessed Letters:") for letter in used_abcs: print(letter, end=" ") guess = guess.lower() if str(guess) in my_word: for i in range(len(my_word)): if my_word[i] == guess: my_list[i] = guess.lower() else: lives_lost += 1 print("") for i in my_list: print(i, end=" ") print(gallows[-(lives_lost + 1)]) if "_" not in my_list: print("You Win!") new_input = input("Press any letter to restart, or hit space to exit") if new_input.upper() in abcs: play() print(my_word) elif new_input == " ": quit() if lives_lost >= 6: print("You Lose!") new_input = input("Press any letter to restart, or hit space to exit") if new_input.upper() in abcs: play() print(my_word) elif new_input == " ": quit() print("Welcome to Matthew Garchik's finance hangman!") play()
3a22e30eeef061f243ed350b149b318153731ea6
akash30g/Shoping-list
/AkashGuptaA1.py
16,880
4.15625
4
""" Made by: Akash Gupta. Date: 8nd September 2016 Detail: This program has two list to store the data which is type of dictionary. When program begin, it will load the data from items.csv into shopItem. Then, user can choose display or add or mark those items which have been loaded in the readList_required. Moreover, use could mark the item, then, after user do this step, the program will put the item that use choose into listCompleted, and remove the item from shopItem. When user choose quit, the program will upload the date from completedList into output.csv Github link: https://github.com/akash30g/AkashGuptaA1 """ from operator import itemgetter # importing dictionarry operator to sort items def main(): # main function of the program shopping list """ pseudocode: def main(): declare shopItem as an list declare listCompleted as a list display Shopping List 1.0 - by Akash Gupta call getUserName() open items.csv file for each_line in file Item = name of item + $ price of price + priority of item shopItem.append(Item) close file while True: Choice = call Menu() if Choice = 'r' or Choice = 'R' shopItem = call readList_required(shopItem) elif Choice = 'c' or Choice = 'C' listCompleted= call readList_completed(listCompleted) elif Choice = 'a' or Choice = 'A' call writelist(shopItem) elif Choice = 'm' or Choice = 'M' deleteitem = markProduct(shopItem) shopItem.remove(deleteitem) listCompleted.append(deleteitem) elif Choice = 'q' or Choice = 'Q' display Thanks for shopping \nHave a nice day!! :) break else: display Invalid menu choice. Please try again. addcsvList(listCompleted) """ print("Shopping List 1.0 - by Akash Gupta") shopItem = [] # declaring the list variable for displaying rquired list listCompleted = [] # declaring the list variable for displaying rquired list getUserName() # calling function to get user name file = open("items.csv", "r") # opening the csv file for each_line in file: # starting 'for' loop to get items from file into list datum = each_line.split(",") # splitting the data to store by comas Item = {"Name": datum[0], "Price": float(datum[1]), 'Priority': int(datum[2]), "Type": datum[3]} # declaring the type data to stored shopItem.append(Item) # adding item to the main displaying list file.close() # closing the file while True: # while loop to keep displaying the menu Choice = Menu() # calling the menu function and asking for users choice if Choice == 'r' or Choice == 'R': # if else statements, based on customers choice, shopItem=readList_required(shopItem) # calling function to read list required as desired by the the user elif Choice == 'c' or Choice == 'C': listCompleted=readList_completed(listCompleted) # calling function to read list completed as desired by the the user elif Choice == 'a' or Choice == 'A': writelist(shopItem) # calling function to add items in the list as desired by the the user elif Choice == 'm' or Choice == 'M': deleteitem = markProduct(shopItem) # calling function to mark item complete as desired by the the user shopItem.remove(deleteitem) # to delete item from required list listCompleted.append(deleteitem) # add completed item to completed list elif Choice == 'q' or Choice == 'Q': # asking customer choice to quit the program print("Thanks for shopping \nHave a nice day!! :)") # printing fair well message break # beaking the loop else: # else statement to start loop again if choice is invalid print("Invalid menu choice. Please try again.") # printing the error addcsvList(listCompleted) def getUserName(): # declaring function to ask user name user_name = input("Please enter your name:") # asking user for hi/her name while user_name == '' or len(user_name) > 15: #validaion of the user input print("Your name cannot be blank and must be <= 15 characters") # error message user_name = input("Please enter your name:") # asking the user name again print("Hi {} Let's go for shopping!!!".format(user_name)) # printing user name and greeting to user def Menu(): # defining the function that displays the menu of choices user can make to run the software. menuChoice = input("Menu: \n\ R - List required items. \n\ C - List completed items. \n\ A - Add new item. \n\ M - Mark an item as completed.\n\ Q - Quit. \n\ >>>") # displaying menu and asking user for his choice return menuChoice # returning the choice def readList_required(ItemList): # defining the function to read the list required """ pseudocode: def readList_required(ItemList): declare count as an integer declare output_info as a String declare totalPrice as an integer if len(ItemList) == 0: display "No required items" else: ItemList = sorted completedList, key = item's priority for eachItem in ItemList output_info = info + "order. name of item $ price of price (priority of item)" count = count + 1 totalPrice = totalPrice + item's price display info + totalPrice """ if len(ItemList)== 0: # checking if there is items on the list or not print("No required Items") print("{} items loaded from items.csv".format(len(ItemList))) else: # if there there are items in the list count = 0 # declaring integer variable to display output in numbering format output_info = "Required items:\n" # declaring string variable and will be used to display output totalPrice = 0 # declaring integer variable to show total price of the list ItemList = sorted(ItemList, key=itemgetter('Priority')) # sorting list based on priority for every_product in ItemList: # loop for every item in list output_info += "{0:}. {1:22}$ {2:.2f} ({3})\n".format(count, every_product["Name"], every_product["Price"], every_product["Priority"]) # formatting how to diaplay the output count =count+1 # increment in count for numbering totalPrice += every_product["Price"] # calculating total price of the list print("{} items loaded from items.csv".format(len(ItemList))) # displaying total number of items in list print(output_info + "Total expected price for {} items: $ {}".format(count, totalPrice)) # displayinf the formatted output return ItemList # returning the list def writelist(shopItem): # defining function to add items to the list """ pseudocode: writelist(shopItem): declare checkProductPrice as a boolean declare checkProductPriority as a boolean display Please enter the product name: ask product name while product_name == '' or len(product_name) > 15: display Please enter the product name: ask product name while checkProductPrice is true: ask product price in float format continue until invalid price while checkProductPriority is true: ask product priority in integer format continue until invalid priority added item = name of item + $ price of price + priority of item shopItem.append(added_item) return shopItem """ checkProductPrice= True # declaring boolean variable to check and end error cheching while loop for price checkProductPriority = True # declaring boolean variable to check and end error checking while loop for priority product_name = input("Please enter the product name:").capitalize() # asking the name of product and capitalizing tbe first letter while product_name == '' or len(product_name) > 15: # checking validity of product name. print("the item name cannot be blank and must be < 15 characters") product_name = input("Please enter the product name:").capitalize() while checkProductPrice: # loop for asking user for product price and error checking try: product_price = float(input("Price: $")) # asking the user a float value price. if product_price < 0: # price cannot be less than 0 print("Price must be >= 0") else: checkProductPrice = False # valid iput will get out of the loop except ValueError: print("Invalid input; Please, enter a valid number") # print error for any invalid value while checkProductPriority: # loop for asking user for product priority and error checking try: product_priority = int(input("Priority:")) # asking the user an int value priority. if product_priority < 0 or product_priority > 3: # priority can only be 1,2 or 3 print("Priority must be 1, 2 or 3") else: checkProductPriority = False except ValueError: print("Invalid input; Please, enter a valid number") added_item= {"Name": product_name, "Price": product_price, "Priority": product_priority} # added iten in dictionary shopItem.append(added_item) # adding item to main list return shopItem #return the updated required list def markProduct(shopItem): # defing function to mAerk item as completed """ pseudocode: def markItem(shopItem): declare checkflag as a boolean if len(shopItem) == 0: display "No required items" else: markedList = call readlist_ rquired(shopItem) while the checkflag is True: try: get chooseItem from the user if chooseItem < 0 Or chooseItem > length of markedList - 1: display "Invalid item number" else: item_marked = markedList[chooseItem] display " XX marked as completed" set checkflag is False except value error: display "Invalid input; enter a valid number" return item_marked """ checkflag = True # declaring boolean variable to if len(shopItem) == 0: # checking if there is items on the list or not print("No items in the list") else: # if there are items in list markedList = readList_required(shopItem) # calling function to read the list and stroring its return value while checkflag: # loop top error check thr input value try: chooseItem = int(input("Enter the number of the item to mark as completed\n>>>")) # ask the user for the item number to be deleted if chooseItem < 0 or chooseItem > len(shopItem) - 1: # input should be either equal total items or greater than zero print("Invalid item number", end="\n\n") else: item_marked = markedList[chooseItem] # storing the marked item print("{} marked as completed".format(item_marked["Name"])) # displaying the marked item checkflag = False # exiting the loop except ValueError: print("Invalid input; enter a valid number", end="\n\n") # error message for invalid value return item_marked def readList_completed(completedList): # defing funtion to read completed list """ pseudocode: def showCompletedItems(completedList): declare count as an integer declare display as a String declare totalPrice as an integer if len(completedList) == 0: display "No completed items" else: completedList = sorted completedList, key = item's priority for eachItem in completedList display = info + "order. name of item $ price of price (priority of item)" count = count + 1 totalPrice = totalPrice + item's price display info + totalPrice """ count = 0 # declaring integer variable to display output in numbering format display = "Completed items:\n" # decalring string variable and will be used to display output totalPrice = 0 # declaring integer variable to show total price of the list if len(completedList) == 0: # if statement to check whether there is item in list or not print("No completed items") else: completedList = sorted(completedList, key=itemgetter('Priority')) # sorting list based on priority for eachItem in completedList: display += "{0:}. {1:18}$ {2:.2f} ({3})\n".format(count, eachItem["Name"], eachItem["Price"], eachItem["Priority"]) count = count+1 totalPrice += eachItem["Price"] # calculating total price of thr list print(display + "Total expected price for {} items: $ {}".format(count, totalPrice)) # printing the required output def addcsvList(listCompleted): # defing function to write list in csv file file_writer = open("output.csv", "w") # opening the file to write output in csv file for each in listCompleted: # for loop started to write in rows file_writer.write("{},{},{},c\n".format(each["Name"], each["Price"], each["Priority"])) # giving the format how to write the list file_writer.close() # closing the file # calling function to add items to the csv list main() # calls the main function # sorry for this late submission, but my program was not working and i was extemely uncomfortable submitting incomplete program. # i knew my marks will be deducted but i could not submit an incomplete file.
9e560d2c12a0c2efed6461224af0c7adb7145c39
AllenLiuX/My-LeetCode
/leetcode-python/数独.py
2,585
3.625
4
# -*- coding: utf-8 -*- import datetime class solution(object): def __init__(self,board): self.b = board self.t = 0 def check(self,x,y,value): #检查每行每列及每宫是否有相同项 for row_item in self.b[x]: if row_item == value: return False for row_all in self.b: if row_all[y] == value: return False row,col=int(x/3)*3,int(y/3)*3 row3col3=self.b[row][col:col+3]+self.b[row+1][col:col+3]+self.b[row+2][col:col+3] for row3col3_item in row3col3: if row3col3_item == value: return False return True def get_next(self,x,y):#得到下一个未填项 for next_soulu in range(y+1,9): if self.b[x][next_soulu] == 0: return x,next_soulu for row_n in range(x+1,9): for col_n in range(0,9): if self.b[row_n][col_n] == 0: return row_n,col_n return -1,-1 #若无下一个未填项,返回-1 def try_it(self,x,y):#主循环 if self.b[x][y] == 0: for i in range(1,10):#从1到9尝试 self.t+=1 if self.check(x,y,i):#符合 行列宫均无条件 的 self.b[x][y]=i #将符合条件的填入0格 next_x,next_y=self.get_next(x,y)#得到下一个0格 if next_x == -1: #如果无下一个0格 return True #返回True else: #如果有下一个0格,递归判断下一个0格直到填满数独 end=self.try_it(next_x,next_y) if not end: #在递归过程中存在不符合条件的,即 使try_it函数返回None的项 self.b[x][y] = 0 #回朔到上一层继续 else: return True def start(self): begin = datetime.datetime.now() if self.b[0][0] == 0: self.try_it(0,0) else: x,y=self.get_next(0,0) self.try_it(x,y) for i in self.b: print(i) end = datetime.datetime.now() print('\ncost time:', end - begin) print('times:',self.t) return s=solution([[0,0,1,0,0,0,2,3,6], [6,0,0,8,2,0,0,0,0], [4,0,0,0,6,0,8,5,0], [0,0,0,0,0,2,0,8,4], [3,0,0,4,0,6,0,0,2], [9,4,0,5,0,0,0,0,0], [0,9,5,0,8,0,0,0,3], [0,0,0,0,3,4,0,0,5], [7,3,4,0,0,0,9,0,0]]) s.start()
3227d51141d6674ffa184f79b9818c5621d6d69c
rodolfoghi/urionlinejudge
/python/1255.py
585
3.84375
4
testes = int(input()) for teste in range(testes): palavra = input().lower() caracteres = {} for c in palavra: if c.isalpha() and c not in caracteres: caracteres[c] = palavra.count(c) # Ordenar o dicionário em ordem #decrescente de valor e crescente de chave caracteres_ordenados = sorted(caracteres.items(), key=lambda x: (-x[1],x[0])) maior = caracteres_ordenados[0][1] resultado = '' for c in caracteres_ordenados: if c[1] == maior: resultado += c[0] else: break print(resultado)
67a6cdba83e0f0b0ddd1a6fda7997673702d8f28
Timidger/Scripts
/Math/Real Zeros.py
1,065
3.6875
4
def RealZeros(equation): numerator,denominator, answer = [],[],[] firstcoe,lastcoe = equation[0],int(equation[-1]) for i in range(1,lastcoe/2 + 1): if lastcoe % i == 0: numerator.append(i) numerator.append(lastcoe) if firstcoe.isdigit() is False: denominator = [1, -1] else: firstcoe = int(firstcoe) for i in range(1,firstcoe +1): if firstcoe % i == 0: denominator.append(i) denominator.append(-i) options = Join(numerator, denominator) print 'The options are {}'.format(options) print for x in options: if eval(equation) == 0: answer.append(x) return answer def Join(list1,list2): list3 = [] for i in list1: for z in list2: list3.append(float(i)/float(z)) for item in list3: if list3.count(item) > 1: list3.remove(item) return list3 while True: question = raw_input('Enter Equation ') print RealZeros(question)
fb0b7cdd94d592620f372ecd6d28c372d6f307f3
limmihir-test/analytics
/test2.py
988
4.03125
4
# The below code has some issue and will throw errors. Plese fix them so that the output is as follows: # value error # invalid literal for int() with base 10: 'a' # My name is Brandon Walsh # That's totally the present! import sys def error_1(): e = None try: x= int('a') except ValueError as e: print('value error') print(e) class Person: def __initalize__(self, first_name, last_name): self.first = first_name self.last = lname def speak(self): print("My name is + " self.fname + " " + self.last) me = Person("Brandon", "Walsh") you = Person("Ethan", "Reed") year == int.input("Greetings! What is your year of origin? ')) def where_are_we(): year = 2020 if year < 2019 print ('Woah, that's the past!') elif year >= 2019 && year < 2021: print ("That's totally the present!") elif: print ("Far out, that's the future!!") error_1() me.speak() you.self.speak where_are_we()
e3ba40d190a2d59a51c455ef0f0ca03f1af07a78
chrisvanndy/holbertonschool-higher_level_programming
/0x0B-python-input_output/11-student.py
2,017
4.03125
4
#!/usr/bin/python3 """Modue creates method class_to_json() which returns the\ dictionary description as simple data structure for JSON\ serialization of an object.""" class Student: """class Student declared with publid instance attr\ first_name, last_name, and age""" def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """ to_json returns the class __dict__. First we check\ to see if "attrs" is a list. Then we loop throug the list\ and confirm that Student hasattr in index of attrs. After\ we confirm a match, we can getattr from self if it was given\ to us via attrs. return the new dict""" # check if attrs is a list passed to our function if isinstance(attrs, list): # create an empty dictionary which will be returned attr_dict = {} # loop through attrs for atribs in attrs: # confirm self has attrs[atribs] if hasattr(self, atribs): # getattr from self if it exists attr_dict[atribs] = getattr(self, atribs) return attr_dict return self.__dict__ def reload_from_json(self, json): """ reload_from will replace all attributes of the Student instance\ example says "json" will always be a dictionary - with key and value,\ so we can use json.items() to loop through the dict passed in, confrim\ that that item[0] for items is present attr in Stuendt and\ then set the attr to the key, value present for each item""" # loop through 'each' of json dicts .items() for each in json.items(): # confirm 'each' key is attr of Student class if hasattr(self, each[0]): # set attributes of 'each' key and value to Student class setattr(self, each[0], each[1])
b34ce665798b7bcc23f0d8668d41a2e95bd0d266
CodeEMP/DCpython
/week1/sat/caesarcipher.py
435
3.75
4
l2i = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26))) i2l = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ")) key = 13 text = input("What to Cipher? ") cipher = "" for c in text.upper(): if c.isalpha(): cipher += i2l[(l2i[c] + key)%26] else: cipher += c text2 = "" for c in cipher: if c.isalpha(): text2 += i2l[(l2i[c] - key)%26] else: text2 += c print(text) print(cipher) print(text2)
07562dea45508d73752f8b1f0ca50718d2fd9a47
sudocoder98/BE-Coursework-and-Practicals
/Current_Semester/DWM/knn.py
1,154
3.71875
4
# K-Nearest Neighbours for 2D Data in Python # Define Math function def sq(n): return n**2 def sqrt(n): return n**0.5 # Accept Data classifiers = [[x,0] for x in input("Enter the list of classifiers separated by spaces: ").split()] historic_data = [tuple([y for y in x.strip().split()]) for x in input("Enter the data points and their classification: ").split(',')] test = tuple(int(x) for x in input("Enter the test coordinates: ").split()) k = int(input("Enter the size of the cluster: ")) # Caluculate distance between test point and historic data points distance = [ ] for data in historic_data: distance.append(sqrt(sq(int(data[0])-test[0])+sq(int(data[1])-test[1]))) # Select k points with minimum distances into cluster cluster = [ ] for i in range(k): cluster.append(historic_data[distance.index(min(distance))]) distance[distance.index(min(distance))]=9999 # Find the maximum occuring classifier in the cluster max = [ "", 0 ] for data in cluster: for classifier in classifiers: if data[2] == classifier[0]: classifier[1] = int(classifier[1]) + 1 if classifier[1]>max[1]: max = classifier print("Classification: ",max[0])
4515d630a46e45e5829cf1341867715ff990de62
nkukarl/notes
/py_partial.py
428
3.796875
4
from functools import partial def foo(a, b, c): print a, b, c # create partial function, let b=1 and c=2 p_foo = partial(foo, b=1, c=2) # for p_foo, only provide one argument, 3 is assigned to a p_foo(3) # provide two arguments, explicitly mention b=4 to overwrite b=1 # in the definition of p_foo p_foo(3, b=4) # similar as above p_foo(3, c=5) # TypeError: foo() got multiple values for keyword argument 'b' p_foo(3, 2)
8f7f61c55b579f6319e5f933531156518db36a7c
EmanuelYano/python3
/URI - Lista 2/1040.py
608
3.71875
4
#!/usr/bin/env python3 #-*- coding: utf-8 -*- n1, n2, n3, n4 = input().split() n1, n2, n3, n4 = float(n1),float(n2),float(n3),float(n4) m = (n1 * 2 + n2 * 3 + n3 * 4 + n4 * 1) / 10 if m < 5.0: print("Media: %.1f"%m) print("Aluno reprovado.") elif m > 7.0: print("Media: %.1f"%m) print("Aluno aprovado.") else: ne = float(input()) print("Media: %.1f"%m) print("Aluno em exame.") print("Nota do exame: %.1f"%ne) m2 = (ne + m) /2 if m2 > 5.0: print("Aluno aprovado.") else: print("Aluno reprovado.") print("Media final: %.1f"%m2) exit(0)
312c010bc1e11e1fb3f38481ec41265859380568
MHKNKURT/python_temelleri
/6-Pythonda Döngüler/while-demo.py
1,262
4
4
# sayilar = [1,3,5,7,9,12,19,21] #1saylar listesini while ile yazdırın. # i = 0 # while (i < len(sayilar)): # print(sayilar[i]) # i += 1 #2 Başlangıç ve bitiş değerlerini kullanıcıdan alıp, aradaki tüm tek sayıları yazdırın. # baslangic = int(input("Başlangıç: ")) # bitis = int(input("Bitiş: ")) # i = baslangic # while i < bitis: # i+=1 # if i%2 == 1: # print(i) #3 1-100 arasındaki sayıları azalan şekilde yazdırın. # i = 100 # while i>=1: # print(i) # i -= 1 # print("Bitti..") #4 Kullanıcıdan alacağınız 5 sayıyı ekranda sıralı bir şekilde yazdırın. # Benim yaptğım for döngüsüyle # list = [int(input("Sayı1: ")),int(input("sayı2: ")),int(input("sayı3: ")),int(input("sayı4: ")),int(input("sayı5: "))] # for x in list: # list.sort() # print(list) #while döngüsüyle # numbers = [] # i = 0 # while i<5: # sayi = int(input("Sayı: ")) # numbers.append(sayi) # i+=1 # numbers.sort() # print(numbers) #5 urunler = [] adet = int(input("Kaç ürün listelensin? :")) i = 0 while i < adet: name = input("Ürün ismi: ") price = input("Ürün fiyatı: ") urunler.append ({ "name": name, "price": price}) i+= 1 for urun in urunler: print(urun)
0237eb989651118a7f95c382d312880b67335af7
subhasmitasahoo/leetcode-algorithm-solutions
/number-of-corner-rectangles.py
807
3.5
4
# Problem link: https://leetcode.com/problems/number-of-corner-rectangles/ # Time complexity: O(R*C*C) # Space complexity: O(C*C) class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: store = {} rlen = len(grid) clen = len(grid[0]) res = 0 for i in range(rlen): for j in range(clen): if grid[i][j] == 1: for k in range(j+1, clen): if grid[i][k] == 1: index = j*200 + k cnt = 0 if index in store: cnt = store[index] res += cnt store[index] = cnt+1 return res
09b6c952844ecbb1dc5b9c298be6c6ad20a52d83
evtodorov/aerospace
/SciComputing with Python/ISA/Calc-ISA.py
2,677
3.796875
4
import math #data p0 = 101325.0 #Pa T0 = 288.15 #K rho0 = 1.225 #kg/m3 hTrop = 11000. #m hStrat = 20000. #m aTrop = -0.0065 #K/m g0=9.80665 #m/s^2 R = 287. TStrat = T0 + aTrop*hTrop pStrat = (TStrat/T0)**(-g0/aTrop/R)*p0 rhoStrat = (TStrat/T0)**(-g0/aTrop/R-1)*rho0 print "*** ISA Calculations ***" #menu menu0 = int() while(menu0<=0 or menu0>=3): menu0 = int(input("What do you want to do? \n \ 1) Calculate pressure and density at altitude \n \ 2) Calculate altitude from pressure \n")) # 01 pressure and density if (menu0==1): print "Calculating pressure and density" menu1 = int() while(menu1<=0 or menu1>=3): menu1 = input("Choose units for the input \n \ 1) Enter an altitude in meters \n \ 2) Enter an altitude in feet \n") if (menu1==1): h = input("Altitude in meters: ") elif (menu1==2): h = input("Altitude in feet: ")*0.3048 else: print "Something is wrong" #troposhpere if(h<=hTrop): #temperature T = T0 + aTrop*h #pressure and density p = (T/T0)**(-g0/aTrop/R)*p0 rho = (T/T0)**(-g0/aTrop/R-1)*rho0 #stratoshpere elif(hTrop<h<=hStrat): #temperature T = TStrat #pressure and density calculation p = math.exp(-g0/R/T*(h-hTrop))*pStrat rho = math.exp(-g0/R/T*(h-hTrop))*rhoStrat else: print "Can't calculate that" #print results print "T = ",T,"K" print "p = ",p,"Pa" print "rho = ",rho,"kg/m3" # 02 altitude elif (menu0==2): print "Calculating altitude (less than 20km)" #input p = input("Enter pressure in Pa: ") #calculate temperature T = T0*(p/p0)**(-aTrop*R/g0) #stratosphere if(T<216.65): T = 216.65 h = math.log(p/pStrat)*(-R*T/g0)+hTrop #troposhpere else: h = (T-T0)/aTrop #check validity if(h>=20000): print "Can't calculate that" #print results menu2 = input("Do you want the altitude in \n 1) meters \n 2) feet \n 3) FL \n") if(menu2==1): print "h = ",h,"m" if(menu2==2): print "h = ", h/0.3048,"ft" if(menu2==3): hFL = h/0.3048/100 if(hFL<10): print "h = FL00"+str(int(hFL)) elif(hFL<100): print "h = FL0"+str(int(hFL)) else: print "h = FL"+str(int(hFL)) #hold dummy = raw_input("Press enter")
5cf9bbed603334d9bcd576b87cec30a2ab411389
ebbitten/Courses
/6.00.1/Quiz/InterDiff.py
948
4.09375
4
def dict_interdiff(d1, d2): ''' d1, d2: dicts whose keys and values are integers Returns a tuple of dictionaries according to the instructions above ''' # Your code here #Initialize any parameters that you'll populate sharedKeys=[] d1Only=[] d2Only=[] interS={} diffS={} # Lets find all the keys for key in d1: if key in d2.keys(): sharedKeys.append(key) else: d1Only.append(key) for key in d2: if key not in sharedKeys: d2Only.append(key) #print(sharedKeys,d1Only,d2Only,type(interS)) for key in sharedKeys: interS[key]=f(d1[key],d2[key]) for key in d1Only: diffS[key]=d1[key] for key in d2Only: diffS[key]=d2[key] returnVal=(interS,diffS) return returnVal def f(a,b): return a+b d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} print(dict_interdiff(d1,d2))
e9ec487b00e82eafe54a87fcac8b0f3332830dd8
Qondor/Python-Daily-Challenge
/Daily Challenges/Daily Challenge #9 - What's Your Number/number.py
469
4.15625
4
def phone_formatter(number: int): """Phone formatter function. Format any 10 digit phone number to USA standard. """ if type(number) != int: return None number = str(number) if len(number) != 10: print("Only 10 numbers, please.") return None return f'({number[0:3]}) {number[3:6]}-{number[6:]}' if __name__ == "__main__": number = int(input("What's Your Number? ")) print(phone_formatter(number))
41575f6dc9c6de4e8e950f82a8fd3d3b83f5ec57
EvelynBortoli/Python
/06-Bucles/EjemploTablasMultiplicar.py
481
3.921875
4
####### Ejemplo tablas de multiplicar print("\n ############ Ejemplo ##############") numeroUsuario = input("\nIngresar el número sobre el cual quieres saber la tabla de multiplicar: ") numeroUsuario = int(numeroUsuario) if numeroUsuario < 1: numeroUsuario = 1 print(f"\n\n######## Tabla de Multiplicar del {numeroUsuario} ##############") cont = 0 for cont in range(0, 11): print(f"{cont} x {numeroUsuario} = {cont*numeroUsuario}") print("\n\t A estudiar!")
4a96dd58db0c5866f39f5774458ff8fa686f0031
Eitherling/Python_homework1
/homework4.11.py
330
3.953125
4
pizzas = ['pizzahut', 'burgerking', 'mcdonald'] for pizza in pizzas: print(pizza.title()) print('*'*80) friendPizzas = pizzas[:] print("My favorite pizzas are:") for pizza in pizzas: print(pizza.title()) print("My friend's favorite pizzas are:") for pizza in friendPizzas: print(pizza.title()) print(pizza)
09688c50bc90cb7eb21575e963427a3983229e42
rongfeng-china/CTCI_6th_python
/17-17.py
1,102
4
4
class Trie: def __init__(self,words): self.root = {} self.end = '*' for word in words: self.add(word) def add(self,word): node = self.root for letter in word: if letter not in node: node[letter] = {} node = node[letter] node[self.end] = self.end def contrainWord(self,word): node = self.root for letter in word: if letter not in node: return False node = node[letter] if self.end in node: return True return False def multiSearch(T,b): trie = Trie(T) result = [] #print trie.contrainWord('ppi') for i in range(len(b)): for j in range(i+1,len(b)+1): word = b[i:j] if trie.contrainWord(word): if word not in result: result.append(word) else: break return result T = ['is', 'ppi', 'hi', 'sis', 'i', 'ssippi'] b = 'mississippi' result = multiSearch(T, b) print result
040738fb2f5efbaa510b3f8445e49d5bd31fd6e4
gottaegbert/penter
/library/lib_study/187_language_pickletools.py
458
3.5625
4
# 此模块包含与 pickle 模块内部细节有关的多个常量,一些关于具体实现的详细注释,以及一些能够分析封存数据的有用函数。 # 此模块的内容对需要操作 pickle 的 Python 核心开发者来说很有用处; # https://docs.python.org/zh-cn/3/library/pickletools.html import pickle import pickletools class Foo: attr = 'A class attribute' picklestring = pickle.dumps(Foo) pickletools.dis(picklestring)