blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
59e950ee6a31216fd2a7f84b73f043e659909652
menard-noe/LeetCode
/Repeated Substring Pattern.py
419
3.671875
4
import math class Solution: def repeatedSubstringPattern(self, str): """ :type str: str :rtype: bool """ if not str: return False ss = (str + str)[1:-1] return ss.find(str) != -1 if __name__ == "__main__": # execute only if run as a script Input = "abab" solution = Solution() print(solution.repeatedSubstringPattern(Input))
cf8a9997126ab7b838ed83fcc708bb9c209b8fc7
JackSSS/sea-c34-python
/students/JonathanStallings/session02/string.py
957
4.09375
4
from __future__ import print_function import sys import traceback def highest_ordinal(): """Which letter has the highest ordinal value?""" string = u"The quick brown fox leaped!" msg = u"The max was {maxOrd} and its value was {maxValue}." \ .format(maxOrd=max(string), maxValue=ord(max(string))) print(msg) # highest_ordinal() # result: The max was x and its value was 120. def lowercase_number(): """What happens when you try to lowercase a number?""" num = 16 try: print(num.lower()) except: print(u"Use of lowercase method on number raises exception.") traceback.print_exc(file=sys.stdout) # lowercase_number() # result: Using a lowercase (string) method on number throws an AttributeError. def input_type(): """Does raw_input always return a string?""" user_input = raw_input() print(type(user_input)) # input_type() # result: Yes. raw_input always returns a string.
ad28c59f909a70f93635a73db6fade1677b6b89b
cenkayberkin/interviewBits4
/mergeKSorted.py
1,473
3.625
4
import heapq class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): heads = [] resultHead = None resultTail = None def __init__(self): self.heads = [] def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ for i in lists: if i != None: heapq.heappush(self.heads,(i.val,i)) while len(self.heads) != 0: newNode = heapq.heappop(self.heads) if self.resultHead == None: self.resultHead = newNode[1] self.resultTail = newNode[1] else: self.resultTail.next = newNode[1] self.resultTail = newNode[1] if newNode[1].next != None: t = newNode[1].next heapq.heappush(self.heads,(t.val,t)) return self.resultHead h11 = ListNode(15) h12 = ListNode(22) h13 = ListNode(35) h21 = ListNode(1) h22 = ListNode(6) h23 = ListNode(12) h24 = ListNode(40) h25 = ListNode(46) h31 = ListNode(3) h32 = ListNode(8) h33 = ListNode(16) h34 = ListNode(33) h11.next = h12 h12.next = h13 h21.next = h22 h22.next = h23 h23.next = h24 h24.next = h25 h31.next = h32 h32.next = h33 h33.next = h34 heads = [h11,h21,h31] s = Solution() finalHead = s.mergeKLists(heads) tmp = finalHead while tmp is not None: print tmp.val tmp = tmp.next
8c871a1239df1f714cdd5bfeb5b203b012b376d5
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/1827.py
1,507
3.546875
4
def isWinner(board, p): for x in range(4): matchCount = 0 for y in range(4): if board[x][y] == p or board[x][y] == 'T': matchCount += 1 if matchCount == 4: return True matchCount = 0 for y in range(4): if board[y][x] == p or board[y][x] == 'T': matchCount += 1 if matchCount == 4: return True matchCount = 0 for x in range(4): if board[x][x] == p or board[x][x] == 'T': matchCount += 1 if matchCount == 4: return True matchCount = 0 for x in range(4): if board[x][3-x] == p or board[x][3-x] == 'T': matchCount += 1 if matchCount == 4: return True return False def isComplete(board): for x in range(4): for y in range(4): if board[x][y] == '.': return False return True inData = [str(line.strip()) for line in open('tick.in') if line.strip() != ""] N = int(inData.pop(0)) for caseNum in range(1, 1+N): board = [] for x in range(4): board.append(inData.pop(0)) if isWinner(board, 'X'): print "Case #%s: X won" % caseNum continue if isWinner(board, 'O'): print "Case #%s: O won" % caseNum continue if isComplete(board): print "Case #%s: Draw" % caseNum continue print "Case #%s: Game has not completed" % caseNum
63bb27e053e3e7f53edc9ccb5c1c738aac28b6ba
nitrozyna/revword.py
/revword.py
125
4
4
print "What is your word?" word = raw_input() reversed_word = word[::-1] print "Your reversed word is %r." % (reversed_word)
6ad93f59273246edc2bacc6ed92735738bd1e6b6
vuhi/python_final_project
/hand.py
3,735
3.515625
4
from card import Face import matplotlib.pyplot as plt from matplotlib.image import imread class Hand: def __init__(self): print('Init hand ...') self.hand_size = 5 self.cards_in_hand = [None] * self.hand_size self.rank = None self.score = 0 def get_score(self): return self.score def get_rank(self): return self.rank def place_card_in_hand(self, card, position): self.cards_in_hand[position] = card def show_hand(self): print('Showing hand...') fig = plt.figure(figsize=(50, 30)) for i, card in enumerate(self.cards_in_hand): fig.add_subplot(1, 7, i + 2,) face = card.face.name suit = card.suit.name path = './images/{}{}s.png'.format(face, suit) plt.imshow(imread(path)) plt.axis('off') plt.show() def evaluate(self): # sort hand by face sorted_cards = sorted(self.cards_in_hand, key=lambda x: x.face.value) # More reference: https://en.wikipedia.org/wiki/List_of_poker_hands flush_count_occurrence = 1 # number of flush occurred in hand straight_count_occurrence = 1 # number of straight occurred in hand face_occurrence_dict = dict() # record face occurrence for pair, three of kind, full house & four of kind # Check for flush, straight, or both for i, card in enumerate(sorted_cards): # ignore first card if i == 0: face_occurrence_dict[card.get_face().name] = 1 continue # count number of card have same suit if card.get_suit() == sorted_cards[i - 1].get_suit(): flush_count_occurrence += 1 # count number of straight if card.get_face().value == (sorted_cards[i - 1].get_face().value + 1): straight_count_occurrence += 1 # special case for baby straight: [ 2, 3, 4, 5, ACE ] if (i == len(sorted_cards) - 1) and (card.get_face() == Face.ACE) and (sorted_cards[0].get_face() == Face.TWO): straight_count_occurrence += 1 # update card face occurrence if card.get_face().name not in face_occurrence_dict.keys(): face_occurrence_dict[card.get_face().name] = 1 else: face_occurrence_dict[card.get_face().name] += 1 pair_count = 0 three_of_kind = 0 four_of_kind = 0 for (face, v) in face_occurrence_dict.items(): if v == 2: pair_count += 1 if v == 3: three_of_kind += 1 if v == 4: four_of_kind += 1 # Begin evaluation: if flush_count_occurrence == 5 and straight_count_occurrence == 5: self.rank = 'Straight Flush' self.score = 15 return if flush_count_occurrence == 5: self.rank = 'Flush' self.score = 8 return if straight_count_occurrence == 5: self.rank = 'Straight' self.score = 6 return if four_of_kind == 1: self.rank = 'Four of a kind' self.score = 12 return if three_of_kind == 1 and pair_count == 1: self.rank = 'Full house' self.score = 10 return if three_of_kind == 1: self.rank = 'Three of kind' self.score = 4 return if pair_count > 0: self.rank = '{} pair(s)'.format(pair_count) self.score = 2 return self.rank = 'None' self.score = -1 return
934a1fd6b0e2ff24594e90572196996dc97a8899
Muthulekshmi-99/guvi
/code/sort no_new constrain.py
110
3.53125
4
a=int(input()) x=list(map(int,input().split())) if (a==len(x)): x.sort() for i in x: print(i,end=' ')
d2d7c82a9e0adb6cefd0751e61fb8f352b6cfb7d
Saurav9jal/Code
/identicalTree.py
694
3.9375
4
###Write Code to Determine if Two Trees are Identical class Node(object): def __init__(self,data): self.data = data self.left = None self.right = None def checkIdentical(root,root1): if(root == None and root1 == None): return True if((root == None and root1 != None ) or (root != None and root1 == None)): return False if((root.data == root1.data) and (checkIdentical(root.left,root1.left)) and (checkIdentical(root.right,root1.right))): return True return False root = Node(5) root.left = Node(1) root.right = Node(3) root1 = Node(5) root1.left = Node(1) root1.right = Node(4) print(checkIdentical(root,root1))
b282e82fc0578d9f3ed98d2ce0cefd0e9721a86b
alqu7095/DS-Unit-3-Sprint-2-SQL-and-Databases
/SC/Northwind.py
1,418
3.5
4
import sqlite3 conn = sqlite3.connect('northwind_small.sqlite3') curs = conn.cursor() query = '''SELECT * FROM Product ORDER BY UnitPrice;''' query curs = conn.cursor() curs.execute(query) curs.fetchall() #Top 10 most expensive products: #Cote de Blaye #Thüringer Rostbratwurst # Mishi Kobe Niku # Sir Rodney's Marmalade # Carnarvon Tigers # Raclette Courdavault # Manjimup Dried Apples # Tarte au sucre # Ipoh Coffee # Rössle Sauerkraut query = '''SELECT AVG(HireDate - BirthDate) as hired_age_avg FROM Employee;''' query curs.execute(query) curs.fetchall() #37.22 years old query = '''SELECT Product.ProductName, Product.UnitPrice, Supplier.CompanyName FROM Product LEFT OUTER JOIN Supplier ON Product.SupplierId = Supplier.Id ORDER BY UnitPrice;''' query curs.execute(query) curs.fetchall() #Top 10 most expensive products by Supplier: #Cote de Blaye - Aux joyeux ecclésiastiques #Thüringer Rostbratwurst - Plutzer Lebensmittelgroßmärkte AG # Mishi Kobe Niku - Tokyo Traders # Sir Rodney's Marmalade - Specialty Biscuits, Ltd. # Carnarvon Tigers - Pavlova, Ltd. # Raclette Courdavault - Gai pâturage # Manjimup Dried Apples - G'day, Mate # Tarte au sucre - Forêts d'érables # Ipoh Coffee - Leka Trading # Rössle Sauerkraut - Plutzer Lebensmittelgroßmärkte AG query = ''' SELECT Product.ProductName, Category.CategoryName FROM Product LEFT OUTER JOIN Category ON Category.ID = Product.CategoryID GROUP BY Product.CategoryID ORDER BY COUNT(DISTINCT Product.ID);''' curs.execute(query) curs.fetchall()
1ff17a44fc699045470757dc91592d52882d9ced
ViataF/Python_mysql_project
/main_menu.py
1,820
3.984375
4
import admin ''' 1. Register user details. 2. Ability to sign-in and sign-out. 3. Upgrade/downgrade user privileges. 4. Show people who have signed-in for the day. 5. Show people who have signed-out for the day. 6. Admin add and remove users in the system. if true or if false save to github ''' # display the login screen with the option for new registration. # This is the case when new employees or visitors arrive at the premises and would like to enter the building. # (Consider this the main screen) def login_screen(): log_screen = "Welcome to Life Choices Academy" + "\n" log_screen += "What would you like to do" + "\n" log_screen += "r) Register as new user" + "\n" log_screen += "l) Login as user" + "\n" print(log_screen) option1 = (input("Choose option (r, l, a):")) if option1 == 'r': return elif option1 == 'l': full_name = input("Please enter your fullname") username = input("Please enter username") password = input("Please enter your password") elif option1 == 'a': # When you are on the main screen, by pressing the “a” key, for admin, you should be presented with a new screen to login. full_name = input("Please enter your fullname") username = input("Please enter username") admin.admin_sign_in(full_name, username) add_or_delete_user = "Would you like to create or delete a user?" add_or_delete_user += "Enter c to create a user account" add_or_delete_user += "Enter d to delete a user account" option_del_or_add = input("Choose option (c or d):") login_screen() # If the login option is clicked (selected), the user should be presented with the option # asking them to enter their full_name, username and password.
a5856a42e25e0569d611ff2acfca7de24171917c
Saujas/LearnPy
/prim.py
307
3.953125
4
def prime(n): c = 0 for i in range(1,n+1): if(n%i==0): c+=1 if(c==2): return 1 else: return 0 var = int(input("Enter end point of range: ")) for j in range(1,var+1): if(prime(j)): print(j,"is prime") else: print(j, "is not prime")
49789f83f1481ecb7cf89858b6317d39e9e5b9bb
selfcompiler/c---files
/spoj/geoprob.py
165
3.5625
4
t = int(raw_input("")) while t>0: string = raw_input("") b,c,d = string.split(" ") b = int(b) c = int(c) d = int(d) print 2*c-b-d t -= 1
2a18bcd7a7f46f6080dabff3238aed181f34ae19
Indian-boult/algoexpert-2
/Anshul/Binary Search Trees/BST Construction.py
3,229
3.703125
4
# BST Construction # Not Complete class BinaryTree: def __init__(self, value): self.value = value self.right = None self.left = None def insert(self, value): currentNode = self while True: # Neither low nor high ? if value < currentNode.value: if currentNode.left is None: currentNode.left = BinaryTree(value) break else: currentNode = currentNode.left else: if currentNode.right is None: currentNode.right = BinaryTree(value) break else: currentNode = currentNode.right return self def getMinvalue(self): currentNode = self while currentNode.left is not None: currentNode = currentNode.left return currentNode.value def search(self, value): currentNode = self while currentNode is not None: if value < currentNode.value: currentNode = currentNode.left break else: currentNode = currentNode.right return self # Not self.value ? def delete(self, value, parentNode=None): currentNode = self while currentNode is not None: if value < currentNode.value: parentNode = currentNode currentNode = currentNode.left elif value > currentNode.value: parentNode = currentNode currentNode = currentNode.right else: if currentNode.left is not None and currentNode.right is not None: currentNode.value = currentNode.right.getMinvalue() currentNode.right.remove(currentNode.value, currentNode) elif parentNode is None: if currentNode.left is not None: currentNode.value = currentNode.left.value currentNode.right = currentNode.left.right currentNode.left = currentNode.left.left elif currentNode.right is not None: currentNode.value = currentNode.right.value currentNode.right = currentNode.right.right currentNode.left = currentNode.right.left else: currentNode.value = None elif parentNode.left==currentNode: parentNode.left=currentNode.left if currentNode.left is not None else currentNode.right elif parentNode.right==currentNode: parentNode.right= currentNode.left if currentNode.left is not None else currentNode.right break return self root = BinaryTree(10) root.left = BinaryTree(5) root.right = BinaryTree(15) root.left.left = BinaryTree(2) root.left.right = BinaryTree(5) root.right.left = BinaryTree(13) root.right.right = BinaryTree(22) root.left.left.left = BinaryTree(1) root.right.left.left = BinaryTree(12) root.right.left.right = BinaryTree(14) print(root.delete(10))
abd665e47b0c4a7c2f128b8ff21e288576c38b23
swetakum/Algorithms
/CTCI/Chapter02LinkedLists/ReturnKthToLast.py
386
3.625
4
class node: def __init__(self, val, next=None): self.val = val self.next = None def printList(head): while head != None: print(head.val, " ") head = head.next def returnkthtolast(head,k): slow = fast = head for i in range(k+1): fast = fast.next while fast: slow = slow.next fast = fast.next return slow
06468a48fb1d4bf5df09fe80179dffd3438692a2
IvanVK/fmi-python
/Game-Project/adventure.py
3,319
3.5625
4
from hero import Hero from villains import Villains from fight import Fight class Adventure(): def __init__(self, map_path): map_file = open(map_path, 'r') self.map = map_file.read().splitlines() map_file.close() self.map = [list(x) for x in self.map] self.players = {} def print_map(self): printing_map = '\n'.join([''.join(x) for x in self.map]) print(printing_map) return printing_map def spawn(self, name, entity): for i in range(len(self.map)): for j in range(len(self.map[i])): if self.map[i][j] == 'P': if type(entity) is Hero: self.map[i][j] = 'H' self.players[name] = [entity, (i, j)] return True elif type(entity) is Villains: self.map[i][j] = 'V' self.players[name] = [entity, (i, j)] return True else: break return False def move(self, player, direction): if player in self.players: position = self.players[player][1] new_position = () oponent = 'V' if type(self.players[player][0]) is Hero else 'H' if direction == 'right' and position[1] + 1 < len(self.map[position[0]]): new_position = (position[0], position[1] + 1) elif direction == 'left' and position[1] - 1 >= 0: new_position = (position[0], position[1] - 1) elif direction == 'up' and position[0] - 1 >= 0: new_position = (position[0] - 1, position[1]) elif direction == 'down' and position[0] + 1 < len(self.map): new_position = (position[0] + 1, position[1]) else: return False if self.map[new_position[0]][new_position[1]] == '.': self.map[new_position[0]][new_position[1]] = self.map[position[0]][position[1]] self.map[position[0]][position[1]] = '.' self.players[player][1] = new_position return True elif self.map[new_position[0]][new_position[1]] == oponent: for oponent_name in self.players: if self.players[oponent_name][1] == new_position: fight = Fight(self.players[player][0], self.players[oponent_name][0]) if not fight is None: fight_outcome = fight.simulate_fight() print(fight_outcome[0]) if fight_outcome[1] == 'H': self.players.pop(oponent_name) self.players[player][1] = new_position self.map[new_position[0]][new_position[1]] = self.map[position[0]][position[1]] self.map[position[0]][position[1]] = '.' elif fight_outcome[1] == 'V': self.players.pop(player) self.map[position[0]][position[1]] = '.' return fight_outcome[1] else: return False
32077e33cd3a3fec3a690c997331b826ee694b78
vaidehinaik/PracticeSession
/GroupAnagrams.py
351
3.96875
4
def groupAnagrams(arr): str_dict = dict() for word in arr: sorted_str = "".join(sorted(word)) if sorted_str in str_dict: str_dict[sorted_str].append(word) else: str_dict[sorted_str] = [word] return list(str_dict.values()) print(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
efa0f2f1f9b563bd72ed2f55ef5321ea72a1fffc
ashutosh-narkar/LeetCode
/three_sum_smaller.py
1,125
4.09375
4
#!/usr/bin/env python """ Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. For example, given nums = [-2, 0, 1, 3], and target = 2. Return 2. Because there are two triplets which sums are less than 2: [-2, 0, 1] [-2, 0, 3] Solution: There are two cases to handle: 1) If A[i] + A[j] + A[k] < target, which means the numbers between j and k are all less than target, because the array is sorted. Then we move the j pointer forward. 2) If A[i] + A[j] + A[k] >= target, we move k pointer backward. """ def three_sum_smaller(nums, target): if not nums: return [] nums.sort() result = 0 for i in range(len(nums) - 2): low = i + 1 high = len(nums) - 1 while low < high: if nums[i] + nums[low] + nums[high] < target: result += high - low low += 1 else: high -= 1 return result if __name__ == '__main__': nums = [-2, 0, 1, 3] print three_sum_smaller(nums, 2)
09a05ea80469164a3087aab07de9d649222cdec8
Skywal/PerceptMulClass
/graph.py
3,352
3.5625
4
# Widget class that displays graph. from PyQt5 import Qt import numpy as np import pyqtgraph as pg import pyqtgraph.examples class Graph(Qt.QWidget): def __init__(self, data_classes=1): super().__init__() layout = Qt.QVBoxLayout(self) # create layout self.view = self.init_plot() layout.addWidget(self.view) # show up plot area self.init_vars(data_classes) self.init_dots_graphs(data_classes=data_classes) self.init_line_graphs(data_classes=data_classes) def init_plot(self): """ Initialize and set up plot widget. Return widget object. """ view = pg.PlotWidget() # make a plot area view.setBackground((255, 255, 255, 0)) view.setAntialiasing(True) view.setAspectLocked(True) view.enableMouse(False) # remove axis from plot view.hideAxis('left') view.hideAxis('bottom') return view def init_vars(self, posible_data_cls): self.plot_color = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', (9, 59, 198), (215, 145, 5)] self.dots_obj_list = [] self.line_obj_list = [] self.data_classes = posible_data_cls def init_line(self, color): """ return line object with color from self.plot_color list """ return self.view.plot(pen=pg.mkPen(color=color, width=1.5)) def init_dot(self, color): """ return dots object with color from self.plot_color list """ return self.view.plot(pen=None, symbol='o', symbolPen=None, symbolSize=5, symbolBrush=color) def init_line_graphs(self, data_classes=1): """ Initialize up to 10 objects corresponding to data classes for plotting line. data_classes - amount of different data represented on one graph.""" for i in range(data_classes): self.line_obj_list.append(self.init_line(self.plot_color[i])) def init_dots_graphs(self, data_classes=1): """ Initialize up to 10 objects corresponding to data classes for plotting dots. data_classes - amount of different data represented on one graph.""" for i in range(data_classes): self.dots_obj_list.append(self.init_dot(self.plot_color[i])) def get_dots_list(self): """ Get list of all dots. Position corresponds to data class. """ return self.dots_obj_list def get_line(self): """ Get list of all lines. Position corresponds to data class """ return self.line_obj_list def get_data_cls(self): """ Return amount of different graphs. """ return self.data_classes def plot_dots_single_class(self, sequence_num=0, x=[0], y=[0]): """ Plot dot object from the list at position sequence_num. """ self.dots_obj_list[sequence_num].setData(x, y) def plot_line(self, sequence_num=0, x=[0], y=[0]): """ Plot line object from the list at position sequence_num. """ self.line_obj_list[sequence_num].setData(x, y) def clear_plot(self): """ Erase all from the plot, also deleting all displaying objects. After re-initialize needed. """ self.view.clear() if __name__ == "__main__": app = Qt.QApplication([]) w = Graph() w.show() app.exec() pyqtgraph.examples.run()
34504ea6b4e4daa4d7e11bf5399afa308e44660d
ashu123git/Guess-the-number
/exercise.py
648
3.9375
4
#it's Ashutosh Choubey print("\t\t\t\t\t\t\t\tCOME LET'S PLAY A GAME") print("-->Guess the number taken by me\n-->You have only 10 guesses") a=53 c=10 while(c>0): b=int(input("Enter any number = ")) if(b<a): print("Your number is less than my number") c=c-1 print("Number of guesses left = ",c) continue elif(b>a): print("Your number is greater than my number") c=c-1 print("Number of guesses left = ",c) continue else: print("Congrats, you have won the game in ",10-c+1,"guesses.") print("") exit() print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tGame over")
d0d7d3642c3619258b06549768755521d29cd4aa
p4arth/GrPa-Solutions
/Week7GrpA3.py
201
3.75
4
def minor_matrix(M, i, j): m = M m.remove(m[i]) print(m) for k in range(len(m)): for h in range(len(m)): if h == j: print(m[k][h]) m[k].remove(m[k][h]) return m
5e2210b2e584792bb44335791b76a837e442332e
s2arora/Bio
/Bioinfo_Problem/bioinformatics_1_3.py
101
4.03125
4
num1 = int(input("Enter a integer: ")) num2 = int(input("Enter another: ")) print("sum:",num1+num2)
08e0bd31247cff43c7759580e33f2f8634aba78e
StephanieLoomans/learning_python
/favorite_numbers.py
303
3.71875
4
favorite_numbers = { 'dan':['9', '44', '55'], 'ahmed':['6', '12', '55'], 'anna':['15', '4', '8'], 'rik':['18', '77', '11'], 'irina':['21','24', '88'], } for name, numbers in favorite_numbers.items(): print(f"\n{name.title()}'s favorite numbers are:") for number in numbers: print(f"\t{number}")
4484109487bd1ea511373d75e09a3f513ce1ac96
dhsim86/hello_py
/lambda/map.py
184
4.03125
4
#!/usr/bin/env python # Basic print('--------------------') print('Basic\n') f = lambda x: x > 0 g = lambda x: x ** 2 print(list(map(f, range(-5, 5)))) print(list(map(g, range(5))))
654ade1bb8b39a2130d17dec5551aedeb4e8ad37
aguilmes/Portfolio
/SopaDeLetras.py
12,272
3.765625
4
import random # DEFINICION FUNCIONES # ******************** def elegirCategoria(): """Selector de categoria. Podes generar tu categoría siguiendo <Categoria>:<Palabra>,<Palabra>""" try: categorias = open("categorias.txt","rt") categoriaLista = [] for linea in categorias: categoria,palabras = linea.split(":") categoriaLista.append(categoria.capitalize()) categorias.seek(0) seleccionarCategoria = input(f"Selecciona una categoria entre {categoriaLista}: ") while seleccionarCategoria.capitalize() not in categoriaLista: seleccionarCategoria = input("Seleccione una categoria valida: ") for linea in categorias: categoria,palabrasTotal = linea.split(":") if seleccionarCategoria.capitalize() == categoria.capitalize(): palabrasTotal = palabrasTotal.strip("\n") categoria = categoria.capitalize() break palabrasTotal = palabrasTotal.split(",") return palabrasTotal,categoria except FileNotFoundError as mensaje: print("No se puede abrir el archivo:",mensaje) except OSError as mensaje: print("ERROR:", mensaje) finally: try: categorias.close() except NameError: pass def imprimir_matriz(matriz, fila = 0, columna = 0): tamaño = len(matriz) if columna == tamaño: print() columna = 0 fila += 1 if columna < tamaño and fila < tamaño: print(f"{matriz[fila][columna]:3}", end= "") imprimir_matriz(matriz, fila, columna + 1) def leerPalabraFila(matriz, fila, cInicial, cFinal): pal = [] for f in range(len(matriz)): for c in range(len(matriz)): if(f == fila and c >= cInicial and c <= cFinal): pal.append(matriz[f][c]) return pal def leerPalabraCol(matriz, col, fInicial, fFinal): pal = [] for f in range(len(matriz)): for c in range(len(matriz)): if(c == col and f >= fInicial and f <= fFinal): pal.append(matriz[f][c]) return pal def validadorPalabra(palabraEncontrada, palabrasTotal): validador = 0 for i in range(len(palabrasTotal)): if(palabrasTotal[i].upper() == palabraEncontrada): validador = 1 return validador def cambiarPalabraHorizontal(matriz, fila, cInicial, cFinal): for f in range(len(matriz)): for c in range(len(matriz)): if(f == fila and c >= cInicial and c <= cFinal): matriz[f][c] = matriz[f][c].lower() return matriz def cambiarPalabraVertical(matriz, col, fInicial, fFinal): for f in range(len(matriz)): for c in range(len(matriz)): if(c == col and f >= fInicial and f <= fFinal): matriz[f][c] = matriz[f][c].lower() return matriz def crearCoordenadasEnMatriz(matriz): tam = len( matriz ) for i in range(tam): matriz[0][i] = str(i) matriz[i][0] = str(i) def ordenarPalabrasEnMatriz(matriz, palabras): tam = len( matriz ) orden = ["horiz", "vert"] coor_ocup = [] for palabra in palabras: palabra_ubicada = 0 intentos = 0 tam_p = len(palabra) while (palabra_ubicada < 1 and intentos < 10): elecc = random.choice(orden) coor = random.randint(1, tam - 1) despla = random.randint(1, tam - tam_p) if elecc == "horiz": cont_intentos_horiz = 0 while cont_intentos_horiz < 10: posib = [] cont_ocup = 0 # guardo en una lista las posibles coordenadas en la matriz for i in range( len(palabra) ): posib.append(f'{coor}{despla + i}') # recorro las dos listas, las coor8denadas ocupadas y las nuevas, para saber si se pisan for i in range( len(coor_ocup) ): for j in range( len(posib) ): if coor_ocup[i] == posib[j]: cont_ocup = cont_ocup + 1 # Si no hay coincidencias la palabra se acomoda en la matriz y se pone 1 en palabra ubicada y se asegura salir del while if cont_ocup == 0: palabra_ubicada = 1 cont_intentos_horiz = 11 for i in range( len(palabra) ): coor_ocup.append(f'{coor}{despla + i}') matriz[coor][despla + i] = palabra[i].upper() # Siempre se suma un intento cont_intentos_horiz = cont_intentos_horiz + 1 if elecc == "vert": cont_intentos_vert = 0 while cont_intentos_vert < 10: posib = [] cont_ocup = 0 # guardo en una lista las posibles coordenadas en la matriz for i in range( len(palabra) ): posib.append(f'{despla + i}{coor}') # recorro las dos listas, las coordenadas ocupadas y las nuevas, para saber si se pisan for i in range( len(coor_ocup) ): for j in range( len(posib) ): if coor_ocup[i] == posib[j]: cont_ocup = cont_ocup + 1 # Si no hay coincidencias la palabra se acomoda en la matriz y se pone 1 en palabra ubicada y se asegura salir del while if cont_ocup == 0: palabra_ubicada = 1 cont_intentos_vert = 11 for i in range( len(palabra) ): coor_ocup.append(f'{despla + i}{coor}') matriz[despla + i][coor] = palabra[i].upper() # Siempre se suma un intento cont_intentos_vert = cont_intentos_vert + 1 # Se suma un intento al while principal intentos = intentos + 1 # MAIN / PROGRAMA PRINCIPAL # ************************* # Inicio del Juego print() print(f"\n///SOPA DE LETRAS CON PYTHON///\n{'*'*31}\n") letras = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ" tablaPuntajes = {} jugar = "s" while(jugar.lower() == "s"): # Inicio sesión Jugador palabrasAEncontrar = () nombreJugador = input("Nombre del jugador: ") tablaPuntajes[nombreJugador] = 0 palabrasTotal,categoria = elegirCategoria() cont_PalabrasTotal = len(palabrasTotal) puntajeMinimo = (1/cont_PalabrasTotal) * 100 print(f"El jugador {nombreJugador} selecciono la categoria: {categoria}\nLas palabras a buscar son: {palabrasTotal}") # Creación e Impresión de la Matriz matriz = [[random.choice(letras) for col in range(16)] for row in range(16)] crearCoordenadasEnMatriz(matriz) ordenarPalabrasEnMatriz(matriz, palabrasTotal) print() imprimir_matriz(matriz) print() while (jugar.lower() == "s" and len(palabrasAEncontrar) < cont_PalabrasTotal): forma = input("De qué forma se encuentra la palabra que acaba de encontrar?:\n\nPresione H, si la palabra esta horizontal\nPresione V, si la palabra esta Vertical\n") # Validacion de la Opciones while (forma.lower() != "h" and forma.lower() != "v"): print("Opcion ingresada incorrecta\n") forma = input("De qué forma se encuentra la palabra que acaba de encontrar?:\n\nPresione H, si la palabra esta horizontal\nPresione V, si la palabra esta Vertical\n") # Lectura Palabra Horizontal if(forma.lower() == "h"): while True: try: fila = int(input("Ingrese numero de fila: ")) cInicial = int(input("Ingrese numero de columna incial: ")) cFinal = int(input("Ingrese numero de columan final: ")) assert fila > 0,"Valor ingresado Incorrecto. Ingrese un número positivo: " assert cInicial > 0,"Valor ingresado Incorrecto. Ingrese un número positivo: " assert cFinal > 0,"Valor ingresado Incorrecto. Ingrese un número positivo: " break except AssertionError as mensaje: print(mensaje) except ValueError: print("Valor ingresado Incorrecto. Ingrese un número positivo") palabraLista = leerPalabraFila(matriz, fila, cInicial, cFinal) print() palabraEncontrada = "".join(palabraLista) print(f"La palabra encontrada es: {palabraEncontrada.capitalize()}") print() #Validacion de la Palabra validador = validadorPalabra(palabraEncontrada, palabrasTotal) if(validador == 1): palabrasAEncontrar = palabrasAEncontrar + (palabraEncontrada,) tablaPuntajes[nombreJugador] = tablaPuntajes[nombreJugador] + puntajeMinimo print("Puntaje Total: ", tablaPuntajes[nombreJugador]) print() matriz = cambiarPalabraHorizontal(matriz, fila, cInicial, cFinal) imprimir_matriz(matriz) print() else: print("\nPalabra indicada incorrecta\n") # Lectura Palabra Vertical elif(forma.lower() == "v"): while True: try: col = int(input("Ingrese el numero de columna en el que se encuentra la palabra: ")) fInicial = int(input("Ingrese la fila en donde empieza la palabra: ")) fFinal = int(input("Ingrese la fila en donde termina la palabra: ")) assert col > 0,"Valor ingresado Incorrecto. Ingrese un número positivo: " assert fInicial > 0,"Valor ingresado Incorrecto. Ingrese un número positivo: " assert fFinal > 0,"Valor ingresado Incorrecto. Ingrese un número positivo: " break except AssertionError as mensaje: print(mensaje) except ValueError: print("Valor ingresado Incorrecto. Ingrese un número positivo") palabraLista = leerPalabraCol(matriz, col, fInicial, fFinal) print() palabraEncontrada = "".join(palabraLista) print(f"La palabra encontrada es: {palabraEncontrada.capitalize()}") print() #Validacion de la Palabra validador = validadorPalabra(palabraEncontrada, palabrasTotal) if(validador == 1): palabrasAEncontrar = palabrasAEncontrar + (palabraEncontrada,) tablaPuntajes[nombreJugador] = tablaPuntajes[nombreJugador] + puntajeMinimo print("Puntaje Total: ", tablaPuntajes[nombreJugador]) print() matriz = cambiarPalabraVertical(matriz, col, fInicial, fFinal) imprimir_matriz(matriz) print() else: print("\nPalabra indicada incorrecta\n") print() # Menu de Sesión de Jugador if len(palabrasAEncontrar) < cont_PalabrasTotal: jugar = input("¿Desea seguir jugando con este jugador?: (Presione s para seguir y cualquier otra tecla para salir): ") else: print("¡Felicitaciones! ¡Has encontrado todas las palabras!") print() # Menu Principal de Juego jugar = input("¿Desea jugar con un nuevo jugador?: (Presione s para seguir y cualquier otra tecla para salir): ") print() print("Tabla de puntajes de sopa de letras:") for jugador, puntaje in tablaPuntajes.items(): print(f"{jugador}: {puntaje}") print("\n\nHasta la próxima!!\n\n")
d83617ff45e5daeb5c3c78331f425369a8efd757
WanderersTeam/The-adventures-of-a-lone-wanderer
/main_menu.py
2,106
3.796875
4
import functions global main_menu main_menu = 1 def mainMenuText(): """Prints options for start of the game""" print(""" 1. New Game 2. Load Game 3. Authors 4. Exit""") global choice choice = input("What to do? [Choose the number]:") return(choice) def newGameLoad(): """Import New Game parameters""" import new_game global attributes attributes = {"heroName": new_game.heroName, "hp": new_game.hp, "exp": new_game.exp, "lvl": new_game.lvl, "strength": new_game.strength, "mana": new_game.mana, "hpPotions": new_game.hpPotions, "manaPotions": new_game.manaPotions, "weapon": new_game.weapon, "weaponAtt": new_game.weaponAtt} return(attributes) def SavedGameLoad(): """Import Saved Game parameters""" import saved_game global attributes attributes = {"heroName": saved_game.heroName, "hp": saved_game.hp, "exp": saved_game.exp, "lvl": saved_game.lvl, "strength": saved_game.strength, "mana": saved_game.mana, "hpPotions": saved_game.hpPotions, "manaPotions": saved_game.manaPotions, "weapon": saved_game.weapon, "weaponAtt": saved_game.weaponAtt} return(attributes) def authors(): """Show Authors of the game""" print("""\n WanderersTeam:\n Alicja Olejniczak\n Bartosz Zawadzki\n Klaudia Slawinska\n\n""") def mainMenu(gameOn): """Main part of Main Menu in game""" while(main_menu == 1): mainMenuText() if(choice == '1'): newGameLoad() print("Started a new game") attributes["heroName"] = functions.create_new_hero() #changes herName to chosen Name gameOn=1 break elif(choice == '2'): SavedGameLoad() gameOn=1 print("Loaded a saved game") break elif(choice == '3'): authors() elif(choice == '4'): gameOn=functions.exit(gameOn) break else: print("We don`t do that here\n") continue return(gameOn)
322a3a2581340b0f3e95390333288d3cc9c54d58
chaun01/python_ML
/data_cleaning/data_cleaning.py
1,637
3.546875
4
#!/usr/bin/env python # coding: utf-8 Type Null Data Missing Data Duplicate Outliers # In[19]: get_ipython().system(' pip install pandas') # In[2]: import numpy as np import pandas as pd # ### Problem 1 # In[39]: df = pd.read_csv('property.csv') df.info() #Check the type of data and whether any data is null df #Print data # In[40]: #Check data is null df['ST_NUM'].isnull() # In[41]: # Detecting missing values in OWN_OCCUPIED i=0 for row in df['OWN_OCCUPIED']: try: int(row) df.loc[i]=np.nan except ValueError: pass cnt+=1 df['OWN_OCCUPIED'] # In[42]: # Any missing values? df.isnull().values.any() # In[43]: # Summarize missing values df.isnull().sum() # In[ ]: # Drop all rows with missing values df. dropna() # In[65]: #Replace missing values with a number 0 //fillna() fills all of null with a given value df['ST_NUM'].fillna(0, inplace=False) df['ST_NUM'] # In[ ]: #Replace missing values with mean df.replace(np.NaN, df['SQ_FT'].mean()) # In[66]: #Replace a specific missing value with a given value df[1,'SQ_FT'] = 1000 df['SQ_FT'] # In[69]: #Drop duplicates df['SQ_FT'].drop_duplicates() df['SQ_FT'] # ### Problem 2 # In[51]: df_nfl = pd.read_csv('nfl.csv') df_nfl.head() # In[52]: df_nfl.info() # In[56]: #Check missing values missing_values_count = df_nfl.isnull().sum() missing_values_count[0:10] #See number of missing values of first 10 columns # In[57]: #Total missing values of all columns total_missing = missing_values_count.sum() total_missing # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
6e49e9253088b8d0c0e649626fd9f71ff101f128
wushengwei2000/Wu
/python/bst/linkedlist.py
1,151
3.90625
4
class ListNode: def __init__(self, val): self.val = val self.next = None class MergeList: def merge(self, p1, p2): root = ListNode(None) p = root while p1 or p2: if not p1: p.next = p2 break if not p2: p.next = p1 break if p1.val <= p2.val: p.next = p1 p1 = p1.next else: p.next = p2 p2 = p2.next p = p.next return root.next def add(self, n1, n2): header = ListNode(0) p = header plus = 0 while n1 or n2: tempSum = (0 if not n1 else n1.val) + (0 if not n2 else n2.val) + plus val = tempSum if tempSum < 10 else 0 plus = 0 if tempSum < 10 else 1 p.next = ListNode(val) p = p.next n1 = None if not n1 else n1.next n2 = None if not n2 else n2.next # Missing => this is the problem if plus > 0: p.next = ListNode(1) return header.next def swap(self, list): if not list: return list head = ListNode(0) head.next = list p1 = head.next p2 = p1.next while p1 and p2: # Swap the value temp = p1.val p1.val = p2.val p2.val = temp # Move to the next p1 = p2.next if not p1: break p2 = p1.next return head.next
a58b82474a3d5085e56f05201b69acca048bb11b
dayanandtekale/Python_Basic_Programs
/if_statements.py
302
4.1875
4
#if str_input%2==0: # print("number is in multiple of 2") #elif str_input%7==0: # print("number is in multiple of 7") num1 = 5 num2 = 10 #if num1>num2: # print("num1 is grater") #else: # print("num2 is grater") print("num1 is grater")if num1>num2 else print("num2 is grater")
6756dec201998d01a43d3876c619659c1571b496
wentsun12/AlgorithmCHUNZHAO
/Week_02/Tree.py
3,078
3.78125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right #94: 二叉树,中序,递归 class Solution: def inorderTraversal(self, root): res = [] self.helper(root, res) return res def helper(self, root, res): if root: self.helper(root.left, res) res.append(root.val) self.helper(root.right, res) #94: 二叉树,中序,栈 class Solution: def inorderTraversal(self, root): res, stack = [], [] while True: while root: stack.append(root) root = root.left if not stack: return res node = stack.pop() res.append(node.val) root = node.right #144:二叉树,前序,递归 class Solution: def preorderTraversal(self, root): res = [] self.helper(root, res) return res def helper(self, root, res): if root: res.append(root.val) self.helper(root.left, res) self.helper(root.right, res) #144:二叉树,前序,栈 class Solution: def preorderTraversal(self, root): stack, res = [root], [] while stack: node = stack.pop() if node: res.append(node.val) stack.append(node.right) stack.append(node.left) return res #590:N叉树,后序,递归 # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def postorder(self, root): res = [] if root== None: return res self.helper(root, res) return res def helper(self, root, res): for child in root.children: self.helper(child, res) res.append(root.val) #590:N叉树,后序,栈 (根据前序来写的,前序:根左右 交换顺序,根右左,然后反序变为左右根,即为后序) class Solution: def postorder(self, root): res = [] if root == None: return res stack = [root] while stack: node = stack.pop() res.append(node.val) stack.extend(node.children) return res[::-1] #589:N叉树,前序,递归 class Solution: def preorder(self, root): res = [] if root == None: return res self.helper(root, res) return res def helper(self,root,res): res.append(root.val) for child in root.children: self.helper(child,res) #589:N叉树,前序,栈 class Solution: def preorder(self, root): res = [] if root==None: return res stack = [root] while stack: node = stack.pop() res.append(node.val) stack.extend(reversed(node.children)) return res #589:N叉树,层序 (没怎么搞明白)
706e85da67e8565964be796b0768be94d77a38f2
gup-abhi/rand_dice_num
/Simpledicegame.py
831
4.0625
4
# importing tkinter import tkinter as tk from tkinter import ttk # importing showinfo from tkinter messagebox from tkinter.messagebox import showinfo # importing random module import random # creating a window win = tk.Tk() # giving a title to our window win.title("Random Number Generator") # creating a function randomly generate a number between 1 to 6 def play(): random_number = random.randint(1, 6) number.config(text=f"Number is : {random_number}") # if number matches to 6 then user wins if random_number == 6: showinfo("Congratulations", "You WON !!") # creating a label to display the number number = ttk.Label(win, text="") number.pack(pady=10) # creating play button to get number play = ttk.Button(win, text="Play", command=play) play.pack(padx=50) # creating window loop win.mainloop()
e22e9b650b621bd6e782f72f8e131c961e4abaa6
dogancanulgu/arin-python-tutorial
/lists2.py
708
3.9375
4
# cities = ['tokyo', 'madrid', 'londra', 'kiev'] # # print(cities.index('madrid')) # # print('ankara' in cities) # for city in cities: # print(f'Gezilen şehir: {city}') # print('Gezilecek şehir kalmadı') # str_cities = 'tokyo, madrid, kiev' # my_list = str_cities.split(', ') # print(my_list) # str_email = 'arinyazilim@gmail.com' # my_list2 = str_email.split('@') # print(my_list2) # for number in range(2,21,2): # print(number) # numbers = list(range(1,11)) # print(numbers) # numbers = [number for number in range(1,11)] # print(numbers) cities = ['izmir', 'ankara', 'istanbul'] print(cities) # cities2 = cities cities2 = cities[:] print(cities2) cities.append('artvin') print(cities) print(cities2)
b81cf676ab443950bec25538ff0d628014d3e88b
IL23/Python_exercises
/Part2/1.py
196
3.765625
4
# 1. Apgriezt pozitīva skaitļa ciparu secību. num = input("Enter number: ") numLength = len(num) revers = "" for i in range(1, numLength+1): revers += num[numLength-i] print(revers)
0e8f2ebc33f6442c152b29e86996fc265d0facab
edu-athensoft/stem1401python_student
/py200622_python2/day01_py200622/ex/function_kevin.py
929
4.28125
4
""" create 2 functions 1. y = 2x 2. y = 2x + 1 (whereas 2x mean 2 * x) call each function for 3 time with different input x of x (value of x) then print out the returned value of y """ # define function with the keyword 'def' # define a function def myfuc1(x): return x # 1. y = 2x # call a function result = myfuc1(5) * 2 print("the result of myfuc1(5) is {} ".format(result)) # call a function again result = myfuc1(10) * 2 print("the result of myfuc1(10) is {} ".format(result)) # call a function again result = myfuc1(55) * 2 print("the result of myfuc1(55) is {} ".format(result)) # 2. y = 2x + 1 # call a function result = myfuc1(5) * 2 + 1 print("the result of myfuc1(5) is {} ".format(result)) # call a function again result = myfuc1(10) * 2 + 1 print("the result of myfuc1(10) is {} ".format(result)) # call a function again result = myfuc1(55) * 2 + 1 print("the result of myfuc1(55) is {} ".format(result))
ee6e33573521232df1e9322bf3e16d3332e15c56
mistrydarshan99/Leetcode-3
/trie/211_add_and_search_word_data_structure_design.py
2,670
4.0625
4
""" Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. Example: addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true """ class WordDictionary_1(object): def __init__(self): """ Initialize your data structure here. """ self.word_dict = collections.defaultdict(list) def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ if word: self.word_dict[len(word)].append(word) def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ if not word: return False if not "." in word: return word in self.word_dict[len(word)] # if you encounter any break, return False for v in self.word_dict[len(word)]: for i, char in enumerate(word): if char != v[i] and char != ".": break # when all the char has been match with a particular v in word_dict WITHOUT break: # return True else: return True return False class WordDictionary_2(object): def __init__(self): self.root = {} def addWord(self, word): node = self.root for char in word: node = node.setdefault(char, {}) node[None] = None # print(node[None]) # return node[None] def search(self, word): def find(word, node): if not word: # print(bool(None in node)) # print(type(None in node)) # print(node.keys()) return None in node char, word = word[0], word[1:] print('char:{}, word:{}'.format(char, word)) if char != ".": return char in node and find(word, node[char]) return any(find(word, kid) for kid in node.values if kid) return find(word, self.root) ''' For solution 2: the structure is dictionayr in dictionayr {{}} eg. word = "ape" self.root = {} {{"a":{"p":{"e":{None:None}}}}} ''' # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
f8d19053cc611e0dfdcbdcf1751ceb9f70a25416
ONOentrepreneur/python-code
/kisuu.py
109
3.578125
4
def gen(): i=1 while i<=30: yield i i+=2 it= gen() for v in it: print(v,end=",")
697d3c6985d24f985669e1fb437afe9d0079c4b4
hdannyyi/my-first-python
/firstProject.py
330
4.03125
4
FirstName = input('What is your first name?') LastName = input('What is your last name?') FavMovie = input('What is your favorite movie?') #print ("First Name: %s" % FirstName) #print ("Last Name: %s" % LastName) #print ("Favorite Movie: %s" % FavMovie) print ("Hello %s %s. I like %s, too" % (FirstName, LastName, FavMovie))
b38ae79f9684a745a9c6ca2a8ec68432d8f2a823
hyang012/leetcode-algorithms-questions
/238. Product of Array Except Self/Product_of_Array_Except_Self.py
843
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Leetcode 238. Product of Array Except Self Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Note: Please solve it without division and in O(n). Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) """ def productExceptSelf(nums): """ :type nums: List[int] :rtype: List[int] """ p = 1 output = [] for i in range(len(nums)): output.append(p) p = p * nums[i] p = 1 for i in range(len(nums)-1, -1, -1): output[i] *= p p = p * nums[i] return output print(productExceptSelf([1, 2, 3, 4]))
e565cf4871a4802b0c2ddc7e60731adb55b23295
tsmith328/AoC2015
/Day24/day24.py
734
3.515625
4
import itertools, operator from functools import reduce items = [] num_groups = 3 with open("input24.txt") as f: for line in f: items.append(int(line.strip())) def find_qe(things, parts): for i in range(1, len(items)): for x in (c for c in itertools.combinations(items, i) if sum(c) == sum(items) // num_groups): if parts == 2: return True elif parts < num_groups: return find_qe(list(set(items) - set(x)), parts - 1) elif find_qe(list(set(items) - set(x)), parts - 1): return reduce(operator.mul, x, 1) def main(): print(find_qe(items, num_groups)) if __name__ == '__main__': main() num_groups = 4 main()
0163e281e5d4d2f67c6c81453b5ec7e298174e3d
jichilen/python
/problem/_34_tree_sum.py
790
3.65625
4
from tree_node import MyTree def tree_sum(root,target): def search(node,target,re): if node is None: return None val = re[0]+node.val if val>target: return None past = re[1].copy() past.append(node.val) if val==target: return [past] re_n = [val,past] left = search(node.left,target,re_n) right = search(node.right, target, re_n) out =[] if left: out.extend(left) if right: out.extend(right) return out re = [0,[]] return search(root,target,re) if __name__ == '__main__': pos = [10,5,4,7,12] inter = [4,5,7,10,12] root = MyTree.constuct_tree(pos,inter) target = 22 print(tree_sum(root,target))
ee69cf33525a2fb7633cb1249282821b6187d1df
gongjianc/Learn
/python/quadratic.py
264
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math #Ҫжb*b - 4ac Ƿ0 def quadratic(a,b,c): x1 = float((-b + math.sqrt(b * b - 4 * a * c)) / (2 * a)) x2 = float((-b - math.sqrt(b * b - 4 * a * c)) / (2 * a)) return x1,x2
73d4b4e4e9b59c36775af69bc0882b260df064ad
lilsweetcaligula/sandbox-codewars
/solutions/python/7.py
309
4.09375
4
def string_parse(s): if type(s) != str: return 'Please enter a valid string' import itertools result = '' for char, chars in itertools.groupby(s): group = ''.join(chars) result += '{}{}'.format( group[:2], '[' + group[2:] + ']' if len(group) > 2 else '') return result
8469b36f6a34ae13ead0752fd3c506525f6cb77b
Carl-Chinatomby/Algorithms-and-Data-Structures
/programing_problems/order_agnostic_binary_search.py
1,519
4.125
4
#!/usr/bin/env python3 """ Given a sorted array of numbers, find out if a given number key is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order. You should assume that the array can have duplicates. Write a function to return the index of the key if it is present in the array, otherwise return -1. Example-1: Input: [1, 2, 3, 4, 5, 6, 7], key = 5, Output: 4 Example-2: Input: [10, 6, 4], key = 10, Output: 0""" from typing import List def binary_search(arr: List[int], low_idx: int, high_idx: int, num: int) -> int: if high_idx >= low_idx: mid_idx = low_idx + ((high_idx - low_idx)//2) is_ascending = arr[low_idx] <= arr[high_idx] if arr[mid_idx] == num: return mid_idx if is_ascending: if arr[mid_idx] > num: return binary_search(arr, low_idx, mid_idx-1, num) else: return binary_search(arr, mid_idx+1, high_idx, num) else: if arr[mid_idx] > num: return binary_search(arr, mid_idx+1, high_idx-1, num) else: return binary_search(arr, low_idx, mid_idx, num) return None def find_pos(arr: List[int], num: int) -> int: low_idx = 0 high_idx = len(arr) - 1 return binary_search(arr, low_idx, high_idx, num) def main(): assert find_pos([1, 2, 3, 4, 5, 6, 7], 5) == 4 assert find_pos([10, 6, 4], 10) == 0 if __name__ == "__main__": main()
4c171d4824b894644e0bf73c27b8f8c998821d7d
Darkspectra/CSE-111-Assignment-1
/Medium03.py
191
3.71875
4
#Medium_03 num=int(input("Enter number:")) sum=0 for i in range(1,num): if(num%i==0): sum=sum+i if(sum==num): print("Perfect Number") else: print("Not Perfect")
0916fe4c35446106bf90cccb6d1ae0bde0009476
Atylonisus/AutomateHello
/hello.py
1,175
4.25
4
#This Program says hello, and asks for my name. print('Hello world!') print('What is your name?') #asks for their name myName = input() #a new variable, which will store whatever the user types here print('It is good to meet you, ' + myName) #concatenates a string, with your myName variable, to produce a single sentence print('The length of your name is:') print(len(myName)) # prints out the number of characters (letters) present in the myName variable print('What is your age?') #asks for age! myAge = input() #creates a new variable named myAge, which prompts the user to type something print('You will be ' + str(int(myAge) + 1) + ' in a year.') """ The above does a lot of little things all at once. It: converts whatever value the user put for the variable myAge into an integer (input() always returns a string value regardless if numbers were used --> 42 would come out as '42' so int(myAge) would actually make it 42) ADDS +1 to that INTEGER value Converts the evaluated integer BACK into a string and concatenates it into the rest of the sentence, to be printed out to the user """
1d2ea1012518151e6549e8b681270fda57f14804
1205-Sebas/TALLERCV-GOMEZ-DIAZ
/Ejercicio6.py
926
4.15625
4
""" 6. Elaborar un algoritmo que permita realizar el inventario de una tienda, es decir cuántas unidades de cada tipo de producto existen actualmente en la tienda. Se debe imprimir una lista ordenada de productos de menor a mayor cantidad. """ import operator a=int(input("Cantidad Aceite:")) b=int(input("Cantidad Arroz:")) c=int(input("Cantidad Cerveza:")) d=int(input("Cantidad Gaseosa:")) e=int(input("Cantidad Panela:")) f=int(input("Cantidad Azucar:")) g=int(input("Cantidad Cafe:")) nombres={"Aceite:":a,"Arroz:":b,"Cerveza:":c,"Gaseosa:":d,"Panela:":e,"Azucar:":f,"Cafe:":g} clients_sort = sorted(nombres) clients_sort clients_sort = sorted(nombres.items()) clients_sort clients_sort = sorted(nombres.items(), key=operator.itemgetter(1), reverse=False) print("INVENTARIO") for name in enumerate(clients_sort): print(name[1][0],nombres[name[1][0]]) t=int(input("Ingrese el promedio: ",i))
0e8bd4c5a652a29dc70031c6f0e897f97bb6c8d8
giuseppeSilvestro/ScientifiComputingWithPython
/RaiseExceptions.py
1,092
4.21875
4
# import math module to use in split_check function import math # this function will take the bill and split it between the number of people def split_check(total, number_of_people): # check the number of people input by the user. if it is less or equal to 1 # raise a ValueError exception if number_of_people <= 1: raise ValueError('More than 1 person is required to split the check') # use math.ceil to round up to the next integer return math.ceil(total / number_of_people) try: total_due = float(input('What is the total? ')) number_of_people = int(input('How many people? ')) # if the line that calls the function is in the try block, the error raise by the # if statement at line 8 will be cought by the except block and will not cause # the program to crash amount_due = split_check(total_due, number_of_people) # 'as err' will give us the chance to print the message contained in the raise line except ValueError as err: print('This is not a valid value.') print('({})'.format(err)) else: print('Each person owes ${}'.format(amount_due))
238e2d87773713788d967de748683b48ce0db390
AnaBiaCosta/curso-python
/exercicios-python/34.py
283
3.75
4
salario = int(input('Seu salário:')) if salario > 1250: aumento = (salario * 110)/100 print('Com aumento de 10% seu salário será de R${}'.format(aumento)) else: aumento = (salario * 115)/100 print('Com aumento de 15% seu salário será de R${}'.format(aumento))
e393052b15dfc2cbabee148aa6121350ac5e1496
ArhiTegio/GB-Python-Basic_2
/Lesson_6/04.Car.py
1,933
3.859375
4
from enum import Enum class Color(Enum): Red = 1 Yellow = 2 Green = 3 class Car: speed = 0 color = Color.Red name = "" is_police = False def __init__(self, speed, color, name, is_police): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): pass def stop(self): pass def turn_direction(self): pass def show_speed(self): print('{} - Скорость соствляет: {}'.format(str(self)[str(self).find('.') + 1:str(self).find(' ')], self.speed)) return self.speed class TownCar(Car): def show_speed(self): if self.speed > 60: print('{} - Превышение скорости на {}'.format(str(self)[str(self).find('.') + 1 :str(self).find(' ')], self.speed - 60)) super().show_speed() class SportCar(Car): def show_speed(self): super().show_speed() class WorkCar(Car): def show_speed(self): if self.speed > 40: print('{} - Превышение скорости на {}'.format(str(self)[str(self).find('.') + 1: str(self).find(' ')], self.speed - 40)) super().show_speed() class PoliceCar(Car): def show_speed(self): super().show_speed() if __name__ == "__main__": car_town = TownCar(80, Color.Red, 'Carmageddon_down_for_Angels_v0.5beta', False) car_town.show_speed() car_sport = SportCar(80, Color.Red, 'Carmageddon_down_for_Angels_v0.5beta', False) car_sport.show_speed() car_worker = WorkCar(80, Color.Red, 'Carmageddon_down_for_Angels_v0.5beta', False) car_worker.show_speed() car_police = PoliceCar(80, Color.Red, 'Carmageddon_down_for_Angels_v0.5beta', False) car_police.show_speed()
ad516745bf2c0a26c24e5dae3ff3483bc8bbd089
James-Oswald/IEEE-Professional-Development-Night
/7-5-21/rev.py
354
3.75
4
#https://leetcode.com/problems/reverse-integer def reverse(x: int) -> int: fullArr=list(str(x)) digiArr=fullArr[1:]if fullArr[0]=="-"else fullArr digiArr.reverse() revVal = int("".join((["-"] + digiArr) if fullArr[0]=="-" else digiArr)) if revVal < -2**31-1 or revVal > 2**31: return 0 return revVal print(reverse(-123))
d3d4d3e539e2f2d73643280624dad3fe2061f4c6
VirajShah21/euler
/py/9.py
285
3.578125
4
import math breakout = False for a in range(1, 1000): for b in range(1, 1000): c_2 = ((a)**2) + ((b)**2) c = math.sqrt(c_2) if a + b + c == 1000: print("a = %d\nb = %d\nc = %d" % (a, b, c)) breakout = True if breakout: break if breakout: break print(a*b*c)
fc41c93123c02481c72861309b47e98df1cab29b
loopfree/Praktikum-Daspro
/Prak 4/segitiga.py
1,565
3.65625
4
# Steven # 16520203 # 26 Maret 2021 # Program GambarSegitiga # Input: N : integer # Output: Jika N > 0 dan ganjil, gambar segitiga sesuai dengan N # Jika tidak, tampilkan pesan kesalahan: # KAMUS # Variabel # N : int def GambarSegitiga(N): # I.S. N > 0 dan N ganjil # F.S. Gambar segitiga dengan tinggi sebesar N sesuai spesifikasi soal # Lengkapilah kamus lokal dan algoritma prosedur di bawah ini # Pola Atas for i in range(1,( (N // 2) + 1 )): # Mencetak pola untuk baris ke X sebelum tengah for j in range(0, N-(i*2-1)): # Mengosongkan baris print(' ', end='') for j in range(0, i * 2 - 1): # Memberi bintang pada baris print('*', end='') print() # Enter # Pola Tengah for i in range(N): print('*', end='') print() # Enter # Pola Bawah for i in [i for i in range(1, (N // 2) + 1)][::-1]: # Mencetak pola untuk baris ke X setelah tengah for j in range(0, N - ( i * 2 - 1 ) ): # Mengosongkan baris print(' ', end='') for j in range(0, i * 2 - 1): # Memberi bintang pada baris print('*', end='') print() # Enter def IsValid(N): # menghasilkan true jika N positif dan ganjil, false jika tidak return (( N > 0 ) and (N % 2 == 1)) # ALGORITMA PROGRAM UTAMA N = int(input()) if (IsValid(N)): # lengkapi dengan pemanggilan fungsi IsValid GambarSegitiga(N) else: # N tidak positif atau N tidak ganjil print("Masukan tidak valid")
af97d2adfeb27d9a5aa7216eb9bb3784138c67cd
firstlord15/Python
/Уроки/Дашина работа.py
368
3.875
4
# Линейный поиск names = ["Володя", "Валера", "Вася", "Саша", "Антон", "Яков"] search_for = "Антон" # что ищем def liner_search(): for v in enumerate(where): if v[1] == what return v[0] # возвращаем индекс return None # или None если не найдено print( liner_search() )
cff6625e2b6f932e325b7411a4c71127eecc7ea6
aye-am-rt/python-practice
/Strings/KUniquesIntSubs/GenerateStringKDistinct.py
1,715
3.984375
4
# Generate a string of size N whose each substring of size M has exactly K distinct characters # Given 3 positive integers N, M and K. the task is to construct a string of length N # consisting of lowercase letters such that each substring of length M having exactly K # distinct letters. # Examples: # Input: N = 5, M = 2, K = 2 # Output: abade # Explanation: # Each substring of size 2 “ab”, “ba”, “ad”, “de” have 2 distinct letters. # Input: N = 7, M = 5, K = 3 # Output: abcaaab # Explanation: # Each substring of size 5 “tleel”, “leelt”, “eelte” have 3 distinct letters. # # Approach: In a string of size N, every substring of size M must contain exactly K distinct # letters # # Construct a string having K distinct alphabets starting from ‘a’ to ‘z’ up to the size of M # and put the rest of letters like ‘a’.. # Since, we have generated a string of size M with K distinct value. Now, keep repeating it # till we reach string size of N. def GenerateString(totalLength, SubSSizeM, DLettersK): ansString = "" cntM = cntK = 0 # counter for M and K for i in range(totalLength): # Loop to generate string size of N cntK += 1 # K is num of distinct letters in each substring cntM += 1 # M is substring size if cntM <= SubSSizeM: # Generating K distinct letters one by one if cntK <= DLettersK: ansString += chr(96 + cntM) else: ansString += 'a' else: # Reset the counter value and repeat the process cntK = cntM = 1 ansString += 'a' print(ansString) if __name__ == '__main__': N = 7 M = 5 K = 3 GenerateString(N, M, K)
fef491c7eb090ab6f04b415d9708e7db7294155d
notini/python_recursive_binary_tree
/binaryTree.py
2,425
4.03125
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None #Inserts value to tree. def insert(self, currNode, value): #no root yet if self.root == None: self.root = Node(value) else: if value < currNode.value: if currNode.left == None: currNode.left = Node(value) else: self.insert(currNode.left, value) else: if currNode.right == None: currNode.right = Node(value) else: self.insert(currNode.right, value) #Checks if value is in tree. def find(self, currNode, value): if currNode.value == value: return currNode if value < currNode.value and currNode.left is not None: return self.find(currNode.left, value) elif value > currNode.value and currNode.right is not None: return self.find(currNode.right, value) #Removes value from tree. def remove(self, currNode, value): if self.root == None: print('Cant remove from empty tree!') else: if self.root.value == value: auxRoot = Node(0) auxRoot.left = self.root result = self._remove(self.root, value, auxRoot) self.root = auxRoot.left return result else: return self._remove(currNode, value, None) def _remove(self, currNode, value, parent): if value < currNode.value: if currNode.left is not None: return self._remove(currNode.left, value, currNode) elif value > currNode.value: if currNode.right is not None: return self._remove(currNode.right, value, currNode) else: if currNode.left is not None and currNode.right is not None: currNode.value = self.minValue(currNode.right) return self._remove(currNode.right, currNode.value, currNode) elif parent.left == currNode: if currNode.left is not None: parent.left = currNode.left else: parent.left = currNode.right elif parent.right == currNode: if currNode.right is not None: parent.right = currNode.right else: parent.right = currNode.left #Returns min value found in tree. def minValue(self, node): if node.left is None: return node.value else: return self.minValue(node.left) #Prints tree in crescent order. def printTree(self, node): if self.root == None: print('Empty Tree!') else: if node is not None: self.printTree(node.left) print(node.value) self.printTree(node.right)
4501f44dd2423fc9ca0d98bc79988215756fd641
milica325/unibl_radionica
/sveske/sources/08_OOPI/OOP_I.py
3,796
4.65625
5
# Code for Object-Oriented Programming with Python - Lesson 1 # SBC - 01/12/12 ### # Slide 9 - Bear: Our first Python class class Bear: print "The bear class is now defined" a = Bear a # Equates a to the class Bear. Not very useful a = Bear() # Creates a new *instance* of the class Bear ### # Slide 10 - Attributes: Access, Creation, Deletion a.name # name attributed has not been defined yet a.name = "Oski" a.color = "Brown" # new attributes are accessed with the "." operator del(a.name) # attributes can be deleted as well a.name # Throws AttributeError Exception ### # Slide 11 - Methods: Access, Creation, and (not) Deletion class Bear: print "The bear class is now defined." def say_hello(self): print "Hello, world! I am a bear." a = Bear() # create a new instance of the bear class a.say_hello # This provides access to the method itself a.say_hello() # This actually executes the method ### # Slide 12 - The __init__ method class Bear: def __init__(self, name): self.name = name def say_hello(self): print "Hello, world! I am a bear." print "My name is %s." % self.name a = Bear() # Now you need to specify one argument to create the Bear class a = Bear("Yogi") a.name a.say_hello() # Prints desired text ### # Slide 13 - Scope: self and "class" variables class Bear: population = 0 def __init__(self, name): self.name = name Bear.population += 1 def say_hello(self): print "Hello, world! I am a bear." print "My name is %s." % self.name print "I am number %i." % Bear.population a = Bear("Yogi") # Create a new instance of the Bear class. Needs 1 argument a.say_hello() # Prints name and 1st bear b = Bear("Winnie") b.say_hello() # Prints name and 2nd bear c = Bear("Fozzie") Bear.say_hello(c) # Need "self" argument when calling directly from class ### # Slide 15 - A Zookeeper's Travails I class Bear: def __init__(self, name, weight): self.name = name self.weight = weight a = Bear("Yogi", 80) b = Bear("Winnie", 100) c = Bear("Fozzie", 115) # Create three new Bear instances my_bears = [a, b, c] # Combine them into a list total_weight = 0 for z in my_bears: total_weight += z.weight # Loop over the list and add to the total weight total_weight < 300 # The zookeeper only needs to make one trip. ### # Slide 17 - A Zookeeper's Travails II class Bear: def __init__(self, name, weight): self.name = name self.weight = weight def eat(self, amount): self.weight += amount def hibernate(self): self.weight /= 1.20 a = Bear("Yogi", 80) b = Bear("Winnie", 100) c = Bear("Fozzie", 115) my_bears=[a, b, c] a.weight a.eat(20) a.weight # After eating, Yogi gains 20 kg b.eat(10) # Winnie eats c.hibernate() # Fozzie hibernates` total_weight = 0 for z in my_bears: total_weight += z.weight total_weight < 300 # Now the keeper needs two trips. ### # Slide 19 - A Zookeeper's Travails III class Bear: def __init__(self, name, fav_food, friends=[]): self.name = name self.fav_food = fav_food self.friends = friends def same_food(self): for friend in self.friends: if (friend.fav_food == self.fav_food): print "%s and %s both like %s" % \ (self.name, friend.name, self.fav_food) a = Bear("Yogi", "Picnic baskets") b = Bear("Winnie", "Honey") c = Bear("Fozzie", "Frog legs") ### # Slide 20 - A Zookeeper's Travails III c.friends # empty list c.fav_food # 'Frog legs' c.same_food() # Returns None since no friends c.friends = [a, b] # Now Fozzie has two friends c.same_food() # But still no overlap in food tastes c.fav_food = "Honey" # Fozzie now likes honey c.same_food() # And shares same food with Winnie
bb596882dd9fdf844b7996063ba7c672eb7f908a
ipsorus/lesson_2
/string_challenges.py
2,148
4.125
4
# Вывести последнюю букву в слове word = 'Архангельск' def last_letter(word): print(f'Последнняя буква в слове {word}: {word[-1]}') #last_letter(word) # Вывести количество букв "а" в слове word = 'Архангельск' def count_letters(word): letters = [] res = 0 letters = list(word) for letter in letters: if letter == 'а': res += 1 print(f'Количество букв \'а\' в слове: {res}') #count_letters(word) # Вывести количество гласных букв в слове word = 'Архангельск' def vowel(word): vowel_list = ['а', 'о', 'у', 'э', 'е', 'ы', 'я', 'и'] vowel = 0 word_letters = list(word.lower()) for vowel_letter in word_letters: if vowel_letter in vowel_list: vowel += 1 print(f'Количество гласных букв в слове: {vowel}') #vowel(word) # Вывести количество слов в предложении sentence = 'Мы приехали в гости' def count_words(sentence): words = sentence.split() print(f'Количество слов в предложении: {len(words)}') #count_words(sentence) # Вывести первую букву каждого слова на отдельной строке sentence = 'Мы приехали в гости' def first_letter(sentence): words = sentence.split() for i in words: print(i[0]) #first_letter(sentence) # Вывести усреднённую длину слова. from statistics import mean sentence = 'Мы приехали в гости' def average_word_len(sentence): words_average_list = [] words = sentence.split() for i in words: words_average_list.append(len(i)) print(f'Средняя длина слова: {mean(words_average_list)}') #average_word_len(sentence) if __name__ == '__main__': last_letter(word) count_letters(word) vowel(word) count_words(sentence) first_letter(sentence) average_word_len(sentence)
1dff787a8cdf5bd4e80df675841a32cc1c8e1908
timisaurus/workspace-python-Hello_world
/book/is_triangle.py
636
4.34375
4
# This program calculates if a triangle with 3 different lenght would be possible. x = int(input('Lenght a:')) y = int(input('Lenght b:')) z = int(input('Lenght c:')) def is_triangle(a, b, c): ab = a + b ac = a + c bc = b + c result = True if bc < a: result = False if ac < b: result = False if ab < c: result = False if result == True: print('possible triangle') if result == False: print('inpossible triangle') x = int(input('Lenght a:')) y = int(input('Lenght b:')) z = int(input('Lenght c:')) is_triangle(x, y, z) is_triangle(x, y, z)
10faff94628776074504921d378550b0e089ba2b
zsmountain/lintcode
/python/stack_queue_hash_heap/551_nested_list_weight_sum.py
1,869
4.09375
4
''' Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Have you met this question in a real interview? Example Example 1: Input: the list [[1,1],2,[1,1]], Output: 10. Explanation: four 1's at depth 2, one 2 at depth 1, 4 1 2 + 1 2 1 = 10 Example 2: Input: the list [1,[4,[6]]], Output: 27. Explanation: one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4 2 + 6 3 = 27 ''' """ This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation class NestedInteger(object): def isInteger(self): # @return {boolean} True if this NestedInteger holds a single integer, # rather than a nested list. def getInteger(self): # @return {int} the single integer that this NestedInteger holds, # if it holds a single integer # Return None if this NestedInteger holds a nested list def getList(self): # @return {NestedInteger[]} the nested list that this NestedInteger holds, # if it holds a nested list # Return None if this NestedInteger holds a single integer """ class Solution(object): # @param {NestedInteger[]} nestedList a list of NestedInteger Object # @return {int} an integer def depthSum(self, nestedList): # Write your code here return self.helper(nestedList, 1) def helper(self, nestedList, depth): sum = 0 for item in nestedList: if item.isInteger(): sum += depth * item.getInteger() else: sum += self.helper(item.getList(), depth + 1) return sum s = Solution() print(s.depthSum([[1, 1], 2, [1, 1]])) print(s.depthSum([1, [4, [6]]]))
ce105e7a1ef22746b05019c4b9d610072cd6b384
hxxtsxxh/codewithmosh-tutorials
/DisplayingCurrentTIme.py
352
3.5
4
# import time module import time import datetime # 24-hour format below print(time.strftime("%H:%M:%S")) # 12-hour format below print(time.strftime("%I:%M:%S")) # datetime module e = datetime.datetime.now() print(e.strftime("%Y-%m-%d %H:%M:%S")) print(e.strftime("%d/%m/%Y")) print(e.strftime("%I:%M:%S %p")) print(e.strftime("%a, %b %d, %Y"))
8d76e00de54a7d6c997ef7fe88ab0e6f86877957
stepc0re/TestRepo
/test.py
1,886
3.84375
4
import sys class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def Name(self): return self.firstname + " " + self.lastname # instead of Name ein __str__ , i say print x nicht x. Name, str wird automatisch benutzt def __str__(self): return self.firstname + " " + self.lastname class Employee(Person): def __init__(self, first, last, staffnum): super().__init__(first, last) self.staffnumber = staffnum def GetEmployee(self): return self.Name() + ", " + self.staffnumber x = Person("Marge", "Simpson") y = Employee("Homer", "Simpson", "1007") print(x.Name()) print(y.GetEmployee()) # # class Fahrzeug: # def __init__(self, rader, geschwindigkeit): # self.numrader = rader # self.speed = geschwindigkeit # # def Geschwindigkeit(self): # return self.speed # # class Motor(Fahrzeug): # def __init__(self, rader, geschwindigkeit, motor): # Fahrzeug.__init__(self, rader, geschwindigkeit) # self.kindofmotor = motor # # # def getmotor(self): # return self.numrader + self.speed # # x = Fahrzeug(4, 200) # y = Motor(2, 200, "diesel") # # print(x.numrader()) # print(y.getmotor()) class Person: def __init__(self, first, last, age): self.firstname = first self.lastname = last self.age = age def __str__(self): return self.firstname + " " + self.lastname + ", " + str(self.age) class Employee(Person): def __init__(self, first, last, age, staffnum): super().__init__(first, last, age) self.staffnumber = staffnum # overridden die str von Person class def __str__(self): return super().__str__() + ", " + self.staffnumber x = Person("Marge", "Simpson", 36) y = Employee("Homer", "Simpson", 28, "1007") print(x) print(y)
c73533c1987d9eaa6af0f200fb2ddb1651057c5c
kannyg87/python-
/Howmanycoins.py
279
3.953125
4
print('you have 0 coins') answer = input('Do you want another coins? ') answer = answer.lower() count = 0 while answer == 'yes': count +=1 print('you have %d coin' % count) answer = input('Do you want another coins? ') if answer == 'no': print ("Bye")
88cee63d41f55f998e096642a02abe8da7431db6
zhenyong97/leecode_learning
/question26删除排序数组的重复项/farmer_solution.py
426
3.609375
4
class Solution: def removeDuplicates(self, nums): for index, item in enumerate(nums): mark = nums.count(item) if mark == 1: pass else: for i in range(mark-1): nums.pop(index) return len(nums) if __name__ == '__main__': a = Solution() nums = [1,1,1,2,2,2,2,3,3,] a.removeDuplicates(nums) print(nums)
ee7fd8d1977b5c972c165c2474bce283a7cb4749
Darya1501/Python-course
/lesson-8/task-5.py
344
3.796875
4
# Произведение количества положительных и отрицательных чисел a = int(input()) count_positive = 0 count_negative = 0 while a != 0: if a < 0: count_negative += 1 if a > 0: count_positive += 1 a = int(input()) print(count_negative * count_positive)
66af88db005b6d4a24cf4595b897ba0edba2a111
Yuliya-Karuk/get-repo
/lesson04/easy_homework.py
1,900
3.890625
4
# Все задачи текущего блока решите с помощью генераторов списков! # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список, элементы которого будут # квадратами элементов исходного списка # [1, 2, 4, 0] --> [1, 4, 16, 0] import random lst_beg = [random.randint(-10, 10) for i in range(5)] lst_last = [(lambda i: i*i)(i) for i in lst_beg] print('Начальный список - ', lst_beg, 'Конечный список - ', lst_last) # Задание-2: # Даны два списка фруктов. # Получить список фруктов, присутствующих в обоих исходных списках. fruits = ["яблоко", "банан", "киви", "арбуз", "клубника", "слива", "черешня", "инжир", "хурма"] exotic_fruit = ["инжир", "маракуйа", "ананас", "хурма"] print('Список фруктов - ', fruits, '\nСписок экзотических фруктов - ', exotic_fruit) inter = [i for i in fruits if i in exotic_fruit] print('Фрукты в обоих списках', inter) # Задание-3: # Дан список, заполненный произвольными числами. # Получить список из элементов исходного, удовлетворяющих следующим условиям: # + Элемент кратен 3 # + Элемент положительный # + Элемент не кратен 4 original = [random.randint(-100, 100) for i in range(10)] last = [i for i in original if i >= 0 and i % 3 == 0 and i % 4 != 0] print('Начальный список', original, '\nКонечный список', last)
8fb17a5d1238afd46a7d87179467415ba82aaebc
brenj/solutions
/hacker-rank/python/data-types/sets.py
590
4.34375
4
# Sets Challenge """ You are given two set of integers M and N and you have to print their symmetric difference in ascending order. The first line of input contains value of M followed by M integers, then value of N followed by N integers. Symmetric difference between M and N mean those values which either exist in M or in N but not in both. """ raw_input() m = set(map(int, raw_input().split())) raw_input() n = set(map(int, raw_input().split())) # symmetric_difference = m.difference(n).union(n.difference(m)) for integer in sorted(list(m.symmetric_difference(n))): print integer
6cabf25b8c8c2de53e5254d2bfb758d26c3711fb
dogedogethedoge/NIM
/NIM/server.py
1,599
3.71875
4
# -*- coding: utf-8 -*- """This file contains the socket server used for the Expanding Nim game. It is a very simple implementation that has methods to wait for a player to move, update all players after each move, and establish connections. @author: Munir Contractor <mmc691@nyu.edu> """ import socket class Server(): """The socket server that maintains communication with the players""" DATA_SIZE = 1024 def __init__(self, host, port): """ Args: **host:** Host for the server\n **port:** Port to run the server on\n """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((host, port)) self.player_sockets = [None, None] self.socket.listen(2) def establish_connections(self): """Establishes connection with the players""" self.player_sockets[0], _ = self.socket.accept() self.player_sockets[1], _ = self.socket.accept() return [self.receive(0), self.receive(1)] def update_all_clients(self, data): """Updates all players by sending the data to the client sockets""" for sck in self.player_sockets: sck.sendall(data) def receive(self, player): """Receives a move from the specified player""" return self.player_sockets[player].recv(self.DATA_SIZE) def close(self): """Close the server""" self.socket.close() def __del__(self): self.close()
eabbb9ac482cce3474f42d1997105f80af389e96
cifpfbmoll/practica-6-python-fperi90
/P6ej10.py
1,454
4.3125
4
# Escribe un programa que te pida los nombres y notas de alumnos. Si escribes una nota fuera del intervalo de 0 a 10, # el programa entenderá que no quieres introducir más notas de este alumno. Si no escribes el nombre, el programa # entenderá que no quieres introducir más alumnos. Nota: La lista en la que se guardan los nombres y notas tiene # esta estructura [[nombre1, nota1, nota2, etc], [nombre2, nota1, nota2, etc], [nom3, nota1, nota2, etc], etc] # Dame un nombre: Héctor Quiroga # Escribe una nota: 4 # Escribe otra nota: 8.5 # Escribe otra nota: 12 # Dame otro nombre: Inés Valls # Escribe una nota: 7.5 # Escribe otra nota: 1 # Escribe otra nota: 2 # Escribe otra nota: -5 # Dame otro nombre: # Las notas de los alumnos son: # Héctor Quiroga: 4.0 - 8.5 # Inés Valls: 7.5 - 1.0 - 2.0 lista=[] auxiliar=[] nombre="A" while(nombre!=""): nombre=input("Dame un nombre: ") if(nombre!=""): lista.append(nombre) nota=float(input("Dame una nota: ")) while nota>=0 and nota<=10: lista.append(nota) nota=float(input("Dame una nota: ")) auxiliar.append(lista) lista=[] print("Las notas de los alumnos son: ")#por ahora he llegado hasta aqui, me falta averiguar el print for i in range(len(auxiliar)): print(auxiliar[i][0],": ",end="") for j in range(1,len(auxiliar[i])): print(" - ",auxiliar[i][j],end=" ") print("\n") print("finalizado")
5499fa55e3d9c618fb3af71bf07fbf766a44a76a
leinian85/year2019
/month01/code/day08/exercise07.py
746
3.84375
4
# 4. (扩展)方阵转置.(不用做成函数) # 提示:详见图片. list02 = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] list03 = [ [1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19] ] def phalanx_permute(list_phalanx): """ 方阵转置函数 :param list_phalanx: 二维列表方阵 :return: """ for i in range(len(list_phalanx) - 1): for j in range(i + 1, len(list_phalanx)): list_phalanx[i][j], list_phalanx[j][i] = list_phalanx[j][i], list_phalanx[i][j] phalanx_permute(list02) for item in list02: print(item) phalanx_permute(list03) for item in list03: print(item)
a3c179aec737de30cf872a8adc665d2f0e28a943
HeywoodKing/mytest
/MyPractice/tryexception.py
871
3.765625
4
# Filname:tryexception.py re = iter(range(5)) try: for i in range(100): print re.next() except StopIteration: print 'here is end ', i print 'hahahaha' #Ľṹ try: print "try" except exception1: print 'except exception1' except exception2: print 'except exception2' except: print 'except' else: print 'else' finally: print 'finally' try: print(a*2) except TypeError: print('TypeError') except: print('Not Type Error & Error noted') def test_func(): try: m = 1 / 0 except NameError: print('Catch NameError in the sub-function') try: test_func() except ZeroDivisionError: print('Catch error in the main program.') print 'hahhaaha' try: raise StopIteration except: print 'raise StopIteration' print 'HHHHHHaaa'
08d9cd21e4446e72ef308ce8890605f7d5aa6482
hajelav/programs
/affirm_coding_challenge/facilities/facility.py
1,907
3.703125
4
#! /bin/python import sys import csv import json from pprint import pprint import traceback ''' This function compares two dictionaries, returns True/False ''' def compareDict(dictOne,dictTwo): if((not dictOne) or (not dictTwo)): return False if(len(dictOne) != len(dictTwo)): return False for key in dictOne: if key not in dictTwo: return False return True ''' parse the facility schema json and convert it into dictionary ''' def loadFacilitySchema(fileName): facilitySchema = {} try: facilitySchema = json.load(open(fileName)) #pprint(facilitySchema) except: raise return facilitySchema ''' parses the Facilities.csv and stores it into csv. Other than storing the csv into list, we check if the schema of csv matches with the json config. This is done because, in future we may want to enhance the facilities, we need to update the jsonfile( where is schema is defined) ''' def getFacilitiesFromCsv(jsonConfig, csvFile): facilityList = [] try: with open(csvFile) as csvfile: dictReader = csv.DictReader(csvfile) schema = loadFacilitySchema(jsonConfig) for row in dictReader: if(compareDict(schema, row)): facilityList.append(row) else: print 'csv file doesnt match the schema %s' %traceback.format_exc() return facilityList except Exception as e: print 'error parsing facilities.csv %s' %traceback.format_exc() #sort the facility list , as we want to always pick the the cheapest loan if(facilityList): facilityList = sorted(facilityList, key=lambda k: float(k['interest_rate'])) return facilityList if __name__ == "__main__": print json.dumps(getFacilities("facilitySchema.json","facilities.csv"), indent=4)
7be20a8cf40acaee1cc86f66bf27a5cb52acd52e
HalfMoonFatty/Interview-Questions
/019. Remove Nth Node From End of List.py
863
3.84375
4
''' Problem: Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. ''' class Solution(object): def removeNthFromEnd(self, head, n): if not head: return None # make dummy head dummy = ListNode(0) dummy.next = head # both fast and slow from dummy head fast, slow = dummy, dummy # move the fast pointer n steps ahead for i in range(n): fast = fast.next while fast and fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return dummy.next
a689400c3523e0a5e4556203dee0273cb858b7bc
Aziz1Diallo/python
/factorial.py
809
3.625
4
'''agsag agsfga agfag ''' def facto(n): if n==0: return 1 else: return n * facto(n-1) def main0(): ''' gsousgj skj dsogsd adfkja; ''' print("0! = ",facto(0)) print("4! = ",facto(4)) def sum1(n): s=0 while n > 0: s += 1 n -= 1 return s val = 0 def sum2(): s=0 while val > 0: s += 1 val -= 1 return s def sum3(): s=0 for i in range(val, 0, -1): s += 1 return s def maina(): global val val = 5 print(sum1(input)) print(sum2()) print(sum3()) def main1(): global val val = 5 print(sum1(input)) print(sum3()) print(sum2()) def main2(): global val val = 5 print(sum2()) print(sum1(input)) print(sum3())
d705e943ee04147d7617ce491d814fb95f21d3d3
porregu/unit2
/yearsoftheuser.py
178
3.953125
4
name=input("what's your name ?") print(" that's a cool name") years=float(input("how old are you?")) old=(75-years) print(old) later=input("you will turn 75 in this many years ")
128ab9982f5a29fad4af13a9d6620b7e11b8ae03
gagankandel0/Insight_projects
/Python Assignment/Ques5.py
249
3.765625
4
def sample(str1): a='ing' b='ly' if len(str1)>=3: if str1[-3:]!='ing': result=str1+a else: result=str1+b else: return str1 return result print(sample('sw'))
7f633113313b2ab2ff55e199bab6b7eee786a7e7
daniel-reich/ubiquitous-fiesta
/GP8Tywnn2gucEfSMf_6.py
248
3.53125
4
def error(n): dict = {1 : "Check the fan", 2 : "Emergency stop", 3 : "Pump Error", 4 : "c", 5 : "Temperature Sensor Error"} if n >5 or n<1: return 101 else: return "{}: e{}".format(dict[n],n)
1f0a3d23fbbe700da1ef3e2c8c9f57845c1e5118
pavanmutyala3448/Bank_Managment_System_Python
/bms.py
3,597
3.828125
4
from random import * class User: def __init__(self,name,age,gender,address): self.name=name self.age=age self.gender=gender self.address=address def show_User_Details(self): print('\n') print('*** Personal Details ***') print('Name : ',self.name) print('Age : ', self.age) print('Gender : ', self.gender) print('Address : ', self.address) print('\n') class Bank(User): def __init__(self,name,age,gender,address): super().__init__(name,age,gender,address) self.balance=0 def Deposit(self,amount): self.amount=amount self.balance=self.balance+self.amount print('\n') print(self.amount,'Amount is Deposited , Your Account Balance is : ₹',self.balance) print('\n') def Withdrawal(self,amount): self.amount=amount if self.amount>self.balance: print('\n') print('Not Sufficient Balance In Your Account, Add More funds to withdrawal') print('\n') else: self.balance=self.balance-self.amount print('\n') print(self.amount,' is Withdrawal , Remaining Amount In Your Account is : ₹',self.balance) print('\n') def view_balance(self): if self.balance==0: print('\nYour Current balance is : ₹',self.balance) print('\nAdd Some Money To Your Account') else: self.show_User_Details() print('\nYour Current balance is : ₹', self.balance) def UpdateDetails(self,uname,uage): self.name=uname self.age=uage print('\nYour Data is Updated \n') self.show_User_Details() print('\n*** WELCOME TO BANK MANAGEMENT SYSTEM ***\n') print('*** Please Create an Account ***') Name=input('Enter Your Name :') Age=int(input('Enter Your Age :')) Gender=input('Enter Your Gender :') Address=input('Enter Your Address :') bank=Bank(Name,Age,Gender,Address) a=randint(1,10) print('** Verification Number **') print(a) print('** **') print('Enter the Number on screen to create your account') b=int(input('Enter Number ')) if b==a: print('Account is created') while True: if bank: print('To Do More Action with Your Account Choose the Below ,press the keys') print('1.See Details\n2.Deposit\n3.Withdrawal\n4.View balance\n5.Update Details\n 6.To Exit') n=int(input('Enter Your Choice:')) if n==1: bank.show_User_Details() elif n==2: print('\n** DEPOSIT SECTION **') amount=int(input('Enter Your Amount To deposit :')) bank.Deposit(amount) elif n==3: print('\n** WITHDRAWAL SECTION **') withdrawal_amount = int(input('Enter Your Amount To Withdrawal :')) bank.Withdrawal(withdrawal_amount ) elif n==4: bank.view_balance() elif n == 5: name=input('Enter Your Updated Name :') age = int(input('Enter Your Updated Age :')) bank.UpdateDetails(name,age) elif n==6: print('\nYou Are Exited From bank') print('\n*** THANK YOU VISIT AGAIN ***') break else: print('\nYou Are Exited From bank') print('\n*** THANK YOU VISIT AGAIN ***') break else: print('Error in Creating') else: print('Your Account is not created')
148a60fa3e06a3ece884814b23d5024a3e652cd7
Shauryayamdagni/IITM_python
/test2.py
124
3.8125
4
arr=[] brr=[1,2,3] arr.append(brr) arr.append(brr) arr.append(brr) print(arr) arr[2][0]=0 arr[2][1]=0 arr[2][2]=0 print(arr)
18d0042786d0f560deacfee70730d21e863a973f
luodiweiyu/GlyphClientPython
/pointwise/glyphapi/utilities.py
49,671
3.5
4
import numpy as np import math """ Utility classes that mimic the behavior of the Glyph pwu::* utilites. """ class GlyphUtility: tolerance = 1e-7 class Vector2(object): """ Utility functions for two dimensional vectors, which are represented as a list of two real values. """ def __init__(self, *args): """ Construct a 2D vector, all zeroes by default. """ self.vector_ = None if len(args) == 0: self.vector_ = np.zeros([2]) elif len(args) == 1: if isinstance(args[0], (list, tuple)) and len(args[0]) == 2: self.vector_ = np.array([float(i) for i in args[0]]) elif isinstance(args[0], np.ndarray): self.vector_ = args[0] elif isinstance(args[0], Vector2): self.vector_ = args[0].vector_ elif len(args) == 2: self.vector_ = np.array([float(i) for i in args]) if self.vector_ is None: raise ValueError("Invalid parameter %s" % str(args)) elif self.vector_.size != 2 or self.vector_.ndim != 1: raise ValueError("Vector2 must be a list/tuple of 2 values") def __eq__(self, other): """ Check for equality of two vectors """ return self.equal(other) def __add__(self, other): """ Add two vectors together and return the result as a new Vector2 """ return Vector2(np.add(tuple(self), tuple(other))) def __sub__(self, other): """ Subtract one vector from another and return the result as a new Vector2. """ return Vector2(np.subtract(tuple(self), tuple(other))) def __mul__(self, other): """ Multiply the components of a vector by either the components of another vector or a scalar and return the result as a new Vector2. """ if isinstance(other, (float, int)): other = (other, other) return Vector2(np.multiply(tuple(self), tuple(other))) def __truediv__(self, other): """ Divide the components of a vector by either the components of another vector or a scalar and return the result as a new Vector2. """ if isinstance(other, (float,int)): other = (other, other) return Vector2(np.true_divide(tuple(self), tuple(other))) def __div__(self, other): """ Divide the components of a vector by either the components of another vector or a scalar and return the result as a new Vector2. """ return self.__truediv__(other) def __str__(self): """ Return a string representation of a Vector2 """ return str(tuple(self)) def __iter__(self): return (e for e in self.vector_) def __len__(self): return len(self.vector_) def index(self, i): """ Return a component of a Vector2 """ return self.vector_[i] @property def x(self): """ The X component of a Vector2 """ return self.vector_[0] @x.setter def x(self, v): """ Set the X component of a Vector2 """ self.vector_[0] = v @property def y(self): """ The X component of a Vector2 """ return self.vector_[1] @y.setter def y(self, v): """ Set the Y component of a Vector2 """ self.vector_[1] = v def equal(self, other, tolerance=GlyphUtility.tolerance): """ Check for equality between two vectors within an optional tolerance """ return np.linalg.norm(np.subtract(tuple(self), tuple(other))) \ <= tolerance def notEqual(self, other, tolerance=GlyphUtility.tolerance): """ Check for inequality between two vectors within an optional tolerance """ return not self.equal(other, tolerance) def add(self, vec2): """ Add the components of two vectors and return the result as a new Vector2 """ return self + vec2 def subtract(self, vec2): """ Subtract one vector from another and return the result as a new Vector2 """ return self - vec2 def negate(self): """ Negate the component values and return the result as a new Vector2 """ return self * -1 def scale(self, scalar): """ Scale the component values by a scalar and return the result as a new Vector2 """ return self * scalar def divide(self, scalar): """ Divide the component values by a scalar and return the result as a new Vector2 """ return self / scalar def multiply(self, vec2): """ Multiply the component values of a vector by the component values of another vector and return the result as a new Vector2 """ return self * vec2 def dot(self, vec2): """ Return the scalar dot product of two vectors """ return np.dot(self.vector_, vec2.vector_) def normalize(self): """ Return the normalized form of a vector as a new Vector2 """ norm = np.linalg.norm(self.vector_) if norm == 0: raise ValueError('Vector is zero vector') else: return self / norm def length(self): """ Return the scalar length of a vector """ return np.linalg.norm(self.vector_) @staticmethod def minimum(vec1, vec2): """ Return the minimum components of two vectors as a new Vector2 """ return Vector2(np.minimum(tuple(vec1), tuple(vec2))) @staticmethod def maximum(vec1, vec2): """ Return the maximum components of two vectors as a new Vector2 """ return Vector2(np.maximum(tuple(vec1), tuple(vec2))) class Vector3(object): """ Utility functions for three dimensional vectors, which are represented as a list of three real values. """ def __init__(self, *args): """ Construct a 3D vector, all zeroes by default. """ self.vector_ = None if len(args) == 0: self.vector_ = np.zeros([3]) elif len(args) == 1: if isinstance(args[0], (list, tuple)) and len(args[0]) == 3: self.vector_ = np.array([float(i) for i in args[0]]) elif isinstance(args[0], np.ndarray): self.vector_ = args[0] elif isinstance(args[0], Vector3): self.vector_ = args[0].vector_ elif isinstance(args[0], Vector2): self.vector_ = args[0].vector_ self.vector_.append(0.0) elif len(args) == 3: self.vector_ = np.array([float(i) for i in args]) if self.vector_ is None: raise ValueError("Invalid parameter %s" % str(args)) elif self.vector_.size != 3 or self.vector_.ndim != 1: raise ValueError("Vector3 must be 3 float values") def __eq__(self, other): """ Check for equality of two vectors """ return self.equal(other) def __add__(self, other): """ Add two vectors together and return the result as a new Vector3. """ return Vector3(np.add(tuple(self), tuple(other))) def __sub__(self, other): """ Subtract one vector from another and return the result as a new Vector3. """ return Vector3(np.subtract(tuple(self), tuple(other))) def __mul__(self, other): """ Multiply the components of a vector by either the components of another vector or a scalar and return the result as a new Vector3. """ if isinstance(other, (float, int)): other = (other, other, other) return Vector3(np.multiply(self.vector_, tuple(other))) def __truediv__(self, other): """ Divide the components of a vector by either the components of another vector or a scalar and return the result as a new Vector3. """ if isinstance(other, (float, int)) and other != 0.0: return Vector3(1.0 / other * self.vector_) else: return np.true_divide(self.vector_, tuple(other)) def __div__(self, other): """ Divide the components of a vector by either the components of another vector or a scalar and return the result as a new Vector3. """ return self.__truediv__(other) def __str__(self): """ Return a string representation of a Vector3 """ return str(tuple(self)) def __iter__(self): return (e for e in self.vector_) def __len__(self): return len(self.vector_) def index(self, i): """ Return a component of a Vector3 """ return self.vector_[i] @property def x(self): """ The X component of a Vector3 """ return self.vector_[0] @x.setter def x(self, v): """ Set the X component of a Vector3 """ self.vector_[0] = v @property def y(self): """ The Y component of a Vector3 """ return self.vector_[1] @y.setter def y(self, v): """ Set the Y component of a Vector3 """ self.vector_[1] = v @property def z(self): """ The Z component of a Vector3 """ return self.vector_[2] @z.setter def z(self, v): """ Set the Z component of a Vector3 """ self.vector_[2] = v def equal(self, other, tolerance=GlyphUtility.tolerance): """ Check for equality between two vectors within an optional tolerance """ return np.linalg.norm(np.subtract(tuple(self), tuple(other))) \ <= tolerance def notEqual(self, other, tolerance=GlyphUtility.tolerance): """ Check for inequality between two vectors within an optional tolerance """ return not self.equal(other, tolerance) def add(self, other): """ Add the components of two vectors and return the result as a new Vector3 """ return self + other def subtract(self, other): """ Subtract one vector from another and return the result as a new Vector3 """ return self - other def negate(self): """ Negate the component values and return the result as a new Vector3 """ return self * -1.0 def scale(self, scalar): """ Scale the component values by a scalar and return the result as a new Vector3 """ return self * scalar def divide(self, scalar): """ Divide the component values by a scalar and return the result as a new Vector3 """ return self / scalar def multiply(self, scalar): """ Multiply the component values of a vector by the component values of another vector and return the result as a new Vector3 """ return self * scalar def cross(self, other): """ Return the cross product of two vectors as a new Vector3 """ return Vector3(np.cross(self.vector_, tuple(other))) def dot(self, other): """ Return the scalar dot product of two vectors """ return np.dot(self.vector_, tuple(other)) def normalize(self): """ Return the normalized form of a vector as a new Vector3 """ norm = np.linalg.norm(self.vector_) if norm == 0: raise ValueError('Vector is zero vector') else: return self / norm def length(self): """ Return the scalar length of a vector """ return np.linalg.norm(self.vector_) def distanceToLine(self, pt, direction): """ Return the scalar distance from a vector to a line defined by a point and direction. """ lineVec = Vector3(direction).normalize() ptVec = self - Vector3(pt) ptProj = lineVec * ptVec.dot(lineVec) return (ptVec - ptProj).length() @staticmethod def minimum(vec1, vec2): """ Return the minimum components of two vectors as a new Vector3 """ return Vector3(np.minimum(tuple(vec1), tuple(vec2))) @staticmethod def maximum(vec1, vec2): """ Return the maximum components of two vectors as a new Vector3 """ return Vector3(np.maximum(tuple(vec1), tuple(vec2))) @staticmethod def affine(scalar, vec1, vec2): """ Return a new Vector3 that is the affine combination of two vectors """ return Vector3(np.add( np.multiply(tuple(vec1), (scalar, scalar, scalar)), np.multiply(tuple(vec2), (1.0-scalar, 1.0-scalar, 1.0-scalar)))) @staticmethod def barycentric(pt, vec1, vec2, vec3, clamp=False): """ Return a new Vector3 that has the barycentric coordinates of the given point in the frame of the given three vectors. """ pt = Vector3(pt) v1 = Vector3(vec1) v2 = Vector3(vec2) v3 = Vector3(vec3) a = b = 0.0 v12 = v2 - v1 v13 = v3 - v1 cross = v12.cross(v13) area = 0.5 * cross.length() if area == 0.0: mode = 23 len12 = v12.length() len13 = v13.length() len23 = (v2 - v3).length() if len12 >= len13: if len12 >= len23: mode = 11 if len12 == 0.0 else 12 elif len13 >= len23: mode = 13 if mode == 12: a = (pt - v2).length() / len12 b = 1.0 - a elif mode == 13: a = (pt - v3).length() / len13 b = 0.0 elif mode == 23: a = 0.0 b = (pt - v3).legnth() / len23 else: # mode = 11 a = 1.0 b = 0.0 else: cross1 = (v2 - pt).cross(v3 - pt) a = 0.5 * cross1.length() / area if cross.dot(cross1) < 0.0: a = -a cross2 = (pt - v1).cross(v13) b = 0.5 * cross2.length() / area if cross.dot(cross2) < 0.0: b = -b a = 0.0 if clamp and a < 0.0 else a b = 0.0 if clamp and b < 0.0 else b b = 1.0 - a if clamp and (a + b) > 1.0 else b return Vector3((a, b, 1.0 - a - b)) class Quaternion(object): """ Utility functions for quaternions, which are represented as a list of four real values (x, y, z, and angle) """ def __init__(self, axis=(0.0, 0.0, 0.0), angle=0, _quat=None): """ Construct a quaternion, with a degenerate axis and zero angle by default """ if _quat is not None: self.quat_ = _quat # normalize self.quat_ /= np.sqrt(sum(k*k for k in self.quat_)) self.angle_ = np.degrees(np.arccos(self.quat_[0]) * 2) self.axis_ = Vector3(self.quat_[1:4]) self.axis_ = self.axis_ / np.sin(np.radians(self.angle_ / 2)) elif len(axis) == 3: if not isinstance(axis, Vector3): axis = Vector3(axis) if axis.length() == 0.0 or angle == 0.0: self.quat_ = (1.0, 0.0, 0.0, 0.0) self.angle_ = 0.0 self.axis_ = axis else: length = axis.length() # clamp the angle between -2*pi and +2*pi while angle < -360.0: angle += 360.0 while angle > 360.0: angle -= 360.0 if angle == 90.0 or angle == -270.0: w = math.sqrt(0.5) u = w / length elif angle == 180.0 or angle == -180.0: w = 0.0 u = 1.0 / length elif angle == -90.0 or angle == 270.0: w = math.sqrt(0.5) u = -w / length else: angle = angle / 2.0 w = np.cos(np.radians(angle)) u = np.sin(np.radians(angle)) / length # normalize, since that's what Glyph does self.quat_ = (w, u*axis.x, u*axis.y, u*axis.z) self.quat_ /= np.sqrt(sum(k*k for k in self.quat_)) angleRadians = np.arccos(w) * 2.0 self.angle_ = np.degrees(angleRadians) self.axis_ = Vector3(self.quat_[1:4]) / np.sin(angleRadians/2.0) else: raise ValueError("Invalid parameter") if len(self.quat_) != 4: raise ValueError("Quaternion must be list/tuple of 4 values") def __mul__(self, other): """ Return the quaternion product of two quaternions as a new Quaternion """ if isinstance(other, (float, int)): return Quaternion(_quat=(self.quat_ * other)) else: w0, x0, y0, z0 = self.quat_ w1, x1, y1, z1 = other.quat_ quatProduct = np.array( [w1*w0 - x1*x0 - y1*y0 - z1*z0, \ w1*x0 + x1*w0 + y1*z0 - z1*y0, \ w1*y0 + y1*w0 + z1*x0 - x1*z0, \ w1*z0 + z1*w0 + x1*y0 - y1*x0]) return Quaternion(_quat=quatProduct) def __truediv__(self, other): """ Return the quaternion divided by a scalar as a new Quaternion """ other = (other, other, other, other) return Quaternion(_quat=(np.true_divide(self.quat_, other))) def __div__(self, other): return self.__truediv__(other) def __str__(self): """ Return the string form of a Quaternion as axis and angle """ return "(%s, %f)" % (str(tuple(self.axis_)), self.angle_) def __iter__(self): return (e for e in (tuple(self.axis_) + (self.angle_,))) @property def axis(self): """ Return the rotation axis of a quaternion as a Vector3 """ return self.axis_ @property def angle(self): """ Return the scalar rotation angle in degrees """ return self.angle_ def equal(self, quat2): """ Compare two quaternions for equality """ return np.array_equal(self.quat_, quat2.quat_) def notEquals(self, quat2): """ Compare two quaternions for inequality """ return not self.equal(quat2) def rotate(self, quat2): """ Rotate a quaternion by another quaternion and return the result as a new Quaternion """ return self * quat2 def conjugate(self): """ Return the conjugate of a quaternion as a new Quaternion """ return Quaternion(_quat=np.append(self.quat_[0], -1 * self.quat_[1:4])) def norm(self): """ Return the scalar normal for a quaternion """ return np.linalg.norm(self.quat_) def inverse(self): """ Return the inverse of a quaternion as a new Quaternion """ conj = self.conjugate().quat_ norm2 = np.square(self.norm()) return Quaternion(_quat=(conj / norm2)) def normalize(self): """ Return the normalized version of a quaternion as a new Quaternion. Note: When constructed with an arbitrary axis and angle, a Quaternion is already normalized by default. """ return self / self.norm() def asTransform(self): """ Compute and return a rotation Transform from a quaternion. This produces an exact Cartesian transformation when a quaternion axis is aligned with a Cartesian axis. """ w, x, y, z = self.quat_ q = x * x + y * y + z * z + w * w s = (2.0 / q) if q > 0.0 else 0.0 xs = x * s ys = y * s zs = z * s wx = w * xs wy = w * ys wz = w * zs xx = x * xs xy = x * ys xz = x * zs yy = y * ys yz = y * zs zz = z * zs m = np.zeros([16]) # In Glyph order # If along a Cartesian axis, snap to -1, 0, and 1 if within tolerance if (x == 0.0 and y == 0.0) or (x == 0.0 and z == 0.0) or \ (y == 0.0 and z == 0.0): m[ 0] = _clamp(1.0 - (yy + zz), 1.0, -1.0, 1e-15) m[ 1] = _clamp(xy + wz, 1.0, -1.0, 1e-15) m[ 2] = _clamp(xz - wy, 1.0, -1.0, 1e-15) m[ 3] = 0.0 m[ 4] = _clamp(xy - wz, 1.0, -1.0, 1e-15) m[ 5] = _clamp(1.0 - (xx + zz), 1.0, -1.0, 1e-15) m[ 6] = _clamp(yz + wx, 1.0, -1.0, 1e-15) m[ 7] = 0.0 m[ 8] = _clamp(xz + wy, 1.0, -1.0, 1e-15) m[ 9] = _clamp(yz - wx, 1.0, -1.0, 1e-15) m[10] = _clamp(1.0 - (xx + yy), 1.0, -1.0, 1e-15) m[11] = 0.0 m[12] = 0.0 m[13] = 0.0 m[14] = 0.0 m[15] = 1.0 else: m[ 0] = 1.0 - (yy + zz) m[ 1] = xy + wz m[ 2] = xz - wy m[ 3] = 0.0 m[ 4] = xy - wz m[ 5] = 1.0 - (xx + zz) m[ 6] = yz + wx m[ 7] = 0.0 m[ 8] = xz + wy m[ 9] = yz - wx m[10] = 1.0 - (xx + yy) m[11] = 0.0 m[12] = 0.0 m[13] = 0.0 m[14] = 0.0 m[15] = 1.0 # Python order m = m.reshape((4,4)).transpose() return Transform(m) class Plane(object): """ Utility functions for infinite planes, which are represented as a list of four plane coefficient values. """ def __init__(self, **kargs): if len(kargs) == 1 and 'coeffs' in kargs: coeffs = kargs['coeffs'] if not isinstance(coeffs, (list, tuple)) or len(coeffs) != 4: raise ValueError("Coefficients must be a list of 4 values") self.normal_ = Vector3(coeffs[0:3]).normalize() self.d_ = coeffs[3] elif len(kargs) == 2 and set(kargs.keys()) == set(('normal', 'origin')): self.normal_ = Vector3(kargs['normal']).normalize() self.d_ = self.normal_.dot(Vector3(kargs['origin'])) elif len(kargs) == 3 and set(kargs.keys()) == set(('p1', 'p2', 'p3')): v0 = Vector3(kargs['p1']) v1 = Vector3(kargs['p2']) v2 = Vector3(kargs['p3']) self.normal_ = (((v1 - v0).normalize()).cross( (v2 - v0).normalize())).normalize() self.d_ = self.normal_.dot(v0) elif len(kargs) == 4 and set(kargs.keys()) == set(('A', 'B', 'C', 'D')): self.normal_ = \ Vector3((kargs['A'], kargs['B'], kargs['C'])).normalize() self.d_ = kargs['D'] else: raise ValueError('Plane must be initialized with coefficient ' + 'list, point and normal, three points (p1, p2, p3), or ' + 'coefficients (A, B, C, D)') def __iter__(self): return (e for e in (tuple(self.normal_) + (self.d_,))) def __str__(self): """ Return the string form of a plane represented as a tuple of the four plane coefficients """ return str(tuple(self)) def equation(self): """ Return the plane equation as tuple of the four plane coefficients """ return tuple(self) @property def A(self): """ Return the A plane coefficient """ return self.normal_.vector_[0] @property def B(self): """ Return the B plane coefficient """ return self.normal_.vector_[1] @property def C(self): """ Return the C plane coefficient """ return self.normal_.vector_[2] @property def D(self): """ Return the D plane coefficient """ return self.d_ def normal(self): """ Return the plane normal as a tuple """ return tuple(self.normal_) def constant(self): """ Return the scalar plane constant """ return self.d_ def inHalfSpace(self, vec): """ Check if a point is in the positive half space of a plane """ return self.normal_.dot(Vector3(vec)) >= self.d_ def distance(self, vec): """ Return the positive scalar distance of a point to a plane """ return math.fabs(self.normal_.dot(Vector3(vec)) - self.d_) def line(self, origin, direction): """ Return the intersection of a line represented as a point and distance to a plane. If the line does not intersect the plane, an exception is raised. """ if not isinstance(origin, Vector3): origin = Vector3(origin) if not isinstance(direction, Vector3): direction = Vector3(direction).normalize() den = self.normal_.dot(direction) if den < 1e-10 and den > -1e-10: raise ValueError("Line does not intersect plane") s = (self.d_ - self.normal_.dot(origin)) / den return origin + direction * s def segment(self, p1, p2): """ Return the intersection of a line represented as two points to a plane as a new Vector3. If the segment does not intersect the plane, an exception is raised. """ if not isinstance(p1, Vector3): p1 = Vector3(p1) if not isinstance(p2, Vector3): p2 = Vector3(p2) ndp1 = self.normal_.dot(p1) ndp2 = self.normal_.dot(p2) if ((ndp1 < self.d_ and ndp2 < self.d_) or \ (ndp1 > self.d_ and ndp2 > self.d_)): raise ValueError("Segment does not intersect plane") return self.line(p1, tuple(p2 - p1)) def project(self, pt): """ Return the closest point projection of a point onto a plane as a new Vector3 """ if not isinstance(pt, Vector3): pt = Vector3(pt) return pt + self.normal_ * (self.d_ - pt.dot(self.normal_)) class Extents(object): """ Utility functions for extent boxes, which are represented as a list of two vectors (the min and max of the box). """ def __init__(self, *args): """ Construct an extent box with the given min/max or None. Extents((xmin, ymin, zmin), (xmax, ymax, zmax)) Extents(Vector3, Vector3) Extents(xmin, ymin, zmin, xmax, ymax, zmax) """ self.box_ = None if len(args) == 1: if isinstance(args[0], Extents): self.box_ = args[0].box_ else: self.box_ = np.array(args[0]) elif len(args) == 2: if isinstance(args[0], Vector3) and isinstance(args[1], Vector3): self.box_ = np.array([args[0].vector_, args[1].vector_]) elif isinstance(args[0], (list, tuple, np.ndarray)) and \ isinstance(args[1], (list, tuple, np.ndarray)): self.box_ = np.array([args[0], args[1]]) else: raise ValueError("Invalid argument %s" % str(args)) elif len(args) == 3: self.box_ = np.array([args, args]) elif len(args) == 6: self.box_ = np.array(args) self.box_.shape = [2,3] elif len(args) != 0: raise ValueError("Invalid argument %s" % str(args)) if self.box_ is not None: if self.box_.size == 3 and self.box_.ndim == 1: self.box_ = np.array([self.box_, self.box_]) if self.box_.size != 6 or self.box_.ndim != 2: raise ValueError("Extent box must be 2x3 matrix") elif not np.less_equal(self.box_[0], self.box_[1]).all(): raise ValueError("Min must be less than or equal to Max") def __repr__(self): return str(self.box_) def __iter__(self): if self.box_ is not None: return (e for e in self.box_.flatten()) def __eq__(self, other): """ Check for equality of two extent boxes """ if self.box_ is not None: try: return np.array_equal(self.box_, other.box_) except: return np.array_equal(self.box_, other) else: return False def minimum(self): """ Return the minimum corner point of an extent box """ return self.box_[0] def maximum(self): """ Return the maximum corner point of an extent box """ return self.box_[1] def isEmpty(self): """ Check if an extent box is empty """ return self.box_ is None def diagonal(self): """ Return the length of the diagonal of an extent box """ if self.box_ is not None: return np.linalg.norm(self.box_[0] - self.box_[1]) else: return 0.0 def enclose(self, pt): """ Return a new Extents that encloses the given point """ if isinstance(pt, Vector3): pt = pt.vector_ if self.box_ is None: return Extents([np.array(pt), np.array(pt)]) else: return Extents([np.minimum(self.box_[0], pt), np.maximum(self.box_[1], pt)]) def expand(self, value): """ Return a new Extents box that is expanded by the given amount at both minimum and maximum corners """ return Extents([self.box_[0] - value, self.box_[1] + value]) def isIntersecting(self, other): """ Return true if two extent boxes intersect or share a corner, edge or face """ if isinstance(other, (list, tuple)): other = Extents(other) elif not isinstance(other, Extents): raise ValueError("Invalid argument") elif self.box_ is None: return False return (max(self.box_[0, 0], other.box_[0, 0]) <= \ min(self.box_[1, 0], other.box_[1, 0])) and \ (max(self.box_[0, 1], other.box_[0, 1]) <= \ min(self.box_[1, 1], other.box_[1, 1])) and \ (max(self.box_[0, 2], other.box_[0, 2]) <= \ min(self.box_[1, 2], other.box_[1, 2])) def isInside(self, pt, tol=0.0): """ Return true if a point is within an extent box, within an optional tolerance """ if self.box_ is None: return False pt = tuple(pt) return (self.box_[0, 0] + tol) <= pt[0] and \ (self.box_[1, 0] - tol) >= pt[0] and \ (self.box_[0, 1] + tol) <= pt[1] and \ (self.box_[1, 1] - tol) >= pt[1] and \ (self.box_[0, 2] + tol) <= pt[2] and \ (self.box_[1, 2] - tol) >= pt[2] def translate(self, offset): """ Return a new Extents object that is translated by the given offset """ if self.box_ is None: raise ValueError("Self is empty") elif isinstance(offset, Vector3): offset = tuple(offset) return Extents([np.add(self.box_[0], tuple(offset)), np.add(self.box_[1], tuple(offset))]) def rotate(self, quat): """ Return a new Extents object that is rotated by the given Quaternion """ if self.box_ is None: raise ValueError("Self is empty") elif not isinstance(quat, Quaternion): raise ValueError("quat is not a Quaternion") xform = quat.asTransform() result = Extents() obox = self.box_ for i in (0,1): for j in (0,1): for k in (0,1): p = xform.apply((obox[i, 0], obox[j, 1], obox[k, 2])) result = result.enclose(p) return result class Transform(object): """ Utility functions for transform matrices, which are represented as a list of sixteen real values. The matrix is represented in a column-first order, which matches the order used in Glyph. """ @staticmethod def identity(): """ Return an identity Transform """ return Transform(list(np.eye(4))) def __init__(self, matrix=None): """ Construct a Transform from an optional set of 16 real values. If an argument is not supplied, set to the identity matrix. """ if matrix is None: self.xform_ = Transform.identity().xform_ return elif isinstance(matrix, Quaternion): self.xform_ = matrix.asTransform().xform_ return elif isinstance(matrix, Transform): self.xform_ = matrix.xform_ return elif isinstance(matrix, np.matrix): self.xform_ = matrix.A return elif isinstance(matrix, np.ndarray): self.xform_ = matrix if matrix.size == 16: self.xform_ = self.xform_.reshape((4,4)) return elif not isinstance(matrix, (list, tuple)): raise ValueError("Invalid argument") # Assume that the incoming transformation matrix is in Glyph order # (column-first), and transpose to row-first for mathematical # operations if len(matrix) == 4: # Assume a list/tuple of 4 lists/tuples self.xform_ = np.array(matrix).transpose() elif len(matrix) == 16: self.xform_ = np.array(matrix).reshape((4,4)).transpose() else: raise ValueError("Invalid xform matrix") def __eq__(self, other): """ Compare equality of two transforms """ if isinstance(other, Transform): return np.array_equal(self.xform_, other.xform_) elif isinstance(other, (list, tuple, np.matrix, np.ndarray)): return np.array_equal(self.xform_, Transform(other).xform_) else: raise ValueError("Invalid argument") def __str__(self): """ Return the string representation of a Transform, as a one- dimensional array of floats in column-wise order """ return str(tuple(self)) def __iter__(self): # account for transposed glyph notation return (e for e in self.xform_.transpose().flatten()) @property def matrix(self): return list(self) @staticmethod def translation(offset): """ Return a new Transform that is a translation by the given offset """ return Transform.identity().translate(offset) def translate(self, offset): """ Return a new Transform that adds translation to an existing Transform """ if not isinstance(offset, Vector3): offset = Vector3(offset) col = np.dot(self.xform_, np.array(tuple(offset.vector_) + (1.0,))) xf = np.array(self.xform_) np.put(xf, [3, 7, 11, 15], col) return Transform(xf) @staticmethod def rotation(axis, angle, anchor=None): """ Return a new Transform that is a rotation by the given angle about the given axis at the (optional) given anchor point """ return Transform.identity().rotate(axis, angle, anchor) def rotate(self, axis, angle, anchor=None): """ Return a new Transform that adds rotation to a Transform by the given angle about the given axis at the (optional) given anchor point """ if not isinstance(axis, Vector3): axis = Vector3(axis) if anchor is not None: if not isinstance(anchor, Vector3): anchor = Vector3(anchor) axform = Transform.translation(anchor) axform = axform.rotate(axis, angle) axform = axform.translate(Vector3()-anchor) return Transform(np.dot(self.xform_, axform.xform_)) # handle Cartesian rotations cartesian = False if axis.x == 0.0 and axis.y == 0.0: # Axis is 0 0 Z cartesian = True ct1 = 0 ct2 = 5 pst = 1 nst = 4 if axis.z > 0.0: angle = -angle elif axis.x == 0.0 and axis.z == 0.0: # Axis is 0 Y 0 cartesian = True ct1 = 0 ct2 = 10 pst = 2 nst = 8 if axis.y < 0.0: angle = -angle elif axis.y == 0.0 and axis.z == 0.0: # Axis X 0 0 cartesian = True ct1 = 5 ct2 = 10 pst = 9 nst = 6 if axis.x < 0.0: angle = -angle if cartesian: absAngle = math.fmod(math.fabs(angle), 360.0) if absAngle == 90.0: ca = 0.0 sa = 1.0 elif absAngle == 180.0: ca = -1.0 sa = 0.0 elif absAngle == 270.0: ca = 0.0 sa = -1.0 else: ca = math.cos(math.radians(absAngle)) sa = math.sin(math.radians(absAngle)) if angle < 0.0: sa = -sa mat = np.eye(4).flatten() mat[ct1] = ca mat[nst] = -sa mat[pst] = sa mat[ct2] = ca rxform = Transform(mat) else: rxform = Quaternion(axis, angle).asTransform() return Transform(np.dot(self.xform_, rxform.xform_)) @staticmethod def scaling(scale, anchor=None): """ Return a new Transform that is a scale by the given factor (which can be a scalar or a three-dimensional vector) about an optional anchor point """ return Transform.identity().scale(scale, anchor) def scale(self, scale, anchor=None): """ Return a new Transform that adds scaling to a Transform by the given factor (which can be a scalar or a three- dimensional vector) about an optional anchor point """ if isinstance(scale, (float, int)): scale = ((float(scale), float(scale), float(scale))) else: scale = tuple(scale) if anchor is not None: if not isinstance(anchor, Vector3): anchor = Vector3(anchor) axform = Transform.translation(anchor) axform = axform.scale(scale) axform = axform.translate(Vector3()-anchor) return Transform(np.dot(self.xform_, axform.xform_)) # transpose to make slicing easier xf = self.xform_.transpose() xf[0][0:3] = np.multiply(xf[0][0:3], scale) xf[1][0:3] = np.multiply(xf[1][0:3], scale) xf[2][0:3] = np.multiply(xf[2][0:3], scale) xf = xf.transpose() return Transform(xf) @staticmethod def calculatedScaling(anchor, start, end, tol=0.0): """ Return a transform matrix that scales a given point from one location to another anchored at a third point """ if isinstance(anchor, (list, tuple)): anchor = Vector3(anchor) if isinstance(start, (list, tuple)): start = Vector3(start) if isinstance(end, (list, tuple)): end = Vector3(end) fac = Vector3() da0 = start - anchor da1 = end - anchor fac.x = 1.0 if math.fabs(da0.x) < tol else (da1.x / da0.x) fac.y = 1.0 if math.fabs(da0.y) < tol else (da1.y / da0.y) fac.z = 1.0 if math.fabs(da0.z) < tol else (da1.z / da0.z) end1 = ((start - anchor) * fac) + anchor da1 = end1 - anchor fac.x = 1.0 if math.fabs(da0.x) < tol else (da1.x / da0.x) fac.y = 1.0 if math.fabs(da0.y) < tol else (da1.y / da0.y) fac.z = 1.0 if math.fabs(da0.z) < tol else (da1.z / da0.z) return Transform.scaling(fac, anchor) @staticmethod def ortho(left, right, bottom, top, near, far): """ Return an orthonormal view Transform from a view frustum """ if (left == right): raise ValueError("left and right plane constants cannot be equal") if (bottom == top): raise ValueError("bottom and top plane constants cannot be equal") if (near == far): raise ValueError("near and far plane constants cannot be equal") irml = 1.0 / (right - left) itmb = 1.0 / (top - bottom) ifmn = 1.0 / (far - near) mat = np.eye(4).flatten() # these are in Python order mat[0] = 2.0 * irml mat[5] = 2.0 * itmb mat[10] = -2.0 * ifmn mat[3] = -(right + left) * irml mat[7] = -(top + bottom) * itmb mat[11] = -(far + near) * ifmn return Transform(mat) @staticmethod def perspective(left, right, bottom, top, near, far): """ Return a perspective view Transform from a view frustum """ if (left == right): raise ValueError("left and right plane constants cannot be equal") if (bottom == top): raise ValueError("bottom and top plane constants cannot be equal") if (near == far): raise ValueError("near and far plane constants cannot be equal") irml = 1.0 / (right - left) itmb = 1.0 / (top - bottom) ifmn = 1.0 / (far - near) mat = np.zeros([16]) # these are in Glyph order mat[0] = 2.0 * near * irml mat[5] = 2.0 * near * itmb mat[8] = (right + left) * irml mat[9] = (top + bottom) * itmb mat[10] = -(far + near) * ifmn mat[11] = -1.0 mat[14] = -2.0 * far * near * ifmn # Python order mat = mat.reshape((4,4)).transpose() return Transform(mat) @staticmethod def mirroring(normal, distance): """ Return a new Transform that mirrors about a plane given by a normal vector and a scalar distance """ return Transform.identity().mirror(normal, distance) @staticmethod def mirrorPlane(plane): """ Return a new Transform that mirrors about a given plane """ return Transform.identity().mirror(plane.normal_, plane.d_) def mirror(self, normal, distance): """ Return a new Transform that adds mirroring about a plane given by a normal vector and a scalar distance """ if not isinstance(normal, Vector3): normal = Vector3(normal) normal = normal.normalize() # These are in Glyph order mat = np.zeros([16]) mat[ 0] = 1.0 - 2.0 * normal.x * normal.x mat[ 1] = -2.0 * normal.y * normal.x mat[ 2] = -2.0 * normal.z * normal.x mat[ 3] = 0.0 mat[ 4] = -2.0 * normal.x * normal.y mat[ 5] = 1.0 - 2.0 * normal.y * normal.y mat[ 6] = -2.0 * normal.z * normal.y mat[ 7] = 0.0 mat[ 8] = -2.0 * normal.x * normal.z mat[ 9] = -2.0 * normal.y * normal.z mat[10] = 1.0 - 2.0 * normal.z * normal.z mat[11] = 0.0 mat[12] = 2.0 * normal.x * distance mat[13] = 2.0 * normal.y * distance mat[14] = 2.0 * normal.z * distance mat[15] = 1.0 # transpose back to Python order mat = mat.reshape((4,4)).transpose() return Transform(np.dot(self.xform_, mat)) @staticmethod def stretching(anchor, start, end): """ Return a new Transform that is a stretching transform. If the vector defined by the start and end points is orthogonal to the vector defined by the start and anchor points, the transform is undefined and the matrix will be set to the identity matrix. """ return Transform.identity().stretch(anchor, start, end) def stretch(self, anchor, start, end): """ Return a new Transform that adds stretching to a Transform. If the vector defined by the start and end points is orthogonal to the vector defined by the start and anchor points, the transform is undefined and the matrix will be set to the identity matrix. """ if not isinstance(anchor, Vector3): anchor = Vector3(anchor) if not isinstance(start, Vector3): start = Vector3(start) if not isinstance(end, Vector3): end = Vector3(end) aToStart = start - anchor aToEnd = end - anchor sDir = (end - start).normalize() if math.fabs(aToStart.normalize().dot(sDir)) >= 0.01: factor = (aToEnd.dot(sDir) / aToStart.dot(sDir)) - 1.0 # These are in Glyph order mat = np.eye(4).flatten() mat[ 0] = factor * sDir.x * sDir.x mat[ 1] = factor * sDir.y * sDir.x mat[ 2] = factor * sDir.z * sDir.x mat[ 4] = factor * sDir.x * sDir.y mat[ 5] = factor * sDir.y * sDir.y mat[ 6] = factor * sDir.z * sDir.y mat[ 8] = factor * sDir.x * sDir.z mat[ 9] = factor * sDir.y * sDir.z mat[10] = factor * sDir.z * sDir.z # transpose back to Python order to apply translation mat = mat.reshape((4,4)).transpose() axform = Transform.translation(Vector3()-anchor) mat = np.dot(mat, axform.xform_) axform = Transform.translation(anchor) mat = np.dot(axform.xform_, mat) # Glyph order mat = mat.transpose().flatten() # mat = np.ravel(mat) mat[ 0] += 1.0 mat[ 5] += 1.0 mat[10] += 1.0 mat[12] -= anchor.x mat[13] -= anchor.y mat[14] -= anchor.z # Python order mat = mat.reshape((4,4)).transpose() return Transform(np.dot(self.xform_, mat)) else: return Transform(self.xform_) def apply(self, vec): """ Return a new Vector3 that is transformed from a given point """ # apply transform to a point if not isinstance(vec, Vector3): vec = Vector3(vec) rw = np.array(tuple(vec.vector_) + (1.0,)) rw = np.dot(self.xform_, rw) vec = np.array(rw[0:3]) if rw[3] != 0.0: vec = vec / rw[3] return Vector3(vec) def applyToDirection(self, direct): """ Return a a new Vector3 that is a transformed direction vector. This differs from apply as follows: When transforming a point by a 4x4 matrix, the point is represented by a vector with X, Y, and Z as the first 3 components and 1 as the fourth component. This allows the point to pick up any translation component in the matrix. This method represents the direction as a vector with 0 as the fourth component. Since a direction can be thought of as the difference between two points, a zero fourth component is the difference between two points that have 1 as the fourth component. """ # apply transform to a direction vector, as opposed to a point if not isinstance(direct, Vector3): direct = Vector3(direct) rw = np.array(tuple(direct.vector_) + (0.0,)) rw = np.dot(self.xform_, rw) direct = np.array(rw[0:3]) if rw[3] != 0.0: direct = direct / rw[3] return Vector3(direct) def applyToNormal(self, normal): """ Return a new Vector3 that is a transformed normal vector. A normal vector is transformed by multiplying the normal by the transposed inverse matrix. """ if not isinstance(normal, Vector3): normal = Vector3(normal) rw = np.array(tuple(normal.vector_) + (0.0,)) rw = np.dot(np.linalg.inv(self.xform_).transpose(), rw) normal = np.array(rw[0:3]) return Vector3(normal).normalize() def applyToPlane(self, plane): """ Return a new Plane that is transformed plane """ o = self.apply(plane.project((0, 0, 0))) n = self.applyToNormal(plane.normal_) return Plane(origin=o, normal=n) def __mul__(self, other): """ Return a the multiplication of self and either another Transform (a new Transform) or a Vector3 (a new, transformed Vector3) """ if isinstance(other, Vector3): return self.apply(other) elif isinstance(other, Transform): return Transform(np.dot(self.xform_, other.xform_)) else: raise ValueError("Invalid argument") def multiply(self, other): """ Return a new Transform that is the multiplication of self and another Transform. This is equivalent to 'self * other'. """ if isinstance(other, Transform): return self * other else: raise ValueError("Invalid argument") def determinant(self): """ Return the scalar determinant of the transformation matrix """ return np.linalg.det(self.xform_) def transpose(self): return Transform(self.xform_.transpose()) def inverse(self): return Transform(np.linalg.inv(self.xform_)) def _clamp(v, high, low, tol=0.0): """ Clamp a value to a range, or zero if within tolerance """ if v > high-tol: return high elif v < low+tol: return low elif v > -tol and v < tol: return 0.0 else: return v
5c51e6c96682225a208ed221f2b23681b1d1add8
coderplug/adventofcode2018
/day4/2/script.py
5,897
3.71875
4
from datetime import datetime, timedelta def input(filename): with open(filename, "r", encoding="utf-8") as f_in: lines = f_in.read().splitlines() return lines def parse_entries(entries): parsed_entries = [] for entry in entries: parts = entry.split(" ") date_parts = parts[0].split("-") year = int(date_parts[0][1:]) month = int(date_parts[1]) day = int(date_parts[2]) time_parts = parts[1].split(":") hour = int(time_parts[0]) minute = int(time_parts[1][:-1]) action_parts = parts[2:] entry = Entry(year, month, day, hour, minute, action_parts) parsed_entries.append(entry) return parsed_entries class Entry: def __init__(self, year, month, day, hour, minute, action): self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.action = action def __repr__(self): return "[{}-{}-{} {}:{}] {}".format(self.year, self.month, self.day, self.hour, self.minute, ' '.join(self.action)) def __str__(self): return "[{}-{}-{} {}:{}] {}".format(self.year, self.month, self.day, self.hour, self.minute, ' '.join(self.action)) def get_date(self): return datetime(self.year, self.month, self.day, self.hour, self.minute) def sort_entries(unsorted_entries): sorted_entries = entries_merge_sort(unsorted_entries) return sorted_entries def entries_merge_sort(unsorted_list): list_length = len(unsorted_list) if list_length > 1: sorted_list = [] #Divide: Divide the n-element sequence to be sorted into two subsequences of n=2 # elements each. middle = list_length // 2 left_half = unsorted_list[:middle] right_half = unsorted_list[middle:] #Conquer: Sort the two subsequences recursively using merge sort. sorted_left_half = entries_merge_sort(left_half) sorted_right_half = entries_merge_sort(right_half) left_index = 0 right_index = 0 #Combine: Merge the two sorted subsequences to produce the sorted answer. while len(sorted_list) != list_length: left_entry = sorted_left_half[left_index] right_entry = sorted_right_half[right_index] left_time = datetime(left_entry.year, left_entry.month, left_entry.day, left_entry.hour, left_entry.minute) right_time = datetime(right_entry.year, right_entry.month, right_entry.day, right_entry.hour, right_entry.minute) if left_time > right_time: sorted_list.append(right_entry) right_index += 1 else: sorted_list.append(left_entry) left_index += 1 if left_index == len(sorted_left_half): sorted_list.extend(sorted_right_half[right_index:]) elif right_index == len(sorted_right_half): sorted_list.extend(sorted_left_half[left_index:]) return sorted_list else: return unsorted_list def find_guards_list(entries): mode = 0 current_guard = None sleep = None wake = None shift_starts = None shift_ends = None guard_list = [] for entry in entries: if entry.action[0] == "Guard" and entry.action[2] == "begins" and entry.action[3] == "shift": if current_guard is not None: shift_ends = entry.get_date() current_guard.shifts.append((shift_starts, shift_ends)) guard_id = int(entry.action[1][1:]) current_guard = find_guard(guard_list, guard_id) if current_guard is None: current_guard = Guard(guard_id) guard_list.append(current_guard) shift_starts = entry.get_date() elif entry.action[0] == "falls" and entry.action[1] == "asleep": sleep = entry.minute elif entry.action[0] == "wakes" and entry.action[1] == "up": wake = entry.minute current_guard.sleep_time.append((sleep, wake)) return guard_list def find_guard(guard_list, guard_id): for guard in guard_list: if guard.id == guard_id: return guard return None class Guard: def __init__(self, id): self.sleep_time = [] self.id = id self.shifts = [] def find_index_max_count(list): max_index = 0 for index in range(len(list)): if list[max_index] < list[index]: max_index = index return max_index def find_minute_count_list(guard): sleep_minute_count = [0] * 60 for (sleep_from, sleep_to) in guard.sleep_time: for minute in range(sleep_from, sleep_to): sleep_minute_count[minute] += 1 return sleep_minute_count def find_most_frequently_sleeping_guard(guards): max_count = 0 max_minute = 0 max_minute_guard = None for guard in guards: guard_minute_count_list = find_minute_count_list(guard) guard_max_minute = find_index_max_count(guard_minute_count_list) guard_max_minute_count = guard_minute_count_list[guard_max_minute] if max_count < guard_max_minute_count: max_count = guard_max_minute_count max_minute = guard_max_minute max_minute_guard = guard return (max_minute_guard, max_minute) def output(filename, text): with open(filename, "w", encoding="utf-8") as f_out: f_out.write(text) def main(): unsorted_entries = input("input.txt") unsorted_parsed_entries = parse_entries(unsorted_entries) sorted_parsed_entries = sort_entries(unsorted_parsed_entries) guards = find_guards_list(sorted_parsed_entries) (guard, minute) = find_most_frequently_sleeping_guard(guards) output("output.txt", str(guard.id * minute)) main()
8dcc4b89c759898227722bcbd701f19f3dafb88e
GuilhermeRamous/python-exercises
/string_remover.py
292
4
4
"""Remove todas as ocorrências de uma determinada substring da string principal""" def string_remover(string, removed_part): return string.replace(removed_part, "") texto = input("Texto: ") parte_removida = input("Parte que será removida: ") print(string_remover(texto, parte_removida))
99bf204858fa36bbf5acfef9fc3812249c95959c
bielamonika/kurs_python
/09.03/range_zadanie2.py
217
3.578125
4
skladniki = ['ryz','cebula','pieczarki','ser','suszone pomidory','pieprz','sol','olej'] print("Przygotuj nastepujace skladniki: ") for item in skladniki: print(item) print("Podgrzej w garnku.") print("Zamieszaj.")
dde2856049f33de450483980fdf26d3e2535e8b6
nishithamv/Personalized-Voice-Synthesizer
/all_words.py
1,964
3.546875
4
all_w = "the you and it a 's to of that in we is do they er was yeah have but for on this know well so oh got if with " \ "she at there think just can would mm them up now about me very out my mean right which people like really other" \ " something actually take those only into us quite hundred again used mhm ah never point eight new big after " \ "today even ooh aye job children area obviously idea aha eh saw around situation change boy usually changed wish" \ " oil garage ee oi zero oops" s_list = ['aha eh ee oi ah ooh mm er mhm aye', 'oh there are around a hundred children in the area', 'oops you never saw me even if it was mean', 'something has obviously changed with us', 'people usually change job very often and quit', 'she was really quite today only', 'he used zero of my idea but gave credit', 'at this point we have to take the right decision', 'do they know which out of those is new', 'so think about the situation after that', 'yeah just wish them again at the end', 'actually the other eight got up on time', 'for now the homeless boy would like us', 'we put big can of garage oil into the well'] all_w_set = set(all_w.split(' ')) s_list_set = set() file = open('split.txt', "r") word_dicts = [] diphone_dict = {} for line in file: line = line.strip() if diphone_dict.get(line.split(" ")[0], None): print('repeated', line.split(" ")[0]) diphone_dict[line.split(" ")[0]] = line.split(" ")[2:] all_possible_diphones = set() all_generated = set() for key in diphone_dict.keys(): for sound in diphone_dict[key]: all_possible_diphones.add(sound) print(len(all_possible_diphones)) for word in all_w_set: for sound in diphone_dict[word]: all_generated.add(sound) print(len(all_generated)) print(all_possible_diphones-all_generated)
2586907485e755f37405fa1f0895c6533fd29828
Vodrech/WorkApplier
/Settings/save.py
4,247
3.71875
4
import os """ The save.py handles the save functionality for the gui to save settings for the TableSpecialSearch.py file Usage: > Create Instance of class > Set the instance object to the current setting name that is going to be changed > Edit the value """ class SaveSettings: def __init__(self, object, value): self.object = object self.value = value self.settingsPath = os.getcwd() + '\\Settings\\TableSpecialSearch.py' def read_settings_file(self): numLine = 0 try: with open(self.settingsPath, 'r') as file: content = file.readlines() for line in content: if line.__contains__(self.object): return [content, numLine] numLine += 1 except FileNotFoundError as e: raise e('File does not exist!') finally: file.close() def save_settings_file(self): variables = self.read_settings_file() position = variables[1] content = variables[0] try: with open(self.settingsPath, 'w') as file: if len(content) > position: if content[position].__contains__(self.object): if type(self.value) == bool: if self.value == True: newLine = (" '" + self.object + "'" + ":" + " " + 'True' + ',\n') else: newLine = (" '" + self.object + "'" + ":" + " " + 'False' + ',\n') content[position] = newLine file.writelines(content) elif type(self.value) == str: if self.value.isdecimal(): newLine = (" '" + self.object + "'" + ":" + " " + self.value + ",\n") else: newLine = (" '" + self.object + "'" + ":" + " " + "'" + self.value + "'" + ",\n") content[position] = newLine file.writelines(content) elif type(self.value) == int: newLine = (" '" + self.object + "'" + ":" + " " + self.value + ',\n') content[position] = newLine file.writelines(content) elif type(self.value) == list: newLine = (" '" + self.object + "'" + ":" + " [") loopCount = 0 if len(self.value) != 0: # TODO: FIXIIXIXIXIXIXIXIIX for x in self.value: loopCount += 1 if type(x) == int: newLine += str(x) elif type(x) == str: if x.isdecimal(): newLine += str(x) else: newLine += "'" + x + "'" else: Exception('Can not define the lists datatype, please check error log!') if loopCount != len(self.value): newLine += ', ' newLine += "]" + ',\n' content[position] = newLine file.writelines(content) return newLine else: raise Exception('Could not define correct datatype') else: raise Exception(' The current active line in save.py does not match the creteria') else: raise Exception('The line amount is overriding, please check error log') except FileNotFoundError as e: raise e('File does not exist') finally: file.close()
989a617d646dbb8b97998c67a2aa27b935632904
drkthakur/learn-python
/python-poc/python-self-poc/DS/recursion/pascal.py
244
3.671875
4
def pascal(n): line = 1 while(line <= n): C = 1 i = 1 while(i <= line): print(C) C = C * (line - i)/i i = i + 1 print("\n") line = line + 1 print(pascal(5))
6a860aec19688ee3933dfec3f7780f2f5365adeb
sotrnguy92/udemyPython
/udemy4/pythonDataTypesAndVariables/variablesHomework4.py
208
4.25
4
#This program reads 3 strings and prints the three strings repeated ten times str1 = input("enter a string: "); str2 = input("enter a string: "); str3 = input("enter a string: "); print((str1+str2+str3)*10)
5dc661bdc9db20088a59fdf40e4ef0bb4dd32762
DrEaston/leaderBoard
/old/leaderBoard_working.py
5,803
3.640625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 25 20:17:17 2020 Curtis Easton This is a program that takes a .csv file from schoology, and imports it into a Course object. Student info is stored in a list of Student Objects within a Course, including individual quiz scores. Within the Course class are some functions for printing high scores. """ import bisect import random class Student: def __init__(self,ID,firstName,lastName): self.name = firstName + " " + lastName self.ID = ID self.score = 0 self.quizzes = [] self.nickName =[] def addScore(self,newScore): self.score += float(newScore) class Quiz: def __init__(self,quizName): self.name = quizName self.scores = [] self.students = [] class Course: def __init__(self): self.nickNames=[] self.studentIDs=[] self.studentNames=[] self.studentList=[] self.quizIDs=[] self.quizList=[] self.idsWithNickNames=[] self.chosenNames=[] self.numHundos = [] self.hundoStudents = [] self.highScores = [] self.highScorers =[] self.toPrint = [] def getNickname(self,initID): if initID in self.idsWithNickNames: idx=self.idsWithNickNames.index(initID) return self.chosenNames[idx] else: return initID def insertScoreUser (self,student,score,user,scoreList,userList): i=bisect.bisect_right(scoreList,float(score)) scoreList.insert(i,score) ID=student.ID ID=self.getNickname(ID) userList.insert(i,ID) def getHighScores(self,numScores): self.highScores = [] self.highScorers = [] for item in self.studentList: if (item.score>0): self.insertScoreUser(item,item.score,item.ID,self.highScores,self.highScorers) self.toPrint=[self.highScorers,self.highScores] return self.toPrint def printLeaders(self,namesScores): numScores=len(namesScores[1]) for x in range(1,numScores): str1=namesScores[0][-x] str_length=len(str1)+(13-len(namesScores[0][-x])) str1=str1.ljust(str_length) print(str1 + " - " + str(int(namesScores[1][-x])) + " pts") def printHighScores(self,numScores): print("The top scores are:") self.toPrint=self.getHighScores(numScores) self.printLeaders(self.toPrint) def writeNicknames(self): writeStr=[] with open("nickNamesList.txt","w") as fout: for element in (self.nickNames): writeStr=element[0] for x in range(1,len(element)): writeStr=writeStr+","+element[x] fout.write(writeStr) fout.write('\n') def importNicknames(self): with open('nickNamesList.txt', 'r') as fin: text=(fin.readlines()) #read schoology .csv into python for x in range(len(text)): #iterate through all the quiz scores to be added self.nickNames.append(text[x].rstrip('\n').split(",")) #change current data into list for item in self.nickNames: if item[0] != 'N/A': self.idsWithNickNames.append(item[3]) self.chosenNames.append(item[0]) def addNickname(self,firstname,nickName): #add new student nickname for element in self.nickNames: if element[1] == firstname: #use firstname to find student print("edit student: "+ firstname + " "+element[2]+"?") #display student last name print("type y/n") result=input() #use user input to decide if correct student found if result == 'y': #if correct student found, edit student. else move to next student w/ same first name element[0]=nickName self.writeNicknames() break # Import Data and Load into Course object intSci=Course() with open('March30.csv', 'r') as fin: text=(fin.readlines()) #read schoology .csv into python categories=text.pop(0).split(",") #pop the categories line for x in range(len(text)): #iterate through all the quiz scores to be added text[x]=text[x].split(",") #change current data into list quizAttempt=text[x] for y in range(len(quizAttempt)): #remove inexplicable quotations in data file quizAttempt[y]=quizAttempt[y].replace("\"","") text[x]=quizAttempt for x in range(len(text)): quizAttempt=text[x] #create and update Student objects if quizAttempt[0] in intSci.studentIDs: #if student is already added to studentList idx=intSci.studentIDs.index(quizAttempt[0]) #get student index if (quizAttempt[13] != ''): #if there is a quiz score intSci.studentList[idx].quizzes.append(float(quizAttempt[13])) #add score to list intSci.studentList[idx].addScore(float(quizAttempt[13])) #update total score else : #if student is not there, create student and add result intSci.studentNames.append(quizAttempt[1] + " " + quizAttempt[2]) #add student name to master list intSci.studentIDs.append(quizAttempt[0]) # add student number to master list intSci.studentList.append(Student(quizAttempt[0],quizAttempt[1],quizAttempt[2])) #initialize and store student object if (quizAttempt[13] != ''): intSci.studentList[-1].quizzes.append(float(quizAttempt[13])) intSci.studentList[-1].addScore(float(quizAttempt[13])) #Output intSci.importNicknames() intSci.printHighScores(24) #intSci.mostHundos()
735cddc51a5e9c19da4a04f182f59f1895e15ec6
chaojiechen92/alg
/special_leetcode/array/数组中的第k个最大元素.py
1,642
3.5
4
class Solution: # O(n^2) 最孬的算法 def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ lens = len(nums) i = 1 while i < lens: j = i - 1 val = nums[i] while j >= 0 and nums[j] < val: nums[j + 1] = nums[j] j -= 1 nums[j + 1] = val i += 1 return nums[k - 1] # 选择排序 def findKthLargest2(self, nums, k): i = 0 lens = len(nums) res = 0 while i < k: j = 0 while j < lens - i - 1: if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] j += 1 res = nums[j] i += 1 return res # 快排思想 def findKthLargest3(self, nums, k): def partion(nums, s, e): j = s val = nums[e] while s <= e - 1: if nums[s] > val: nums[j], nums[s] = nums[s], nums[j] j += 1 s += 1 nums[e], nums[j] = nums[j], nums[e] return j mid = partion(nums, 0, len(nums) - 1) while mid != k - 1: if mid > k - 1: mid = partion(nums, 0, mid - 1) elif mid < k - 1: mid = partion(nums, mid + 1, len(nums)-1) return nums[mid] #  优先队列的思 路解决大输入情况 if __name__ == "__main__": print(Solution().findKthLargest3([3, 2, 1, 5, 6, 4], 2))
8eb42caeac6918bb2732eab649315b06a74813b4
SauravShoaeib/College
/CS_127/Python/borough.py
644
4.25
4
#Saurav Hossain #09/24/18 #Ask the user for the borough, an name for the output file, and then display the fraction of the population that has lived in that borough, over time. #Taken from lab and modified import matplotlib.pyplot as plt import pandas as pd x = input() y = input() #Open the CSV file and store in pop pop = pd.read_csv('nycHistPop.csv',skiprows=5) #Compute the fraction of the population in the Bronx, and save as new column: pop['Fraction'] = pop[x]/pop['Total'] #Create a plot of year versus fraction of pop. in Bronx (with labels): pop.plot(x = 'Year', y = 'Fraction') #Save to the file: fig = plt.gcf() fig.savefig(y)
4bc98f96817195ede38c4ae82916b3d1b9e5b372
raswolf/Python
/module4/store/coupon_calculations.py
769
4.0625
4
""" Program: coupon_calculations.py Author: Rachael Wolf Last date modified: 09/21/2020 The purpose of this program is to accept the amount of the purchase, the cash coupon, and the percent coupon. From these it will calculate and return the total payment for the order item. """ def calculate_order(price, cash_coupon, percent_coupon): payment = price tax = price * .06 shipping = 0 if price < 10: shipping = 5.95 elif 10 <= price < 30: shipping = 7.95 elif 30 <= price < 50: shipping = 11.95 payment -= cash_coupon payment -= payment * (percent_coupon/100) return max(payment, 0) + tax + shipping # this is actually cleaner and easier without nested ifs? # the only thing that really changes is the shipping
c3405aab4e973d1b99a6a72bfd6329f40b2a9102
ethan21-meet/meetyl1
/lesson4.py
1,012
3.9375
4
from turtle import Turtle import turtle class Ball(Turtle): def __init__(self,r,color,dx,dy): Turtle.__init__(self) self.penup() self.r = r self.dx = dx self.dy = dy self.color(color) self.shape("circle") self.shapesize(r/10) def move(self,screen_width,screen_height): current_x = self.xcor() new_x = current_x +self.dx current_y = self.ycor() new_y = current_y + self.dy right_side_ball = new_x +self.r left_side_ball = new_x +self.r upper_side_ball = new_y +self.r lower_side_ball = new_y +self.r self.goto(new_y,new_x) if right_side_ball > screen_width: new_x = -new_x if left_side_ball > screen_width: new_x = -new_x if upper_side_ball > screen_height: new_y = -new_y if lower_side_ball > screen_height: new_y = -new_y self.goto(new_y,new_x) screen_width = turtle.getcanvas().winfo_width()/2 screen_height = turtle.getcanvas().winfo_height()/2 ball_1 = Ball(10,"red",10,10) while 1==1: ball_1.move(screen_width,screen_height)
05f9612f39df2dcf521938c0811d7281af710d73
poojataksande9211/python_data
/python_tutorial/excercise_11_decorators/decorators_intro.py
368
4.15625
4
#intro to decorators # def square(a): # return a**2 # s=square(7) # print(s) #------------------ def square(a): return a**2 s=square #here we assing function to variable s....yahape func ko call nahi kar rahe... print(s(7)) #s kam karega function ki tarah print(s.__name__) #it will print name of s print(s) #both s and square at same laocation print(square)
10b869fef91a302f336b379f92dd0062c1923cdf
BourgonLaurent/pyParker
/MouseToolsbyScottCaratozzolo/auth.py
895
3.578125
4
import requests import json from datetime import datetime, timedelta def Authentication(): """Gets an authentication(access) token from Disney and returns it""" r = requests.get("https://disneyworld.disney.go.com/authentication/get-client-token") auth = json.loads(r.content) return auth['access_token'], auth['expires_in'] time_of_expire = None access_token = None def getHeaders(): """Creates the headers to send during the request and returns it""" global time_of_expire global access_token if time_of_expire == None or (datetime.now() > time_of_expire): access_token, expires_in = Authentication() time_of_expire = datetime.now() + timedelta(seconds=(expires_in-10)) headers = {"Authorization":"BEARER {}".format(access_token)} else: headers = {"Authorization":"BEARER {}".format(access_token)} return headers
4c5dda9485035660017873c4349db25cba6e8bd4
nosrefeg/Python3
/mundo3/exercicios/081.py
617
4.09375
4
numeros = [] while True: numeros.append(int(input('Digite um número: '))) continua = input('Quer continuar? (S/N) ').strip().upper() while continua not in 'SN': print('Apenas S ou N') continua = input('Quer continuar? (S/N) ').strip().upper() if continua == 'N': break print('¨¨' * 30) print(f'Foram digitados {len(numeros)} números!') numeros.sort(reverse=True) print(f'Os números de forma decrescente são {numeros}') if 5 in numeros: print(f'O número 5 está na lista, na {numeros.index(5) + 1}ª posição') else: print('O número 5 NÃO está na lista!')
2424accc6b69a9e090c366d28c5c942396c36330
manuelalvarezco/Phyton
/funciones_conjuntos.py
178
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 25 12:41:48 2020 @author: luismanuelalvarez """ def f(x): return x ** 2 - 3 * x + 1 print(f(3))
36938b2c3f3b000452ead843e4553f28550eb772
SabithaSubair/Luminar_PythonDjangoProjects_May
/samplepgms/add10nums.py
178
3.9375
4
# sum=0 # # for i in range(1,10): # # sum=sum+i # # print("result",sum) #another way a=int(input("Enter range:")) sum=0 for i in range(a): sum=sum+i print("result",sum)
a5b447f3062bdd0e3d76ae035190fa2cf65f0c0b
jeancarlo-Topo/Repositorio_General
/Calculadora.py
5,396
3.796875
4
menu = """ Bienvenido ala calculadora,actualmente se encuentra bajo actualizacion por lo que apreciamos su paciencia, muchas gracias 1 - Suma 2 - Resta 3 - Multiplicacion 4 - Division 5 - Division Entera 6 - Potencia 7 - Raiz 8 - Determinacion de raiz cuadrada de un numero 9 - Factoriales 10 - Fibbonacci (Numeros enteros mayores a 1) Elige una opcion: """ opcion = int(input(menu)) def suma(valor1, valor2): sumatoria = valor1 + valor2 return sumatoria # esta suma es ineficiente, si quisiera sumar muchos datos no podria, hay que revisar eso def resta(valor1, valor2): resta = valor1 - valor2 return resta #ineficiente, revisar eso que se indico en la suma def multiplicacion(valor1, valor2): multiplicacion = valor1*valor2 return multiplicacion def division(valor1, valor2): try: division = valor1/valor2 return division except ZeroDivisionError as _e:#_e estoy diciendo al except que me guarde el error en _e, el underscore es para que no me tire el error de unused variable #Hay que revisar bien esta sintaxis para usarla en otras cosas, esto ayudaria a no usar if que muchas veces joden print(f'Division entre 0 es infinito, no es posible hacer la division' ) #tengo que agregar las opciones donde se vuelve infinito o negativo def div_entera(valor1, valor2): div_entera = valor1%valor2 return div_entera def potencia(valor1, valor2): poten = valor1**valor2 poten = round(poten,2) return poten def raiz(valor1, valor2): try: valor2 = 1 / valor2 raiz = valor1 ** valor2 raiz = round(raiz,2) return raiz except TypeError as _e: print(f'Por ahora no es posible la raiz de un numero negativo') #Hay que revisar lo que hay que hacer para variables negativas def factorial(valor1): #Aqui el factorial es un int <= a 1, la formula de factorial es n*(n-1)!, esta es la que estaremos integrando a la calculadora #if valor1 == 1: # return 1 #elif valor1 == 0 : # return 1 OJO QUE AQUI LO PODIA HACER SEPARADO PERO ES LO MISMO QUE DECIR QUE SI EL NUMERO ES MENOR A 2 , OSEA 1 Y 0 ENTONCES DEVUELVAME 1 if valor1 < 2 : return 1 return valor1 * factorial(valor1-1) fibonacci_cache ={}#La computadora tiene que hacer muchas iteraciones varias veces por lo que este diccionario ayuda a que se guarden los datos para que la funcion tome los datos ya cacheados y luego trabaje sobre eso def fibonacci(valor1): #print(valor1) if 0 <= valor1 <= 1 : return 1 valor1 = fibonacci(valor1 - 1)+ fibonacci(valor1 - 2) fibonacci_cache[valor1] = valor1 #print(valor1) #FIBONACCI tiene un error que no permite que se hagan iteraciones rapido return valor1 def run(): if opcion == 1: valor1 = float(input('Ingrese un primer valor a sumar: ')) valor2 = float(input('Ingrese un segundo valor sumar: ')) print(f'La suma es: {suma(valor1, valor2)}') #Aqui estamos usando formatos para printear diferente elif opcion == 2 : valor1 = float(input('Ingrese un primer valor: ')) valor2= float(input('Ingrese valor a restar: ')) print(f'La resta es {resta(valor1, valor2)}') elif opcion == 3 : valor1 = float(input('Ingrese un primer valor: ')) valor2 = float(input('Ingrese valor por que quieres multiplicar: ')) print(f'La Multipliacion es {multiplicacion(valor1, valor2)}') elif opcion == 4 : valor1 = float(input('Ingrese un primer valor: ')) valor2 = float(input('Ingrese un por que quieres dividir: ')) if division(valor1, valor2) == None:#Aqui le digo al programa que si me devuelven un none entonces no haga nada, si no estuviera entonces haria un print de lo que sigue y no es la idea pass else: print(f'La Division es {division(valor1, valor2)}') elif opcion == 5 : valor1 = float(input('Ingrese un primer valor: ')) valor2 = float(input('Ingrese un por que quieres dividir: ')) print(f'La Division entera es {div_entera(valor1, valor2)}') elif opcion == 6 : valor1 = float(input('Ingrese valor: ')) valor2 = float(input('Ingrese la potencia: ')) print(f'La potencia es {potencia(valor1, valor2)}') elif opcion == 7 : valor1 = float((input("Ingrese un numero:"))) valor2 = float((input("Ingrese la raiz a usar:"))) if raiz(valor1, valor2) == None: pass else: print(f'La raiz {str(int(valor2))} de {str(int(valor1))} es {str(raiz(valor1, valor2))}') elif opcion == 8 : print(f'Actualmente se esta trabajando en integrar esta funcion') elif opcion == 9 : valor1 = int(input("Ingrese un numero: ")) if valor1 < 0 : valor1 = abs(valor1) print(f' No se puede valorar un negativo, por lo tanto se toma su valor absoluto') print(f' El factorial de {valor1} es {factorial(valor1)}') elif opcion == 10 : valor1 = int(input("Ingrese un numero: ")) if valor1 < 0 : print(f'Recuerde que para calcular los fibbonacci los numeros son enteros, osea del 0 en adelante') print(f'El numero fibonnacci de {valor1} es {fibonacci(valor1)}') #Quiero probar otra vez el branch if __name__ == '__main__': run()
2ce44a1b9b49105eac488b9a63c5c1d88883450d
sahasatvik/assignments
/CS2201/tabulation.py
885
4.34375
4
#!/usr/bin/env python3 import numpy as np ''' Finding the intervals in which a function has roots using tabulation. ''' def tabulation(f, lo, hi, n): ''' Yields intervals which contain roots of the function f. A total of n intervals of equal length within [lo, hi] will be considered. ''' # Create the n + 1 points demarcating the intervals points = np.linspace(lo, hi, n + 1) # Calculate f at each of these points values = f(points) for i in range(n): # Root found if f changes sign within the interval if values[i] * values[i + 1] <= 0: yield points[i], points[i + 1] def f(x): return 10**x + x - 4 if __name__ == '__main__': # Display all intervals containing roots to the console for interval in tabulation(f, 0, 1, 10): print(f"Root present in the interval [{interval[0]}, {interval[1]}]")
46e91f71f436d8a213a0932e69c5bb7cd1ddd733
ambosing/PlayGround
/Python/language study/function.py
542
3.859375
4
def hello(): print('Hello, world') def add(a, b): print(a + b) def add2(a, b): return (a + b) def add_sub(a, b): return (a + b, a - b) def add_sub2(a, b): return ([a + b, a - b]) hello() add(3, 4) res = add2(3, 4) print(res) x, y = add_sub(10, 5) print(x, y) tu = add_sub(10, 5) print(tu) lst = add_sub2(10, 5) print(lst) x, y = map(int, input().split()) def calc(x, y): return (x + y, x - y, x * y, x / y) a, s, m, d = calc(x, y) print('덧셈: {0}, 뺄셈: {1}, 곱셈: {2}, 나눗셈: {3}'.format(a, s, m, d))
18a349914894ebd98fcb9f13dd40fd35f8902e09
luka-ve/AoC2020
/06.py
1,225
3.515625
4
def part1(data): groups = data.split('\n\n') groups = [group.split('\n') for group in groups] # Concatenate every group's individual strings and convert to set n_different_questions_per_group = [len(set(''.join(group))) for group in groups] return sum(n_different_questions_per_group) # Concatenate every group's individual strings and convert to set # Compare the element count of every group set to the group's size def part2(data): groups = data.split('\n\n') groups = [group.split('\n') for group in groups] # Group sizes are needed to compare the count of each set element per group to the group size group_sizes = [len(group) for group in groups] groups_concatenated = [''.join(group) for group in groups] # Convert every group string to a tuple, eliminating duplicates group_answered_questions = [tuple(set(q)) for q in groups_concatenated] total_count = [] for i, group in enumerate(group_answered_questions): group_count = 0 for question in group: if groups_concatenated[i].count(question) == group_sizes[i]: group_count += 1 total_count.append(group_count) return sum(total_count)
6002393876b826ac00d3fbee852b6577a4dc10c0
apoorvaagrawal86/PythonUdemyPython
/basicsyntax/string_methods2.py
218
3.921875
4
a = "1abc2abc3abc4abc" print(a.replace('abc','ABC',2)) #count replaces the specified items in the string sub = a[1:6] print(sub) #sub, first element is inclusive, last element is exclusive step = a[1:6:3] print(step)