blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b737e0dc9e2362272d198b2364fd808e333d9d37
cargarma/python-ejercicios
/condicionales.py
381
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Utilización de IF print("Programa de evaluación de notas de alumnos") nota_alumno = input("Introduce la nota del alumno:") def evaluacion(nota): if nota < 0 or nota > 10: return "Error en la nota" else: valoracion="aprobado" if nota<5: valoracion="suspenso" return valoracion print(evaluacion(int(nota_alumno)))
4a42450af059caffdbe97fbe76ceb443aef156f1
katielkrieger/algorithms
/20170517_SumOfPairs_5kyu_Python/SumOfPairs.py
833
3.65625
4
def sum_pairs(ints, s): dict = {ints[0]: s - ints[0]} j = 1 while (j < len(ints)): if ints[j] in dict.values(): return [s-ints[j],ints[j]] dict[ints[j]] = s - ints[j] j+=1 return None # best practice: # def sum_pairs(lst, s): # cache = set() # for i in lst: # if s - i in cache: # return [s - i, i] # cache.add(i) # original method -- too slow for the really large lists # def sum_pairs(ints, s): # i,j = 0,1 # while (j < len(ints)): # while (i < j): # print(i,j,"=",ints[i],ints[j]) # if ints[i] + ints[j] == s: # return [ints[i],ints[j]] # i+=1 # i=0 # j+=1 # print(sum_pairs([11, 3, 7, 5], 10)) # [3,7] print(sum_pairs([1, 4, 8, 7, 3, 15], 8)) # [1,7]
5e6c557a2ac2662d9838f19d1e738936b16612a1
Shandmo/Struggle_Bus
/Chapters 1-8/cities.py
1,208
4.40625
4
### 6-11 Cities ### #use names of three cities as keys, store information about each city, include its country, population, and one fact. cities = { "Washington D.C.": { "country": 'United States', "population": 1_250_000, "neat fact": "The \"D.C.\" part stands for District of Columbia." }, "Baghdad": { "country": "Afghanistan", "population": 856_000, "neat fact": "This city gets shit on constantly by terrorists." }, "Paris": { "country": "France", "population": 5_000_000, "neat fact": "The germans straight dicked this one." } } for key,value in cities.items(): #get the keys/values from cities. print("\n{}".format(key)) #Print the city name (key). for k,v in value.items(): #get the key/values from the internal dictionary. if k == "country": #multiple conditionals to add extra text formatting to the output. print("Location: {}".format(v)) elif k == "population": print("Estimated population: {}".format(v)) elif k == "neat fact": print("Neat fact: {}".format(v))
18deabe68e3200f8e8df925995b01146c962957c
goksinan/Intro-to-PyTorch
/eg_3_nn_module.py
1,189
3.640625
4
import torch from torch import nn from torchvision import datasets, transforms class Network(nn.Module): def __init__(self): super().__init__() # Inputs to hidden layer linear transformation self.hidden = nn.Linear(784, 256) # Output layer, 10 units - one for each digit self.output = nn.Linear(256, 10) # Define sigmoid activation and softmax output self.sigmoid = nn.Sigmoid() self.softmax = nn.Softmax(dim=1) def forward(self, x): # Pass the input tensor through each of our operations x = self.hidden(x) x = self.sigmoid(x) x = self.output(x) x = self.softmax(x) return x transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=(0.5,), std=(0.5,), inplace=False)]) trainset = datasets.MNIST('MNIST_data/', download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) dataiter = iter(trainloader) images, labels = dataiter.next() inputs = images.view(images.shape[0], -1) model = Network() x = model.forward(inputs) print(x.sum(1))
913d7bd51eafc76190dab45bd6d08712e38d452b
All3yp/Daily-Coding-Problem-Solutions
/Solutions/210.py
1,267
4.28125
4
""" Problem: A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer: If n is even, the next number in the sequence is n / 2 If n is odd, the next number in the sequence is 3n + 1 It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture. Bonus: What input n <= 1000000 gives the longest sequence? """ from typing import List def get_collatz_sequence_length(num: int, acc: int = 0) -> int: if num == 1: return acc if num % 2 == 0: return get_collatz_sequence_length(num // 2, acc + 1) return get_collatz_sequence_length(3 * num + 1, acc + 1) def get_longest_collatz_sequence_under_1000000() -> int: longest_sequence_value = 0 longest_sequence = 0 for i in range(1, 1_000_000): curr_sequence = get_collatz_sequence_length(i, 0) if curr_sequence > longest_sequence: longest_sequence = curr_sequence longest_sequence_value = i return longest_sequence_value if __name__ == "__main__": # NOTE: brute force implementation, it will take quite a bit of time to execute print(get_longest_collatz_sequence_under_1000000()) """ SPECS: TIME COMPLEXITY: O(log(n)) SPACE COMPLEXITY: O(log(n)) """
ce7f86a885e80e96d1e572ef0ae0fe9dde1a69fa
Krisva403/Discord_Bot
/games.py
7,651
3.515625
4
import random # game Snakeeyes class snakeeyes: def __init__(self, players): self.players = players self.scores ={} # used for only one player per round self.turn_left ={} # score-board for player in players: self.scores[player.id] = 0 self.turn_left[player.id] =True def process_input(self, message): # find a player who wrote the command player = None for p in self.players: if p.id == message.author.id: player = p break if player is not None: # check for roll command if message.content[1:] == "roll": # check if the player is still in the game allowed_turn = self.turn_left.get(player.id) if allowed_turn is None: return player.name + " has lost, wait for game to finish..." # if player is in the game continue to get 2 random numbers and add them too score-board if allowed_turn is True: self.turn_left[player.id] = False roll1 = random.randint(1,6) roll2 = random.randint(1,6) player_score = self.scores.get(player.id) player_score = player_score + roll1 + roll2 self.scores[player.id] = player_score output = str(player.name) + " has rolled - " + str(roll1) + "," + str(roll2) + ". Final score: " + str(player_score) # check winningconditions # if player has rolled "snakeeyes"(two 1) than he wins if roll1 == 1 and roll2 == 1: output = "!" + str(player.name) + " has rolled snake eyes, player wins\n" if player_score == 21: output = "!" + output + ", player has won\n" elif player_score > 21: output = output + ", player has lost\n" # take out player from the list after they lost self.turn_left.pop(player.id) # check if player is the only one standing if len(self.turn_left) == 1: for key in self.turn_left: for p in self.players: if p.id == key: # if he is delcare him as a default winner return "!" + output + ". " +str(p.name) + " is last one standing, default win\n" self.new_round() return output else: # if its not players turn return: return player.name + "turn is over, wait for others to finish their turn..." else: # if command doesnt exist return: return "Command not recognized by snake eyes" else: print("Player was not found") return None # new round def new_round(self): round_over = True for key in self.turn_left: if self.turn_left.get(key): round_over = False break if round_over: for key in self.turn_left: self.turn_left[key] = True # game tic tac toe class Tictactoe: def __init__(self, players): # the game board self.board = [":white_large_square:", ":white_large_square:", ":white_large_square:", ":white_large_square:", ":white_large_square:", ":white_large_square:", ":white_large_square:", ":white_large_square:", ":white_large_square:"] # declaring marks self.marks = [":regional_indicator_x:",":o2:"] # mark index self.mark_index = 0 self.players = players self.completed_turn = None self.winningConditions = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] # function for output for the board def get_output(self): line = "" for x in range(len(self.board)): line += self.board[x] if (x + 1) % 3 == 0: line += "\n" return line def process_input(self, message): # check if there is to many players for the game if len(self.players) > 2: return "too many players" player = None # find a player who wrote the command for p in self.players: if p.id == message.author.id: player = p break if player is not None: # check for command !place if message.content[1:6] == "place": # check if its that players turn if self.completed_turn != player: # check that tehre is no more than 8 symbols if len(message.content) != 8: return "bad input" # say that cordinates are on 7 symbol and that its start from 1 instead of 0 cord = int(message.content[7:]) cord = cord - 1 # check that the cordinate is not taken if self.board[cord] != ":white_large_square:": return "you cant place here" # place mark self.board[cord] = self.marks[self.mark_index] self.completed_turn = player # check if there is a winner if self.checkWinner(self.marks[self.mark_index]): return "!\n" + self.get_output() + "\n" + str(player.name) + " has won! \n" # check if its a tie if self.checkTie(): return "!\n" + self.get_output() + "\nGame has ended in a tie!\n" # after a turn increase mark index self.mark_index = self.mark_index + 1 # and make it so at the next round its 0 again if self.mark_index > 1: self.mark_index = 0 return self.get_output() else: return "Its not your turn" else: return "command not recognized" return "player not found" # function to se who's a winner def checkWinner(self, mark): gameOver = False # checking if one of the mark are placed into winning conditions for condition in self.winningConditions: if self.board[condition[0]] == mark and self.board[condition[1]] == mark and self.board[condition[2]] == mark: gameOver = True break return gameOver # function to see if it's a tie def checkTie(self): tie = True # if there is no white squares left its a tie for x in range(len(self.board)): if self.board[x] == ":white_large_square:": tie = False break return tie
d71f366648343377ac6123504f8336b46dac4dec
Jennifer0606/Codewares
/8kyu/python/solved/ensure_question.py
776
4.40625
4
""" https://www.codewars.com/kata/5866fc43395d9138a7000006/train/python Given a string, write a function that returns the string with a question mark ("?") appends to the end, unless the original string ends with a question mark, in which case, returns the original string. ensure_question("Yes") == "Yes?" ensure_question("No?") == "No?" """ # my solution def ensure_question(s): while len(s) > 1: return s if s[-1] == "?" else s+"?" return "?" # # best solution # def ensure_question(s): # return s.rstrip('?') + '?' # # # # other solution # def ensure_question(s): # return s if s.endswith('?') else s + '?' print(ensure_question("")) # return "?" print(ensure_question("Yes")) # return "Yes?" print(ensure_question("No?")) # return "No?"
a8ed2f221fba0b6153061f1a733155390b28320a
nikitakumar2017/Assignment-3
/TuplesQuestion1.py
119
4.3125
4
'''Print a tuple in reverse order. ''' tup=(1,2,3,4,5) tuprev=reversed(tup) print("Reversed tuple is ",tuple(tuprev))
7e41f2afca4abd517bed47dbe87a48795e28b49f
zil-kiev/Python-Vladimir2
/homework_2_6.py
337
3.953125
4
a = int (input('введите число а:')) b = int (input('введите число b:')) c = int (input('введите число с:')) if a == b or a == c or b == c: print('треугольник равнобедренный') else: print('треугольник не равнобедренный')
e49ba8662b6908b14f8d100c34a15520566c61e4
akimi-yano/algorithm-practice
/lc/review_1200.MinimumAbsoluteDifference.py
1,319
4.03125
4
# 1200. Minimum Absolute Difference # Easy # 1038 # 47 # Add to List # Share # Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. # Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows # a, b are from arr # a < b # b - a equals to the minimum absolute difference of any two elements in arr # Example 1: # Input: arr = [4,2,1,3] # Output: [[1,2],[2,3],[3,4]] # Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. # Example 2: # Input: arr = [1,3,6,10,15] # Output: [[1,3]] # Example 3: # Input: arr = [3,8,-10,23,19,-4,-14,27] # Output: [[-14,-10],[19,23],[23,27]] # Constraints: # 2 <= arr.length <= 10^5 # -10^6 <= arr[i] <= 10^6 # This solution works: class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() ans = {} for i in range(len(arr)-1): abs_diff = abs(arr[i] - arr[i+1]) if abs_diff not in ans: ans[abs_diff] = [] ans[abs_diff].append([arr[i], arr[i+1]]) to_return = list(ans.items()) to_return.sort(key = lambda elem : elem[0]) return to_return[0][1]
e4593187568d37163318ffe847b427b1dfe9ed9b
tarunkant/exercism_python
/pangram/pangram.py
198
3.875
4
sentence= raw_input("give a sentence ") sentence= sentence.replace(' ','') if set(sentence.lower()) >= set('abcdefghijklmnopqrstuvwxyz'): print"It is pangram" else: print"It is not pangram"
611fd03a850ba534f2cb3abcf2e10ed8d9cd6325
idiego209/python_exercises
/reverse_string/reverse_string.py
785
4.21875
4
#!/usr/bin/env python # https://leetcode.com/problems/reverse-string/ # reverse_string.py # Write a function that reverses a string. The input string is given as # an array of characters char[]. Do not allocate extra space for another # array, you must do this by modifying the input array in-place with # O(1) extra memory. You may assume all the characters consist of # printable ascii characters. # Author: https://github.com/idiego209 class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ middle = int(len(s)/2) for i in range(middle): tmp = s[i] s[i] = s[-(i + 1)] s[-(i + 1)] = tmp return s
e3a3f668d3ca5ef8c1827287a8090d7e70b1f4b9
mau-vela/PythonClass-2015
/Class3-ErrorsTesting/ordinaltest.py
578
3.578125
4
import unittest import ordinal class Testordinal(unittest.TestCase): def setUp(self): self.value = 1 def test_first(self): self.assertEqual(ordinal.ordinal(self.value), "1st") def test_second(self): self.assertEqual(ordinal.ordinal(2), "2nd") def test_third(self): self.assertEqual(ordinal.ordinal(3), "3rd") def test_eleven(self): self.assertNotEqual(ordinal.ordinal(111), "111st") def test_other(self): self.assertEqual(ordinal.ordinal(34), "34th") if __name__ == '__main__': #Add this if you want to run the test with this script. unittest.main()
487f37b9e463d398b35ea186c82019438c03dbc6
lingxueli/CodingBook
/Data Structure/BinarySearchTreeOrBinarySearch.py
1,178
3.8125
4
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def inorder(node): if not node: return inorder(node.left) print(node.val) inorder(node.right) def preorder(node): if not node: return print(node.val) preorder(node.left) preorder(node.right) def search(node, key): if node is None or node.val == key: return node if node.val < key: return search(node.right, key) else: return search(node.left, key) # 4 # / \ # 2 6 # / \ \ # 1 3 7 # node = Node(4, Node(2, Node(1), Node(3)), Node(6, None, Node(7))) inorder(node) # 1 2 3 4 5 6 7 preorder(node) # 4 2 1 3 7 6 print(search(node, 6).val) # 6 print(search(node, 9)) # None def binarySearch(nums, low, high, x): if high < low: return None mid = (low + high)//2 if nums[mid] == x: return mid elif nums[mid] > x: return binarySearch(nums, low, mid-1, x) else: return binarySearch(nums, mid+1, high, x) nums = [1, 2, 3, 4, 5, 6, 7, 8] print(binarySearch(nums, 0, len(nums) - 1, 4)) # 3 print(binarySearch(nums, 0, len(nums) - 1, 40)) # None
877a679d8b8e24d5600be0fd47729c9b9c94bb34
oluwafemi2016/Analytics
/Python_Activities.py
23,436
4.0625
4
# coding: utf-8 # ### Activity 1: The goal of this code is to extract numbers in a text document and sum all the numbers together # In[3]: #Importing regular expression library import re # In[69]: #get the 2D array containing array of numbers for each line handle = open("regex_sum_1119177.txt") numlist = list() for line in handle: line = line.rstrip() nums = re.findall('([0-9]+)',line) #print(nums) if len(nums) <1 : continue numlist.append(nums) # In[70]: print((len(numlist))) # In[71]: # get all the numbers into 1D array numblist = list() numbs = list() for j in range(len(numlist)): numbs = numlist[j] #print(numbs) for num in numbs: numblist.append(num) #print(numblist) # In[72]: #print((numblist)) # In[73]: # turn the array of strings to array of floats numbers = list() for j in range(len(numblist)): numbers.append(float(numblist[j])) # In[74]: #print(numbers) # In[75]: sum = 0 for number in numbers: sum = sum + number # In[76]: print("sum of numbers in the text:", sum) # ### Activity 2: Get the minimum and maximum values from a list of numbers # In[65]: def Minimax(num): largest = 0 smallest = None while True: if num == "done" : break try : numVal = int(num) ##numVals = num except: print("Invalid input") if numVal > largest: largest = numVal if smallest is None : smallest = numVal elif numVal < smallest : smallest = numVal #print("Maximum is", largest) #print("Minimum is", smallest) # ### Activity 3: Writing a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. # In[66]: def UpperCase(fname): try: fh = open(fname) for line in fh: line = (line.rstrip()).upper() print(line) except: print("Filename",fname, "does not exist") # ### Activity 4: Writing a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. # # In[67]: def extract(fname): snum = 0; try: fh = open(fname) except: print("Filename does not exist") count = 0 for line in fh: line = line.rstrip() if line.startswith("X-DSPAM-Confidence:") : count = count + 1 idx = line.find("0") num = float(line[idx:]) snum = snum+num continue print("Average spam confidence:", snum/count) # ### Activity 5: Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. # In[68]: def textToList(fname): try: fh = open(fname) lst = list() for line in fh: line = line.rstrip() linesplit = line.split() for word in linesplit: if not word in lst: lst.append(word) lst.sort() except: print("File", fname, "does not exist") print(lst) # ### Activity 6: Open the file mbox-short.txt and read it line by line. After finding a line that starts with 'From ' like the following line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count. # # In[70]: def ExtractEmail(fname): fh = open(fname) count = 0 lnsp = list() for line in fh: line = line.rstrip() if line.startswith("From "): lnsp = line.split()[1] print(lnsp) count = count+1 print("There were", count, "lines in the file with From as the first word") # ### Activity 7: Writing a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer. # In[71]: def EmailSenders(fname): handle = open(fname) dicts = dict() senders = list() for line in handle: line = line.rstrip() if line.startswith("From "): senders.append(line.split()[1]) ##print(senders) for sender in senders: dicts[sender] = dicts.get(sender,0)+1 #getting the maximum bigCount = None bigSender = None for sender,count in dicts.items(): if bigCount is None or count > bigCount: bigCount = count bigSender = sender print(bigSender, bigCount) #print(dicts) # ### Activity 8: Writing a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. # In[72]: def HourDistribution(fname): handle = open(fname) dicts = dict() senders = list() times = list() for line in handle: line = line.rstrip() if line.startswith("From "): senders.append(line.split()[5]) for time in senders: times.append(time.split(":")[0]) #print(times) for time in times: dicts[time] = dicts.get(time,0)+1 #print(dicts) for key,value in sorted(dicts.items()): print(key,value) # ### Activity 9: Retrieving the following document using the HTTP protocol in a way that can examine the HTTP Response headers # In[1]: import socket # In[2]: #creating the connection mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('data.pr4e.org', 80)) # In[3]: #sending the request ## converts unicode to UTF8 using encode cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode() mysock.send(cmd) # In[4]: #receiving data stream from server while True: data = mysock.recv(512) if len(data)<1: break print(data.decode()) mysock.close() # In[2]: print(ord('i')) # In[7]: import urllib.request, urllib.parse, urllib.error # In[8]: x = urllib.request.urlopen('http://data.pr4e.org/romeo.txt') # In[9]: print(x) # ### Activity 10: Scraping HTML Data with BeautifulSoup: # #### The program will use urllib to read the HTML from the data files below, and parse the data, extracting numbers and compute the sum of the numbers in the file # In[220]: from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors #Secure Sockets Layer, are cryptographic protocols designed to #provide communications security over a computer network ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = "http://py4e-data.dr-chuck.net/comments_1119179.html" html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') # In[209]: #getting the text in the html document tags = soup('span') # In[210]: print(tags) # In[211]: #Importing regular expression library import re taglist = list() for tag in tags: nums = tag.contents[0] #print(nums) if len(nums) <1 : continue taglist.append(nums) # In[212]: print(((taglist))) # In[213]: # get all the numbers into 1D array Tagslist = list() tnumbs = list() for j in range(len(taglist)): tnumbs.append(float(taglist[j])) #print(tnumbs) #for tnum in tnumbs: #Tagslist.append(tnum) # In[214]: print(tnumbs) # In[215]: sums = 0 for number in tnumbs: sums = sums + number # In[216]: print("sum of numbers in the text:", sums) # ### Activity 11: Following Links in HTML Using Beautiful Soup # #### The program will use urllib to read the HTML from the data files below, extract the href= values from the anchor tags, scan for a tag that is in a particular position from the top and follow that link, repeat the process a number of times, and report the last name you find. # # In this assignment you will write a Python program that expands on http://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position relative to the first name in the list, follow that link and repeat the process a number of times and report the last name you find. # In[280]: import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors #Secure Sockets Layer, are cryptographic protocols designed to #provide communications security over a computer network ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = "http://py4e-data.dr-chuck.net/known_by_Charmaine.html" # In[281]: # Retrieve all of the anchor tags repeat = 7 position = 18 while repeat >0: html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('a') taglst = list() for tag in tags: taglst.append(tag.get('href', None)) url = taglst[position-1] repeat = repeat - 1 print(url) # In[282]: #Extract the last name from the url urlName = list() urlName.append(url) LastName = re.findall('by_(\S.*\S)[^ html]', urlName[0]) print(LastName[0]) # ### Activity 12: Extract Data from XML # #### The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file and enter the sum, # Write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file. # The data consists of a number of names and comment counts in XML as follows: # # # # <comment> # <name>Matthias</name> # <count>97</count> # </comment> # # # You are to look through all the <comment> tags and find the <count> values sum the numbers. The closest sample code that shows how to parse XML is geoxml.py. But since the nesting of the elements in our data is different than the data we are parsing in that sample code you will have to make real changes to the code. # To make the code a little simpler, you can use an XPath selector string to look through the entire tree of XML for any tag named 'count' with the following line of code: # # counts = tree.findall('.//count') # # Take a look at the Python ElementTree documentation and look for the supported XPath syntax for details. You could also work from the top of the XML down to the comments node and then loop through the child nodes of the comments node. # In[37]: import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl # In[38]: # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # In[110]: #Parsing the XML in Python and extracting the count values url = "http://py4e-data.dr-chuck.net/comments_1119181.xml" parms = dict() parms['url'] = url data = urllib.request.urlopen(url, context=ctx).read() #print('Retrieved', len(data), 'characters') #print(data.decode()) tree = ET.fromstring(data) counts = tree.findall('comments/comment/count') # In[111]: #print((counts)) # In[112]: countlist = list() for count in counts: countlist.append(int(count.text)) # In[113]: print((countlist)) # In[114]: sum_count = 0 for number in countlist: sum_count = sum_count + number print(sum_count) # ### Activity 13: Extracting Data from JSON # #### The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file. # # write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: # We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the # In[4]: import json import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl # In[22]: url = "http://py4e-data.dr-chuck.net/comments_1119182.json" # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.urlopen(url, context=ctx).read() # In[23]: info = json.loads(data) # In[24]: ## getting the comments list comments = info['comments'] # In[25]: ## get the counts countlist = list() for count in comments: countlist.append(count['count']) print(countlist) # In[26]: ## the sum SumCount = 0 for count in countlist: SumCount = SumCount + count print(SumCount) # ### Activity 14: Using the GeoJSON API # #### In this program you will use a GeoLocation lookup API modelled after the Google API to look up some universities and parse the returned data. # # Write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps. # API End Points # # To complete this project, use this API endpoint that has a static subset of the Google Data: # # http://py4e-data.dr-chuck.net/json? # This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get "No address..." response. # To call the API, you need to include a key= parameter and provide the address that you are requesting as the address= parameter that is properly URL encoded using the urllib.parse.urlencode() function as shown in http://www.py4e.com/code3/geojson.py # # Make sure to check that your code is using the API endpoint is as shown above. You will get different results from the geojson and json endpoints so make sure you are using the same end point as this autograder is using. # In[1]: import urllib.request, urllib.parse, urllib.error import json import ssl api_key = False # If you have a Google Places API key, enter it here # api_key = 'AIzaSy___IDByT70' # https://developers.google.com/maps/documentation/geocoding/intro if api_key is False: api_key = 42 serviceurl = 'http://py4e-data.dr-chuck.net/json?' else : serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?' # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # In[6]: address = input('Enter location: ') parms = dict() parms['address'] = address if api_key is not False: parms['key'] = api_key url = serviceurl + urllib.parse.urlencode(parms) print('Retrieving', url) uh = urllib.request.urlopen(url, context=ctx) data = uh.read().decode() print('Retrieved', len(data), 'characters') try: js = json.loads(data) except: js = None if not js or 'status' not in js or js['status'] != 'OK': print('==== Failure To Retrieve ====') print(data) print(json.dumps(js, indent=4)) lat = js['results'][0]['geometry']['location']['lat'] lng = js['results'][0]['geometry']['location']['lng'] print('lat', lat, 'lng', lng) location = js['results'][0]['formatted_address'] print(location) # ### Activity 15: Counting Email in a Database # #### This application will read the mailbox data (mbox.txt) and count the number of email messages per organization (i.e. domain name of the email address) using a database with the following schema to maintain the counts. # In[34]: ###Test import sqlite3 import re email = 'femi.oyedokun@antaeus.com' print(re.findall('@(\w+)',email)) # In[28]: ##Code starts here import sqlite3 import re conn = sqlite3.connect('organdb.sqlite') ## connects to sqlite cur = conn.cursor() ## the handle cur.execute('DROP TABLE IF EXISTS Counts') cur.execute('CREATE TABLE Counts (org TEXT, count INTEGER)') fname = input('Enter file name: ') if (len(fname) < 1): fname = 'mbox-short.txt' fh = open(fname) for line in fh: if not line.startswith('From: '): continue pieces = line.split() email = pieces[1] org_unstrp = re.findall('@(.*).*', email) for domain in org_unstrp: org = domain.strip('') cur.execute('SELECT count FROM Counts WHERE org = ? ', (org,)) row = cur.fetchone() if row is None: cur.execute('''INSERT INTO Counts (org, count) VALUES (?, 1)''', (org,)) else: cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?', (org,)) conn.commit() # https://www.sqlite.org/lang_select.html sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10' for row in cur.execute(sqlstr): print(str(row[0]), row[1]) cur.close() # In[29]: print(org_strip) # ### Activity 16: Multi-Table Database # #### In this activity I will parse an XML list of albums, artists, and Genres and produce a properly normalized database using a Python program # In[ ]: import xml.etree.ElementTree as ET import sqlite3 conn = sqlite3.connect('trackProdb.sqlite') ##making a database connection cur = conn.cursor() ##file/database handle # Make some fresh tables using executescript() cur.executescript(''' DROP TABLE IF EXISTS Artist; DROP TABLE IF EXISTS Genre; DROP TABLE IF EXISTS Album; DROP TABLE IF EXISTS Track; CREATE TABLE Artist ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Genre ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Album ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT UNIQUE ); CREATE TABLE Track ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE, album_id INTEGER, genre_id INTEGER, len INTEGER, rating INTEGER, count INTEGER ); ''') fname = input('Enter file name: ') if ( len(fname) < 1 ) : fname = 'Library.xml' # <key>Track ID</key><integer>369</integer> # <key>Name</key><string>Another One Bites The Dust</string> # <key>Artist</key><string>Queen</string> ### lookup function, to extract the key of a child tag in the xml def lookup(d, key): found = False for child in d: if found : return child.text if child.tag == 'key' and child.text == key : found = True return None stuff = ET.parse(fname) all = stuff.findall('dict/dict/dict') print('Dict count:', len(all)) for entry in all: if ( lookup(entry, 'Track ID') is None ) : continue name = lookup(entry, 'Name') artist = lookup(entry, 'Artist') genre = lookup(entry, 'Genre') album = lookup(entry, 'Album') count = lookup(entry, 'Play Count') rating = lookup(entry, 'Rating') length = lookup(entry, 'Total Time') if name is None or artist is None or album is None or genre is None : continue print(name, artist, album, genre, count, rating, length) cur.execute('''INSERT OR IGNORE INTO Artist (name) VALUES ( ? )''', ( artist, ) ) cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist, )) artist_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id) VALUES ( ?, ? )''', ( album, artist_id ) ) cur.execute('SELECT id FROM Album WHERE title = ? ', (album, )) album_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', (genre,)) cur.execute('SELECT id FROM Genre WHERE name = ? ', (genre,)) genre_id = cur.fetchone()[0] cur.execute('''INSERT OR REPLACE INTO Track (title, album_id, genre_id, len, rating, count) VALUES ( ?, ?, ?, ?, ?, ? )''', ( name, album_id, genre_id, length, rating, count ) ) conn.commit() # ### Activity 17: Multi-Table Database/Many-to-Many Relationship # #### I will be writing a Python program to build a set of tables using the Many-to-Many approach to store enrollment and role data in a course. # # This application will read roster data in JSON format, parse the file, and then produce an SQLite database that contains a User, Course, and Member table and populate the tables from the data file. # In[ ]: import json import sqlite3 conn = sqlite3.connect('RosterProjdb.sqlite') cur = conn.cursor() # Do some setup cur.executescript(''' DROP TABLE IF EXISTS User; DROP TABLE IF EXISTS Member; DROP TABLE IF EXISTS Course; CREATE TABLE User ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Course ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE ); CREATE TABLE Member ( user_id INTEGER, course_id INTEGER, role INTEGER, PRIMARY KEY (user_id, course_id) ) ''') fname = input('Enter file name: ') if len(fname) < 1: fname = 'roster_data_sample.json' # [ # [ "Charley", "si110", 1 ], # [ "Mea", "si110", 0 ], str_data = open(fname).read() json_data = json.loads(str_data) for entry in json_data: name = entry[0]; title = entry[1]; role = entry[2]; print((name, title, role)) cur.execute('''INSERT OR IGNORE INTO User (name) VALUES ( ? )''', ( name, ) ) cur.execute('SELECT id FROM User WHERE name = ? ', (name, )) user_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Course (title) VALUES ( ? )''', ( title, ) ) cur.execute('SELECT id FROM Course WHERE title = ? ', (title, )) course_id = cur.fetchone()[0] cur.execute('''INSERT OR REPLACE INTO Member (user_id, course_id, role) VALUES ( ?, ?, ? )''', ( user_id, course_id, role ) ) conn.commit()
a4d85233ecb8ddfe6a01219c7ce716a61c22d7a6
ashnaagrawal/python
/avg.py
173
3.953125
4
print('THis program calculates the avg of two numbers.'); num1 = 4; num2 = 8; print('the average of', num1, ' and' , num2); print('The average is:', (num1 + num2)/2 );
afd8fcfbdd3fbaee6c1a7604a51bb974a551033f
yunnyisgood/python-oop
/encapsulation/grade.py
1,256
3.875
4
class Grade: def __init__(self, kor, math, eng): self.kor = kor self.math = math self.eng = eng def sum(self): return self.kor + self.math + self.eng def avg(self): return self.sum()/3 def get_grade(self): score = int(self.avg()) # grade = '' # --> 없어도 됨. 자바는 정적언어이기 때문에 미리 변수 선언을 해줘야하지만, 파이썬은 동적언어이기 때문에 하지 않아도 된다. if score >= 90: grade = 'A학점' elif score >= 80: grade = 'B학점' elif score >= 70: grade = 'C학점' elif score >= 60: grade = 'D학점' elif score >= 50: grade = 'E학점' else: grade = 'F학점' return grade @staticmethod def main(): g = Grade(int(input('국어점수 입력')), int(input('수학점수 입력')), int(input('영어점수 입력'))) print(f'총점:{g.sum()}') print(f'평균:{g.avg()}') print(f'총점:{g.get_grade()}') # print(f'{g.kor}+{g.math}+{g.eng}={g.sum()}') # print(f'({g.kor}+{g.math}+{g.eng})/3={g.avg()}') # hi Grade.main()
f0fbb98078255ac9eb12099001d3b275e1ebb79a
tripathysamapika5/dsa
/queue/queue.py
1,968
4.125
4
class Queue: def __init__(self, capacity): self.front, self.rear = -1,-1 self.capacity = capacity self.queue = [] def isFull(self): return self.rear + 1 == self.capacity; def isEmpty(self): return self.front == -1 and self.rear == -1 def enqueue(self, item): if self.isFull(): print("Queue is full. Enqueue operation cant be performed.."); else: if self.isEmpty(): self.front += 1 self.queue.append(item) self.rear += 1 print("inserted {}".format(item)) def dequeue(self): if self.isEmpty(): print("Queue is empty. And dequeing cant be performed...") else: temp = self.queue[self.front] self.front += 1 if (self.front > self.rear): self.front = -1 self.rear = -1 print("Removed {}".format(temp)) return temp def peek(self): if self.isEmpty(): print("Queue is empty. Peek operation cant be performed...") else : return self.queue[self.front] def size(self): return self.rear - self.front + 1 def display(self): i = self.front print("queue : {}".format('~'.join([str(item) for item in self.queue[self.front:self.rear+1]]))) if __name__ == '__main__': queue = Queue(5) queue.peek() queue.dequeue() queue.enqueue(5) queue.enqueue(10) queue.enqueue(15) queue.enqueue(20) queue.enqueue(25) queue.enqueue(30) queue.display() print(queue.peek()) queue.dequeue() queue.dequeue() queue.display() print(queue.peek()) queue.enqueue(99) queue.dequeue() queue.dequeue() queue.dequeue() queue.dequeue() queue.enqueue(5) queue.enqueue(15) queue.display()
f84716f1997a09c8db4ade4f6db7b5e718d74869
mccarvik/cookbook_python
/7_functions/7_capture_vars_anon_funcs.py
567
4
4
x =10 a = lambda y:x+y x=20 b= lambda y:x+y # "x" edit affects outcome print(a(10)) print(b(10)) x = 15 print(a(10)) x=3 print(a(10)) x=10 # can capture it and hold it by defining it as a default value: a = lambda y,x=x : x+y x = 20 b = lambda y,x=x : x+y print(a(10)) print(b(10)) funcs = [lambda x: x+n for n in range(5)] # will just return the last val of range for n for each iteration for f in funcs: print(f(0)) # here n is set to a defualt value so each val in range holds funcs = [lambda x, n=n: x+n for n in range(5)] for f in funcs: print(f(0))
a0d4a4636d5f8b25c4a39ff5649b75e755fd1330
zioan/list_comprehensions
/conditions.py
593
3.578125
4
temps = [221, 234, 340, -9999, 230] new_temps = [temp / 10 if temp != -9999 else 0 for temp in temps ] #-9999 is changed with 0 print(new_temps) #### exercices 1 def foo(list): new_list = [] for i in list: if isinstance(i, int): new_list.append(i) else: new_list.append(0) return(new_list) print(foo([99, "no data", 44, 63, "no data"])) #[99, 0, 44, 63, 0] #### exercices 2 def calc_sum(lst): new_lst = [] for i in lst: number = float(i) new_lst.append(number) result = sum(new_lst) return(result) print(calc_sum(["1.2", "2.6", "3.3"]))
7c573b8d99321b4e3152891e1b20749a2795a443
Kirktopode/Python-Homework
/3Program2.py
893
3.90625
4
grade = raw_input("Gimme a grade between 0.0 and 1.0: ") try: g = float(grade) if g > 1.0: print "Yeah, you could never have gotten more than 100%. Nice try, cheater." elif g >= 0.9: print "An A. Whoopdeedoo, go slap it on the fridge at home so mommy and daddy can be proud." elif g >= 0.8: print "You got a B! It's like the new-age C." elif g >= 0.7: print "You got a C? Well, I guess we need more factory workers." elif g >= 0.6: print "D stands for unintelligent. Go ahead and challenge me. Nobody will take your side." elif g < 0.6 and g >= .0: print "F? It's okay, I already called the police. We all know you're only going to end up as a hooker or a thief." else: print "You got a negative score? I would make fun of you, but I'm just so impressed!" except: print "That's not what I asked for."
d0e641290717078c7ba0c1ffb866dad8df817c23
boknowswiki/mytraning
/lintcode/python/0969_longest_repeating_substring.py
1,072
3.640625
4
# hash , binary search from collections import defaultdict class Solution: """ @param str: The input string @param k: The repeated times @return: The answer """ def longestRepeatingSubsequenceII(self, input_str, k): # Write your code here length = len(input_str) start, end = 0, length while start + 1 < end: mid = (start + end) // 2 if self.count_longest(input_str, mid) >= k: start = mid else: end = mid # print(start) # print(end) # print(self.count_longest(input_str, end)) if self.count_longest(input_str, end) >= k: return end else: return start def count_longest(self, input_str, sub_length): cnt = defaultdict(lambda: 0) max_cnt = 1 for i in range(len(input_str) - sub_length + 1): cnt[input_str[i: i + sub_length]] += 1 max_cnt = max(max_cnt, cnt[input_str[i: i + sub_length]]) return max_cnt
c313781a6cf3d3aa80edabcb918122bbb3f5a940
RyanNoelk/Sudoku
/common/solver.py
4,254
3.828125
4
#!/usr/bin/env python # encoding: utf-8 from math import sqrt from copy import deepcopy class Solver: """Given a raw, unsolved puzzle, this class with return a solved puzzle. raw_puzzle = [ [0,7,8,5,6,0,1,0,0], [0,2,3,0,0,0,5,7,0], [0,0,0,0,0,2,6,0,0], [7,0,0,0,9,1,0,5,3], [0,8,0,0,4,0,0,6,0], [4,3,0,6,2,0,0,0,1], [0,0,6,2,0,0,0,0,0], [0,4,7,0,0,0,3,8,0], [0,0,1,0,3,6,7,2,0] ] solution = Solver(raw_puzzle) pprint(solution.solve_puzzle()) raw_puzzle = [ [0,1,0,0], [0,0,2,0], [0,2,0,0], [0,0,3,0] ] solution = Solver(raw_puzzle) pprint(solution.solve_puzzle()) """ def __init__(self, puzzle, find_unique_solution=False): # The unsolved raw puzzle self.puzzle = puzzle # TODO: We are assuming that we have a square puzzle, make this work for rectangles # The total box height and width self.height = self.width = len(self.puzzle) # The inner box height and width self.box_height = self.box_width = int(sqrt(self.height)) # The maximum int value of the number that can be used in the puzzle self.max_value = self.height if self.height > self.width else self.width # All solved solutions self.solutions = [] self.find_unique_solution = find_unique_solution # Predefined ranges self._range_box_height = range(self.box_height) self._range_box_width = range(self.box_width) self._range_max_value = range(1, self.max_value + 1) def solve_puzzle(self): """:return: the solved puzzle""" self._solve(self.puzzle) def _solve(self, puzzle, current_y=0, current_x=0): """Recursive function that solves a sudoku puzzle using backtracking :param current_x: current position of the x-axis :param current_y: current position of the y-axis :param puzzle: the current puzzle :return: a valid puzzle or None """ if self.find_unique_solution: if len(self.solutions) > 1: return None y, x = self._next_empty(puzzle, current_y, current_x) if x is None or y is None: self.solutions.append(deepcopy(puzzle)) return None for write_val in self._range_max_value: if self._validate_insertion(puzzle, y, x, write_val): puzzle[y][x] = write_val if self._solve(puzzle, y, x) is not None: return puzzle puzzle[y][x] = 0 return None def _next_empty(self, puzzle, y_start, x_start): """ Returns the position of the next empty value, none if there aren't any. Then sets moves the pointer to the next number. :param x_start: starting position of the x-axis :param y_start: starting position of the y-axis :param puzzle: the current puzzle :return: the y, x coordinates of the next empty square """ for y in range(y_start, self.height): for x in range(x_start, self.width): if 0 == puzzle[y][x]: return y, x x_start = 0 return None, None def _validate_insertion(self, puzzle, y, x, num): """ Checks the puzzle if its valid :param x: x-axis location :param y: y-axis location :param num: The number to be tried :return: If the puzzle is valid """ # check the row for val in puzzle[y]: if num == val: return False # check the column for val in puzzle: if num == val[x]: return False # check the box start_y = int(y / self.box_height) * self.box_height start_x = int(x / self.box_width) * self.box_width for val_y in self._range_box_height: for val_x in self._range_box_width: if num == puzzle[val_y+start_y][val_x+start_x]: return False return True
5ed921042deccca7a57b98b845b6633ee7a35516
quigsml/PythonTrainingFiles
/Part1_IntroProgramming/Chapter9_Files/Chapter9_Practice.py
1,029
4.0625
4
import os # "r" open a file for reading only # "w" opens for writing only. Overites existing or creates new # "w+" opens for reading & writing. overwrites existing or creates new. #st = open("st.txt", "w") #st.write("Hi from Python!") #st.close() # use with-statement to automatically close file. f is just a variable. with open("st.txt", "w") as f: f.write("Hi from Python using With_Statement!") #with open("st.txt", "r") as f: # print(f.read()) #can only read once without closing and reopening again. #can save as another variable: my_list = [] with open("st.txt", "r") as f: my_list.append(f.read()) print(my_list) import csv with open("st.csv", "w", newline="") as f: w = csv.writer(f, delimiter=",") w.writerow(["one", "two", "three"]) w.writerow(["four", "five", "six"]) with open("st.csv", "r") as f: r = csv.reader(f, delimiter=",") for i in r: print(",".join(i))
124c3499ef5bd5cad01e8a680f10eb2443f3c7b3
codigoenlaweb/calculator
/src/main.py
3,887
3.875
4
from tkinter import * from tkinter import font from typing import Sized root = Tk() root.title("calculator") # VARIABLES i = 0 # FUNCTION # ADD INPUT def click_button(e): global i e_text.insert(i, e) i += 1 # REMOVE INPUT def clean(): global i e_text.delete(0, END) i = 0 def result(): global i equation = e_text.get() equation_filter_x = equation.replace("x", "*") equation_filter_exp = equation_filter_x.replace("^", "**") equation_result = eval(equation_filter_exp) e_text.delete(0, END) e_text.insert(i, equation_result) i = 0 # INPUT e_text = Entry(root) # BUTTON # NUMBER btn1 = Button(root, command= lambda: click_button(1)) btn2 = Button(root, command= lambda: click_button(2)) btn3 = Button(root, command= lambda: click_button(3)) btn4 = Button(root, command= lambda: click_button(4)) btn5 = Button(root, command= lambda: click_button(5)) btn6 = Button(root, command= lambda: click_button(6)) btn7 = Button(root, command= lambda: click_button(7)) btn8 = Button(root, command= lambda: click_button(8)) btn9 = Button(root, command= lambda: click_button(9)) btn0 = Button(root, command= lambda: click_button(0)) # ACTION btn_delete = Button(root, command= lambda: clean()) btn_barckets_left = Button(root, command= lambda: click_button("(")) btn_barckets_right = Button(root, command= lambda: click_button(")")) btn_decimal = Button(root, command= lambda: click_button(".")) btn_equal = Button(root, command= lambda: result()) # OPERATOR btn_sum = Button(root, command= lambda: click_button("+")) btn_subt = Button(root, command= lambda: click_button("-")) btn_mult = Button(root, command= lambda: click_button("x")) btn_division = Button(root, command= lambda: click_button("/")) btn_exp = Button(root, command= lambda: click_button("^")) # CONFIG STYLE # INPUT e_text.config(font=("calibri 20"), width=14) # NUMBER btn1.config(text="1", width=5, height=2) btn2.config(text="2", width=5, height=2) btn3.config(text="3", width=5, height=2) btn4.config(text="4", width=5, height=2) btn5.config(text="5", width=5, height=2) btn6.config(text="6", width=5, height=2) btn7.config(text="7", width=5, height=2) btn8.config(text="8", width=5, height=2) btn9.config(text="9", width=5, height=2) btn0.config(text="0", width=5, height=2) # ACTION btn_delete.config(text="AC", width=5, height=2) btn_barckets_left.config(text="(", width=5, height=2) btn_barckets_right.config(text=")", width=5, height=2) btn_decimal.config(text=".", width=5, height=2) btn_equal.config(text="=", width=5, height=2) # OPERATOR btn_sum.config(text="+", width=5, height=2) btn_subt.config(text="-", width=5, height=2) btn_mult.config(text="x", width=5, height=2) btn_division.config(text="÷", width=5, height=2) btn_exp.config(text="exp", width=5, height=2) # GRID # INPUT e_text.grid(row=0, column=0, columnspan=4, padx=10, pady=5) # NUMBER btn1.grid(row=4, column=0, padx=0, pady=6) btn2.grid(row=4, column=1, padx=0, pady=6) btn3.grid(row=4, column=2, padx=0, pady=6) btn4.grid(row=3, column=0, padx=0, pady=6) btn5.grid(row=3, column=1, padx=0, pady=6) btn6.grid(row=3, column=2, padx=0, pady=6) btn7.grid(row=2, column=0, padx=0, pady=6) btn8.grid(row=2, column=1, padx=0, pady=6) btn9.grid(row=2, column=2, padx=0, pady=6) btn0.grid(row=5, column=1, padx=0, pady=6) # ACTION btn_delete.grid(row=1, column=0, padx=0, pady=6) btn_barckets_left.grid(row=1, column=1, padx=0, pady=6) btn_barckets_right.grid(row=1, column=2, padx=0, pady=6) btn_decimal.grid(row=5, column=0, padx=0, pady=6) btn_equal.grid(row=5, column=3, padx=0, pady=6) # OPERATOR btn_sum.grid(row=3, column=3, padx=0, pady=6) btn_subt.grid(row=4, column=3, padx=0, pady=6) btn_mult.grid(row=2, column=3, padx=0, pady=6) btn_division.grid(row=1, column=3, padx=0, pady=6) btn_exp.grid(row=5, column=2, padx=0, pady=6) root.mainloop()
7129402aa315d39339923b257b07b99db67a0985
chenxingyuoo/learn
/python_learn/廖雪峰python/10.进程和线程/2.多线程/2.Lock.py
1,302
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time, threading # 假定这是你的银行存款: balance = 0 def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(100000): change_it(n) t1 = threading.Thread(target=run_thread, args=(5,)) t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance) # 理论上结果应该为0,但不一定等于0,由于线程的调度是由操作系统决定的,当t1、t2交替执行时,只要循环次数足够多,balance的结果就不一定是0了。 # 创建一个锁 balance1 = 0 lock = threading.Lock() def change_it1(n): # 先存后取,结果应该为0: global balance1 balance1 = balance1 + n balance1 = balance1 - n def run_thread1(n): for i in range(100000): # 先要获取锁: lock.acquire() try: # 放心地改吧: change_it(n) finally: # 改完了一定要释放锁: lock.release() t3 = threading.Thread(target=run_thread1, args=(5,)) t4 = threading.Thread(target=run_thread1, args=(8,)) t3.start() t4.start() t3.join() t4.join() print(balance1)
b168ddbb428e378710c177eadd4d1f5047d174ed
SSolomevich/Acmp_Python
/acmp/023.py
101
3.71875
4
a=int(input()) summ=0 for b in range(a): if (b>0 and a%b==0): summ=summ+b print(summ+a)
444dca5269f336f8d4608473b5fe6364c46b7922
gayathrig269/Two-Pointers-1
/sort_colors.py
989
3.703125
4
# -*- coding: utf-8 -*- """ TC : O(N) where N is the length of array given SC: O(1) as we are not using any extra space """ class Solution: def sortColors(self, nums: List[int]) -> None: #edge case if not nums or len(nums) == 0: return -1 l = 0 m = 0 h = len(nums) - 1 while m <= h:#traverse the entire array #check for case m = 1 if nums[m] == 1: m += 1 #increment mid pointer #check for case m = 2 elif nums[m] == 2: self.swap(nums,m,h) #swap mid with high pointer h -= 1 #for case m = 0 else: self.swap(nums,m,l)#swap contents of mid and low l += 1 #increment low and mid m += 1 def swap(self,nums: List[int],a :int,b: int): #function to swap elements temp = nums[a] nums[a] = nums[b] nums[b] = temp
a6210a92fdcdeb58c9f3a389d9809548c6c5bdc8
marygeo91/asteroids
/second.py
15,301
3.5
4
#!/usr/bin/env python import numpy as np import timeit as ti import scipy.stats as st import scipy.integrate as ig import matplotlib.pyplot as pl import matplotlib.ticker as tk def euler_forward(previous=np.array([[1.0], [0.0]]), step=1e-3): ''' Using the Euler Forward Method written in the matrix form for this specific system of differential equations, this function receives the last step - as well as a step size value - and returns the following step. ''' assert step > 0.0, 'Step has to be higher than zero!' matrix = np.array([[1.0, step], [-step, 1.0]]) return np.dot(matrix, previous) def euler_backward(previous=np.array([[1.0], [0.0]]), step=1e-3): ''' Using the Euler Backward Method written in the matrix form for this specific system of differential equations, this function receives the last step - as well as a step size value - and returns the following step. ''' assert step > 0.0, 'Step has to be higher than zero!' matrix = (1.0/(1.0+step**2))*np.array([[1.0, step], [-step, 1.0]]) return np.dot(matrix, previous) def euler_symplectic(previous=np.array([[1.0], [0.0]]), step=1e-3): ''' Using the Euler Symplectic Method written in the matrix form for this specific system of differential equations, this function receives the last step - as well as a step size value - and returns the following step. ''' assert step > 0.0, 'Step has to be higher than zero!' matrix = np.array([[1.0-step**2, step], [-step, 1.0]]) return np.dot(matrix, previous) def func(previous=np.array([[1.0], [0.0]])): ''' Returns the vectorial function f(x, v) associated to the specific problem (Harmonic Oscillator), given the previous known point. ''' return np.array([[previous[1][0]], [-previous[0][0]]]) def midpoint_rule(previous=np.array([[1.0], [0.0]]), step=1e-3): ''' Using the Midpoint Rule, this function receives the last step - as well as a step size value - and returns the following step. ''' assert step > 0.0, 'Step has to be higher than zero!' k1 = step*func(previous) k2 = step*func(previous+0.5*k1) return previous+k2 def runge_kutta(previous=np.array([[1.0], [0.0]]), step=1e-3): ''' Using the fourth order Runge-Kutta, this function receives the last step - as well as a step size value - and returns the following step. ''' assert step > 0.0, 'Step has to be higher than zero!' k1 = step*func(previous) k2 = step*func(previous+0.5*k1) k3 = step*func(previous+0.5*k2) k4 = step*func(previous+k3) return previous+k1/6.0+k2/3.0+k3/3.0+k4/6.0 def f_ode(previous, t): ''' Same as func, but this one is specifically for the odeint integrator. ''' return [previous[1], -previous[0]] def calc(solution=np.array([[1.0], [0.0]]), method=euler_forward, step=1e-3, num_step=5e4): ''' This function receives the initial condition, a specific solving method, the step size and the total number of steps and uses all these to compute the solution of a certain system of differential equantions. ''' assert step > 0.0, 'Step has to be higher than zero!' assert int(num_step) >= 1, 'Number of steps has to be higher than one!' for i in range(int(num_step)): solution = np.append(solution, method(solution[:, [i]], step), axis=1) return solution def plot(name='Plots/test_plot.png', title='Plotting test', data=[[[0.0, 1.0], [1.0, 0.8]], [[0.0, 1.0], [0.6, 0.0]]], params=[['k', '-', 1.1], ['r', '--', 0.9]], axes=['Time (t/s)', 'Position (x/m)'], legend=0, labels=['Data 1', 'Data 2'], scale='linear'): ''' This function receives a group of parameters (such as the figure name, the figure title, the markers/lines parameters, the axes labels, the legend position within the figure, the data legends and the axes scale) and a set of data and plots them all together in the same figure. ''' assert len(data) > 0, 'Data cannot be an empty array!' assert len(labels) == len(data), 'Incorrect amount of labels!' assert len(params) == len(data), 'Incorrect amount of marker parameters!' # Sets the size of the generated figure. pl.figure(figsize=(8, 4)) # Sets the rotation of the tick labels. pl.xticks(rotation=15) pl.yticks(rotation=15) # Sets the title parameters. pl.title(title, fontsize=18, weight='bold') # Sets the axes labels parameters. pl.xlabel(axes[0], labelpad=8, fontsize=14) pl.ylabel(axes[1], labelpad=8, fontsize=14) # Sets the background grid parameters. pl.grid(color='gray', linestyle='-.', linewidth=0.8, alpha=0.2) # Sets the axes ticks parameters. ca = pl.gca() ca.tick_params(which='minor', bottom=False, left=False) ca.tick_params(top=True, right=True, length=5, width=1.25, labelsize=10, direction='in', pad=5) if scale == 'log': ca.xaxis.set_major_formatter(tk.ScalarFormatter()) ca.yaxis.set_major_formatter(tk.ScalarFormatter()) if scale == 'linear': ca.ticklabel_format(axis='y', fontstyle='italic', style='sci', useMathText=True, scilimits=(0, 0)) # Sets the axes thickness. sides = ['top', 'bottom', 'left', 'right'] [ca.spines[s].set_linewidth(1.25) for s in sides] # Plots the different sets of data with the received parameters. for i in range(len(data)): ca.plot(data[i][0], data[i][1], params[i][0]+params[i][1], label=labels[i], lw=float(params[i][2])) # Sets the legend parameters. ca.legend(loc=legend, ncol=3, columnspacing=0.65, handletextpad=0.15, labelspacing=0.15, handlelength=1.3, borderpad=0.25, borderaxespad=0.75) # Sets the axes offset text (scientific notation) parameters. xo, yo = ca.get_xaxis().get_offset_text(), ca.get_yaxis().get_offset_text() xo.set_fontsize(8) yo.set_fontsize(8) xo.set_fontstyle('italic') yo.set_fontstyle('italic') # Sets the axes scale. if scale != 'linear': pl.xscale(scale) pl.yscale(scale) # Saves and closes the obtained figure. pl.tight_layout() pl.savefig(name, dpi=500, facecolor='ivory', edgecolor=None) pl.close() def results(method=euler_forward, method_name='Euler Forward', method_tag='feul', time_ana=np.arange(0.0, 10.0, 0.1), step=1e-3, solu_ana=np.cos(np.arange(0.0, 10.0, 0.1)), num_step=5e4, h_list=np.logspace(-5, 0, num=5, base=2)): ''' This function receives, as a function, a computional method to solve a specific set of coupled first order differential equations (as well as the respective method name and tag for the filenames), an array with times and another one with the known analytic solution of the system on those points in time, the step size and the total number of steps used in the analytic solution array and the list of step sizes that will be used with the chosen method. Not only it creates some plots showing the difference between the calculated quantities considering the different step sizes, as it also returns those quantities for a further analysis outside this function. ''' assert step > 0.0, 'Step has to be higher than zero!' assert len(h_list) > 0, 'List of step sizes cannot be an empty array!' assert int(num_step) >= 1, 'Number of steps has to be higher than one!' assert len(time_ana) > 0, 'Analytic times cannot be an empty array!' assert len(solu_ana) > 0, 'Analytic solution cannot be an empty array!' assert len(time_ana) == len(solu_ana), 'Unmatching analytic arrays!' # Creates empty arrays that will contain the calculated quantities (such as # the computed times, the computed solution, the computed total energy of # the considered system, the absolute global error in the computed position # when comparing to the analytic solution, the maximum absolute global # error for each considered step size and the maximum system energy value # for each considered step size as well). time_com, solu_com, solu_ene = [], [], [] posi_err, maxi_err, maxi_ene = [], [], [] # Stores the list of colors used for plotting the data corresponding to the # different considered step sizes. colors = ['g', 'y', 'c', 'b', 'm', 'r'] # Creates and initializes the arrays that will contain all the data labels, # the markers/lines parameters for plotting purposes and, for every step # size considered, the computed system solutions, the absolute global # errors and the total energy of the system - all as functions of the time. data_labels, data_params = ['Ana. Sol.'], [['k', '-', 1.1]] solutions, global_errors, energies = [[time_ana, solu_ana]], [], [] for i in range(len(h_list)): # Calculates the amount of steps needed to get to a specific time. h = h_list[i] N = num_step*step/h # Calculates the time array, the computed system solution, the absolute # global errors in the computed solution for the mass position and its # corresponding maximum value, the initial energy of the system, the # energy of the system relatively to its initial value and, finally, # the maximum of the previously mentioned array. The if/else exception # deals with the odeint integration differently. time_com.append(np.arange(0.0, num_step*step, h)) leng = len(time_com[i]) if method != ig.odeint: solu_com.append(calc(step=h, method=method, num_step=N)[:, :leng]) else: temp = method(f_ode, [1.0, 0.0], time_com[i], hmin=h, hmax=h) solu_com.append(np.swapaxes(temp, 0, 1)) iene = solu_com[i][0][0]**2 + solu_com[i][1][0]**2 solu_ene.append(np.sum(solu_com[i]**2, axis=0)-iene) posi_err.append(np.cos(time_com[i])-solu_com[i][0]) maxi_ene.append(max(np.absolute(solu_ene[i]))) maxi_err.append(max(np.absolute(posi_err[i]))) # Adds the new data labels and respective markers/lines parameters, and # stores the some of the previous calculations in the previously # created arrays for this specific purpose. data_labels.append('h = %.3f' % h) data_params.append([colors[i], '--', 0.9]) solutions.append([time_com[i], solu_com[i][0]]) global_errors.append([time_com[i], posi_err[i]]) energies.append([time_com[i], solu_ene[i]]) # For different step sizes and the considered method, generates three # plots: the first one with the computed solutions as a function of time, # the second one with the computed absolute global errors as a function of # time (relatively to the known analytic solution) and the third one with # the total energy of the system as a function of time (relatively to its # initial value). plot(name='Plots/' + method_tag + '_sol.png', data=solutions, title=method_name + ' - Solution', labels=data_labels, params=data_params, legend=3) plot(name='Plots/' + method_tag + '_err.png', data=global_errors, title=method_name + ' - Error', labels=data_labels[1:], axes=['Time (t/s)', 'Absolute global error (x/m)'], params=data_params[1:]) plot(name='Plots/' + method_tag + '_ene.png', data=energies, title=method_name + ' - Energy', labels=data_labels[1:], axes=['Time (t/s)', 'Total energy variation (E/J)'], params=data_params[1:]) return [solutions, global_errors, energies, maxi_ene, maxi_err] if __name__ == '__main__': # Tests the plotting function. plot() # Generates the analytical solution. step_size, number_steps = 1e-3, 5e4 analytic_times = np.arange(0.0, number_steps*step_size, step_size) analytic_solution = np.cos(analytic_times) # Generates the array of step sizes that will be used. steps_list = 0.512*np.logspace(-9, -4, num=6, base=2, endpoint=True) # Stores the functions, names and tags (for the filenames) for each method. methods = [euler_forward, euler_backward, euler_symplectic, midpoint_rule, runge_kutta, ig.odeint] names = ['Euler Forward', 'Euler Backward', 'Euler Symplectic', 'Midpoint Rule', '$4^{th}$ Runge-Kutta', 'SciPy odeint'] tags = ['eul_for', 'eul_bac', 'eul_sym', 'mid_rul', 'run_kut', 'ode_int'] assert len(names) == len(methods), 'Arrays must have the same length!' assert len(tags) == len(methods), 'Arrays must have the same length!' # Stores the list of colors used for plotting the data corresponding to the # different considered methods. colors = ['g', 'y', 'c', 'b', 'm', 'r'] # Creates an array which will contain the final results of each considered # method and also empty arrays for some useful linear regressions - these # will give an idea of the rate of growth of the quantities (total energy # of the system and absolute global error) plotted in the y axis as a # function of the step size. Then it executes all the calculations for each # method, storing the obtained results directly into the mentioned arrays; # arrays for the labels and marker/lines parameters are also created. final, energy, errors, ene_label, err_label, pars = [], [], [], [], [], [] for i in range(len(methods)): # Exception that deals with the fact that the odeint function does not # integrate for the three bigger step sizes that were chosen. if methods[i] == ig.odeint: slist = steps_list[:3] else: slist = steps_list final.append(results(method=methods[i], method_name=names[i], method_tag=tags[i], time_ana=analytic_times, solu_ana=analytic_solution, h_list=slist)) energy.append([slist, final[i][3]]) ene_label.append(names[i]) l = st.linregress(np.log10(slist), np.log10(final[i][3])) temp = (10**l[1])*(slist**l[0]) energy.append([slist, temp]) ene_label.append(r'$\Delta E=a\times h^{%.3f}$' % l[0]) errors.append([slist, final[i][4]]) err_label.append(names[i]) l = st.linregress(np.log10(slist), np.log10(final[i][4])) temp = (10**l[1])*(slist**l[0]) errors.append([slist, temp]) err_label.append(r'$GE=a\times h^{%.3f}$' % l[0]) pars.append([colors[i], 'x', 7.5]) pars.append([colors[i], ':', 1.1]) # Generates two plots: the maximum value of the total energy of the system # as a function of the step size and the maximum absolute global error as a # function of the step size (for the different considered methods). plot(name='Plots/energy_method.png', title='Total energy vs. Step size', scale='log', axes=['Step size (h/m)', 'Maximum total energy (E/J)'], data=energy, labels=ene_label, params=pars) plot(name='Plots/errors_method.png', title='Global error vs. Step size', scale='log', axes=['Step size (h/m)', 'Maximum global error (x/m)'], data=errors, labels=err_label, params=pars)
0b6f03088fdb1e09b169efe882a33731173f58f3
kashishy/MLTraining
/mlpackage01/MLPractical61.py
2,646
3.640625
4
# Spot checking is used to check which model is best for the given data import pandas as pd from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score import warnings warnings.filterwarnings(action='ignore') filename = 'indians-diabetes.data.csv' hnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pd.read_csv(filename, names=hnames) array = dataframe.values X = array[:, 0:8] Y = array[:, 8] kfold = KFold(n_splits=10) # 1: Spot checking for Logistic Regression from sklearn.linear_model import LogisticRegression model = LogisticRegression() results = cross_val_score(model, X, Y, cv=kfold) print("Validation Score for LogisticRegression : ", results.mean()) # 2: Spot Checking for Linear Discriminant Analysis(LDA) from sklearn.discriminant_analysis import LinearDiscriminantAnalysis model = LinearDiscriminantAnalysis() results = cross_val_score(model, X, Y, cv=kfold) print("Validation Score for Linear Discriminant Analysis : ", results.mean()) # 3: Spot Checking for k-Nearest Neighbors(kNN) from sklearn.neighbors import KNeighborsClassifier model = KNeighborsClassifier() results = cross_val_score(model, X, Y, cv=kfold) print("Validation Score for KNN : ", results.mean()) # 4: Spot Checking for Gaussian Naive Bayes # Naive Bayes calculation the probability of each class and # the conditional probability of each class given each input value # These probabilities are estimated for new data and # multiplied together assuming that they are all # independent ( a simple or naive assumption) from sklearn.naive_bayes import GaussianNB model = GaussianNB() results = cross_val_score(model, X, Y, cv=kfold) print("Validation Score for GaussianNB : ", results.mean()) # 5: Spot Checking for Classification And Regression Tress # (CART or just decision tress) # ________________________________________________________ # CART or just decision trees construct a binary tree # from the training data from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier() results = cross_val_score(model, X, Y, cv=kfold) print("Validation Score for CART Decision Tree : ", results.mean()) # 6: Spot Checking for Support Vector Machines(SVM) # ------------------------------------------------ # SVM seek a line that best separates two classes # Those data instances that are closest to the line that # best separates the classes are called support vectors # and influence where the line is placed from sklearn.svm import SVC model = SVC() results = cross_val_score(model, X, Y, cv=kfold) print("Validation Score for SVM : ", results.mean())
2965803d3a9b80ad371c3fd0a0f913c1721fdef6
kyleclo/practice
/stacks-and-queues/stacks-and-queues.py
1,313
4
4
""" Relation between Stacks and Queues """ from collections import deque class QueueUsingTwoStacks: def __init__(self): self.outbox = [] self.inbox = [] def dequeue(self): if len(self.outbox) == 0: while len(self.inbox) > 0: self.outbox.append(self.inbox.pop()) return self.outbox.pop() def enqueue(self, value): self.inbox.append(value) class StackUsingTwoQueues: def __init__(self): self.current = deque() self.other = deque() def pop(self): while len(self.current) > 1: self.other.appendleft(self.current.pop()) self.current, self.other = self.other, self.current return self.other.pop() def push(self, value): self.current.appendleft(value) if __name__ == '__main__': print 'Enqueue values 1, 2, 3 to queue.' queue = QueueUsingTwoStacks() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print 'Dequeue values 1, 2, 3 in that order.' for _ in range(3): print queue.dequeue() print 'Push values 1, 2, 3 to stack.' stack = StackUsingTwoQueues() stack.push(1) stack.push(2) stack.push(3) print 'Pop values 3, 2, 1 in that order.' for _ in range(3): print stack.pop()
a07516ebb0212f8799774801bf76d76b46bcba12
mariasykpotter/Maze
/maze.py
5,813
4.15625
4
# Implements the Maze ADT using a 2-D array. from arrays import Array2D from lliststack import Stack class Maze: '''Class for Maze representation.Defines constants to represent contents of the maze cells.''' MAZE_WALL = " *" PATH_TOKEN = " x" TRIED_TOKEN = " o" def __init__(self, n_rows, n_cols): '''Creates a maze object with all cells marked as open.''' self._mazeCells = Array2D(n_rows, n_cols) self._startCell = None self._exitCell = None def num_rows(self): ''' Returns the number of rows in the maze. :return: int ''' return self._mazeCells.num_rows() def num_cols(self): ''' Returns the number of columns in the maze. :return: int ''' return self._mazeCells.num_cols() def setWall(self, row, col): ''' Fills the indicated cell with a "wall" marker. :param row: int :param col: int :return: None ''' assert row >= 0 and row < self.num_rows() and \ col >= 0 and col < self.num_cols(), "Cell index out of range." self._mazeCells[row, col] = self.MAZE_WALL def setStart(self, row, col): '''Sets the starting cell position.''' assert row >= 0 and row < self.num_rows() and \ col >= 0 and col < self.num_cols(), "Cell index out of range." self._startCell = _CellPosition(row, col) def setExit(self, row, col): '''Sets the exit cell position.''' assert row >= 0 and row < self.num_rows() and \ col >= 0 and col < self.num_cols(), "Cell index out of range." self._exitCell = _CellPosition(row, col) def inside_the_field(self, tup): ''' Defines whether cell with tup coordinates is inseide the field. :param tup: tuple :return: bool ''' return 0 <= tup[0] < self.num_rows() and 0 <= tup[1] < self.num_cols() def neighbours(self, tup): ''' Returns all the horizontal and vertical neighbours for cell with coordinates tuple. :param tup: tuple :return: list ''' # lst = [(tup[0], tup[1] + 1), (tup[0] + 1, tup[1]), (tup[0], tup[1] - 1), (tup[0] - 1, tup[1]), # (tup[0] + 1, tup[1] - 1), (tup[0] - 1, tup[1] + 1), (tup[0] + 1, tup[1] + 1), (tup[0] - 1, tup[1] - 1)] lst = [(tup[0], tup[1] + 1), (tup[0] + 1, tup[1]), (tup[0], tup[1] - 1), (tup[0] - 1, tup[1])] neighbors = [el for el in lst if self.inside_the_field(el)] return neighbors def findPath(self): ''' Attempts to solve the maze by finding a path from the starting cell to the exit. Returns True if a path is found and False otherwise. :return: bool ''' label = "" stack = Stack() stack1 = Stack() stack.push((self._startCell.row, self._startCell.col)) while not stack.isEmpty(): count = 0 tup = stack.pop() if self._exitFound(tup[0], tup[1]): self._markPath(tup[0], tup[1]) return True elif self._validMove(tup[0], tup[1]): self._markPath(tup[0], tup[1]) stack1.push(tup) if label == "second_time": self.neighbours(tup).pop() for el in self.neighbours(tup): if self._validMove(el[0], el[1]): stack.push(el) count += 1 if not count: last = stack1.pop() self._markTried(last[0], last[1]) stack.push(stack1.peek()) label = "second_time" return False def reset(self): '''Resets the maze by removing all "path" and "tried" tokens.''' for i in range(self.num_rows()): for j in range(self.num_cols()): if self._mazeCells[i, j] == self.PATH_TOKEN or self._mazeCells[i, j] == self.TRIED_TOKEN: self._mazeCells[i, j] = None def draw(self): '''Prints a text-based representation of the maze.''' text = "" for i in range(self.num_rows()): for j in range(self.num_cols()): if self._mazeCells[i, j]: text += self._mazeCells[i, j] else: text += " " text += "\n" print(text) def _validMove(self, row, col): ''' Returns True if the given cell position is a valid move. :param row: int :param col: int :return: True ''' return row >= 0 and row < self.num_rows() \ and col >= 0 and col < self.num_cols() \ and self._mazeCells[row, col] is None def _exitFound(self, row, col): ''' Helper method to determine if the exit was found. :param row: int :param col: int :return: bool ''' return row == self._exitCell.row and col == self._exitCell.col def _markTried(self, row, col): ''' Drops a "tried" token at the given cell. :param row: int :param col: int ''' self._mazeCells[row, col] = self.TRIED_TOKEN def _markPath(self, row, col): ''' Drops a "path" token at the given cell. :param row: int :param col: int ''' self._mazeCells[row, col] = self.PATH_TOKEN class _CellPosition(object): '''Private storage class for holding a cell position''' def __init__(self, row, col): ''' Initialises a cell. :param row: int :param col: int ''' self.row = row self.col = col
847e65703e1be5951386f88cbfe47f89eb7835aa
paco-portada/Python
/ficherosPython/ejercicio1.py
986
3.515625
4
#_*_ coding=UTF-8 _*_ # ejercicio1.py # Programa que guarda en un fichero con nombre primos.dat los # números primos que hay entre 1 y 500. # @author Alvaro Garcia Fuentes from io import open # Funcion para determinar si un número es primo # @param i # @return boolean def esPrimo( i ): for k in range( 2 , int(i/2+1) ): if( int(i) % k == 0 ): return False return True lista = [] fichero = None pw = None # Se calculan los números primos entre 1 y 500 # y se almacenan en la lista for i in range( 1, 500 ): if( esPrimo(i) ): lista += [i] try: # Se crea abre el fichero en modo escritura fichero = open( 'primos.dat' , 'w' ) # Se escriben los datos en el fichero for i in lista: fichero.write( f"{i}" + '\n' ) print( "Fichero creado con éxito." ) except: print( "ERROR: no se pudo crear el fichero." ) try: # Se cierra el fichero if( None != fichero ): fichero.close() except: print( "ERROR: no se pudo cerrar el fichero." ) # Fin del programa
ad423e7d08db27f93ac001dca248230071fbb358
Batto1300/renewable-energy-analysis
/renewable_energy_analysis/cleaning/energy_consumption.py
2,245
3.828125
4
""" This script cleans the original data set containing the energy consumption figures for the world countries. Firsly, we remove some redundant rows. Secondly, we filter the dataset for those countries and years which are common to all datasets. """ import pandas as pd # import class with full paths to files import file_names as fn # original data (csv file) - energy consumption for world countries ORIGINAL_ENERGY_CONSUMPTION = fn.OriginalPaths.CONSUMPTION # years and countries common to all datasets COUNTRIES = fn.CleanedPaths.COUNTRIES YEARS = fn.CleanedPaths.YEARS # name of new csv file to store the new cleaned dataset CLEANED_ENERGY_CONSUMPTION = fn.CleanedPaths.CONSUMPTION # import the data on energy consumption into a dataframe object df_energy_consumption = pd.read_csv(ORIGINAL_ENERGY_CONSUMPTION) # the appropriate header row with the years is in row index 1 header = df_energy_consumption.iloc[1] # change the first entry of header (= "Million...") to "country" header[0] = "country" # change UK to United Kingdom header = list(map(lambda x: str.replace(x, "UK", "United Kingdom"), header)) # set the new header to the dataframe df_energy_consumption.columns = header # drop last 3 columns - simple summary statistics not useful df_energy_consumption.drop(columns = header[-3:], inplace = True) # drop first 2 rows - getting the dataframe into the same format as others df_energy_consumption = df_energy_consumption[3:] # importing countries and years common to all dataframes df_countries = pd.read_csv(COUNTRIES) df_years = pd.read_csv(YEARS) # from dataframe object to list years = list(df_years["years"]) # convert years from integer to string type years = list(map(str, years)) # filter for common countries through merging with countries dataframe df_energy_consumption = pd.merge(df_energy_consumption, df_countries, on="country", how="inner") # set country column as index column - this way we can filter for the years df_energy_consumption.set_index("country", inplace = True) # filter only for the years commom to all data sets df_energy_consumption = df_energy_consumption[years] # save cleaned data set to a new csv file df_energy_consumption.to_csv(CLEANED_ENERGY_CONSUMPTION)
9378bbf9f1164c5e1a49e31558581aae21b382e3
SleepingActor/Example
/example.py
4,890
3.71875
4
######################################################################################################################## i = int(input("процентная ставка в год: ")) # годовая процентная ставка i = i / 100 n = int(input("кол-во месяцев: ")) # кол-во месяцев S = int(input("сумма кредита: ")) # сумма кредита add = 0 # i = 10/1200 # n = 120 # S = 880000 # K = (i * (1+i)**n) / (((1+i)**n) - 1) # A = S * K # Decrease = 22500 # print("Сумма кредита: ", S) # print("Процентная ставка: ", i) # print("Срок кредита(мес): ", n) # print("Коэффициент аннуитета: ", K) # print("Всего в уплату по кредиту: ", A*n) # print("Ежемесячный платёж: ", A) # print("Желаемый ежемесячный платёж: ", Decrease) # print("######################################################") # # while S > 0: # K = (i * (1 + i) ** n) / (((1 + i) ** n) - 1) # коэфициент(зависит от n) # A = S * K # ежемесячный платёж(учитывается коэфициент) # percent = S*i # проценты за пользование кредитными средствами # percent = round(percent, 2) # # add = Decrease - A # # add = round(add, 2) # debt = A - percent + add # что идёт в погашение долга # debt = round(debt, 2) # S = S - debt # новое "тело" кредита # S = round(S, 2) # print("Необходимая добавочная сумма: ", add) # print("Сумма платежа:", percent + debt) # print("В погашение процентов: ", percent) # print("В погашение долга: ", debt) # print("В погашение долга(без доп.платежа): ", debt - add) # print("Остаток долга: ", S) # print(n) # n -= 1 # print("Выплата кредита раньше на", n, "мес.") # print("Управился за", 105 - n, "мес.") # print("Или за", (105 - n)/12, "лет.") ######################################################################################################################## ######################################################################################################################## def fib(x): if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) y = fib(5) print(y) ######################################################################################################################## # Задача на нахождение множества C(n,k) = # n, k = map(int, input().split()) # def bunch(n, k): # if k > n: # return 0 # elif k == 0: # return 1 # else: # return bunch(n - 1, k) + bunch(n - 1, k - 1) # print(bunch(n, k)) ######################################################################################################################## # Задача с нахождением повторяющихся в списке элементов и однократном их выводе на экран # a = [int(i)for i in input().split()] # Чтение из строки информации, разбивается по пробелу # a = [1, 2, 4, 3, 1, 0, 9, 99, 78, 456, 0, 4] # print('a = ', a) # for i in range(len(a)): # print(i, a[i]) # if a.count(i) > 1: # print('Повторное число: ', i) ######################################################################################################################## # Формирование запроса по ссылке + извлечение данных с оной # adress = 'https://stepic.org/media/attachments/course67/3.6.3/' # count = 0 # Отдадочная инфрормация # with open('dataset_3378_3 (2).txt') as r: # Открываем файйл под именем R # url = r.readline().strip() # Считываем одну строчку, обрезая лишнее # get = requests.get(url).text # Получаем данные со страницы # # while get[0] != 'W': # get = requests.get(adress+get).text # Формируем в цикле новый адрес # count += 1 # Отдадочная инфрормация # print(count) # Отдадочная инфрормация # print(get) ########################################################################################################################
491e27e4ed9b0449210bef4b4ca0421935646397
abinashdash17/python_progs
/ex22.py
267
3.765625
4
x = input("Enter a sentence: ") y = x.split(" ") y_set = set(y) wc = {} for word in y_set : count = 0 for item in y : if word == item : count += 1 wc[word] = count for word in sorted(y_set) : print("{} : {}".format(word,wc[word]))
0facc740467ff83c0f817c12420bd0cd5c19efb0
bearzk/cracking-the-coding-interview
/chapter-11-sorting-and-searching/src/extend_sort.py
715
3.953125
4
# coding: utf-8 def merge_sort(a, left, mid, right): cloned = a[:] cnt = left leftCnt = left rightCnt = mid while leftCnt < mid and rightCnt <= right: if cloned[leftCnt] < cloned[rightCnt]: a[cnt] = cloned[leftCnt] leftCnt += 1 else: a[cnt] = cloned[rightCnt] rightCnt += 1 cnt += 1 while leftCnt < mid: a[cnt] = cloned[leftCnt] leftCnt += 1 cnt += 1 def extend_sort(a, b): left = 0 right = len(a) + len(b) - 1 mid = len(a) a.extend(b) merge_sort(a, left, mid, right) if __name__ == "__main__": a = [0, 2, 4, 5] b = [1, 3] extend_sort(a, b) print a
c4b40fd4e0deeca1d7754b32355437c98ee975de
Elmar999/Machine-learning
/churn_telecom_dataset.py
3,630
3.9375
4
# Customer attrition, also known as customer churn, customer turnover, or customer defection, is the loss of clients or customers. #predictive analytics use churn prediction models that predict customer churn by assessing their propensity of risk to churn. # import warnings filter from warnings import simplefilter # ignore all future warnings simplefilter(action='ignore', category=FutureWarning) import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import KFold from sklearn.svm import SVR df = pd.read_csv("Telecommunication_Data.csv") # print(df.loc[:][df['churn'] == 1]) # print the tuples whose churn column is True # print(df.loc[:][df['churn'] == 0]) # print the tuples whose churn column is False title_mapping = {'yes':1 , 'no' :0} # map 'yes' or 'no' indexes to 1 , 0 respectively df['international plan'] = df['international plan'].map(title_mapping) df['voice mail plan'] = df['voice mail plan'].map(title_mapping) # as phone number and state columns doesnt improve our code a lot , it is better to drop them to get rid of this features df = df.drop(labels = ["phone number"] , axis = 1) df = df.drop(labels = ["state"] , axis = 1) df = df.drop(labels = ["total eve charge"] , axis = 1) df = df.drop(labels = ["total day charge"] , axis = 1) df = df.drop(labels = ["total night charge"] , axis = 1) df = df.drop(labels = ["total intl charge"] , axis = 1) df = df.drop(labels = ["account length"] , axis = 1) # x = df.iloc[:,:20] # extract whole data except last column # y = df.iloc[:,20] # extract whole data for last column as a target df["churn"] = df["churn"].astype(int) y = df["churn"].values x = df.drop(labels = ["churn"],axis = 1) # drop churn column from dataset from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.2 , random_state=10) # splitting data by 20/80 division # print(X_train.shape , X_test.shape , y_train.shape , y_test.shape) # bar_chart function help to analize data with visualization def bar_chart(feature , df): sns.set(font_scale=2) true = df[df['churn']==1][feature].value_counts() false = df[df['churn']==0][feature].value_counts() df = pd.DataFrame([true,false]) df.index = ['True','False'] df.plot(kind = 'bar' , figsize = (30,20),map=plt.cm.Reds , annot=True) plt.show() def matrix_cor(): correlation_matrix = df.corr() # # annot = True to print the values inside the square plt.figure(figsize=(40,30)) sns.set(font_scale=3) ax = sns.heatmap(data=correlation_matrix , annot=True) plt.show() # matrix_cor() cor_matrix = df.corr() cor_target = abs(cor_matrix['churn']) relevant_figures = cor_target[cor_target > 0.2] print(relevant_figures) print(df[['total day minutes','customer service calls']].corr()) grd = GradientBoostingClassifier() from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0, 1)) x = scaler.fit_transform(x) scores = [] best_svr = SVR(kernel='rbf') cv = KFold(n_splits=10, random_state=42, shuffle=False) # splitting data to 10 different test and train dataset using Kfold. for train_index, test_index in cv.split(x): X_train, X_test, y_train, y_test = x[train_index], x[test_index], y[train_index], y[test_index] grd.fit(X_train,y_train) scores.append(grd.score(X_test,y_test)) print(np.mean(scores))
74cf66b6a01f315aa514f8351f90d991afac1646
franky3020/Arithmetic_method_class_HW_1
/BubbleSort.py
390
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 16:56:22 2020 @author: frrr """ def is_over_BubbleSort(randomList:list)->bool: for i in range(len(randomList)): for j in range(len(randomList)): if randomList[j] > randomList[i]: tmp = randomList[j] randomList[j] = randomList[i] randomList[i] = tmp return True
f4f6bf40cda8253ca494485d2dc7951b9a932f92
HenriqueNO/Python-cursoemvideo
/Desafios/Teoria#011.py
304
3.625
4
nome = str(input('Qual é o seu nome?')).strip() cores = {'limpa':'\033[m', 'azul':'\033[1;34m', 'amarelo sub':'\033[4;34m', 'verde':'\033[1;32m', 'amarelo neg':'\033[1;33m'} print('Olá! Muito prazer em te conhcer, {}{}{}'.format(cores['azul'], nome, cores['limpa']))
1949244339f199d1acb3339113ec7c32391e3cb7
mckinler1639/CTI110
/P2HW1_PoundsKilograms_RobertMckinley.py
363
4.1875
4
# Convert pounds into kilograms # 15 February 2019 # CTI-110 P2HWI - Pounds to Kilograms Converter # Robert Mckinley # # ask the user to enter a number pounds=int(input("how many pounds you want to convert?")) # Convert the formula kg=pounds/2.2046 # Display the converted number # put in code for two decimal places print(format (kg,".2f"),"kilograms")
d2ff9cdc0e751a81d0857bb78c39a57d664e2e6b
GDUTwuchao/leetcode_jianzhioffer
/python剑指offer/对称二叉树.py
1,004
3.921875
4
''' 请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。 思路: 首先根节点以及其左右子树, 左子树的左子树和右子树的右子树相同 左子树的右子树和右子树的左子树相同即可,采用递归 非递归也可,采用栈或队列存取各级子树根节点 ''' # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetrical(self, pRoot): # write code here return self.isSymBT(pRoot, pRoot) def isSymBT(self, tree1, tree2): if tree1 == None and tree2 == None: return True if tree1 == None or tree2 == None: return False if tree1.val != tree2.val: return False return self.isSymBT(tree1.left, tree2.right) and self.isSymBT(tree1.right, tree2.left)
94b074e06b893e09c17ce897b92db857ecf1586a
BrettParker97/CodingProblems
/2021-06-28/sol.py
1,401
3.59375
4
def closest_nums(nums, k, x): #find closest value in list of nums rightIndex = None leftIndex = None for y in range(len(nums)): if nums[y] < x or leftIndex == None: leftIndex = y elif nums[y] > x: rightIndex = y break #increase/decrease val to add to x each loop #check if our indexes match the value # yes - add them to res and move index # no - move on to next values res = [] val = 0 safe = max(nums) while True: temp1 = x - val temp2 = x + val if leftIndex >= 0: if nums[leftIndex] == temp1 and len(res) != k: res.append(temp1) leftIndex -= 1 elif nums[leftIndex] > temp1: leftIndex -= 1 if rightIndex < len(nums): if nums[rightIndex] == temp2 and len(res) != k: res.append(temp2) rightIndex += 1 elif nums[rightIndex] < temp2: rightIndex += 1 val += 1 if len(res) >= k: break if leftIndex < 0 and rightIndex > len(nums): print("not enough values to check in given array") break #saftey break if temp2 > safe: break return res print(closest_nums([1, 3, 7, 8, 9], 3, 5)) # [7, 3, 8]
c9cbd675cfb5b325b0e266f1a9e42fc72789cd22
DanielFuentes17083/Lab4
/GraphInt.py
2,609
3.65625
4
from tkinter import * #https://likegeeks.com/es/ejemplos-de-la-gui-de-python/ from tkinter import messagebox #importa los mensajes de error import serial #libreria de comunicacion serial import struct #para convertir valores a formatos deseados import time #para refrescar valores while(1): #Se inicializa la conexion con el puerto while(1): #realiza las conecciones con el puerto serial try: numero = str(int(input("> COM: "))) port = "com" + numero break except: print ("Enter a numeric value") try: data = serial.Serial(port, baudrate = 9600, timeout=1500) break except: print("Unable to open port") gui = Tk(className='Comunicacion serial') #se define de forma general la interfaz grafica # set window size gui.geometry("550x250") pot1 = StringVar() pot2 = StringVar() pot1.set("0 V") pot2.set("0 V") puerto = Label(gui, text = "COM:" + numero, font = ("Arial", 25)) entry = Entry(gui, width=32) #textbox def ENVIO(): #funcion que envia el valor de la textbox al puerto serial contador = entry.get() if contador != "": try: contador = int(entry.get()) if contador <= 255 and contador >= 0: data.write(struct.pack('>B',contador)) else: messagebox.showerror(title='Error', message='el valor no puede ser mayor a 255 o menor que 0') except: messagebox.showerror(title='Error', message='Ingrese un numero entero') else: data.write(struct.pack('>B',0)) BT1 = Button(gui, text='Enviar valor', command=ENVIO) #boton label1 = Label(gui, text='Ingrese el valor del contador', font = ("Arial", 12)) label2 = Label(gui, text='S1:', font = ("Arial", 25)) label3 = Label(gui, text='S2:', font = ("Arial", 25)) label4 = Label(gui, textvariable=pot1, font = ("Arial", 25)) #label con el valor del pot1 label5 = Label(gui, textvariable=pot2, font = ("Arial", 25)) #label con el valor del pot2 #posiciones de lo mostrado en el formulario puerto.pack() label1.place(x=300, y=70) label2.place(x=50, y=60) label3.place(x=200, y=60) label4.place(x=25, y=150) label5.place(x=180, y=150) entry.place(x=300, y=110) BT1.place(x=420, y=160) #funcion que recibe los valores y los convierte a 5 V del puerto serial def getSerial(): p1 = ord(data.read()) p2 = ord(data.read()) m1 = "{0:.2f}".format(p1 *(5/255)) m2 = "{0:.2f}".format(p2 *(5/255)) pot1.set(str(m1)+" V") pot2.set(str(m2)+" V") gui.after(10,getSerial) #refresca los valores gui.after(10,getSerial) gui.mainloop()
e5ed1bfa9986d59fee741155eedae9a913fee499
abdullahf97/Detailed-Assignment-01
/Practice Problem 3.33.py
164
3.828125
4
print('Practoce Problem 3.33') def reverse_string(word): return word[::-1] i = reverse_string('dim') print(i) g = reverse_string('bad') print(g)
26f15f34161f52f81a624a8eba787eade847b0f0
infosergio2020/python-practice-review
/practica-03/p-07.py
1,132
3.75
4
# Utilizar como estructura de datos de referencia la generada en el ejercicio 3 y generar funciones # que ejecuten lo siguiente: # (a) Imprimir los 10 primeros puntajes de la estructura. # (b) Imprimir los datos de los usuarios ordenados alfabéticamente por apellido. # (c) Imprimir los datos de los usuarios ordenados por nivel alcanzado. # Nota: utilice expresiones lambda para resolver los incisos. jugadores = { 'jose': [11, 1024, 23], 'emanuel': [4, 2324, 30], 'jefferson': [8, 8024, 90], 'ricardo': [1, 56524, 10], 'miguel': [3, 24, 5], 'esteban': [3, 5240, 580], 'carlos': [4, 3440, 60], 'rodrigo': [6, 240, 40], 'nacho': [7, 120, 230], 'ivan': [12, 540, 110], 'ramiro': [45, 45640, 140]} diezPrimeros = lambda x:x[1][1] porApellido = lambda x:x[0] porNivel = lambda x:x[1][0] print ("los diez primeros son --> {}".format( sorted(jugadores.items(),key=diezPrimeros,reverse=True)[0:10] )) print ("\nordenados por nombre --> {}".format( sorted(jugadores.items(),key=porApellido))) print ("\nordenados por nivel --> {}".format( sorted(jugadores.items(),key=porNivel)))
2f86cb060490cfc1a82f95d9ad256953aba8c45b
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/jammy_chong/lesson04/Mailroom02.py
3,797
3.78125
4
import os import pathlib import datetime donor_list = dict() def main_menu(dispatch_dict): while True: print(main_prompt) action = input("") if action in dispatch_dict: dispatch_dict[action]() if action == "q": break def add_donor(name, total=0, gifts=0, average=0): if name not in donor_list: if gifts > 0: average = round(total/gifts, 2) donor_list[name] = {'total_given': round(total, 2), 'num_gifts':int(gifts), 'average_gift':average} def create_donor_list(): add_donor("Paul Allen", 708.42, 3) add_donor("Mark Zuckerberg", 16396.10, 3) add_donor("Jeff Bezos", 877.33, 1) add_donor("William Gates, III", 653784.49, 2) add_donor("Jammy Chong", 25433.12,2) def create_letter(name,amount,gifts,average): letter = (f"Dear {name},\n\n\tThank you for your very kind donation of ${amount}.\n\n\ \tYou have donated {gifts} times with an average of ${average} per donation.\n\n\ \tIt will be put to very good use.\n\n\t\t\tSincerely,\n\t\t\t\t-The Team.") return letter # Menu Actions: def send_thank_you(): donor_input = "" thank_you_prompt = "For main menu enter 'q' at any time.\nEnter a donor's Full Name or enter 'list' to see the donors list :" while donor_input != "q": donor_input = input(thank_you_prompt) #Donors list and exiting options while donor_input == "list": for name in donor_list: print(name) donor_input = input(thank_you_prompt) if donor_input == "q": break donation_amount = input("Please enter donation amount: ") if donation_amount == "q": break #Assigning donor values if donor_input not in donor_list: new_donor = add_donor(donor_input) donor_list[donor_input]['total_given'] += float(donation_amount) donor_list[donor_input]['num_gifts'] += 1 donor_list[donor_input]['average_gift'] = donor_list[donor_input]['total_given']/donor_list[donor_input]['num_gifts'] print(create_letter(donor_input,donation_amount,donor_list[donor_input]['num_gifts'],\ donor_list[donor_input]['average_gift'])) donor_input = "q" def create_report(): #Using lambda to access values from list of dictionaries sorted_list = sorted(donor_list.items(), key = lambda e: e[1]['total_given'], reverse=True) print("Donor Name"," "*14,"| Total Given | Num Gifts | Average Gift") print("-"*66) for item in sorted_list: print("{:25} ${total_given:>11.2f}{num_gifts:>12d} ${average_gift:>12.2f}".format(item[0], \ **item[1])) def send_thank_you_all(): folder = input("Enter the folder to save the letters: ") path = pathlib.Path('./'+folder) if not path.is_dir(): os.mkdir("./"+folder) for name in donor_list: string_letter = create_letter(name,donor_list[name]['total_given'],\ donor_list[name]['num_gifts'],donor_list[name]['average_gift']) print (string_letter) with open('./'+folder+'/'+name+'.txt', 'w') as f: f.write(string_letter) f.close() def quit(): print("Thank you for using Mailroom.\nExiting Program\n") main_prompt = ("\nYou are in the main menu, Choose an action to perform:\n" "1: Send a Thank You to a single donor.\n" "2: Create a Report.\n" "3: Send letters to all donors.\n" "q: Quit\n") main_dispatch = {"1": send_thank_you, "2":create_report, "3":send_thank_you_all, "q":quit} if __name__ == '__main__': create_donor_list() main_menu(main_dispatch)
b5bb9cb895aad31d9fc18b2a792286271886e6f1
woody0907/pythonpractice
/sumbmation.py
864
3.8125
4
a = [1,2,3,4,5] def custom_sumbmation(): sum = 0 for i in a: sum += i print(sum) def recursion_sumbmation(l): if not l: return 0 return l[0]+recursion_sumbmation(l[1:]) def ternary_sumbmation(l): return 0 if not l else l[0]+ternary_sumbmation(l[1:]) def ternary_sumbmation1(l): return l[0] if not l[1] else l[0]+ternary_sumbmation(l[1:]) def while_sumbmation(l): sum = 0 while l: sum += l[0] l = l[1:] print(sum) def comprehension_test(l): b = [x*x for x in l] print(b) def function_map_test(l): s = list(map(lambda x:x*x,l)) print(s); def function_filter_test(l): s = list(filter(lambda x:x%2==0,l)) print(s) # custom_sumbmation() # print(recursion_sumbmation(a)) # print(ternary_sumbmation(a)) # print(ternary_sumbmation1(a)) print(function_filter_test(a))
730b5f47c49a785f5fbb42a8c16b8f6c78d59e96
jakovlev-fedor/tms_python_fedor_jakovlev
/02_lesson/08_conditional_operators.py
2,456
4.25
4
"""""" """ --------------------------------- 1. Используя функцию > придумать: 3 примера когда результат будет равен True 3 примера когда результат будет равен False """ print('#01---------------') print(100 > 1) print(1000 > 100) print(1 > 0.1) print(1 > 100) print(100 > 1000) print(0.1 > 1) print() """ --------------------------------- 2. Используя функцию < придумать: 3 примера когда результат будет равен True 3 примера когда результат будет равен False """ print('#02---------------') print(9 < 999) print(900 < 9000) print(0.999 < 9) print(999 < 9) print(9000 < 900) print(9 < 0.999) print() """ --------------------------------- 3. Используя функцию == придумать: 2 примера когда результат будет равен True 2 примера когда результат будет равен False """ print('#03---------------') print(0.999 == 0.999) print('abc' == 'abc') print('zzz' == 'zzz') print(0.999 == 'zzz') print('abc' == 'zzz') print('zzz' == 0.999) print() """ --------------------------------- 4. Используя функцию >= придумать: 3 примера когда результат будет равен True 3 примера когда результат будет равен False """ print('#04---------------') print(9 >= 0.999) print(9000 >= 9000) print(999 >= 9) print(999 >= 9000) print(90 >= 900) print(9 >= 999) print() """ --------------------------------- 5. Используя функцию <= придумать: 3 примера когда результат будет равен True 3 примера когда результат будет равен False """ print('#05---------------') print(999 <= 9000) print(90 <= 900) print(9 <= 999) print(9 <= 0.999) print(9000 <= 900) print(999 <= 9) print() """ --------------------------------- 6. Используя функцию != придумать: 2 примера когда результат будет равен True 2 примера когда результат будет равен False """ print('#06---------------') print(0.999 != 'zzz') print('abc' != 'zzz') print('zzz' != 0.999) print(0.999 != 0.999) print('abc' != 'abc') print('zzz' != 'zzz') print()
7b204aa0b1ff134dc2f53d89cb74aed7cea6b154
ydong08/PythonCode
/sourcecode/05/5.1/call_switch.py
788
4.125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import switch_class operator = "+" x = 1 y = 2 for case in switch(operator): # switchֻfor inѭ if case('+'): print x + y break if case('-'): print x - y break if case('*'): print x * y break if case('/'): print x / y break if case(): # ĬϷ֧ print "" operator = "+" x = 1 y = 2 for case in switch(operator): # switchֻfor inѭ if case('+'): print x + y if case('-'): print x - y if case('*'): print x * y break if case('/'): print x / y break if case(): # ĬϷ֧ print ""
cb34dd71a8ddf9f1396ea172c4f7912038618b7b
mayconrcampos/Python-Curso-em-Video
/Exercicios/Exercício - 029 - Radar Eletrônico.py
947
4.25
4
velocidade = float(input('Digite a velocidade em Km/h: ')) if velocidade > 80: multa = (velocidade - 80) * 7 print('MULTADO! Você atingiu velocidade superior a 80km/h') print('Você deverá pagar uma multa de R$ {}'.format(multa)) print('Parabéns, você atrapalha todo mundo!') print('Seu carro será recolhido ao ferro velho') #Quando comando tá no inicio da linha ele sempre será executado. #Quando tiver indentado, ele depende do resultado de if para que else seja executado #REPETINDO CÓDIGO SEM OLHAR PRA CIMA velocidade1 = float(input('Digite a sua velocidade em km/h: ')) if velocidade1 > 80: multa1 = (velocidade1 - 80) * 7 print('MULTADO! Você excedeu o limite de velocidade que é 80km/h') print('Você terá que pagar uma multa no valor de R$ {}'.format(multa1)) else: print("Parabéns, você merece andar de carroça") print('Seu carro será recolhido ao ferro velho') #Ou pode ser usado else
8022b4b9be23e14a7d5a48fb741d3b4c75255888
jonjelinek/euler-python
/problems/7.py
803
4
4
# finding the nth prime number # given the first 6 prime numbers: 2,3,5,7,11,13 what is the 10,001 prime number known_primes = [2, 3, 5, 7, 11, 13] def nth_prime_number(n): if len(known_primes) >= n: return known_primes[n-1] current_number = known_primes[-1] + 1 while len(known_primes) < n: half_val = current_number / 2 prime_not_found = True for prime in known_primes: if prime > half_val: break if current_number % prime == 0: prime_not_found = False break if prime_not_found: known_primes.append(current_number) current_number += 1 print(known_primes) return known_primes[-1] assert nth_prime_number(6) == 13 print(nth_prime_number(10001))
9da4f2dfb70f10b9b15b5a72a3b5a7011afba560
jaychsu/algorithm
/lintcode/111_climbing_stairs.py
1,119
3.953125
4
""" DP: rolling array with `n + 1` """ class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): if n <= 0: return 0 dp = [0] * 3 pre2, pre1, curr = 0, 0, 1 dp[0] = dp[1] = 1 for i in range(2, n + 1): pre2 = pre1 pre1 = curr curr = i % 3 dp[curr] = dp[pre1] + dp[pre2] return dp[curr] """ DP: origin `n` """ class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): if n <= 0: return 0 dp = [0] * n dp[0] = 1 dp[1] = 2 for i in range(2, n): dp[i] = dp[i - 1] + dp[i - 2] return dp[n - 1] """ DP: origin `n + 1` """ class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): if n <= 0: return 0 dp = [0] * (n + 1) dp[0] = dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]
17bf3c0bbd6ca7587e8f5860aa6602f31fde8702
btemovska/ListsAndTuples
/Enumerate_example.py
261
4.15625
4
for index, character in enumerate("abcdefgh"): print(index, character) print(index + 1, character) # 0 a # 1 b # 2 c # 3 d # 4 e # 5 f # 6 g # 7 h # the index number matches the character in the string # #1 a # 2 b # 3 c # 4 d # 5 e # 6 f # 7 g # 8 h
fd6c4e63dd4359cc80b5c16b087263cd90302b0c
enochc/ScoutTrackerUltimate
/scripts/dateutil.py
470
4.15625
4
import datetime today = datetime.datetime.today() def addMonth(months, date): m=0 month = date.month day = date.day mod = -1 if months<0 else 1 while m < abs(months): date = date+datetime.timedelta(days=mod) if month != date.month: m+=1 month = date.month while date.day != day: date = date+datetime.timedelta(days=mod) return date print today print addMonth(-6, today)
07bbf7724e13dfbc0f6bc9e18332afc28099626f
chendamowang/learnpythonthehardway
/ex14.py
666
3.78125
4
from sys import argv script, user_name, bb = argv prompt = '>' print "Hi %s I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) print "Where do you lives %s?" % user_name lives = raw_input (prompt) print "What kind of computer do yu have?" computer = raw_input (prompt) print """ Alrihat, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer) print "Hi %s." % bb print "Do you like me %s?" % bb likes_bb = raw_input(prompt) print "So, you said %r about liking me." % likes_bb
c9dc5c1a9b54d1892e02f13d5cd54353036ec841
edureimberg/learning_python
/ternary.py
216
3.5
4
order_total = 247 #classic if/else if order_total > 100: discount = 25 else: discount = 0 print(order_total,discount) #ternary operator discount = 25 if order_total > 100 else 0 print(order_total,discount)
1bd57c07fe511f5c500b290e05db7e3ba703d36d
yani-valeva/Programming-Basics-Python
/Calculations/RadiansToDegrees.py
77
3.65625
4
import math rad = float(input()) deg = rad * 180 / math.pi print(round(deg));
b0c9bed8704eac1e7970f50ed980167d1b78262a
MiguelSilva96/sdle-practice
/pref_attachment/pref.py
1,871
3.828125
4
''' Generate edges on a graph using preferential attachment. The first node is selected randomly and the second is selected using preferential attachment. ''' import networkx as nx import random as rand import sys import matplotlib.pyplot as plt NODES = 100 STEP = 5 list_to_randomize = [] def add_preferential_edge(node_list, graph): global list_to_randomize rand_val1 = rand.choice(node_list) rand_val2 = rand_val1 while rand_val2 == rand_val1: rand_val2 = rand.choice(list_to_randomize) if graph.has_edge(rand_val1, rand_val2) is False: list_to_randomize.append(rand_val1) list_to_randomize.append(rand_val2) graph.add_edge(rand_val1, rand_val2) def generate_connected_graph(node_count): global list_to_randomize node_list = range(0, node_count) list_to_randomize = list(node_list) graph = nx.Graph() graph.add_nodes_from(node_list) for i in range(1, node_count): add_preferential_edge(node_list, graph) while nx.is_connected(graph) == False: add_preferential_edge(node_list, graph) return graph ######################################### if len(sys.argv) > 1: try: NODES = int(sys.argv[1]) except: print("invalid int, using " + str(NODES)) print("Number of nodes: "+str(NODES)) print("default is 100, configurable by argument") ### Configure plot fig = plt.figure() fig.canvas.set_window_title('Preferential attachment') plt.title('Generation of edges on a graph') plt.xlabel('# of nodes') plt.ylabel('degree') stats = {} graph = generate_connected_graph(NODES) for (i, j) in graph.degree(): try: stats[j] += 1 except: stats[j] = 1 coords = [] for i in stats: coords.append((i, stats[i])) coords.sort(key = lambda x : x[0], reverse = False) keys, values = zip(*coords) plt.plot(values, keys, 'ro-') plt.show()
47f21dd836ae34ad4a31fd5b787299ee13825208
sennagardner/P2_SP20
/Notes/NotesA/03_loops.py
722
4.21875
4
# More on loops # Basic FOR loop for i in range(5, 51, 5): print(i, end=" ") print() # RANGE function (alternative for comprehension) my_list = [x for x in range(100)] print(my_list) my_list = list(range(100)) # iterable print(my_list) # BREAK (breaks out of the loop) for number in my_list: if number > 10: break print(number, end=" ") print("End of loop") # CONTINUE (skips to the end of the loop for that iteration) for number in my_list: if number % 7 == 0: continue print(number, end=" ") # FOR ELSE for number in my_list: print(number, end=" ") if number == 80: break else: print("The loop completed naturally") # Add me as a collaborator on Github
46c2a174f05eb63b067376ea5ef60788b257cc6b
kanisque/Programming
/betterPythonPractices.py
2,858
4.34375
4
#Better Python practices #Shift space to run file in terminal (or set shortcut first) names = ['bob','ross','mat','jack','karen','jess'] colors = ['red','green','blue','yellow','grey','white','black'] #iterating normally for color in colors: print(color) print("----------------") #iterating in reverse for color in reversed(colors): print(color) print("----------------") #enumerating for i,color in enumerate(colors): print(i,color) print("----------------") #looping over two collections for name,color in zip(names,colors): print(name,color) print('----------------') #looping in sorted order for color in sorted(colors): print(color) print('----------------') #looping in reverse order for color in sorted(colors, reverse=True): print(color) print('----------------') #custom sort print(sorted(colors,key =len)) #for-else to distinguish multiople exit points in loops def find(color): for i,value in enumerate(colors): if value == color: return ('Found at '+str(i)) else: return('Not found') #use keyword arguments in functions i.e find(color='_name_of_color') print('Calling for Green:',find(color='green')) print('Calling for Brown:',find(color='brown')) print('----------------') #creating dictionary from lists d = dict(zip(names,colors)) #looping over dictionary keys #if not mutating while looping for k in d: print(k) print('----------------') #if mutating d while looping use d.keys(), makes a copy of keys for k in d.keys(): print(k) print('----------------') #looping over dictionary values for k,v in d.items(): print(k,v) print('----------------') #counting the occurance of same keys colors.append('red') colors.append('green') colors.append('red') d2 = {} for color in colors: if color not in d2: d2[color] = 0 d2[color] += 1 print(d2) print('----------------') #alternative d2.clear() for color in colors: d2[color] = d2.get(color,0) + 1 #get returns value for the key and returns second argument if key not found i.e. 0 here colors.remove('red') colors.remove('green') colors.remove('red') print(d2) print('----------------') #grouping with dictionaries from collections import defaultdict d3 = defaultdict(list) for name in names: key = len(name) d3[key].append(name) print(d3) print('----------------') #use named tuples from collections import namedtuple TestResults = namedtuple('TestResults',['failed','attempted']) testcase1 = TestResults(0,4) print(testcase1.failed,testcase1.attempted) print(testcase1) print('----------------') #use unpacking for atomic transitions (x,y shoud update at once in code below) def fibonacci(n): x,y = 0,1 for i in range(n): print(x) x,y = y, x+y fibonacci(n=10) #use @cache to remove recalling of any function which returns same value for same call
8b5c6733e7a74468c8965e93092cf6f68ccfde8f
ryan-c44/Python-Assignments
/Python Assignments/Assignment1.py
4,255
4.375
4
# Ryan Castles, 6433236, CSIT110 # Question 1 print("Question 1. \n") #Get input from user for title and author. song_title = input("Your favourite song title: ") song_author = input("Your favourite song author: ") print() #print the string using string addition. print("Using string addition") print("Your favourite song is " + song_title + " by " + song_author + ".") print() # Question 2 print("Question 2. \n") #Get input from user for 3 integers and convert to int. first_integer = input("Please enter the 1st positive integer: ") number1 = int(first_integer) second_integer = input("Please enter the 2nd positive integer: ") number2 = int(second_integer) third_integer = input("Please enter the 3rd positive integer: ") number3 = int(third_integer) #Calculate the result result = number1 * number2 * number3 print() print("Display using string addition: ") print("Equation: " + str(first_integer) + " x " + str(second_integer) + " x " + str(third_integer) + " = " + str(result)) print() # Question 3 print("Question 3. \n") #Get input from user for the first subject and convert credit to int. first_code = input("Enter the 1st subject code: ") first_title = input("Enter the 1st subject title: ") first_credit_point = input("Enter the 1st subject credit point: ") credit_value1 = int(first_credit_point) print() #Get input from user for the second subject and convert credit to int. second_code = input("Enter the 2nd subject code: ") second_title = input("Enter the 2nd subject title: ") second_credit_point = input("Enter the 2nd subject credit point: ") credit_value2 = int(second_credit_point) print() #Display chosen subjects. print("Your chosen subjects:") print(first_code + ": " + first_title) print(second_code + ": " + second_title) print("Total credit points: " + str(credit_value1 + credit_value2)) print() # Question 4 print("Question 4. \n") #Get input from user an convert to integer value. one_hundred_level = input("How many 100-level subjects you have completed: ") one_hundred_credit = int(one_hundred_level) * 4 two_hundred_level = input("How many 200-level subjects you have completed: ") two_hundred_credit = int(two_hundred_level) * 5 three_hundred_level = input("How many 300-level subjects you have completed: ") three_hundred_credit = int(three_hundred_level) * 6 #Calculations subject_count = int(one_hundred_level) + int(two_hundred_level) + int(three_hundred_level) total_credit = one_hundred_credit + two_hundred_credit + three_hundred_credit print() #print using formatting print("{0:<8}{1:<13}{2:>10}".format("Level", "Subject Count", "Credit")) print("{0:<8}{1:>13}{2:>10}".format("100", str(one_hundred_level), str(one_hundred_credit))) print("{0:<8}{1:>13}{2:>10}".format("200", str(two_hundred_level), str(two_hundred_credit))) print("{0:<8}{1:>13}{2:>10}".format("300", str(three_hundred_level), str(three_hundred_credit))) print("{0:<8}{1:>13}{2:>10}".format("Total", str(subject_count), str(total_credit))) print() # Question 5 print("Question 5. \n") #Grab user input for adult tickets and convert to int then format. adult_tickets = input("How many adult tickets you want to order: ") adult_cost = int(adult_tickets) * 50.5 formatted_adult_cost = "{:.2f}".format(adult_cost) #User input for child over 10 child_over_ten = input("How many children (>=10 years old) tickets: ") child_over_cost = int(child_over_ten) * 10.5 formatted_child_over = "{:.2f}".format(child_over_cost) #User input for child under 10 child_under_ten = input("How many children (<10 years old) tickets: ") child_under_cost = "free" total_cost = "{:.2f}".format(adult_cost + child_over_cost) #Calculate total tickets total_tickets = int(adult_tickets) + int(child_over_ten) + int(child_under_ten) print() #Print using formatting. print("{0:<18}{1:>17}{2:>15}".format("Type", "Number of tickets", "Cost")) print("{0:<18}{1:>17}{2:>15}".format("Adult", str(adult_tickets), "$" + str(formatted_adult_cost))) print("{0:<18}{1:>17}{2:>15}".format("Children (>=10)", str(child_over_ten),"$" + str(formatted_child_over))) print("{0:<18}{1:>17}{2:>15}".format("Children (<10)", str(child_under_ten), child_under_cost)) print("{0:<18}{1:>17}{2:>15}".format("Total", str(total_tickets), "$" + str(total_cost)))
5973ab0cdd485705652ea453316124f6fd18a1dd
gohar67/IntroToPython
/Practice/lecture4/practice4.py
185
3.890625
4
d = {'name': 'Armen', 'age': 15, 'grades': [10, 8,8, 4, 6, 7]} if 'weight' not in d: n = int(input('write a number: ')) d['weight'] = n print(d) else: print(d['weight'])
092b2594f9159f72119349177487a3c0ffe8ebde
kronecker08/Data-Structures-and-Algorithm----Udacity
/submit/Task4.py
1,306
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) call_outgoing = [] call_incoming = [] for i in calls: call_outgoing.append(i[0]) call_incoming.append(i[1]) call_outgoing = set(call_outgoing) call_incoming = set(call_incoming) num_texts = [] for i in texts: num_texts.append(i[0]) num_texts.append(i[1]) num_texts = set(num_texts) telemarketers = [] for i in call_outgoing: if i in call_incoming: continue elif i in num_texts: continue else: telemarketers.append(i) telemarketers = sorted(telemarketers) print("These numbers could be telemarketers: ") for i in telemarketers: print(i) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """
a16a2c04314f8701514b1167c4eae2440022f7b5
apoorvkk/LeetCodeSolutions
/problems/bin_tree_pruning.py
813
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root is None: return None self._aux_prune_tree(root) return root def _aux_prune_tree(self, node): if node is None: return True left_is_zero = self._aux_prune_tree(node.left) right_is_zero = self._aux_prune_tree(node.right) if left_is_zero: node.left = None if right_is_zero: node.right = None return node.val == 0 and left_is_zero and right_is_zero
701131e192bcc629557833cadb5509d02b04dff0
VibhorSaini88/Assignments
/Assignment04.py
2,032
4.46875
4
#(Q.1)- Write a program to create a tuple with different data types and do the following operations. # Find the length of tuples tuple = ("tuple","false",3.2,1) print(tuple) print(len(tuple)) #(Q.2)-Find largest and smallest elements of a tuples. t=(8,9,2,7,1) print(t) print(max(t)) print(min(t)) #(Q.3)- Write a program to find the product of all elements of a tuple. t=(1,2,3) p=1 p=p*t[0] p=p*t[1] p=p*t[2] print(p) # sets #(Q.1)- Create two set using user defined values. # a. Calculate difference between two sets. s1 = {1,2,3} s2 = {6,2,4} print(s1-s2) # b. Compare two sets. s1 = {1,2,3} s2 = {1,4,5} print(s1^s2) # c. Print the result of intersection of two sets. s1 = {1,2,3} s2 = {1,4,5} print(s1&s2) # dictionary #(Q.1)- Create a dictionary to store name and marks of 10 students by user input. d={} print(d) name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name]= marks name=input("enter name: ") marks=int(input("enter marks")) d[name] = marks print("mydict = ",d) #(Q.2)-Sort the dictionary created in previous question according to marks. for key, value in sorted(d.items(), key=lambda d: d[1]): print ("%s: %s" % (key,value)) #(Q.3)- Count the number of occurrence of each letter in word "MISSISSIPPI". #Store count of every letter with the letter in a dictionary. l = list("MISSISSIPPI") d = {} d['M'] = l.count('M') d['I'] = l.count('I') d['S'] = l.count('S') d["P"] = l.count('P') print(d)
683c4f57a004cce69b09407c99ce867fd471e32c
erickjsantofimioj/ParcialHerramientasComputacionales
/CalculadoraDescuento.py
763
3.953125
4
print('!!!!!Bienvenido a su cafeteria buen sabor!!!!!') cedula = input('Por favor digite su numero de cedula: (solo números aqui): ') rol = input('Por favor digite su rol (Estudiante o Profesor): ') codigo = input('Digite el codigo del producto: ') cantidad = int(input('Digite la cantidad de unidades que llevará: ')) precio = int(input('Digite el precio del producto: ')) precio_final = 0 if rol == "estudiante": precio_final = precio*cantidad-precio*cantidad*0.5 print("El:",rol,"con cedula:",cedula,", debe pagar:",precio_final,"por el producto:",codigo) if rol == "profesor": precio_final = precio*cantidad-precio*cantidad*0.2 print("El:", rol, "con cedula:", cedula, ", debe pagar:", precio_final, "por el producto:", codigo)
63ad3afe759bb7919a7e3c999452c22f777895d1
ledbagholberton/holbertonschool-machine_learning
/math/0x05-advanced_linear_algebra/0-determinant.py
1,358
4.40625
4
#!/usr/bin/env python3 """Function that calculates the determinant of a matrix: matrix is a list of lists whose determinant should be calculated If matrix is not a list of lists, raise a TypeError with the message matrix must be a list of lists If matrix is not square, raise a ValueError with the message matrix must be a square matrix The list [[]] represents a 0x0 matrix Returns: the determinant of matrix""" def determinant(matrix): """Function determinant""" if (type(matrix) != list or len(matrix) == 0 or not all([type(m) == list for m in matrix])): raise TypeError("matrix must be a list of lists") elif len(matrix) is 1: if len(matrix[0]) is not 0: return(matrix[0][0]) else: return(1) elif len(matrix) is not len(matrix[0]): raise ValueError("matrix must be a square matrix") elif len(matrix) is 2: return(matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]) else: total = 0 for fc in range(len(matrix)): As = list(matrix) As = As[1:] for i in range(len(As)): As[i] = As[i][0:fc] + As[i][fc+1:] sign = (-1) ** (fc % 2) sub_det = determinant(As) total += sign * matrix[0][fc] * sub_det return total
bac52f55bdaed00ac76279f0ca1bc8a25fc42b12
bedros-bzdigian/intro-to-python
/week 4/pratical/problem7.py
84
3.59375
4
for x in range(1,21): if (x%3 == 0) and (x%5 == 0): break print (x)
c1a562a6b82aa8d6cf9a4c3b3b2ea9429e91e0fb
yograjshisode/PythonRepository
/Rocpprsci.py
3,133
4.15625
4
'''Rock, paper, scissors, also know as roshambo, is a simple child's game that is frequently used to settle disputes. In the game, a rock breaks the scissors, the scissors cut the paper, and the paper covers the rock. Each option is equally likely to prevail over another. If the players choose the same object a draw is declared and the game is repeated until someone prevails. For more information than you ever thought it was possible to collect about rock, paper, scissors, check out the Web page of the World RPS Society. In this computerized version the human player competes against the computer which chooses a rock, paper, or scissors randomly. The game proceeds until the human player quits the game or until a predetermined score is reached (e.g., 11 pts.) at which time the final tally is displayed. Solutions with fewer numbers of if statements are considered more elegant. Input The human player enters the number of points required for a win. During the play of the game the human player selects whether to play a rock, paper, or scissors by using the keyboard. The human player may also end the game by pressing the Control-D sequence at any time. (Ending the game early does not allow a winner to be determined if the human player is ahead.)''' #temp=int(raw_input("Enter a number : ")) #maxpoint=int(raw_input("How many points required for win? "))''' import random choicelist={"r":0,"s":1,"p":2} chlist=["Rock","Scissor","Paper"] count=int(raw_input("How many points required for win? ")) scnt=0 hcnt=0 #syschoice=(temp * 23) % 3 while(1) : syschoice = random.randint(0, 2) choice = raw_input("Choose (r)ock, (s)cissor, (p)aper ? ") if syschoice==choicelist[choice] : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : draw" elif syschoice==0 and choicelist[choice]==1 : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : Computer win" scnt+=1 elif syschoice==1 and choicelist[choice]==0 : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : Human win" hcnt+=1 elif syschoice==0 and choicelist[choice]==2 : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : Human win" hcnt += 1 elif syschoice==2 and choicelist[choice]==0 : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : Computer win" scnt += 1 elif syschoice==1 and choicelist[choice]==2 : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : Computer win" scnt += 1 elif syschoice==2 and choicelist[choice]==1 : print "Human: ", chlist[choicelist[choice]], "Computer : ", chlist[syschoice], "Result : Human win" hcnt += 1 if(count==scnt) : print "Final score : Computer : ", scnt ,"Human : ", hcnt, "Computer win......." exit() if(count==hcnt) : print "Final score : Human : ", hcnt, "Computer : ", scnt, "Human win........." exit()
dac461cd6cd6f88947fbf0a0551cfd8b1a80a5a8
StefanDimitrovDimitrov/Python_Basic
/01. First-Steps in Codding Lab+Exr/06.str_num_concatination.py
233
3.78125
4
def str_num_concat(f_name, l_name, age, town): print(f"You are {f_name} {l_name},a {age}-years old person from {town}.") f_name = input() l_name = input() age = input() town = input() str_num_concat(f_name, l_name, age, town)
35245d908e57b04b65f81fff8073fc90d7ade45f
WiktorSa/Operating-Systems
/OS1/algorithms/RR.py
2,090
3.703125
4
import collections from algorithms.Algorithm import Algorithm # Round Robin class RR(Algorithm): def __init__(self, no_simulations: int, quant: int): super().__init__(no_simulations) self.quant = quant def perform_simulation(self, processes: collections.deque): overall_waiting_time = 0 current_process = processes.popleft() waiting_processses = collections.deque() current_quant = 0 # The max length is 10000 so that we could analyse any processes that were left over for i in range(10000): # Here we add processes that have arrived to the queue of processes while len(processes) > 0 and processes[0].arrival_time == i: waiting_processses.append(processes.popleft()) # Swap the finished process with a new one if current_process.burst_time <= 0 and len(waiting_processses) > 0: current_process = waiting_processses.popleft() # Replace the process with a new process based on the quant if current_quant >= self.quant and len(waiting_processses) > 0: waiting_processses.append(current_process) current_process = waiting_processses.popleft() current_quant = 0 current_process.burst_time -= 1 current_quant += 1 overall_waiting_time += len(waiting_processses) # Increasing waiting time for all waiting_processes # (useful if we want to analyse waiting time for individual processes) for process in waiting_processses: process.waiting_time += 1 print("RR results:") print("Waiting time: {wait_time}".format(wait_time=overall_waiting_time)) if len(waiting_processses) != 0: print("Processes still in queue") while len(waiting_processses) > 0: print(waiting_processses.popleft()) else: print("No processes left") print() self.overall_waiting_time += overall_waiting_time
b384ebea193eec83a0b46b678f3480799aef9f67
aviolette/aoc2020
/elves.py
559
3.65625
4
def striplines(file_name): for line in open(file_name, "r"): line = line.strip() yield line def intlines(filename): for line in striplines(filename): yield int(line) def stripsort(file_name, func): lines = [func(line) for line in striplines(file_name)] lines.sort() return lines def group_lines(file_name): group = [] for line in striplines(file_name): if len(line): group.append(line) else: yield group group = [] if group: yield group
2bc6e52b0907409e0737bada10e72881edbae844
byted/AdventOfCode-2020
/10/calc.py
1,976
4.0625
4
import sys import re with open('input.txt') as f: voltages = sorted([int(l) for l in f.readlines()]) one_counter = 0 three_counter = 0 current_out = 0 target_range = list(range(current_out+1, current_out+3+1)) for vix, v in enumerate(voltages): if v > target_range[-1]: print(f'no fitting adapter') sys.exit() for tix, target_v in enumerate(target_range): if v == target_v: target_range = list(range(v+1, v+3+1)) if tix == 0: one_counter += 1 if tix == 2: three_counter += 1 break three_counter += 1 # for our own adapter print(f'Challenge 1: 1s: {one_counter} - 3s: {three_counter} -> {one_counter * three_counter}') # Challenge 2 # # We ignore our own adapter as its always +3 from the highest adapter -> it is always included and doesn't change the number of possibilities # If we calculate & store in how many ways a number can be reached from the last three preceding numbers (NOT values in our voltages list!) # we can iteratively traverse the sorted! voltages list and calculate the possibilities for the next value based on our stored values # initial known number of ways to reach spot i # - negatives are needed as we go back to -2 if i == 1 # - we can ommit voltages[-1] itself from the range as its never read # - use defaultdict instead but we're trying ot explain here ways_to_reach = { i: 0 for i in range(-2, voltages[-1]) } # we start a 0 per definition and there is only one way to start ways_to_reach[0] = 1 for v in voltages: # current number can be reached by looking up the preceding three values # if such a value is not in our voltages, it will be 0; thus not contribute # if it is in our voltages, we already calculated the ways to reach this old value and can re-use it ways_to_reach[v] = ways_to_reach[v-1] + ways_to_reach[v-2] + ways_to_reach[v-3] print(f'Challenge 2: {ways_to_reach[voltages[-1]]}')
0427d34457f455ae3f9398d355063616d2cbdb6d
snolbo/TDT4113
/ex2 rockpaperscissor/PlayerTypes.py
4,540
3.953125
4
import random import numpy as np class Player: dict_str2num = {"rock": 0, "paper": 1, "scissor": 2} dict_num2str = {0:"rock",1:"paper",2:"scissor"} def __init__(self): self.chosen_action = None def choose_action(self): choice = input("Rock, Paper or Scissor?: ") choice = choice.lower() if choice in self.dict_str2num: return choice else: print("Illegal choice, choose again...: ") return self.choose_action() def evaluate_choosing_random(self, score_array): # random.choice possible_choices = [] max_index = np.argmax(score_array) for x in range(0, 3): if score_array[x] == score_array[max_index]: possible_choices.append(x) choice = 0 if len(possible_choices) == 1: choice = possible_choices[0] else: random_index = random.randint(0, len(possible_choices)-1) choice = possible_choices[random_index] return choice def receive_result(self, result, my_choice, opponent_choice): print("You choose: " + my_choice + ", Opponent choose: " + opponent_choice ) text_result = "" if result ==1: text_result = "You won!" elif result == 0: text_result = "Draw" else: text_result = "Opponent won" #print(text_result) def get_name(self): return "Player" class Random(Player): def choose_action(self): return self.dict_num2str[random.randint(0,2)] def get_name(self): return "Random" def receive_result(self, result, my_choice, opponent_choice): return class Sequential(Player): def __init__(self): super(Sequential, self).__init__() self.chosen_action = -1 def choose_action(self): self.chosen_action +=1 return self.dict_num2str[self.chosen_action % 3] def receive_result(self, result, my_choice, opponent_choice): return def get_name(self): return "Sequential" class MostCommon(Player): def __init__(self): self.opponent_statistics = [0, 0, 0] def choose_action(self): return self.dict_num2str[self.evaluate_choosing_random(self.opponent_statistics)] def receive_result(self, result, my_choice, opponent_choice): #super(MostCommon, self).receive_result(result, my_choice, opponent_choice) choice_index = self.dict_str2num[opponent_choice] self.opponent_statistics[self.dict_str2num[opponent_choice]] +=1 def get_name(self): return "MostCommon" class Historian(Player): def __init__(self, memory): super(Historian, self).__init__() self.action_sequence = [] self.memory = memory def choose_action(self): #logic for finding most common subsequnce. When memory count is known, could have created table with all # combinations of subsequences to faster find and store subsequence occurences, but brute force ftw! choice = 0 if len(self.action_sequence)-1 - self.memory < 0: # print("Historian choose random because action sequnce not long enough") choice = self.dict_num2str[random.randint(0,2)] else: subsequence = self.action_sequence[len(self.action_sequence) - self.memory:] most_common_choice = [0,0,0] for i in range(0,len(self.action_sequence) - len(subsequence) ): if self.action_sequence[i:i+len(subsequence)] == subsequence: most_common_choice[self.action_sequence[i+len(subsequence)]] +=1 # increment likelyhood of next element since subseq match choice = self.evaluate_choosing_random(most_common_choice) choice = self.dict_num2str[(choice + 1) % 3] # rock paper scissor, beats left, looses right return choice def receive_result(self, result, my_choice, opponent_choice): #super(Historian, self).receive_result(result, my_choice, opponent_choice) self.action_sequence.append(self.dict_str2num[opponent_choice]) def get_name(self): return "Historian(" + str(self.memory) + ")" #p0 = Player() #p1 = Random() #p2 = Sequential() #p3 = MostCommon() #p4 = Historian() # DEBUG TESTING #dict = {0:"rock",1:"paper",2:"scissor"} #for i in range(0, 20 ): #print("Round " + str(i)) #act = p4.choose_action() #print("Historian choose " + str(act) ) #p4.receive_result(1, act, p2.choose_action() )
0ce9e6c8527d288c8e3604bfe388d590e9497906
liwang0904/Deep-Learning
/Statistical Methods for Machine Learning/Chapter 6/6.4.5_python_choice.py
292
3.65625
4
from random import seed from random import choice seed(1) sequence = [i for i in range(20)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] print(sequence) for _ in range(5): selection = choice(sequence) # 4 # 18 # 2 # 8 # 3 print(selection)
1ea72be3e24bb59336cba9ebec2ff1aa0b63d230
SS4G/AlgorithmTraining
/exercise/leetcode/python_src/by2017_Sep/Leet274.py
433
3.609375
4
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ citations.sort(reverse=True) h = 0 for i in range(len(citations)): if citations[i] >= i + 1: h += 1 else: break return h if __name__ == "__main__": s = Solution() c = [15, 11] print(s.hIndex(c))
9c8b592cdcd9e7cf9d130f80d738c2bae60292e6
deathboydmi/machine-learning-course
/preproc.py
4,703
3.515625
4
# To add a new cell, type '#%%' # To add a new markdown cell, type '#%% [markdown]' # %% [markdown] # # Best Artworks of All Time # ## Collection of Paintings of the 50 Most Influential Artists of All Time # ### https://www.kaggle.com/ikarus777/best-artworks-of-all-time # # I am going to solve the problem of recognizing a genre from a painting. # Since this task is educational, I can afford some tricks associated with the formation of a new dataset and data preprocessing to make my life easier. # %% import os import cv2 as cv import numpy as np import pandas as pd # %% artists = pd.read_csv('../data/artists.csv') artists.head() # %% artists = artists.drop(['bio', 'wikipedia', 'years'], 1) artists = artists.sort_values(by=['paintings']) artists = artists.reset_index(drop=True) # %% for i, row in artists.iterrows(): artists.at[i, 'name'] = artists.at[i, 'name'].replace(" ", "_") artists.at[i, 'genre'] = artists.at[i, 'genre'].replace(" ", "_") (artists.head()) # %% # artists_by_nationality = artists.drop(['genre'], 1) # artists_by_nationality = artists_by_nationality.drop_duplicates(subset='nationality', keep='last') # for i, row in artists_by_nationality.iterrows(): # nationalities = artists_by_nationality.at[i, 'nationality'].split(',') # artists_by_nationality = artists_by_nationality.drop(i) # for nationality in nationalities: # # find nationality in "nationality" column # if (artists_by_nationality['nationality'][artists_by_nationality['nationality'] == nationality].empty): # row.at['nationality'] = nationality # artists_by_nationality = artists_by_nationality.append(row) # artists_by_nationality = artists_by_nationality.sort_values(by=['paintings']).drop_duplicates(subset=['nationality'], keep='last').drop_duplicates(subset=['name'], keep='last') # (artists_by_nationality.reset_index(drop=True)) # %% artists_by_genre = artists.drop(['nationality'], 1) artists_by_genre = artists_by_genre.drop_duplicates( subset='genre', keep='last') for i, row in artists_by_genre.iterrows(): genres = artists_by_genre.at[i, 'genre'].split(',') artists_by_genre = artists_by_genre.drop(i) for genre in genres: # find genre in "genre" column if (artists_by_genre['genre'][artists_by_genre['genre'] == genre].empty): row.at['genre'] = genre artists_by_genre = artists_by_genre.append(row) artists_by_genre = artists_by_genre.sort_values(by=['paintings']).drop_duplicates( subset=['genre'], keep='last').drop_duplicates(subset=['name'], keep='last') artists_by_genre = artists_by_genre[artists_by_genre.paintings >= 100].reset_index( drop=True) artists_by_genre # %% [markdown] # We have a dataset of 16 classes. From the classes we will choose 100 images for training and from the remaining 10 for validation. # %% artists = artists_by_genre["name"].to_list() for i, artist in enumerate(artists): if artist == 'Albrecht_Dürer': artists[i] = 'Albrecht_Dürer' genres = artists_by_genre["genre"].to_list() name_genre = dict(zip(artists, genres)) # %% # print(genres) # with open("./genres_list", 'w') as file: # for genre in genres: # file.write(genre + '\n') # exit() # %% groot_data_path = "../data/images/" for path, subdirs, files in os.walk(groot_data_path): i = 1 for artist in artists: if artist in path and 'resized' not in path: for name in files: if (i > 110): break src_im = cv.imread(os.path.join( path, name), cv.IMREAD_GRAYSCALE) if src_im is None: print("bad read:", os.path.join( path, name)) height, width = src_im.shape dst_im = src_im if height < width: dst_im = src_im[:, width//2 - height//2:width//2 + height//2] elif height > width: dst_im = src_im[height//2 - width // 2:height//2 + width//2, :] dst_im = cv.resize( dst_im, (64, 64), interpolation=cv.INTER_CUBIC) new_file_path = '../data/genres/' + \ name_genre[artist] + '/' + name try: if not cv.imwrite(new_file_path.replace('jpg', 'png'), dst_im): print("bad write:", new_file_path) except Exception as e: print(str(e)) print("bad write:", new_file_path) exit() i += 1 exit() # %%
75e21f0ce5ade18a1bc9c89e4edb44129038d306
Gladarfin/Practice-Python
/turtle-tasks-master/turtle_10.py
252
4.3125
4
import turtle turtle.shape('turtle') def draw_circle(direction): step=2*direction for i in range(180): turtle.forward(2) turtle.left(step) for i in range(0, 3, 1): draw_circle(1) draw_circle(-1) turtle.right(60)
e8386a2b36e4ab7e4ad29899ddc62d63c5a899cc
emmas0507/leetcode
/linked_list_cycle_2.py
655
4.0625
4
class Node(object): def __init__(self, value, next=None): self.value = value self.next = next def linked_list_cycle_2(list): slow = list fast = list while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow.value == fast.value: break if fast is None or fast.next is None: return None fast = list while fast.value != slow.value: fast = fast.next slow = slow.next return fast.value n1 = Node(1) n2 = Node(2, n1) n3 = Node(3, n2) n4 = Node(4, n3) n5 = Node(5, n4) n1.next = n4 print(linked_list_cycle_2(n5))
572ac5469dd94fbf3a6e7879dda765e66a94020a
tzyl/hackerrank-python
/week_of_code/31/colliding_circles.py
6,727
4.28125
4
from math import pi def calculate_expected_square_iterative(n, k): """Calculates the expected square of the size of a randomly picked final component. Equivalent to all radii being 1.""" # Conditioning on first step we just solve the case 1, 1, 1,..., 1, 2. x = 1 for i in range(k): current_n = n - (k - 1) + i current_k = i + 1 mu = current_n / (current_n - 1) sigma_squared = (current_n - 2) / (current_n - 1) ** 2 E_N = (current_n - 1) / (current_n - current_k) E_N_squared = x if current_k == 1: # Edge case to prevent division by zero. x = (current_n + 2) / (current_n - 1) continue x = sigma_squared * (E_N - (E_N_squared - E_N) / (current_n - 2)) + (mu ** 2) * E_N_squared return x n, k = map(int, input().strip().split()) radii = [int(s) for s in input().strip().split()] if k == 0: print(pi * sum(r ** 2 for r in radii)) else: mu = sum(radii) / n sigma_squared = sum((r - mu) ** 2 for r in radii) / n E_N = n / (n - k) E_N_squared = calculate_expected_square_iterative(n, k) total_area = pi * (n - k) * (sigma_squared * (E_N - (E_N_squared - E_N) / (n - 1)) + (mu ** 2) * E_N_squared) print(total_area) # # RECURSIVE # def calculate_expected_square(n, k): # """Calculates the expected square of the size of a randomly picked final # component. Equivalent to all radii being 1.""" # if k == 0: # return 1 # elif k == 1: # return (n + 2) / (n - 1) # # Conditioning on first step we just solve the case 1, 1, 1,..., 1, 2. # mu = n / (n - 1) # sigma_squared = (n - 2) / (n - 1) ** 2 # E_N = (n - 1) / (n - k) # E_N_squared = calculate_expected_square(n - 1, k - 1) # return sigma_squared * (E_N - (E_N_squared - E_N) / (n - 2)) + (mu ** 2) * E_N_squared # def calculate_expected_square(n, k): # """Calculates the expected square of the size of a randomly picked final # component. Equivalent to all radii being 1.""" # if k == 0: # return 1 # elif k == 1: # return (n + 2) / (n - 1) # # Conditioning on first step we just solve the case 1, 1, 1,..., 1, 2. # mu = n / (n - 1) # sigma_squared = (n - 2) / (n - 1) ** 2 # # cov = (n + 1) / (n - 1) - mu ** 2 # E_N = (n - 1) / (n - k) # E_N_squared = calculate_expected_square(n - 1, k - 1) # # print(n, k) # # print("Solving: " + "1 " * (n - 2) + "2", "with n = ", n - 1, "k = ", k - 1) # # print("mu", mu) # # print("cov", cov) # # print("sigma_squared", sigma_squared) # # print("E_N", E_N) # # print("E_N_squared", E_N_squared) # return sigma_squared * (E_N - (E_N_squared - E_N) / (n - 2)) + (mu ** 2) * E_N_squared # # return sigma_squared * E_N + (E_N_squared - E_N) * cov + (mu ** 2) * E_N_squared # # return (mu ** 2) * E_N_squared # if k == 0: # print(pi * sum(radii) **2) # else: # mu = sum(radii) / n # # pairs = sum(radii) ** 2 - sum(r ** 2 for r in radii) # # pairs /= n * (n - 1) # # cov = pairs - mu ** 2 # sigma_squared = sum((r - mu) ** 2 for r in radii) / n # # Calculate E[N] and E[N^2] where N is the random variable counting the # # number of original creatures in a randomly picked final creature. # # Think of this by starting with each of the n - k final creatures with size 1. # # We then distribute k units randomly across these so we have # # N = 1 + X_1 + ... + X_k where X_i ~ Ber(1 / (n - k)) # # = 1 + Y where Y ~ Bin (k, 1 / (n - k)) # E_N = n / (n - k) # E_N_squared = calculate_expected_square(n, k) # total_area = pi * (n - k) * (sigma_squared * (E_N - (E_N_squared - E_N) / (n - 1)) + (mu ** 2) * E_N_squared) # # total_area = pi * (n - k) * (sigma_squared * E_N + (E_N_squared - E_N) * cov + (mu ** 2) * E_N_squared) # print(total_area) # # print("mu", mu) # # print("pairs", pairs) # # print("cov", cov) # # print("sigma_squared", sigma_squared) # # print("E_N", E_N) # # print("E_N_squared", E_N_squared) # from math import pi # n, k = map(int, input().strip().split()) # radii = [int(s) for s in input().strip().split()] # if n == 1: # print(pi * radii[0] **2) # else: # mu = sum(radii) / n # pairs = sum(radii) ** 2 - sum(r ** 2 for r in radii) # pairs /= n * (n - 1) # cov = pairs - mu ** 2 # sigma_squared = sum((r - mu) ** 2 for r in radii) / n # # Calculate E[N] and E[N^2] where N is the random variable counting the # # number of original creatures in a randomly picked final creature. # # Think of this by starting with each of the n - k final creatures with size 1. # # We then distribute k units randomly across these so we have # # N = 1 + X_1 + ... + X_k where X_i ~ Ber(1 / (n - k)) # # = 1 + Y where Y ~ Bin (k, 1 / (n - k)) # E_N = 1 + k / (n - k) # E_N_squared = 1 + k / (n - k) * (3 + (k - 1) / (n - k)) # total_area = pi * (n - k) * (sigma_squared * E_N + (E_N_squared - E_N) * cov + (mu ** 2) * E_N_squared) # print(total_area) # print("mu", mu) # print("pairs", pairs) # print("cov", cov) # print("sigma_squared", sigma_squared) # print("E_N", E_N) # print("E_N_squared", E_N_squared) # r_1 r_2 r_3 ... r_n # k = 1 # + \sigma 2 r_i r_j # / (n (n - 1) / 2) # E[X] # var[X] # E[X^2] = var[x] - E[X] ^2 # X ~ Unif[r_1,....,r_n] # Y | X = r_i ~ Unif[r_1,...,r_n] \ {r_i} # E[Y] = \sigma E[Y | X = r_i] P(X = r_i) = 1 / n (n - 1) (n - 1) \sigma r_i = E[X] # E[X + Y + Z] = E[X] + E[Y] + E[Z] # E[(X_1 + X_2 + X_3) ^2] ? X_i ~ Unif[r_1, ...., r_n] not indep. # We have n - k creatures after k seconds with radii X_1 , .... , X_n-k. # X_i identically distributed but not independent. # E[X_1 ^2 + X_2 ^2 + ... + X_n ^2] = E[X_1 ^2] + .... + E[X_n-k ^2] # = (n - k) * E[X_i ^2] # = (n - k) * (var(X_i) + E[X_i] ^ 2) # = (n - k) * (sigma^2 E[N] + mu^2 E[N^2]) # X_i | N = m = Y_1 + .... + Y_m # sample of random number of terms # var(X_i) = N * var(Y_i) + N(N-1) cov(Y_i, Y_j) = N * sigma^2 + N(N-1) * cov # Y_i ~ Unif[r_1, ..., r_n] # E[X_i] = N * E[Y_i] = N * mu # X_i # size probability # k + 1 2 ^ k / (n (n - 1) ... (n - k + 1)) # k 2 / # . # . # . # 1 (n - 2) (n - 3) (n - 4) .... (n - 1 - k) / n (n - 1) .... (n - k + 1) = (n - k) (n -k - 1) / n (n - 1)
a42beb3c69a30bcfd7c660d18a702b484d8c1172
inovei6un/SoftUni-Studies-1
/FirstStepsInPython/Advanced/Lab/Multidimensional_Lists/01_Sum_Matrix_Elements.py
511
3.59375
4
""" 3, 6 7, 1, 3, 3, 2, 1 1, 3, 9, 8, 5, 6 4, 6, 7, 9, 1, 0 """ # # 01 solution # n_rows, m_column = [int(x) for x in input().split(', ')] # matrix = [[int(y) for y in input().split(', ')] for x in range(n_rows)] # print(sum(sum(row) for row in matrix)) # print(matrix) # # 02 solution n_rows, m_column = [int(x) for x in input().split(', ')] matrix = [] for row in range(n_rows): lines = [int(x) for x in input().split(", ")] matrix.append(lines) print(sum(sum(row) for row in matrix)) print(matrix)
374b23dc02ffbca702994b7b63230c16de448689
juleskuehn/comp4107
/A3/q3.py
4,762
4.03125
4
''' COMP4107 fall 2018 assignment 3 question 3 Student name: Yunkai Wang Student num: 100968473 We can use self organizing maps as a substitute for K-means. In Question 2, K-means was used to compute the number of hidden layer neurons to be used in an RBF network. Using a 2D self-organizing map compare the clusters when compared to K-means for the MNIST data. Sample the data to include only images of '1' and '5'. Use the scikit-learn utilities to load the data. You are expected to (a) document the dimensions of the SOM computed and the learning parameters used to generate it (b) provide 2D plots of the regions for '1' and '5' for both the SOM and K-means solutions. You may project your K-means data using SVD to 2 dimensions for display purposes. ''' import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from math import ceil, sqrt from random import shuffle from sklearn.decomposition import PCA from sklearn.cluster import KMeans # minisom library found at https://github.com/JustGlowing/minisom # Can be installed by running 'pip3 minisom' from minisom import MiniSom mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # return part of the data that matches the given label def partition(x_data, y_data,label): return [(np.array(input).ravel(), label) for (input, output) in zip(x_data, y_data) if output == label] def getTrainingData(): # get the datas for 1 and 5 ones = partition(x_train, y_train, 1) fives = partition(x_train, y_train, 5) # shuffle the training data so that the execution process won't always be the same trainingData = ones + fives shuffle(trainingData) return trainingData def getTestingData(): # get the datas for 1 and 5 ones = partition(x_test, y_test, 1) fives = partition(x_test, y_test, 5) # shuffle the training data so that the execution process won't always be the same testingData = ones + fives shuffle(testingData) return testingData # calculate the number of output neurons, n is the number of samples, # given the number of samples n, there should be >= 5 * sqrt(n) neurons def calculate_dimension(n): return ceil(sqrt(5 * sqrt(n))) def draw(som, x, y, data, title): for item in data: pixels, label = item i, j = som.winner(pixels) plt.text(i, j, label) plt.axis([0, x, 0, y]) plt.title(title) plt.savefig("./document/" + title + ".png") plt.clf() # clear current figure for the next figure # plt.show() def train(trainingData, num_epoch=500, num_split=2, input_len=784, sigma=1, learning_rate=0.1): x = calculate_dimension(len(trainingData)) y = calculate_dimension(len(trainingData)) # create the self organizing map som = MiniSom(x, y, input_len, sigma=sigma, learning_rate=learning_rate) data = [pixels for pixels, _ in trainingData] # draw the SOM before training draw(som, x, y, trainingData, "Before_training") for i in range(num_split): # training the SOM for the number of epochs specified som.train_random(data, int(num_epoch / num_split)) # draw the SOM after training draw(som, x, y, trainingData, 'After_training_for_%s_epochs' % int((i + 1) * (num_epoch / num_split))) return som def display_PCA(trainingData): # unpack the pixels and the labels data = [pixels for pixels, _ in trainingData] labels = [label for _, label in trainingData] # create PCA for 1 and 5 pca = PCA(n_components=2) pca.fit(data) pca_list = pca.transform(data) # reduce the data to 2D for displaying purpose plt.scatter(pca_list[:, 0], pca_list[:, 1], c=labels, s=0.5) title = "Without_kmeans" plt.title(title) plt.savefig("./document/" + title + ".png") plt.clf() # clear current figure for the next plot num_clusters = range(2, 6) for cluster_size in num_clusters: kmeans = KMeans(n_clusters=cluster_size) kmeans.fit(data) title = "With_" + str(cluster_size) + "_clusters" plt.scatter(pca_list[:, 0], pca_list[:, 1], c=kmeans.labels_, s=0.5) plt.title(title) plt.savefig("./document/" + title + ".png") plt.clf() # clear current figure for the next plot # plt.show() # use only 1024 data for just for a faster running time trainingData = getTrainingData()[:1024] # get the training data input_len = 784 # each image in MNIST database contains 784 pixels sigma = 1 # not sure what to choose for now, just testing 1 learning_rate = 0.1 # not sure what to choose for now, just testing 0.1 som = train(trainingData, num_epoch=500, learning_rate=learning_rate, sigma=sigma, input_len=input_len) # plt.show() display_PCA(trainingData)
071f3de053aab92497a395b225411ad2d75a2396
dobis32/reservation-maker
/project/app/src/todayString.py
461
3.71875
4
from datetime import datetime def getTodayString(): today = datetime.now() month = None if today.month < 10: month = '0' + str(today.month) # add padding zero else: month = str(today.month) day = None if today.day < 10: day = '0' + str(today.day) # add padding zero else: day = str(today.day) date = '{month}-{day}-{year}'.format(month= month, day = day, year = today.year - 2000) return date
bb6183403eb049abcc2f0c5b610bd1f33d068092
manhar336/manohar_learning_python_kesav
/Revision/tuples.py
599
4.09375
4
fruits = "apple","mango","banana" places_kms = (10,20,30,40) print("tuple1 method:",fruits,type(fruits),tuple(enumerate(fruits))) tup1,tup2 = (10,20,30,40),("a","b","""C""") list1 = list(tup1) print("converting tuple into list",list1) print(tup1,tup2) alist = [1,2,3,3,5] print("conversting list into tuple:",tuple(alist)) print("slice method in tuple",fruits[2]) print("range slice method in tuple:",fruits[0:2]) print("zero based indexing",places_kms[0::2]) print("min method in tuple:",min(fruits)) print("max method in tuple:",max(places_kms)) print("Concatenation method:",fruits + places_kms)
abe7b97d29f498e5c759dc692a6b38eb1f515a9d
amangour30/MILPSolver
/input.py
850
3.59375
4
from pulp import * n1 = raw_input("Please enter number of integer variables: ") print "N1: ", n1 n2 = raw_input("Please enter number of continuous variables: ") print "N2: ", n2 print "Please enter the wegihts of the objective function C1 \n" C = [] for i in range(int(n1)): n = raw_input("c %d:"%(i+1)) C.append(int(n)) for i in range(int(n2)): n = raw_input("c %d:"%(i+1)) C.append(int(n)) numm = raw_input("Please enter number of equations: ") print "M: ", numm b = [] A = [] G = [] for i in range(int(numm)): print "Add %d th equation:"%(i+1) temp = [] temp2 = [] for j in range(int(n1)): aij = raw_input("a %d %d:"%(i+1, j+1)) temp.append(aij) for j in range(int(n2)): aij = raw_input("g %d %d:"%(i+1, j+1)) temp2.append(aij) bi = raw_input("b %d:"%(i+1)) A.append(temp) G.append(temp2) b.append(bi)
3dcb2a9ac77771774f0bd79606da019a075ec409
laisOmena/Recursao-em-Python
/lista2/quest05.py
559
3.84375
4
nome = input("Digite seu nome: ") nome1 = [] for i in range(0, len(nome)): nome1.append(nome[i]) nome1 = nome1[::-1] nome2 = [] for i in range(0, len(nome1)): nome2.append(nome1[i]) if nome1[i + 1] == " ": break nome2 = nome2[::-1] nome3 = "" for i in nome2: nome3 = nome3 + i letra0 = [] for i in range(0, len(nome)): if nome[i - 1] == " ": letra0.append(nome[i]) break letra2 = "" for i in letra0: letra2 = i letra1 ="" for i in nome[0]: letra1 = i print("{},{}. {}.".format(nome3, letra1, letra2))
b73ddfab804a3102d2bffcb8afc8ed93625735e6
paulhkoester16/automatic_diff
/automatic_diff/learning_rates.py
5,189
3.59375
4
''' Classes for various learning rate schedules ''' import numpy as np class LearningRate: ''' Base class for learning rates Base class implements constant learning rate for standard gradient descent. Child classes can be implemented to add complexity to the learning rate schedule, for example decaying learning rates or momentum Parameters ---------- lr: float Learning rate for standard gradient descent algorithms ''' @classmethod def create(cls, *arg): ''' Learning rate factory `arg` is expected to either be the arg list for a LearningRate or an already instantiated LearningRate ''' if isinstance(arg[0], cls): val = arg[0] else: val = cls(*arg) return val def __init__(self, lr=0.1): self._init_lr = lr self.lr = self._init_lr @property def lr(self): # pylint: disable=missing-docstring return self.__lr @lr.setter def lr(self, lr): self.__lr = lr # pylint: disable=attribute-defined-outside-init def update(self, grad_descent): ''' Update for standard gradient descent Gradient step is learning rate * gradient step of f(x) Parameters ---------- grad_descent: gradient_descent.GradientDescent Returns ------- np.array Step vector for next iteration ''' return np.array(grad_descent.dy) * self.lr class TimeDecayLearningRate(LearningRate): ''' Similar to LearningRate, except the learning rate decays with the number of iterations Parameters ---------- decay_rate: float One iteration `n`, learning rate decays by a further factor of (1 + `decay_rate` * `n`) kwargs: Keyword arguments passed to `LearningRate`'s constructor ''' def __init__(self, decay_rate=1e-2, **kwargs): super().__init__(**kwargs) self.decay_rate = decay_rate def update(self, grad_descent): ''' Parameters ---------- grad_descent: gradient_descent.GradientDescent Returns ------- np.array Step vector for next iteration ''' self.lr = self._init_lr / (1 + self.decay_rate * grad_descent.num_iter) return np.array(grad_descent.dy) * self.lr class GradDecayLearningRate(LearningRate): ''' Similar to LearningRate, except the learning rate decays based recent gradient steps. Need to recall references for this particular version. Parameters ---------- patience: int Learning rate is based on the `patience` most recent gradient steps ''' def __init__(self, patience=5, **kwargs): super().__init__(**kwargs) self.patience = patience self.this_dy = None self.prev_dy = None self.this_x = None self.prev_x = None self.prev_lr = [] def update(self, grad_descent): ''' Parameters ---------- grad_descent: gradient_descent.GradientDescent Returns ------- np.array Step vector for next iteration ''' if grad_descent.num_iter > 0: self.prev_dy = self.this_dy.copy() self.prev_x = self.this_x.copy() self.this_dy = np.array(grad_descent.dy) self.this_x = np.array(grad_descent.x) if grad_descent.num_iter > 0: delta_dy = self.this_dy - self.prev_dy delta_x = self.this_x - self.prev_x self.lr = np.dot(delta_x, delta_dy) / np.dot(delta_dy, delta_dy) self.lr = min(abs(self.lr), abs(self._init_lr)) self.prev_lr.append(self.lr) if len(self.prev_lr) > self.patience: self.prev_lr.pop(0) self.lr = np.mean(self.prev_lr) return np.array(grad_descent.dy) * self.lr class MomentumLearningRate(LearningRate): ''' Similar to LearningRate, except learning rate adapts based on momentum Parameters ---------- decay_rate: float One iteration `n`, learning rate decays by a further factor of (1 + `decay_rate` * `n`) momentum_rate: float Scale factor for how much previous gradient steps affect next step kwargs: Keyword arguments passed to `LearningRate`'s constructor ''' def __init__(self, momentum_rate=0.9, decay_rate=1e-1, **kwargs): super().__init__(**kwargs) self.momentum_rate = momentum_rate self.decay_rate = decay_rate self.nu = None def update(self, grad_descent): ''' Parameters ---------- grad_descent: gradient_descent.GradientDescent Returns ------- np.array Step vector for next iteration ''' self.lr = self._init_lr / (1 + self.decay_rate * grad_descent.num_iter) if grad_descent.num_iter == 0: self.nu = np.zeros_like(grad_descent.x) self.nu = self.momentum_rate * self.nu + np.array(grad_descent.dy) * self.lr # print(self.nu) return self.nu
90267d507d032032bcc5746168d754bb6112c753
abay-90/NISprogramming
/Module 3/PRG Module 3 Prax Activity/ShapeManager_Answer.py
381
3.625
4
from Square import * from Rectangle import * from Cube import * from Box import * shapes = list() shapes.append(Square("Square 1", 10)) shapes.append(Rectangle("Rectangle 1", 20, 10)) shapes.append(Cube("Cube 1", 10)) shapes.append(Box("Box 1", 20, 10, 5)) print("Number of shapes: ", Shape.count) print("-" * 50) for current in shapes: print(current) print("-" * 50)
99b38795e16028bd82c3174ed09776c185a8fd41
Annapoorneswarid/ANNAPOORNESWARI_D_RMCA_S1A
/Programming_Lab/27-01-2021/2..py
479
4.09375
4
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> >>> >>> print("Enter Year") Enter Year >>> endYear =int(input()) 2040 >>> startYear=2020 >>> print("List of leap year:") List of leap year: >>> for year in range(startYear,endYear): if (0==year%4) and(0!=year%100)or(0==year%400): print(year) 2020 2024 2028 2032 2036 >>> >>>
29c7b3a63d0f6020640798d5d758474f28ab6ef0
deshpande-aditya/Py_Triaining
/class_func.py
347
3.75
4
##Practice class functions in Python. from student import student ##use similar code as student program written previously. student1 = student("Rasika", "Biochem", 89.0, "First") student2 = student("kayden", "Genetics", 71.0, "First") student3 = student("Alexa", "Genetics", 89.0, "First") print(student1.percent) print(student1.on_honor_roll())
5efd2910e0416f7f85ed8759cfeb127654ffbc7a
fandiandian/python_learning_excerise
/part1.4习题/musice_shuffling(音乐随机播放).py
1,645
3.828125
4
# 音乐随机播放 # music random play(Music shuffling) # 要求:随机播放 m 首歌各一次,然后重复。 # 估计不按顺序播放两首歌的概率(即歌曲 2 后面不播放歌曲 3 ,歌曲 9 后面不播放歌曲 10) # 创建一个长度为 m 的数组,打乱顺序 # 不放回的随机取样,样本总量为 m ,抽取 m 个样本 # 还有一种是使用 random.choice() 得到样本,在原始数组中将其删除 # 最直接的方式 random,shuffle() # 长度为 m ,间隔为 m-1,所需的结果为:连续的次数/ (m-1) import random m = int(input('请确定歌曲的数量:\n')) # 连续歌曲计数 n = 0 # 创建歌曲数组 music_repositories = [i for i in range(1,m+1)] # 乱序 ''' # 第一种 最简单的 # random.shuffle(music_repositories) # 第二种 random.choice() # music_repositories_copy = [] # for ms in range(m): # musics = random.choice(music_repositories) # music_repositories_copy += [musics] # music_repositories.remove(musics) ''' # 第三种 通过循环,数组的元素依次与后面的元素进行互换 # random.randint(m,n):包括上下限,random.randrange(m,n):不包括上限 # randint(m,n) 的实现方式通过调用 randrange(m,n+1) 实现的 for ms in range(m): mss = random.randrange(ms,m) music_repositories[ms],music_repositories[mss] = music_repositories[mss],music_repositories[ms] for i in range(m-1): if music_repositories[i] + 1 == music_repositories[i + 1]: n += 1 print(music_repositories) print(' {} 首歌随机播放,其中连续播放的有 {} 次,概率是:{:.2f}%'.format(m ,n ,(n/(m-1))*100 ))
38aa007de11889faae7b14473ea05c001e73786d
bwest619/Python-Crash-Course
/Ch 3 - Lists/every_function.py
1,890
3.953125
4
#try it yourself, page 50 languages = ['python', 'css', 'html', 'c', 'javascript'] print(languages) print(languages[1].title()) print("My first computer language is " + languages[0].title() + ".") print(languages[-1]) languages.append('java') print(languages) languages.insert(2, 'php') print(languages) languages[4] = 'ruby' print(languages) languages.append('c') print(languages) languages.insert(5, 'visual basic') print(languages) del languages[3] print(languages) print("\n") popped_language = languages.pop(3) print("The language I haven't looked at yet is " + popped_language.title() + ".") print("\n") first_language = languages.pop(0) print("My first computer language is " + first_language.title() + "!") print("\n") too_difficult = 'c' languages.remove(too_difficult) print("The language I hated to start learning was " + too_difficult.title() + ".") print(languages) print("\n") print("The languages sorted alphabetically is:") print(sorted(languages)) print("The languages in their original order is:") print(languages) print("\n") print("The languages listed in reverse alphabetical order is:") print(sorted(languages, reverse = True)) print("The original order is still:") print(languages) print("\n") languages.reverse() print("The languages in reverse order is:") print(languages) languages.reverse() print("The languages reveresed back to their original order is:") print(languages) print("\n") languages.sort() print("The languages in alphabetical order is:") print(languages) languages.sort(reverse = True) print("The languages in reverse alphabetical order is:") print(languages) languages.sort() print("The languages reversed back to alphabetical order is:") print(languages) print("The length of the list of languages is:") print(len(languages)) print("\n") print(languages[-1]) # always prints the last item in the list... unless the list is empty.
2ab4395b7e3849a3f6c702155d01102b044c0d48
yuqiong11/Data-Structure-And-Algorithms
/recursion/gcd.py
297
3.984375
4
# input: two non-negative integer, output: the greatest common divisor # example: given 6, 27, output 3 # euclid's division algorithm def gcd(x, y): if y == 0: return x else: return gcd(y, x % y) print(gcd(27, 0)) print(gcd(0, 27)) print(gcd(6, 27)) print(gcd(85, 408))
11f98317ae4d6503891293a015b8662b7330dba8
Santiagonk/Aprende_con_alf
/Ficheros/Ejercicio_5.py
1,629
3.515625
4
from urllib import request from urllib.error import URLError def det_pib(url, country = 'ES'): ''' Funcion toma una url y un codigo de pais, y devuelve diccionario con los PIBs por año del pais seleccionado - url variable tipo string con la url deseada - country el codigo del pais ''' try: f = request.urlopen(url) except URLError: return('!la url ' + url + 'no existe!') else: data = f.read().decode('utf-8').split('\n') # tomamos datos y codificamos a utf-8 y separamos por /n queden filas con datos por pais data = [i.split('\t') for i in data] #separamos cada fila por /n queden separados por años data = [list(map(str.strip, i)) for i in data] #Retiramos los espacios vacios de cada string con la funcion strip dentro del map for i in data: i[0] = i[0].split(',')[-1] #Tomamos el codigo de cada pais data[0][0] = 'year' # renombramos el espacio de la primera columna y primera fila con 'año' data = {i[0]:i[1:] for i in data} # pasamos a un diccionario con la informacion por cada pais result ={data['year'][i]:data[country][i] for i in range(len(data['year']))} # guardamos el pib por año del pais seleccionado return result def main(): country = input('Introduce el codigo del país: ') url ='https://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?file=data/sdg_08_10.tsv.gz&unzip=true' result= det_pib(url, country) print('El PIB por año de ',country,' es: ') print('año','\t', 'PIB') for word in result: print(word + '\t' + result[word]) if __name__ == "__main__": main()
364c0007fe770d22c324d5dc7c37b6a8d3b4b13e
AdiVittala/Python-Development
/assigning_function_to_variable.py
2,338
4.6875
5
###Assigning varibales to functions### #def greet(name): # return "hello "+name #greet_someone = greet("John") #print (greet_someone) ###Define fucntions inside other functions #def greet(name): # def get_message(): # return "Hello " # result = get_message()+name # return result #print (greet("John")) ### Fucntions can be passed as parameters to other functions### #def greet(name): # return "Hello " + name #def call_func(func): # other_name = "John" #return other_name # return func(other_name) #print (call_func(greet)) ### Outside function is evaluated first and then the inside function passed as argument is evaluated next ###Fucntions can return other functions (or generate fucntions as a return value)### #def compose_greet_func(): # def get_message(): # return "Hello there!" #return get_message #greet = compose_greet_func()### assigning a function to variable makes the variable a function ### #print (greet()) #print (type (greet)) #### Read Access to outer Scope ### - Need to understand better #def compose_greet_func(name): # def get_message(): # return "Hello there "+name+"!" # print (type (get_message)) #return get_message ### When returning a function with no arguments parenthesis need not be specified### #greet = compose_greet_func("John") #print (greet()) ####Fucntion decorators are simply wrappers to existing functions.### ### Function wrapping the string output of another function by p tags### ### A Decorator function takes one fucntion(usually whose output we want modified, without actually changing the fucntion) ### as an argument and returns the output to another fucntion #def get_text(name): # return "lorem ipsum, {} dolor sit amet".format(name) #def p_decorate(func): # def func_wrapper(name): # return "<p>{}</p> fuck you".format(func(name)) # return func_wrapper #get_text = p_decorate(get_text)### This can be expressed in Python syntax as @p_decorate just before defning the function get_text #print (get_text("John")) ###Python Decorator Syntax### def p_decorate(func): def func_wrapper(name): return "<p>{}</p> fuck you".format(func(name)) return func_wrapper @p_decorate def get_text(name): return "lorem ipsum, {} dolor sit amet".format(name) print (get_text("John"))
49c1344690991f8404e0661ac7f24a1ff86d7b2b
imdasein/zsk
/OOP/01.py
859
4.09375
4
''' 定义一个学生类 ''' # 定义一个空的类 class Student(): # 一个空类,pass必须有,表示跳过,否则会报错 pass # 定义一个对象 mingyue = Student() # 定义一个学Python的学生 class PythonStudent(): name = None age = 8 course = "python" #def的缩进层级和系统变量一样,二是默认有一个self参数 def doHomework(self): print("I am doing my homework.") #推荐在函数末尾使用return语句 return None # 实例化 yueyue = PythonStudent() #用点号操作符 print(yueyue.age) print(yueyue.name) #注意成员函数的调用没有传递参数 yueyue.doHomework() # 类和对象的成员分析 -类和对象都可以存储成员,成员可以归类所有,也可以归对象所有 -类存储成员时使用的是和类关联的一个对象
b7afd72beb84315890d677cb69e1061fd2c59b1d
artem12345-png/SAOD
/3 algoritms.py
3,760
3.703125
4
import timeit import random import matplotlib.pyplot as plt import numpy as np # Метод сортировки Radix Sort def Radix_sort(list1): list = list1 long = len(list) r = 1 max_element = max(list) is_check = True ts = 0 fin_ls = [0 for i in range(len(list))] ts = timeit.default_timer() while ((max_element // r) > 0): counter = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for element in list: counter[int((element / r) % 10)] += 1 for i in range(1, len(counter)): counter[i] = counter[i] + counter[i - 1] list.reverse() for element in list: fin_ls[counter[int((element / r) % 10)] - 1] = element counter[int((element / r) % 10)] -= 1 r*=10 list = fin_ls fin_ls = [0 for i in range(len(list))] xR.append(timeit.default_timer() - ts) # Проверка корректной сортировки for i in range(long - 1): if fin_ls[i] > fin_ls[i + 1]: is_check = False if is_check: print("Radix Sort successful") else: print('Radix Sort ERROR!!!') return # Метод сортировки Selection Sort def Selection_Sort(list1): list = list1 # Переменная для подсчета времени сортировки ts = 0 long = len(list) # Переменная для проверки правильной сортировки is_check = True # Запуск таймера ts = timeit.default_timer() # Начало сортировки for i in range(long - 1): smallest = i for j in range(i + 1, long): if list[j] < list[smallest] : smallest = j list[i], list[smallest] = list[smallest], list[i] # Вывод затраченого времени для сортировки xS.append(timeit.default_timer() - ts) # Проверка корректной сортировки for i in range(long - 1): if list[i] > list[i + 1]: is_check = False if is_check : print("Selection Sort successful") else: print('Selection Sort ERROR!!!') # Метод сортировки Heap Sort def Heap_Sort(list1): list = list1 long = len(list) ts = 0 ts = timeit.default_timer() is_check = True for i in range(long // 2 - 1, -1, -1): Heapify(list, long, i) for i in range(long - 1, 0, -1): list[0], list[i] = list[i], list[0] Heapify(list, i, 0) xH.append(timeit.default_timer() - ts) # Проверка корректной сортировки for i in range(long - 1): if list[i] > list[i + 1]: is_check = False if is_check: print("Heap Sort successful") else: print('Heap Sort ERROR!!!') def Heapify(list, long, i): max_el = i l = 2 * i + 1 r = 2 * i + 2 if ((l < long) and (list[l] > list[max_el])): max_el = l if ((r < long) and (list[r] > list[max_el])): max_el = r if (max_el != i): list[i], list[max_el] = list[max_el], list[i] Heapify(list, long, max_el) def test(list1): list = list1 ts = 0 ts = timeit.default_timer() list.sort() xT.append(timeit.default_timer() - ts) y = [] xH = [] xR = [] xS = [] xT = [] list = [] for i in range(50000, 1050000, 50000): list1 = [random.randint(0, 100000) for j in range(i)] Radix_sort(list1) Selection_Sort(list1) Heap_Sort(list1) test(list1) y.append(i) print(xH) print(xS) print(xT) print(xR) fig, ax = plt.subplots() ax.plot(xH, y) ax.plot(xR, y) ax.plot(xS, y) ax.plot(xT, y) plt.show()
d22ded25d52af9a2417f67c015c7e91ba69dfe81
ocder/My-code
/python/判断是否是质数.py
337
3.90625
4
import math def IsPrime(n): if n > 1: for i in range(2, n): if (n % i) == 0: print("不是质数") break else: print("是质数") else: print("不是质数") if __name__ == '__main__': num = int(input("请输入一个数:")) IsPrime(num)
f81b9bee6399c80973901661088366b98e7a147e
Jenny-Jo/AI
/python/python04_tuple.py
546
4.0625
4
#2. 튜플 #리스트[ ]와 거의 같으나, """삭제와 수정"""이 """안된다."""" a = (1, 2, 3) b = 1, 2, 3 print(type(a)) print(type(b)) # <class 'tuple'> # a.remove(2) # AttributeError: 'tuple' object has no attribute 'remove' 속성에러 # print(a) print(a + b) # (1, 2, 3, 1, 2, 3) print(a * 3) # (1, 2, 3, 1, 2, 3, 1, 2, 3) # print(a - 3) # TypeError: unsupported operand type(s) for -: 'tuple' and 'int'