blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
3220a794fdfcdb0762080907c5e567f184e9b872
danny-hunt/Problems
/ghost/ghost.py
1,727
3.953125
4
""" Ghost is a two-person word game where players alternate appending letters to a word. The first person who spells out a word, or creates a prefix for which there is no possible continuation, loses. Here is a sample game: Player 1: g Player 2: h Player 1: o Player 2: s Player 1: t [loses] Given a dictionary of words, determine the letters the first player should start with, such that with optimal play they cannot lose. For example, if the dictionary is ["cat", "calf", "dog", "bear"], the only winning start letter would be b. """ import string import re """ for each letter in the alphabet, see whether that letter gives P1 a forced win a letter gives a forced win iff there is no forced win for the second player in response AND there is a valid word with that starting letter sequence function: determine winner from state A = current string + indication of who is to play say player one = 0 player two = 1 """ alphabet = list(string.ascii_lowercase) dictionary = ["cat", "calf", "dog", "bear"] dictionary.sort() dictionary_with_lengths = [ [x, len(x)] for x in dictionary] print(dictionary_with_lengths) def word_exists(string, dictionary = dictionary): count = 0 for word in dictionary: if word.startswith(string): count += 1 if count > 0: return True if count < 1: return False def who_wins(to_play = 0, string = ''): existing_length = len(string) if not word_exists(string): print(f'player {to_play} wins through lack of word') return 0 #for import string dictionary = ["cat", "calf", "dog", "bear"] dictionary.sort() alphabet = list(string.ascii_lowercase) #for letter in alphabet: # if
8086dd17a1c45e65d4c0a5d61222a88e1494fd1e
sanu11/Codes
/Leetcode/112.PathSum.py
873
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def calculate(self,root,sum,value): if(root.left == None and root.right == None): if value == sum: return True else: return False a,b = False,False if(root.left): a=self.calculate(root.left,sum,value+root.left.val) if(root.right): b=self.calculate(root.right,sum,value+root.right.val) return a|b def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if(root!=None): return self.calculate(root,sum,root.val) else: return False
4ab015642d40b219ced7b874821e227cdb72d39f
daniel-reich/ubiquitous-fiesta
/q3zrcjja7uWHejxf6_12.py
350
3.96875
4
def negative_sum(chars): r, add = [], "-" while "-" in chars: s = chars.index("-") chars = chars[s:] s = 0 while s + 1 < len(chars) and chars[s + 1].isnumeric(): s += 1 add = int(chars[: s + 1]) r.append(add) add = "-" chars = chars[s + 1 :] return sum(r)
d32a9f4814a2d28b908db36af8b2f729b0d12e50
shannonmlance/leetcode
/learning/arrayAndString/introductionToArray/findPivotIndex.py
2,296
4
4
# Given an array of integers nums, write a method that returns the "pivot" index of this array. We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index. # If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index. # Example 1: # Input: nums = [1,7,3,6,5,6] # Output: 3 # Explanation: The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. Also, 3 is the first index where this occurs. # Example 2: # Input: nums = [1,2,3] # Output: -1 # Explanation: There is no index that satisfies the conditions in the problem statement. # Constraints: # The length of nums will be in the range [0, 10000]. # Each element nums[i] will be an integer in the range [-1000, 1000]. class Solution: def pivotIndex(self, nums): # if the array is empty, then there is no left and right of the pivot index if len(nums) < 1: return -1 # initialize the pivot at index 0 pivot = 0 # initialize the sum of the left of the pivot as nothing (if the pivot is at index 0, there are no values to the left) left = 0 # initialize the sum of the right of the pivot as the sum of the entire array, minus the value at the pivot index right = sum(nums) - nums[pivot] # perform this loop as long as the pivot is less than the length of the array, minus one, and as long as the left and right variables do not equal the same value while pivot < len(nums)-1 and left != right: # move the pivot index to the right # add the current pivot index's value to the left variable left += nums[pivot] # subtract the next pivot index's value from the right variable right -= nums[pivot+1] # increment the pivot index pivot += 1 # if the left and right variable equal the same value, then return the current pivot index if left == right: return pivot # else, return -1 as there is no valid pivot index return -1 nums = [-1,-1,-1,0,1,1] s = Solution() a = s.pivotIndex(nums) print(a)
c55c68b5690365faf5709675407afd2047170111
Ian-Dzindo01/HackerRank_Challenges
/Python/Diagonal difference .py
721
3.5
4
#!/bin/python3 import math import os import random import re import sys def diagonalDifference(arr): dia1 = 0 dia2 = 0 for x in range(len(arr)): for y in range(len(arr)): if(x == y): dia1 += arr[x][y] cnt1 = 0 cnt2 = len(arr) - 1 for x in range(len(arr)): dia2 += arr[cnt1][cnt2] cnt1 += 1 cnt2 -= 1 res = abs(dia1 - dia2) return res if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) fptr.write(str(result) + '\n') fptr.close()
7ffbd3dc291d20aa9d7f779dee2fdfcfe63775ca
chander0067/programming1
/all items list and available.py
4,545
3.9375
4
"""Name Chander deep There two function below 1. first is the list of all movies and 2. The other function is to hire the movies or items which are available which are available for hiring Git hub link https://github.com/chander0067/programming1.git """ """LIST of MOVIES # function listMovies() then say”All items on file(* indicates item is currently out)” open file ("items.csv",'r') read file movie= f.readlines() set n=0 for i in movie: movieName = i.strip().split(',')[0] discp = i.strip().split(',')[1] price = float(i.strip().split(',')[2]) availablity= i.strip().split(',')[-1] print(str(n)+" - "+"%-45s"%(movieName+"("+discp+")")+"= $"+"%7.2f"%(price),sep=" ",end="") n+=1 if item is all gone "out": say (" *") else: say () close file () """ def listMovies(): print("All items on file (* indicates item is currently out):") f= open("items.csv",'r') movie= f.readlines() n=0 for i in movie: movieName = i.strip().split(',')[0] discp = i.strip().split(',')[1] price = float(i.strip().split(',')[2]) availablity = i.strip().split(',')[-1] print(str(n)+" - "+"%-45s"%(movieName+"("+discp+")")+"= $"+"%7.2f"%(price),sep=" ",end="") n+=1 if availablity== "out": print(" *") else: print() f.close() """ hireItems Function function hireItems(): open file ("items.csv",'r') read file f.readlines() set n=0 hList=[] for i in item: movieName = i.strip().split(',')[0] description = i.strip().split(',')[1] cost = float(i.strip().split(',')[2]) availiblity = i.strip().split(',')[-1] if availablity == "in": say (str(n)+" - "+"%-45s"%(movieName+"("+description+")")+"= $"+"%7.2f"%(cost),sep=" ") n+=1 hList.append(i) close file f.close() while True: movieChoice = int(input("Enter the number of an item to hire ")) if movieChoice >= 0 and movieChoice < n: open file in write mode f= open("items.csv",'w') m = item.index(hList[movieChoice]) movie = item[m] movieName = movie.strip().split(',')[0] description = movie.strip().split(',')[1] cost = float(movie.strip().split(',')[2]) print (movieName+ " hired for $"+ "%.2f" %(cost) ) item[m] = movieName+","+description+","+str(cost)+","+"out\n" file="" for i in item: add a file after each execution file = file + i write file say f.write(file) f close file say .close() break else: say ("Invalid input. \n") """ def hireItems(): f= open("items.csv",'r') item= f.readlines() n=0 hList=[] for i in item: movieName = i.strip().split(',')[0] description = i.strip().split(',')[1] cost = float(i.strip().split(',')[2]) availiblity = i.strip().split(',')[-1] if availiblity == "in": print(str(n)+" - "+"%-45s"%(movieName+"("+description+")")+"= $"+"%7.2f"%(cost),sep=" ") n+=1 hList.append(i) f.close() while True: movieChoice = int(input("Enter the number of an item to hire ")) if movieChoice >= 0 and movieChoice < n: f= open("items.csv",'w') m = item.index(hList[movieChoice]) movie = item[m] movieName = movie.strip().split(',')[0] description = movie.strip().split(',')[1] cost = float(movie.strip().split(',')[2]) print (movieName+ " hired for $"+ "%.2f" %(cost) ) item[m] = movieName+","+description+","+str(cost)+","+"out\n" file="" for i in item: file = file + i f.write(file) f.close() break else: print("Invalid input. \n")
b37e497d07024809c3dbfe48e62b395490c4e75b
afifaniks/algopy
/hackerrank-interview/encryption.py
772
3.5
4
import math def encryption(s): no_sp = "" length = 0 for c in s: if c != ' ': no_sp += c length += 1 root = math.sqrt(length) col = math.ceil(root) row = math.floor(root) if row*col < length: row += 1 grid = [] index = 0 for i in range(row): grid_row = [] for j in range(col): if (index < length): grid_row.append(no_sp[index]) else: grid_row.append("") index += 1 grid.append(grid_row) result = "" for i in range(col): for j in range(row): result += grid[j][i] result += " " result = result[:-1] return result print(encryption("chillout"))
3df491b0984fa3063485e71007771bc22370ffb8
samyun/Ohio-Union-EMS-Autofill-Tool
/Test/test_get_teardown_time.py
4,450
3.828125
4
def parse_time(time): """ Parse a time in the format '12:00 AM' into three parts: hour, minute, AM/PM. Args: time (str): time in format '12:00 AM' Returns: parsed_time (3-tuple): first element is the hour as an int, second element is the minute as an int, and third element is the AM/PM as a str """ time_split = time.split(' ') time_number_part_split = time_split[0].split(':') time_first_number = int(time_number_part_split[0]) time_second_number = int(time_number_part_split[1]) time_ampm_part = time_split[1] return time_first_number, time_second_number, time_ampm_part def get_teardown_time(event_start_time, foo=30): """ Given the event start time, find the setup time based on the delays/advances in settings.json Args: event_start_time (str): event start time (in the format '12:00 AM') Returns: setup_time (str): time to setup for event (in format '12:00 AM') """ time_first_number, time_second_number, time_ampm_part = parse_time(event_start_time) time_second_number += foo i = 0 while time_second_number >= 60: time_second_number -= 60 time_first_number += 1 i += 1 # cover unlikely event of 12+ hour delays extra_ampm_flips = int(i/12) time_first_number += 12 * extra_ampm_flips i -= 12 * extra_ampm_flips if extra_ampm_flips % 2 == 1: if time_ampm_part == "AM": time_ampm_part = "PM" else: time_ampm_part = "AM" while time_first_number > 12: time_first_number -= 12 i -= 1 if i + time_first_number > 12 and i > 0: if time_ampm_part == "AM": time_ampm_part = "PM" else: time_ampm_part = "AM" # return new time formatted_time = "" if time_first_number < 10: formatted_time += "0" formatted_time += str(time_first_number) else: formatted_time += str(time_first_number) formatted_time += ":" if time_second_number < 10: formatted_time += "0" formatted_time += str(time_second_number) else: formatted_time += str(time_second_number) formatted_time += " " + time_ampm_part return formatted_time def test_12am(): assert get_teardown_time("12:00 AM") == "12:30 AM" def test_12pm(): assert get_teardown_time("12:00 PM") == "12:30 PM" def test_1130pm(): assert get_teardown_time("11:30 PM") == "12:00 AM" def test_1130am(): assert get_teardown_time("11:30 AM") == "12:00 PM" def test_10am(): assert get_teardown_time("10:00 AM") == "10:30 AM" def test_10pm(): assert get_teardown_time("10:00 PM") == "10:30 PM" def test_2am(): assert get_teardown_time("2:00 AM") == "02:30 AM" def test_2pm(): assert get_teardown_time("2:00 PM") == "02:30 PM" def test_130am(): assert get_teardown_time("1:30 AM") == "02:00 AM" def test_130pm(): assert get_teardown_time("1:30 PM") == "02:00 PM" def test_1am(): assert get_teardown_time("1:00 AM") == "01:30 AM" def test_1pm(): assert get_teardown_time("1:00 PM") == "01:30 PM" def test_1230am(): assert get_teardown_time("12:30 AM") == "01:00 AM" def test_1230pm(): assert get_teardown_time("12:30 PM") == "01:00 PM" def test_12am_60(): assert get_teardown_time("12:00 AM", 60) == "01:00 AM" def test_12pm_60(): assert get_teardown_time("12:00 PM", 60) == "01:00 PM" def test_1130pm_60(): assert get_teardown_time("11:30 PM", 60) == "12:30 AM" def test_1130am_60(): assert get_teardown_time("11:30 AM", 60) == "12:30 PM" def test_10am_60(): assert get_teardown_time("10:00 AM", 60) == "11:00 AM" def test_10pm_60(): assert get_teardown_time("10:00 PM", 60) == "11:00 PM" def test_2am_60(): assert get_teardown_time("2:00 AM", 60) == "03:00 AM" def test_2pm_60(): assert get_teardown_time("2:00 PM", 60) == "03:00 PM" def test_130am_60(): assert get_teardown_time("1:30 AM", 60) == "02:30 AM" def test_130pm_60(): assert get_teardown_time("1:30 PM", 60) == "02:30 PM" def test_1am_60(): assert get_teardown_time("1:00 AM", 60) == "02:00 AM" def test_1pm_60(): assert get_teardown_time("1:00 PM", 60) == "02:00 PM" def test_1230_60am(): assert get_teardown_time("12:30 AM", 60) == "01:30 AM" def test_1230_60pm(): assert get_teardown_time("12:30 PM", 60) == "01:30 PM"
aecff5eb13f900dd7e2b23bd5cdada98299906fc
JamesGrogan/EnoraPython
/question_2_functions.py
575
3.859375
4
import math as math # Function definitions def trapezium_rule(f, m, x, a, b, n): """Implements the trapezium rule""" h = (b-a)/float(n) s = 0.5*(f(m, x, a) + f(m, x, b)) for i in range(n): s = s + f(m, x, a + i*h) return h*s def bessel(m, x, theta): """Holds the formula for the integral in the Bessel function""" return math.cos(m*theta - x*math.sin(theta)) def bessel_value(m, x): """Calculates the value of the Bessel function using the trapezium rule""" return (1 / math.pi) * trapezium_rule(bessel, m, x, 0, math.pi, 10000)
71e3d5f3ad1083c948eba1bde30e757a2f1d3573
Lucasmiguelmac/Project-Euler-Problems-in-Python
/problem_4.py
393
3.765625
4
def is_palindrome(num): strn = str(num) if strn[0] == strn[-1]: if strn[1] == strn[-2]: if strn[2] == strn[-3]: return True palindrome_lst = [] for i in range(100, 1000): for j in range(100, 1000): product = i * j if is_palindrome(product): palindrome_lst.append(product) print(max(palindrome_lst))
261fff40cd97ee0bb538651bde92227a7bfe0122
cheris8/Python_Algorithm
/section_6/Q2/p02.py
795
3.53125
4
# 전위순회 tree = [0, 1, 2, 3, 4, 5, 6, 7] start = 0 root = 1 cnt = 0 while cnt < len(tree)-1: if start == 0: if root*2 < len(tree): cnt += 1 print(tree[root]) root *= 2 elif 2*(root//2)+1 < len(tree): cnt += 1 print(tree[root]) root = 2*(root//2)+1 cnt += 1 print(tree[root]) start += 1 else: if start == 1: root = start*2+1 if root * 2 < len(tree): cnt += 1 print(tree[root]) root *= 2 elif 2 * (root // 2) + 1 < len(tree): cnt += 1 print(tree[root]) cnt += 1 root = 2 * (root // 2) + 1 print(tree[root]) start += 1
450b697a65a6f833bd1d41a04c59e8d4df1244c9
sarthak1598/WebScraping-With-Python
/Save-scraped-Data.py
767
3.84375
4
# This is basic script using iterative programming logic to save the extracted data from the requested domain in the file in # the hard drive as raw data and returns a content length in bytes # Specific function used in scraping: # used basic file handling operation in python import requests url = raw_input("enter the web url") response = requests.get(url) response.raise_for_status() savefile = open('raw_data.txt', 'wb') # opened the new file to hold the extracted data for chunk in res.iter_content(100000): # assumed data size in bytes to be loaded into the file savefile.write(chunk) # writing the data to the file savefile.close() # closing the file # program ends
4b433037321d280c228bfa267fb20e20752b8d0d
yzl232/code_training_leet_code
/Count Univalue Subtrees.py
1,763
4.03125
4
''' Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. For example: Given binary tree, 5 / \ 1 5 / \ \ 5 5 5 return 4. ''' class Solution: def countUnivalSubtrees(self, root): self.cnt = 0 self.dfs(root) return self.cnt def dfs(self, root): if not root: return True l, r = self.dfs(root.left), self.dfs(root.right) if l and r and all(not x or x.val==root.val for x in (root.left, root.right)): self.cnt += 1 return True return False # bottom-up, first check the leaf nodes and count them, # then go up, if both children are "True" and root.val is # equal to both children's values if exist, then root node # is uniValue suntree node. #尝试这么做: if self.dfs(root.left) and self.dfs(root.right) and all #错了。 因为如果左边为False, 会跳过right。 right也必须跑, 这里计算cnt, 和一般的题目不一样。 ''' class Solution: def countUnivalSubtrees(self, root): self.cnt = 0 self.dfs(root) return self.cnt def dfs(self, root): if not root: return True l, r = self.dfs(root.left), self.dfs(root.right) if l and r and (not root.left or root.left.val == root.val) and (not root.right or root.right.val == root.val): self.cnt += 1 return True return False ''' # bottom-up, first check the leaf nodes and count them, # then go up, if both children are "True" and root.val is # equal to both children's values if exist, then root node # is uniValue suntree node.
4cdb01ea8818e892c47bd8e08ddfc7b81193d079
vsei8678/CTI-110
/M5LAB1.py
278
3.765625
4
# CTI-110 # M5LAB1: Shapes # Vincent Sei # October 20, 2017 from turtle import* pensize(6) # Draw a square pencolor("red") for i in range(4): forward(150) left(90) # Draw a triangle pencolor("blue") pendown() for i in range(3): forward(200) left(120)
b88a5daf1acf248d5198a7fe0124689b9c2cfb3f
gopichand-24/market_data_processor
/sp500_tickers.py
1,474
3.65625
4
#! /usr/bin/env python3 '''Script to get the list of S&P 500 tickers''' import requests from bs4 import BeautifulSoup import pandas as pd def get_sp500_table(): ''' Parse a wikipedia article to extract information on the S&P 500 companies :return: Data Frame containing company tickers, names, sector information etc., of all the companies in S&P 500. ''' # Todo:- Add a test case for this function. url = "https://en.wikipedia.org/wiki/List_of_S&P_500_companies" resp = requests.get(url) # resp.text is the content of the response in unicode. soup = BeautifulSoup(resp.text, "lxml") table = soup.find('table', {'class': 'wikitable sortable'}) # Each row in the table is limited by <tr>..</tr>. rows = table.findAll('tr') # The first row is the header of the table. Each cell in the header is # delimited by <th>..</th> columns = [x.text for x in rows[0].findAll('th')] # The cells in each row are delimited by <td>..</td> df = pd.DataFrame([[cell.text for cell in row.findAll('td')] for row in rows[1:]], columns=columns) return df def get_sp500_tickers(): '''Get the list of S&P 500 tickers''' return get_sp500_table()['Ticker symbol'].tolist() if __name__ == "__main__": # from time import time # start = time() print(*get_sp500_tickers(), sep='\n') # print("time taken = ", time()-start, " s")
487df0b6216073c876e40fb3f646d46459fe2eb4
ashitpadhi/python-coding
/Sum_2_linked_list/solution.py
1,105
3.71875
4
# Q: Sum 2 linked list class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumber(self, l1:ListNode, l2:ListNode) -> ListNode: ans = ListNode(None) pointer:ListNode = ans carry = sum = 0 while (l1!=None or l2!=None): sum = carry if (l1!=None): sum += l1.val l1 = l1.next if (l2!=None): sum += l2.val l2 = l2.next carry = int(sum/10) pointer.next = ListNode(sum%10) pointer = pointer.next if (carry>0): pointer.next = ListNode(carry) return ans.next # Test sum2list = Solution() l1_node2 = ListNode(2) l1_node4 = ListNode(4) l1_node3 = ListNode(3) l1_node2.next = l1_node4 l1_node4.next = l1_node3 l2_node5 = ListNode(5) l2_node6 = ListNode(6) l2_node4 = ListNode(4) l2_node5.next = l2_node6 l2_node6.next = l2_node4 answer = sum2list.addTwoNumber(l1_node2,l2_node5) while answer!=None: print(answer.val) answer = answer.next
d7444e6ec84a5be186c263099a598006c9a56f52
rafaelpederiva/Resposta_Python_Brasil
/Exercícios de Estrutura Sequêcnial/Exercício 05 - Metros em Centímetros.py
223
4.15625
4
#Exercício 05 #Faça um Programa que converta metros para centímetros. valor = int(input('Digite aqui um valor em metro para conversão em centímetros: ')) print('O valor em centímetros de', valor, 'é: ', valor * 100)
4bcc73f10d13c97b6203dbfe5acf2415de88f606
DuongTuan3008/duongquoctuan-fundamentals-c4e26
/Fundamentals/Session3/Homework/CRUD.py
1,079
4
4
our_items = ["T-shirt","Sweater"] while True: Request = input("Welcome to our shop, what do you want (C, R, U, D)? ") if Request =="R": print(our_items) elif Request =="C": new_item = input("Enter new item: ") our_items.append(new_item) print(our_items) elif Request == "U": updated_item = input ("Update position? ") if updated_item.isdigit() == True: new_item = input("New item? ") our_items.remove(our_items[int(updated_item)]) our_items.insert(int(updated_item),new_item) print(our_items) else: print("Position is invalid. Please try again!") elif Request == "D": updated_item = input("Delete position? ") if updated_item.isdigit() == True: our_items.remove(our_items[int(updated_item)]) print(our_items) else: print("Position is invalid. Please try again!") elif Request == "Exit": break else: Request = input("Cannot execute your request. Try again! ")
fccbf7eb9b91bee97bb61538b17c373c792ca937
marcosguilhermef/processo-de-regress-o-em-python-descobrir-peso-baseado-na-altura
/teste.py
66
3.6875
4
import numpy as np array = [1,2,3,4,5] print(array.reshape(-1,1))
964a542e9d5f6387cf182e309693a7c10b2517a4
dmitto2243/TurtleArtDesign-
/project.py
639
3.5625
4
import turtle turtle.bgcolor("black") bob = turtle.Turtle() turtle.tracer(0) bob.speed(10) bob.color("red") for times in range(180): bob.forward(100) bob.right(30) bob.forward(20) bob.left(60) bob.forward(50) bob.right(30) bob.penup() bob.setposition(0, 0) bob.pendown() bob.right(2) for times in range(256): bob.circle(10000) bob.right(120) bob.left(180) bob.right(150) bob.left(120) bob.right(110) bob.left(100) bob.right(20) bob.left(80) bob.right(12) bob.left(18) bob.right(2) bob.left(8)
e918bf8645270b5a8258c4ee4905f4776eaa3f33
Srivishnu01/7cards-game
/game.py3
3,597
3.75
4
import random class card: def __init__(self,num,flower): self.num=num self.flower=flower def __eq__(self,card2): return self.num==card2.num def isMagic(self): return 2 if self.num==2 else 1 if self.num==11 and self.flower=='C' else 0 def __str__(self): if self.num in range(2,11): t=str(self.num) elif self.num==1: t='A' elif self.num==11: t='J' elif self.num==12: t='Q' elif self.num==13: t='K' return t+self.flower def __int__(self): if self.num in range(3,11): return self.num elif self.isMagic(): return 0 else: return 10 def Cards(s): out="" for i in s: out+=str(i)+" " return out def totalPoints(s): total=0 for i in s: total+=int(i) return total won=0 cards=[card(n,f) for n in range(1,14) for f in "CDHS"] random.shuffle(cards) p={0:cards[0:7],1:cards[7:14]} cards=cards[14:] recent=cards.pop() curMagic=0 def refill(): global cards,p cards=[card(n,f) for n in range(1,14) for f in "CDHS"] for x in p.keys(): for item in p[x]: try: cards.remove(item) except: print(Cards(cards),"---",Cards(p[0]),Cards(p[1]),item) input() if len(cards)<=1: input("CARDS EXHAUSTED") random.shuffle(cards) def dropAndTake(pi, cardNow): global recent,won,curMagic,cards Cim= cardNow.isMagic() if Cim: p[pi].remove(cardNow) curMagic+=cardNow.num else: for i in p[pi]: if i==cardNow: p[pi].remove(i) if not recent==cardNow: try: p[pi].append(cards.pop()) except IndexError: refill() p[pi].append(cards.pop()) if totalPoints(p[pi])<10: won+=1 print("Player[%d] Won - place %d"%(pi,won)) print("p[%d] :"%pi+Cards(p[pi])) del p[pi] input() recent=cardNow def game(pi): global curMagic,cards ci=None hasMagic2, hasClaverJack, hasRecentMagic=False, False, False CJI,M2I=-1,-1 Rim=recent.isMagic() for i in p[pi]: if hasMagic2 and hasClaverJack: break Cim=i.isMagic() if Cim: if Cim==2: hasMagic2=True M2I=i elif Cim==1: hasClaverJack=True CJI=i if Cim==Rim: ci=i hasRecentMagic=True if curMagic: if not hasRecentMagic: #penalty if len(cards)<curMagic: refill() if len(cards)<curMagic: input("CARDS EXHAUSTED") p[pi]+=cards[:curMagic] cards=cards[curMagic:] curMagic=0 return 0 elif hasClaverJack:ci=CJI elif hasMagic2:ci=M2I else: max=-1 for i in p[pi]: if int(i)>max: max=int(i) ci=i dropAndTake(pi,ci) def start(): pi=0 while len(p)>1: print("p[%d] :"%pi+Cards(p[pi])) print("recent "+str(recent)+" left cards"+str(len(cards))) game(pi) print("p[%d] :"%pi+Cards(p[pi])) print("recent "+str(recent)) #input() pi^=1 start()
a780cc4e432d06d7f0bc33038b53fce9b971bb4b
georgeteo/Coding_Interview_Practice
/chapter_4/binary_tree.py
2,952
3.78125
4
''' My implementation of Binary Trees in Python ''' class binary_tree(object): def __init__(self, id, depth, left_child=None, right_child=None): self.__id = id self.__left_child = left_child self.__right_child = right_child self.__depth = depth @property def id(self): return self.__id @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, left_child_data): self.__left_child = left_child_data @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, right_child_data): self.__right_child = right_child_data @property def depth(self): return self.__depth @depth.setter def depth(self, depth): self.__depth = depth def add_children(self, right_child, left_child): self.__left_child = binary_tree(left_child, self.depth + 1) self.__right_child = binary_tree(right_child, self.depth + 1) def insert(self, data): bt = binary_tree(data, self.depth + 1) self.__left_child.push() bt.left_child = self.__left_child self.__right_child.push() bt.right_child = self.__right_child self.__left_child = bt self.__right_child = None def push(self): self.pre_order_traversal(increment) def pre_order_traversal(self, callback): if self.__left_child is not None: self.__left_child.pre_order_traversal(callback) self.__id, self.__depth = callback(self.__id, self.__depth) if self.__right_child is not None: self.__right_child.pre_order_traversal(callback) def in_order_traversal(self, callback): self.__id, self.__depth = callback(self.__id, self.__depth) if self.__left_child is not None: self.__left_child.in_order_traversal(callback) if self.__right_child is not None: self.__right_child.in_order_traversal(callback) def post_order_traversal(self, callback): if self.__right_child is not None: self.__right_child.post_order_traversal(callback) self.__id, self.__depth = callback(self.__id, self.__depth) if self.__left_child is not None: self.__left_child.post_order_traversal(callback) def print_node(val, count): buf = " " * count print buf + str(val) return val, count def increment(val, count): count +=1 return val, count if __name__ == "__main__": bt = binary_tree(0, 0, binary_tree(1, 1), binary_tree(2, 1)) bt.left_child.add_children(3,4) bt.right_child.add_children(5,6) print "Pre Order Traversal:" bt.pre_order_traversal(print_node) print "" print "In Order Traversal" bt.in_order_traversal(print_node) print "" print "Post Order Traversal" bt.post_order_traversal(print_node) print ""
5a3e08941add19e86ba1aa82ea8ac0b26d53bcdc
Aasthaengg/IBMdataset
/Python_codes/p02389/s891437445.py
149
3.5
4
inputs = input().split(' ') height = int(inputs[0]) width = int(inputs[1]) area = height * width length = height * 2 + width * 2 print(area, length)
5550c62d01f699e4852270c89e09f9a8a1e99ad8
realfan-1s/LeetCode_Easy
/RomanToInt.py
994
3.515625
4
# 暴力解法 def romanToInt(s: str): romanDict = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } sum = 0 i = 0 while i < len(s): if (i < len(s) - 1) and ((s[i] == "I" and s[i + 1] in "VX") or (s[i] == "X" and s[i + 1] in "LC") or (s[i] == "C" and s[i + 1] in "DM")): sum = sum + romanDict[s[i + 1]] - romanDict[s[i]] i += 2 else: sum += romanDict[s[i]] i += 1 return sum # 构建字典 def RomanToInt(s: str): d = { 'I': 1, 'IV': 3, 'V': 5, 'IX': 8, 'X': 10, 'XL': 30, 'L': 50, 'XC': 80, 'C': 100, 'CD': 300, 'D': 500, 'CM': 800, 'M': 1000 } return sum(d.get(s[max(i - 1, 0):i + 1], d[n]) for i, n in enumerate(s)) print(RomanToInt("MDLXX"))
1897b1411e366d9423011a21a181dc7c54d213ad
chejain/CTCI
/2. Linked List/ListOperations.py
1,592
3.8125
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self,val): newNode = Node(val) newNode.next = self.head self.head = newNode return def display(self): tempvar = self.head while tempvar: print (tempvar.data, '->', end=' ') tempvar = tempvar.next pass print ('') return def removeDuplicates(self): if self.head is None or self.head.next is None: return currPtr = self.head while currPtr: nextPtr = currPtr.next prevPtr = currPtr while nextPtr: if currPtr.data == nextPtr.data: prevPtr.next = nextPtr.next else: prevPtr = nextPtr nextPtr = nextPtr.next currPtr = currPtr.next return def deleteMiddle(self): if self.head is None or self.head.next is None: self.head = None return else: prevptr = None slowptr, fastptr = self.head, self.head while fastptr and fastptr.next: prevptr = slowptr slowptr = slowptr.next fastptr = fastptr.next if fastptr.next: fastptr = fastptr.next if slowptr: print (slowptr.data, prevptr.data) prevptr.next = prevptr.next.next return
fbcc2071ca33acebf426b2813ccda994dc48ca96
jijuntao/Python
/python_learn/study_2.py
6,432
4.3125
4
#笔记: # 变量 # 概念:变量不仅可以是数字,还可以是任意数据类型,每个变量都存储了一个值 # 命名:变量名必须是大小写英文、数字和下划线(_)的组合,且不能用数字开头。如可以命名mes_1,不可以1_mes。 # 变量名不能包含空格,但可以用下划线来分割单词。如可以get_mes,不可以get mes。 # 不要用python关键字和函数名用作变量名。如print # 变量名应简短和描述性。如name比n好,student_name比s_n好 # 慎用小写字母l和大写字母O,因为他们可能被人错看成1和0 # # input()函数: # 格式:变量名=input('输入说明文字') # input()函数不论输入的内容是数字还是字符串都将视为字符串类型 # 需要输入为整型或浮点型时要转换格式 # 格式:变量名=int(input('输入数字')) # 变量名= float(input('输入小数')) # # 数据类型: # 常用的有字符串、整型、浮点型、布尔型以及空值 # 字符串(str):就是一系列字符。在python中,用引号括起得都是字符串,其中引号可以是单引号也可以是双引号。如'This is car' # 整型(int):python可以处理任意大小的整数,包含负数,和数学上的写法一样,可进行加减乘除运算 # 浮点型(float):就是小数,整数运算永远是精确的,而浮点数运算则可能会是四舍五入的误差 # 布尔型:一个布尔值只有Ture、False两种值,要么是Ture,要么是False # 空值:空值是python里一个特殊值,用None表示。None不能理解为0,因为0是有意义的,而None是一个特殊的空值。 # # 查看变量类型: # 利用type函数查看,如: # a=3 # print(type(a)) # # 类型转化如: # 整数型的10转换成字符串型的10 —— int(10)写成str(10)即可 # # 字符串基本操作: # 修改变量值的大小写:可用函数title()实现首字母大写,如:name='ada love' print(name.title())即可 # 可用函数upper()实现字母全大写,如:name='ada love' print(name.upper())即可 # 可用函数lower()实现字母全小写,如:name='ADA LOVE' print(name.lower())即可 # # 字符编码:字符串也是数据类型的一种,在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。 # # 运算符:算数运算符 / 赋值运算符 / 比较运算符 / 逻辑运算符 / 身份运算符 / 运算符的优先级 # 算术运算符:+ 加-两个对象相加 a = 6,b = 2 a + b = 8 # - 减-得到负数或是一个数减去另一个数 a - b = 4 # * 乘-两个数相乘或是返回一个被重复若干次的字符串 a * b = 12 # ** x的y次方 a ** b = 36 # / 除-x除以y a / b = 3 # % 取模-返回除法的余数,即取余 a % b = 0 # // 取整-返回商的整数部分(向下取整) 9 // 2 = 4 或 -9 // 2 = -5 # # 赋值运算符:= 赋值运算符 c = a + b # += 加法赋值运算符 c += a 等效于 c = c + a # -= 减法赋值运算符 c -= a 等效于 c = c - a # *= 乘法赋值运算符 c *= a 等效于 c = c * a # /= 除法赋值运算符 c /= a 等效于 c = c / a # **= 幂赋值运算符 c **= a 等效于 c = c ** a # %= 取模赋值运算符 c %= a 等效于 c = c % a # //= 取整赋值运算符 c //= a 等效于 c = c // a # # 比较运算符:== 等于 # != 不等于 # <> 不等于。类似!= # > 大于 # < 小于 # >= 大于等于 # <= 小于等于 # # 逻辑运算符:and 布尔"与" 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 # or 布尔"或" 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 # not 布尔"非" 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 # # 身份运算符:is is是判断两个标识符是不是引用自一个对象,x is y,类似 id(x) == id(y),如果引用的是同一个对象则返回 True,否则返回 False # is not is not是判断两个标识符是不是引用自一个对象,x is not y,类似 id(x) != id(y),如果引用的不是同一个对象则返回 True,否则返回 False # # 运算符优先级:** 指数优先级最高 # * / % // 乘除取模取整 # +- 加减 # & 和,相当于and # <= < > >= 比较运算符 # <> == != 等于运算符 # = %= /= //= += -= *= **= 赋值运算符 # is is not 身份运算符 # 练习: # 1.华氏温度转换成摄氏温度 h_Temp = float(input('请输入华氏温度:')) # input()函数默认是字符串型,所以要进行数据类型转换 s_Temp = round(5 * (h_Temp - 32) / 9,2) # round()函数为round(x,y),其中x:计算公式 y:小数保留的位数 print('摄氏温度为:',s_Temp) a = round(32/5,2) print("a的值为:%.2f" % a) # %.2f 在结果中可显示小数末尾0,如6.40 # 2.输入圆的半径计算周长和面积(2种表达形式) r = int(input('请输入圆的半径:')) π = 3.1415926 # π定义为常量 c = round(π*2*r,2) s = round(π*r**2,2) print('圆的周长是:',c) print('圆的周长是:',s) import math # import xx导入模块,对于模块中的函数,每次调用需要“模块.函数”来用 r_1 = float(input('请输入圆的半径:')) c_1 = round(math.pi*2*r_1,2) # math.pi 代表圆周率 s_1 = round(math.pi*r_1**2,2) print('圆的周长是:',c_1) print('圆的周长是:',s_1) # 3.输入年份判断是否是闰年(2种表达形式) year= int(input('请输入年份,如2008:')) if (year % 4 == 0 & year % 100 ==0) | (year % 400 == 0): #判断闰年的方法是被4整除并且被100整除,或者被400整除 print('该年是闰年:%s'%year) else: print('该年不是闰年')
294e88c3aea81842e5a0ad76ef6e63b1f8a2bc5e
dongyifeng/algorithm
/python/interview/matrix/transposition.py
364
3.890625
4
#coding:utf-8 # 矩阵倒置 # 将倒置矩阵 def transposition(matrix): if matrix is None and len(matrix) > 0:return n = len(matrix) m = len(matrix[0]) if m <= 0 :return r = [[0 for j in range(n)] for i in range(m)] for i in range(n): for j in range(m): r[j][i] = matrix[i][j] return r m = [[1,2,3],[4,5,6]] print m t = transposition(m) print t
f799882c13db504199d1790a60f89f6d8d529aa4
klhoran/LaunchCode-DataScience
/ex3/lrCostFunction.py
1,973
3.59375
4
#from ex2.costFunctionReg import costFunctionReg import numpy as np from sigmoid import sigmoid # ============================================================= def lrCostFunction(theta, X, y, mylambda): """computes the cost of using theta as the parameter for regularized logistic regression and the gradient of the cost w.r.t. to the parameters. """ m = y.size # number of training examples J = 0 h = sigmoid(np.dot (X, theta)) #J = -(1.0 / m) * (np.sum (y.values.flatten () * np.log (h) + ((1 - y.values.flatten ()) * np.log (1 - h)))) + ( #(mylambda / (2 * m) * (np.sum (theta[1:] ** 2)))) # ====================== YOUR CODE HERE ====================== # Instructions: Compute the cost of a particular choice of theta. # You should set J to the cost. # # Hint: The computation of the cost function and gradients can be # efficiently vectorized. For example, consider the computation # # sigmoid(X * theta) # # Each row of the resulting matrix will contain the value of the # prediction for that example. You can make use of this to vectorize # the cost function and gradient computations. # J = -(1. / m) * ((y * np.transpose (np.log (sigmoid (np.dot (X, theta))))) + ((1 - y) * np.transpose (np.log (1 - sigmoid (np.dot (X, theta)))))).sum () + ((float (mylambda) / (2 * m)) * np.power (theta[1:theta.shape[0]], 2).sum ()) grad = (1. / m) * np.dot (sigmoid (np.dot (X, theta)).T - y, X).T + (float (mylambda) / m) * theta # the case of j = 0 (recall that grad is a n+1 vector) nongrad = (1. / m) * np.dot (sigmoid (np.dot (X, theta)).T - y, X).T # and then assign only the first element of nongrad to grad grad[0] = nongrad[0] if return_grad: return J, grad.flatten () else: return J #if np.isnan(J[0]): # return(np.inf) # ============================================================= return (J[0])
1e69660eb5f1e5b356c9efb60ed7ce0f7a93456c
ccamara/python-basico
/02 control flow/04-for.py
337
4.28125
4
for i in range(1, 5): print(i) else: print("The for loop is over") # Ejemplo con listas, sacado de http://www.codecademy.com/courses/python-beginner-en-pwmb1/1/6 start_list = [5, 3, 1, 2, 4] square_list = [] for number in start_list: number = number ** 2 square_list.append(number) square_list.sort() print(square_list)
bc6539f011a14e92e63713cc70b39f0c3f452f55
jhoonb/autoria
/2ano/python/exercicios-resolvidos/repeticao-ex6.py
570
4.3125
4
""" 6. Faça um programa que imprima na tela os números de 1 a 20, um abaixo do outro. Depois modifique o programa para que ele mostre os números um ao lado do outro. """ # um abaixo do outro contador = 1 while contador <= 20: print(contador) contador += 1 # um ao lado do outro contador = 1 while contador <= 20: # um parametro no final e dentro da função print # faz com que se mude o comportamento # end= ', ' faz com que no lugar de pular linha, # apenas se insira uma virgula e continue na mesma # linha print(contador, end=', ') contador += 1
e456447771c90bc1f106dd9c442bb6e46ee1474a
DrZaius62/LearningProgramming
/Python/Scripts/mapIt.py
370
3.65625
4
#! /usr/bin/env python3 # mapIt.py - Opens addresses on google maps from clipboard or cli import sys, webbrowser, pyperclip #get a street address from cli or clipboard if len(sys.argv) > 1: address = ' '.join(sys.argv[1:]) else: address = pyperclip.paste() #open browser to the google maps page webbrowser.open('https://www.google.com/maps/place/' + address)
815f54c47db78593e6a8d3f99258d90355758593
carlos-sales/exercicios-python
/ex009.py
544
3.9375
4
num = int(input('Gafanhoto, digita um número aí! = ')) print('TABUADA DE {} '.format(num)) print('{:3} X 1 = {:3}'.format(num, num*1)) print('{:3} X 2 = {:3}'.format(num, num*2)) print('{:3} X 3 = {:3}'.format(num, num*3)) print('{:3} X 4 = {:3}'.format(num, num*4)) print('{:3} X 5 = {:3}'.format(num, num*5)) print('{:3} X 6 = {:3}'.format(num, num*6)) print('{:3} X 7 = {:3}'.format(num, num*7)) print('{:3} X 8 = {:3}'.format(num, num*8)) print('{:3} X 9 = {:3}'.format(num, num*9)) print('{:3} X 10 = {:3}'.format(num, num*10))
10d5d46327ffd23d42f94174206ef6149e20f69a
yahua/LearnPython
/function.py
227
3.671875
4
a = -100 print abs(a) jdz = abs print jdz(a) def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x print 'print my_abs:',my_abs(a) print my_abs('a')
4aa67e58f2fe31edd41933d9e545f0944d6c4e10
skalinef3/Python
/Arreglos.py
910
4.1875
4
#Desarrolle un programa que permita ingresar dos arreglos #uno numerico y otro alfabetico, ornearlos, e imprimir mayor o menor #para cada caso print "Bienvenidos" arreglonum = [] arregloalfa = [] resp = raw_input(" Desea ingresar valores S/N? ") while resp == "s": dato = raw_input(" Por favor, Ingrese Palabras o Numeros -> ") if dato.isdigit(): arreglonum.append(dato) if dato.isalpha(): arregloalfa.append(dato) resp= raw_input (" Agregar otro? ") print "Ordenando arreglos.....\n" arreglonum.sort() arregloalfa.sort() if len(arreglonum) > len(arregloalfa): print "El arreglo mayor es el Numerico, y contiene"+str(len(arreglonum))+" elementos.\n" else: print "El arreglo mayor es el Alfabetico, y contiene "+str(len(arregloalfa))+" elementos.\n" print "A continuacion los arreglos." print "Numerico" print (arreglonum) print "Alfabetico" print (arregloalfa)
a1ad2c45b644cdcd3b651537a226f85aa126642a
bkmau/Practice_Python
/NametupleAndDictionary.py
458
4.125
4
from collections import namedtuple print("Using regular tuple to represent a RGB") color = (55, 155, 255) print(color) print(color[1]) print("For more readable, i use dictionary to represent a RGB") color = {"red": 55, "green": 155, "blue": 255} print(color) print(color["red"]) print("But i have nametuple that i can represent a RGB easily") Color = namedtuple("Color", ["red", "green", "blue"]) color = Color(55, 155, 255) print(color) print(color.blue)
5e54122674acfcb8825437cc41c92c576ba00262
ExperienceNotes/Python_Leetcode
/Leet_Code/Valid Palindrome.py
324
3.515625
4
s = "A man, a plan, a canal: Panama" s_1 = '' flag = 0 for i in s: if i.isalnum(): s_1 += i.lower() if s_1 == '': print('T') for i in range(len(s_1)): if s_1[i] == s_1[(len(s_1)-1)-i]: pass else: print('F') flag = 1 break if flag == 0: print('T')
0a0a0577b9db12b69cd30485f68738dd32ddb77a
hit5heng/cookbook_and_code
/Grokking_Algorithms/p52_quicksort.py
1,164
4.03125
4
""" 快速排序 """ def quicksort(array): if len(array) < 2: return array # 基线条件: 空或者之后一个元素的数组是有序的 else: pivot = array[0] less = [i for i in array[1:] if i <= pivot] greater = [i for i in array[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater) a01 = [12,45,7,98,0,34,12,54,6,99] a01_sorted = quicksort(a01) print(a01_sorted) """ 选择 """ def order_by(target, condition): """ 按照某一参数排序 类似 sorted(list, key = lambda:..., reverse=True) :param target: :param condition: :return: """ # new_list = target #(新建列表,不动原列表) for r in range(len(target) - 1): for c in range(r + 1, len(target)): if condition(target[r]) > condition(target[c]): target[r], target[c] = target[c], target[r] # return new_list def order(target): for r in range(len(target) - 1): for c in range(r + 1, len(target)): if target[r] > target[c]: target[r], target[c] = target[c], target[r] a01_sorted = order(a01) print(a01)
a46d84c788bd8c0e62ee2c01bedb58a048f7a7ff
keinam53/Zrozumiec_Programowanie
/in_is.py
992
3.796875
4
# favourite_spotrs = ["Koszykówka","Siatkówka","Baseball","Hokej"] # if "Koszykówka" in favourite_spotrs: # print("Zagrajmy w kosza") # else: # print("Nie porzucamy") # person = { # "imie" : "Mariusz", # "nazwisko" : "Baran" # } # if "imie" in person: # print(person["imie"]) # if "car" in person: # print(person["car"]) #Zad1 # shopping_list = input("Podaj listę zakupów rozdzielając przecinkiem ") # shopping_elements = shopping_list.split(",") # if "chleb" in shopping_elements or "bułki" in shopping_elements: # print("Chleb lub bułki są na liście") # else: # print("Nie ma chleba lub bułek") #ZAD2 # nr_tel = input("Podaj nr. tel ") # if "0" in nr_tel: # print("W nr.tel jest 0") # else: # print("Nie ma zera") #ZAD3 # value = None # if value is True: # print("value is True") # elif value is False: # print("Value is False") # elif value is None: # print("Value is None") # else: # print("Value to inna wartość")
40a266da4b3736a0b268eaa4403b37499d7e1762
GaganHeer/AI_Projects
/Learning_ActionPrediction/ngrams.py
4,135
3.546875
4
""" Gagan Heer A00933997 Learning: Action Prediction Ngrams Please look over the README.md file if there is any trouble using this file """ import random import re patterns = dict() def ngrams(): print("R = Rock, P = Paper, S = Scissors\n") data = '' quit = False gameNum = 1 bigram = None playerScore = 0 botScore = 0 mostOccurences = 0 mostLikelyMove = None # Keep playing as long as the player doesn't quit while quit == False: playerAction = (input('Select an option (R,P,S) or Q to Quit: ')).upper() if playerAction in 'RPS': # If there is enough data then make a bigram and update the dictionary print('Game Num: ', gameNum) data += playerAction if(len(data) >= 3): bigram = data[len(data)-3:-1] newMove = data[len(data)-1] if bigram + newMove in patterns: patterns[bigram + newMove] += 1 else: patterns[bigram + newMove] = 1 print('Bigram: ', bigram) print('Players Last Move: ', newMove) # If not enough data collected yet (less than 3 games played) then choose a random action if(bigram == None): botAction = get_action(None) # If there is enough data to create a bigram then try to beat the most likely choice else: # Find all keys that match the bigram that was created from the previous players move bigramMatches = [] for key in patterns: if bigram in key[0:2]: bigramMatches.append(key) # Iterate over all the bigram matches to find the move that is most likely to occur next for match in bigramMatches: if patterns[match] > mostOccurences: mostOccurences = patterns[match] mostLikelyMove = match[-1] if(mostOccurences > 0): print('Players Most Likely Move: ', mostLikelyMove) mostOccurences = 0 botAction = get_action(mostLikelyMove) # Uncomment for random Rock, Paper, Scissors decisions #botAction = get_action(None) print('You Selected: ', playerAction) print('Bot Selected: ', botAction) result = get_result(playerAction, botAction) print(result) if(result == 'You Win'): playerScore += 1 elif(result == 'You Lose'): botScore += 1 print('Your Score: ', playerScore) print('Bot Score: ', botScore) gameNum += 1 elif playerAction in 'Q': quit = True print('---Final Score---\nYou: ', playerScore, '\nBot: ', botScore, '\nThanks For Playing') else: print('Please select a valid option') print("\n\n") def get_result(playerAction, botAction): result = None if playerAction == botAction: result = 'You Tie' elif playerAction == 'R': if botAction == 'P': result = 'You Lose' else: result = 'You Win' elif playerAction == 'P': if botAction == 'S': result = 'You Lose' else: result = 'You Win' else: if botAction == 'R': result = 'You Lose' else: result = 'You Win' return result def get_action(playerMostLikelyMove): # Return best action if playerMostLikelyMove == 'R': return 'P' elif playerMostLikelyMove == 'P': return 'S' elif playerMostLikelyMove == 'S': return 'R' else: # Return random action if no likely move is identified botAction = random.randrange(0,3) if botAction == 0: return 'R' elif botAction == 1: return 'P' elif botAction == 2: return 'S' if __name__ == '__main__': ngrams()
f08ce19a6157e240ba03c575887b3401ffe14ea6
coffeblackpremium/exerciciosPythonBasico
/pythonProject/EstruturaDecisao/exercicio003/exercicio003.py
401
4.03125
4
""" 003)Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. """ letra_digitada = input('Digite (F) para feminino e (M) para Masculino: ') if letra_digitada.lower() == 'f': print('Seu sexo é Feminino') elif letra_digitada.lower() == 'm': print('Seu sexo é masculino') else: print('Sexo invalido!')
7d25969aba3284afc479dc2c49db0ea14d3fe7f5
lorenzoaulisa/FollowTheLeader
/Learn.py
997
4.53125
5
#The program starts and a turtle is created import turtle #The program will say the text "hello world" in the console. print("hello world") #The program will say the text "howdy y'all" in the console. print("howdy y'all") #The program will say the text "I will now count my roosters" in the console. print(" I will now count my roosters") #The program will now calculate the number of roosters Lorenzo has on his farm print("Roosters: ", 100.0 +21.5 +17.5 - 25 * 3 % 4) #After calculating that Lorenzo has 136 roosters on his farm the program will now say #"I shall now count the number of dead bodies in Lorenzo's basement print("I shall now count my dead bodies in my basement") #The program will now calculate how many dead bodies Lorenzo has in his basement print(3.55 + 2.2 + 1.5 - 5 + 4 % 2 - 1 / 4 + 6) #After calculating that Lorenzo has 8 dead bodies in Lorenzo's basement, the program shall now # have the turtle leave the area turtle.forward(500) #The program ends turtle.exitonclick()
d511fc10cef78b9691e0f9660bc69884e0cbb6e3
dikoko/practice
/1 Numerics/1-19_excel.py
693
3.90625
4
# Given a positive integer, return its corresponding column title as appear in an Excel sheet. # # For example: # 1 -> A # 2 -> B # 3 -> C # ... # 26 -> Z # 27 -> AA 26+1 # 28 -> AB 26+2 def excel_number(N): out_list = [] while N > 0: N -= 1 # make each 0 based digit = N % 26 out_list.append(digit) N //=26 out_list.reverse() return "".join(map(lambda x: chr(ord('A')+x), out_list)) if __name__ == '__main__': n1 = 26 # Z n2 = 27 # AA n3 = 28 # AB n4 = 980089 # BCSUS print(excel_number(n1)) print(excel_number(n2)) print(excel_number(n3)) print(excel_number(n4))
d2231cedc579fbb36644852c794a04ffd661987c
SPecialisation/stan
/la-voiture/usr/bin/env python n = input ("entrer votre nom")# je demande le nom de la personne print ("bonjour",n) # je lui dis bonjours a = input ("entrer votre age") # je demande son age a= int (a) # je précise que a sera une valeur numérique if (a > 18) : print ("vous pouvez conduire une voiture") elif (a < 18) : print ("vous ne pouvez pas conduire une voiture") if (a<0): print("car vous n'etes pas née au revoir")
419
3.9375
4
#!/usr/bin/env python n = input ("entrer votre nom")# je demande le nom de la personne print ("bonjour",n) # je lui dis bonjours a = input ("entrer votre age") # je demande son age a= int (a) # je précise que a sera une valeur numérique if (a > 18) : print ("vous pouvez conduire une voiture") elif (a < 18) : print ("vous ne pouvez pas conduire une voiture") if (a<0): print("car vous n'etes pas née au revoir")
fe91b63aa40c89604d4e30576508949edff63b75
ArtZubkov/pyDev
/Metody_dlya_integralov.py
4,219
4.46875
4
# ''' , ( ), . , . ''' # def func(x): y = x*x return y; print('f(x)=x^2') # a = 0 b = 0 while a == b: a = float(input(' : ')) b = float(input(' : ')) if a > b: a, b = b, a # n1 = int(input(' n1: ')) n2 = int(input(' n2: ')) # # 3/8 def m38(func,a,b,n): h=(b-a)/n s1=s2=0 for i in range(1,n): if i%3!=0: s1=s1+func(a+i*h) else: s2=s2+func(a+i*h) res=3*h/8*(func(a)+func(b)+3*s1+2*s2) return res # def serp(func,a,b,n): h=(b-a)/n a=a+h*0.5 s=0 for i in range(1,n+1): s=s+func(a+h*i) s=s*h return s # def rpr(func,a,b,n): h=(b-a)/n res=0 for i in range(1,n+1): res=res+func(a+h*i) res=res*h return res # def lpl(func,a,b,n): h=(b-a)/n res=0 for i in range(n): res=res+func(a+h*i) res=res*h return res # def Boole(func,a,b,n): h=(b-a)/n s=7*(func(a)+func(b)) s1=s2=s3=0 for i in range(1,n): if i%2==1: s1=s1+func(a+h*i) else: if i%4==0: s3=s3+func(a+h*i) else: s2=s2+func(a+h*i) s=s+32*s1+12*s2+14*s3 res=s*h*4/90 return res # def Weddle(func,a,b,n): h=(b-a)/n s1=s2=s3=s4=0 for i in range(1,n): if i%3==0: if i%6==0: s4=s4+func(a+h*i) else: s3=s3+func(a+h*i) else: if i%2==0: s2=s2+func(a+h*i) else: s1=s1+func(a+h*i) res=h/140*(41*(func(a)+func(b))+216*s1+27*s2+272*s3+82*s4) return res # def trap(func,a,b,n): h=(b-a)/n s=0 for i in range(1,n): s=s+func(a+h*i) res=h*((func(a)+func(b)/2+s)) return res # def parabola(a, b, n): h = (b-a)/n s1 = 0 for i in range(1,n): if i % 2 == 0: s1 += 4*func(a+h*i) else: s1 += 2*func(a+h*i) res = h/3*(func(a) + s1 + func(b)) return res # print(' :') print(' | n1 ={0:6}'.format(n1),' | n2 ={0:6}'.format(n2)) print(' |', end = '') print(' {0:11.7} |'.format(Boole(func,a,b,n1)),'{0:11.7}'.format(Boole(func,a,b,n2))) print(' |', end = '') print(' {0:11.7} |'.format(rpr(func,a,b,n1)),'{0:11.7}'.format(rpr(func,a,b,n2))) # n = int(input(' - (n): ')) eps = float(input(' (Eps): ')) # while abs(rpr(func,a,b,n)) - abs(rpr(func,a,b,2*n)) > eps: n *= 2 # print('\n : {0:7}'.format(rpr(func,a,b,n))) print(' , ',eps, ' :',n)
2dc7f74be024da55feaf49d78e2b4a87680af8cc
goodGopher/HWforTensorPython
/DZto15032021/prog1_factorial.py
1,510
4.25
4
"""Calculating factorial. Functions: input_check(in_str): Сheck in_str for integer type factorial(input_int): Сalculate factorial menu(): Show user's actions. main(): Allows to enter number and to see his factorial. """ import checks def factorial(input_int): """Calculate factorial""" a = checks.input_check(input_int) if a or input_int == "0": if a < 0 : raise ValueError elif a == 0: return 1 elif a == 1 or a == 2: return a else: return factorial(a-1)*a else: raise TypeError def menu(): """Show user's actions.""" print("Для выхода введите \"выход\" ") print("Введите целое положительное число:",end = " ") def main(): """Allows to enter number and to see his factorial.""" while True: try: menu() a = input() if a == "выход": print("Выход из программы") exit() print(f"{a}! = {factorial(a)}") except TypeError: print("Введено не целое положительное число") except ValueError: print("Введено отрицательное число") except RecursionError: print("Введено слишком большое число") if __name__ == "__main__": main()
7c251741330fd6ca038e39891250c7e9bc05a59f
nasima-akter-tania/Leet-code
/ClassOne/search_in_list.py
311
3.75
4
# search a value in list A = [1,4,5,3,5,2,6,7,9,10] for element in A: print(element) target = 10 for element in A: if element == target: print("Found", target) a = [1,8,13,5,4] find = 5 start = 0 end = len(a) while start < end: if a[start] == find: print("Found") start +=1
ba873ba27bc4bd5d97e40275e23b3c80e068047b
kwsherwood/portfolio
/python/ex4.py
843
4.40625
4
# Practive from Python programming for humanists # working with lists and dictionaries # # first example, a dictionary because {} my_info = { 'fname': 'Ken', 'lname': 'Sherwood', 'hometown': 'Indiana', 'ppn':"his", 'fav_food':'paella'} print("This is the my_info dict") print(my_info) print("This is the first item") print(my_info['fname']) my_info['fname'] = 'Kenny' # Pratice replacing an item in the dictionary print("this is another variant of the name", my_info['fname']) # THIS is the example of a list, which can move through items numerically. my_name_var = ['Ken','Kenn','Kenny','Kenneth','Kent','Kencito'] print('A list of name variants: \n') print(my_name_var) # This loops through and prints one for each line. for n in my_name_var: print('\n') print(f'This is a variant: {n}') print('\n')
a132d536bf8cb3812037f631a790866e2bd0196f
DiegoT-dev/Estudos
/Back-End/Python/CursoPyhton/Mundo 01/Aulas/Aula07.py
1,157
4.3125
4
# ____________________Operadores Aritméticos_____________________ # # + -> Adição / _________Precedências_______ # - -> Subtração / 1. () # * -> Multiplicação / 2. ** # / -> Divisão / 3. * / // % # ** -> Potência / 4. + - # // -> Divisão Inteira / # % -> Módulo (resto da divisão) / # # Alguns testes.... #print('='*21) #print(' '*10,'Oi',' '*10) #print('='*21) #nome = input('Qual é o seu nome? ') #print('Prazer em te conhecer {:>20}!'.format(nome)) #print('Prazer em te conhecer {:<20}!'.format(nome)) #print('Prazer em te conhecer {:^20}!'.format(nome)) #print('Prazer em te conhecer {:-^20}'.format(nome)) # para quebrar linha no meio \n e para não quebrar no final , end="" n1 = int(input('Digite um número: ')) n2 = int(input('Agora outro número: ')) s = n1+n2 m = n1*n2 d = n1/n2 di = n1//n2 e = n1**n2 print('A soma é {} o produto é {} e a divisão é {:.3f}!'.format(s, m, d)) print('Já a divisão inteira é {0} e a potenciação de {2} elevado a {3} é igual a {2}!'.format(di, e, n1, n2))
5f3fd3f5f7d377459f22c85248ee90dd0fa9be15
harshitsilly/Basics
/3 - Iteration/Additional Exercises 3/difficult_exercise2.py
2,769
4.09375
4
#25-01-2012 #additional exercises 3, question 11 #sample solution import random print("Hangman") print("This program plays hangman between two players") print() player1 = input("Please enter the name of player one: ") player2 = input("Please enter the name of player two: ") #decide which player will be guessing startPlayer = random.randint(1,2) if startPlayer == 1: print() print("{0} you get to set the word to guess.".format(player1)) print() splayer = player1 gplayer = player2 else: print() print("{0} you get to set the word to guess.".format(player2)) print() splayer = player2 gplayer = player1 #get the word from the user targetStr = input("{0}, please enter a string: ".format(splayer)) guesses = int(input("{0}, how many guesses should {1} get?: ".format(splayer,gplayer))) print() print() character = None #create a blank string for output outputStr = "" #counter for guesses noOfGuesses = 0 wordFound = False while noOfGuesses < guesses and wordFound == False: noOfGuesses = noOfGuesses + 1 character = input("{0}, please enter a character to find in the string: ".format(gplayer)) found = False for eachChar in range(len(targetStr)): if targetStr[eachChar] == character: if outputStr == None: outputStr = character found = True elif len(outputStr) == len(targetStr): #get the OutputStr up to the character before the character to add #add the character to this string and then add the Output string from #the character after the character we add outputStr = outputStr[:eachChar] + character + outputStr[eachChar+1:] found = True else: outputStr = outputStr + character found = True else: if len(outputStr) < len(targetStr): outputStr = outputStr + "_" if found: print() print("The letter {0} was in the string".format(character)) print("the string is now {0}".format(outputStr)) print() else: print() print("The letter {0} was not in the string".format(character)) print("the string is still {0}".format(outputStr)) print() print("You have {0} guesses remaining.".format(guesses-noOfGuesses)) print() print(outputStr) #decide if the word has been found if outputStr == targetStr: wordFound = True if wordFound: print("Well done {0}, you have guessed that the word is {1}".format(gplayer,targetStr)) print("You took {0} guesses".format(noOfGuesses)) else: print("Sorry {0}, you didn't get the word {1} in {2} guesses".format(gplayer,targetStr,guesses))
228a0311bc0fd44ccafd6ddfc7312163196b63cb
ogbanugot/Numerical-Analysis-techniques
/newton_raphson.py
714
4.125
4
import scipy from scipy.misc import derivative import math '''Newton-Raphson method f is a function {derivative(f, a, dx=1e-6)} the derivative of f at a a is the left end point xn''' maxItr = 100 def f(x): return x**2 - 10*x +23 def newtonRaph(a): iteration = 0 a += 0.1 while iteration<maxItr: x = a - f(a)/derivative(f, a, dx=1e-6) iteration+=1 print("iteration number =",iteration) if f(x) == 0: print("the zero is",x) break else: a = x return x def main(a): newtonRaph(a)
9cf4a3aad16ba2cabe4b92c5157f656999b2549f
nengen/pythRSQL
/Assignment1/problem_3.py
449
4.03125
4
def print_x(n): for i in range(n): for j in range(n): if(j == i): #print first x in the row print("#", end = '') elif(j == n-1-i): #print last x in row, decremented by i each loop print("#", end= '') else: print(" ", end = '') #print space print("") #print nothing so we get next line print_x(5) print_x(10)
722177990c286cafdff4bbe4211194ac9e9569d2
danielmedinam03/Diplomado-Python2021
/EjerciciosVarios/calculadoraFuncion2.0.py
950
4.15625
4
numero1=float(input("Digite numero 1: ")) numero2=float(input("Digite numero 2: ")) opcion=int(input("Si desea realizar una suma digite 1: \n"+ "Si desea realizar una resta digite 2: \n"+ "Si desea realizar una division digite 3: \n"+ "Si desea realizar una multiplicacion digite 4: \n"+ "Opcion: ")) def operacion(numero1, numero2, opcion): if opcion==1: resultado=numero1+numero2 print("resultado: ", resultado) elif opcion==2: resultado=numero1-numero2 print("resultado: ", resultado) elif opcion==3: if numero2==0: print("No se puede dividir en 0") else: resultado=numero1/numero2 print("resultado: ", resultado) elif opcion==4: resultado=numero1*numero2 print("resultado: ", resultado) operacion(numero1,numero2, opcion) print(type(numero1))
56b478225daaa2dceeaa52ee7e2a531b82548497
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-3/3-1-4-10-Lists-collections-of-data-lists-andloops-Making-use-of-lists.py
993
4.375
4
#!/usr/bin/python3 """ Calculate the sum of all the values stored in the myList list. - the list is assigned a sequence of five integer values; - the i variable takes the values 0, 1, 2, 3, and 4, and then it indexes the list, selecting the subsequent elements: the first, second, third, fourth and fifth; - each of these elements is added together by the += operator to the total variable, giving the final result at the end of the loop; - note the way in which the len() function has been employed - it makes the code independent of any possible changes in the list's content. """ myList = [10, 1, 8, 3, 5] total = 0 for i in range(len(myList)): total += myList[i] print(total) """ The second face of the for loop But the for loop can do much more. It can hide all the actions connected to the list's indexing, and deliver all the list's elements in a handy way. """ myList = [10, 1, 8, 3, 5] total = 0 for i in myList: total += i print(total) print(sum(myList))
43dc4a8aac51f46168f26f4bbd99fb901d3159c6
Chien10/coding-exercises
/2.strings/longest_substring_without_repeating_characters.py
1,962
4.03125
4
""" Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Given "dvdf", the answer is "vdf", with the length of 3 Note that the answer must be a substring, "pwke" is a subsequence and not a substring (substring means every character must stands next to each other in the original string) """ from typing import List from collections import Counter # O(n**2) in time and O(n) in space def brute_force(a_str: str) -> str: ls = '' for i, _ in enumerate(a_str): hist = {a_str[i]: 1} temp_ls = a_str[i] for char in a_str[i + 1:]: temp = hist.get(char, 0) if temp == 0: temp_ls += char hist[char] = 1 else: # If the character has already appears, we finish the search break if len(temp_ls) > len(ls): ls = temp_ls return ls # O(n) in both time and space # Failed! def fail_find_lswrc(a_str: str) -> int: len_str = 0 hist = {} for char in a_str: len_str += 1 hist[char] = -1 len_sub = [0] * len_str start, current_idx, dup_idx = '', None, None for i in range(len_str): if i == 0: len_sub[i] = 1 start += a_str[i] current_idx = i hist[a_str[i]] = i else: if hist[a_str[i]] == -1: len_sub[i] = 1 + len_sub[current_idx] start += a_str[i] current_idx = i hist[a_str[i]] = i else: start = a_str[i] if dup_idx is None: dup_idx = i len_sub[i] = i - hist[a_str[dup_idx]] else: len_sub[i] = i - hist[a_str[dup_idx]] dup_idx = i current_idx = i hist[a_str[i]] = i print('hist:',hist) print('len_sub:',len_sub) print('dup_idx:',dup_idx) print(80*'-') print(len_sub) max_idx = -1 max = 0 for i, val in enumerate(len_sub): if val > max: max = val max_idx = i return max def find_lswrc(a_str: str):
0ab975bc16c6c3104c88c971b3ee099f4f35d1c0
srikanthpragada/PYTHON_19_MAR_2021
/demo/oop/ExDemo.py
176
3.578125
4
radius = input("Enter radius :") try: r = int(radius) print(22 / 7 * r ** 2) except Exception as ex: print(ex.__class__.__name__) print(ex) print("The End!")
0d6440d0edec029271e1d778f8d26607d81a66fb
ArturSargsyans/Calculus-Dictionary
/cd_UserStory.py
1,292
3.75
4
import json def loadCalculusDictionary(): with open("cd_data.json") as data_file: chapters = json.load(data_file) return chapters def chooseTheChapter(chapters): print("Here are the chapters") for key in chapters: print(key) chaptersname = input('please enter the name of the chapter that you want') chosenchapter = chapters[chaptersname] return chosenchapter def chooseTheCategory(chapter): for categories in chapter: print(categories) categoryname = input('please input whatever you want to access (definition, theorem...)') chosencategory = chapter[categoryname] return chosencategory def openTheDescription(category): print("here is the information available") for description in category: print(description) descriptionname = input("choose one you want to learn") chosendescription = category[descriptionname] return chosendescription def main(): calculusDictionary = loadCalculusDictionary() calculusDictionary = chooseTheChapter(calculusDictionary) calculusDictionary = chooseTheCategory(calculusDictionary) calculusDictionary = openTheDescription(calculusDictionary) print(calculusDictionary) main()
235aefb4609b127a3cdd1039a637b03d17c46b84
kamilWyszynski1/CodeWars
/TribonacciSequence/main.py
327
4
4
def tribonacci(signature, n): if n == 0: return [] elif n == 1: return [signature[0]] elif n == 2: return [signature[0], signature[1]] if len(signature) == n: return signature signature.append(signature[-1] + signature[-2] + signature[-3]) return tribonacci(signature,n)
5ff9b42014fe87e8578c92557ef625fc573db98c
alvesgabriel/uri
/iniciante/uri2166.py
205
3.625
4
def square_2(n): if n == 0: return 0 return 1 / (2 + square_2(n - 1)) def main(): n = int(input().strip()) print('%.10f' % (1 + square_2(n))) if __name__ == '__main__': main()
4886eaa2a3fe9f0797a0b55fd402e851aee37854
sheriline/python
/D9/vote.py
3,680
3.859375
4
class Position: positions = { 1: {"Position": "President", "votesPerVoter": 1}, 2: {"Position": "Vice-President", "votesPerVoter": 1}, } def displayPos(self): position = Position.positions for p in position: for item in position[p]: print(f"{item}: {position[p][item]}") return "" def addPos(self, position, voteNo): pos = Position.positions posId = 0 for p in pos: posId = p posId += 1 pos[posId] = {"Position": position, "votesPerVoter": voteNo} def removePos(self, key): pos = Position.positions del pos[key] # p = Position() # p.addPos("Secretary",1) # print(p.displayPos()) # p.removePos(3) # print(p.displayPos()) # Output: # Position: President # votesPerVoter: 1 # Position: Vice-President # votesPerVoter: 1 # Position: Secretary # votesPerVoter: 1 # Position: President # votesPerVoter: 1 # Position: Vice-President # votesPerVoter: 1 ######################################################## class Candidates(Position): candidates = { 1: {"Position": 1, "Name": "Seatiel Austria"}, 2: {"Position": 2, "Name": "Diana Geromo"}, 3: {"Position": 2, "Name": "Shey Malaca"}, 4: {"Position": 1, "Name": "Emelyn Soria"}, } def displayCandi(self): cand = Candidates.candidates pos = Position.positions for p in pos: print(f'{pos[p]["Position"]} {pos[p]["votesPerVoter"]} VOTE') for c in cand: if cand[c]["Position"] == p: print(f'{c} {cand[c]["Name"]}') print("\n") return "*****************************" def addCandi(self, position, name): cand = Candidates.candidates candId = 0 for c in cand: candId = c candId += 1 cand[candId] = {"Position": position, "Name": name} def removeCandi(self, key): cand = Candidates.candidates del cand[key] # e = Candidates() # e.addCandi(2,"Jeon Jungkook") # print(e.displayCandi()) # e.removeCandi(5) # print(e.displayCandi()) # Output: # President: # 1 Seatiel Austria # 4 Emelyn Soria # Vice-President: # 2 Diana Geromo # 3 Shey Malaca # 5 Jeon Jungkook # President: # 1 Seatiel Austria # 4 Emelyn Soria # Vice-President: # 2 Diana Geromo # 3 Shey Malaca ########################################################### class Vote(Candidates): votes = {1: {1: 0, 4: 0}, 2: {2: 0, 3: 0}} def __init__(self, voter): self.voter = voter def votecast(self, obj): vote = Vote.votes # vote2 = {} vote.update({1: {1: 1, 4: 0}, 2: {2: 0, 3: 1}}) return vote v = Vote("Shey") print(v.displayCandi()) # Output: # President 1 VOTE # 1 Seatiel Austria # 4 Emelyn Soria # Vice-President 1 VOTE # 2 Diana Geromo # 3 Shey Malaca # print(len(v.positions)) #2 obj = {} def cast(): poslen = len(v.positions) count = 1 while count < poslen + 1: try: vote = int( input( "Please enter the number of your candidate for" + " " + v.positions[count]["Position"] + ": " ) ) if vote not in v.candidates.keys(): raise ValueError except ValueError: print("Please try again:)") break else: obj[count] = vote count += 1 return obj cast() if not obj: again = input("Do you want to continue? (y/n) ") if again == "y": print("\n") print(v.displayCandi()) cast() else: pass else: print(v.votecast(obj))
a88e5054903fcf716e19a480fed39b9e2206b764
joew1994/isc-work
/python/strings.py
944
3.96875
4
#STRINGS #sequences of charactors #indexed same as index lists #name = darwin #for c in name: # print c #d #a #r #w #i #n #can use double or single quotes for strings - doesnt matter which you use as long as its the same at begining and end of string #stings cant be changed once made = are immutable #name = "charles" + " " + "darwin" = charles darwin = concatenates strings #question 1 s = "I love to write python" print s for x in s: print x print s[5] print s[-1] print len(s) print s[0], s[0][0], s[0][0][0] #question 2 split_s = s.split() print split_s for word in split_s: if word.find("i"): print "I found 'i' in: '{0}'".format(word) split_s = s.split() print split_s for word in split_s: if word.find("i") >-1: print "I found 'i' in: '{0}'".format(word) #question 3 something = "completely different" print dir(something) print something.count('t') print something.find('plete')
1536fdf2137e01552a37eaca66fcf3ff4b6ae1eb
AgiNetz/FIT-VUT-projects
/4. Semester/IPP - Principles of programming languages/Interpreter/errhandle/OperandTypeError.py
666
3.640625
4
class OperandTypeError(BaseException): def __init__(self, operand, instruction, type, should): self.operand = operand self.instruction = instruction self.type = type self.should = should def __str__(self): return "Operand %d of instruction \"%s\" should be of type \"%s\", is \"%s\"!" % (self.operand, self.instruction, self.should, self.type)
e1f2f2fb7d9e28f454524b2655656526fa5b5c6c
XUEMANoba/python-jichu
/05-day/输入和输出.py
537
3.828125
4
''' height = 170 print(height) name = "雪漫" type(name) yingxiong =input ("请输入英雄名字") height = 170 int(height) ''' ''' a=1 b=2 c=0 c=a+b print("c的值:",c) ''' ''' a = float(input("")) b = int(input("")) print(a) print(b) ''' ''' name = "娄雪曼" print("我的名字%s"%name) ''' ''' student_no = 1 print("我的学号%06d"% student_no) ''' ''' p = 10 w = 1 m = p*w print("单价%.02f,购买%.02f,一共%.02f"%(p,w,m)) ''' ''' dianliang = 0.67 print("剩余%.02f%%"%(dianliang*100)) '''
d98c28c97ef61ac9001a8e272ed439724e52f841
hejj16/Introduction-to-Algorithms
/Algorithms/counting_sort.py
967
4.09375
4
def counting_sort(list): '''a function to sort a list of integers, the function will NOT change the original list''' max_int = list[0] min_int = list[0] for i in list: if int(i) != i: print("Must be a list of integers") return None if i > max_int: max_int = i if i < min_int: min_int = i for i in range(len(list)): list[i] -= min_int #normalize all elements to [0,inf) new_max_int = max_int-min_int new_list = [0]*len(list) count_list = [0]*(new_max_int+1) for i in list: count_list[i] += 1 for i in range(1,len(count_list)): count_list[i] += count_list[i-1] for i in range(len(list)-1,-1,-1): new_list[count_list[list[i]]-1] = list[i] count_list[list[i]] -= 1 for i in range(len(list)): list[i] += min_int new_list[i] += min_int return new_list
f02acbce9dabb282fd87088e30122555df58bcb2
Trilokpandey/pythonprogrammings
/oops16.py
968
3.640625
4
############Object Introspection#################### class Employee: def __init__(self,fname,lname): self.fname=fname self.lname=lname #self.email=f"{fname}.{lname}@gmail.com" def explain(self): return f"my name is {self.fname} {self.lname}" @property def email(self): if self.fname==None or self.lname==None: return "email is not set" return f"{self.fname}.{self.lname}@gmail.com" @email.setter def email(self,string): print("setting now...") names=string.split("@")[0] self.fname=names.split(".")[0] self.lname=names.split(".")[1] @email.deleter def email(self): self.fname=None self.lname=None sonu=Employee("sonu","pandey") print(type(sonu)) print(id(sonu)) print(type("hello guys")) print(id("hello guys")) print(id("hello ")) m="hello guys" print(dir(m)) print(dir(sonu)) import inspect print(inspect.getmembers(sonu))
af72f0ac34f934003d08433d874668ea20b4d488
eyssam/gaih-students-repo-example
/Homeworks/HW1.py
618
3.640625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: value1= (input("Please enter Value1:")) value2= (input("Please enter Value2:")) value3= input("Please enter Value3:") value4= input("Please enter Value4:") value5= input("Please enter Value5:") print(f"value1:{value1}") print(f"value2:{value2}") print(f"value3:{value3}") print(f"value14:{value4}") print("value5:{}".format(value5)) print ("data_type of Value1:",type(value1)) print ("data_type of Value2:",type(value2)) print ("data_type of Value3:",type(value3)) print ("data_type of Value4:",type(value4)) print ("data_type of Value5:",type(value5)) # In[ ]:
abcf00f674156666b6a35342758fa996e26cd6f9
jingshu-fk/scripts_collections
/functional/read_file.py
4,133
3.734375
4
# 读文本文件 # def main(): # f = open('致橡树.txt', 'r', encoding='utf-8') # print(f.read()) # f.close() # # # if __name__ == '__main__': # main() # 增加一定的健壮性和容错性。 # def main(): # f = None # try: # f = open('致橡树.txt', 'r', encoding='utf-8') # print(f.read()) # except FileNotFoundError: # print('无法打开指定的文件') # except LookupError: # print('指定了未知的编码') # except UnicodeDecodeError: # print('读取文件时解码错误') # # finally块的代码总是会执行,关闭打开的文件,释放程序中获取的外部资源。 # finally: # if f: # f.close() # # # if __name__ == '__main__': # main() # 还可以用for循环逐行读取或者用readlines方法将文件按行读取到一个列表容器中。 # import time # # # def main(): # with open('致橡树.txt', 'r', encoding='utf-8') as f: # # 打印整个文本内容 # print(f.read()) # # with open('致橡树.txt', mode='r', encoding='utf-8') as f: # # 打印每行 # for line in f: # print(line) # time.sleep(1) # print() # # with open('致橡树.txt', 'r',encoding='utf-8') as f: # lines = f.readlines() # print(lines) # # if __name__ == '__main__': # main() ''' 写文本文件 在使用open函数时指定好文件名并将文件模式设置为'w'即可。注意如果需要对文件内容进行追加式写入,应该将模式设置为'a'。如果要写入的文件不存在会自动创建文件而不是引发异常。下面的例子演示了如何将1-9999之间的素数分别写入三个文件中(1-99之间的素数保存在a.txt中,100-999之间的素数保存在b.txt中,1000-9999之间的素数保存在c.txt中) 1、必须是素数 2、1-10000之间不同区间写入不同文件 ''' from math import sqrt def is_prime(n): # 判断素数的函数 assert n > 0 for factor in range(2, int(sqrt(n)) + 1): if n % factor == 0: return False return True if n != 1 else False def main(): filenames = ('a.txt', 'b.txt', 'c.txt') fs_list = [] try: for filename in filenames: fs_list.append(open(filename, 'w', encoding='utf-8')) for number in (1, 10000): if is_prime(number): if number < 100: fs_list[0].write(str(number) + '\n') elif number < 1000: fs_list[1].write(str(number) + '\n') else: fs_list[2].write(str(number) + '\n') except IOError as ex: print(ex) print('写文件时发生错误') finally: for fs in fs_list: fs.close() print('操作完成') # # # # 读取二进制文件 # # def main(): # try: # with open('guido.jpg', 'rb') as fs1: # data = fs1.read() # print(type(data)) # with open('基多.jpg', 'wb') as fs2: # fs2.write(data) # # except FileNotFoundError as e: # print('指定的文件无法打开') # except IOError as e: # print('读取文件时出现错误') # print('程序已执行结束') # # if __name__ == '__main__': main() # # # 读取json文件 # # import json # # # def main(): # mydict = { # 'name': '舒景平', # 'age': 24, # 'qq': 1048707084, # 'friends': ['刘昊文', '刘尚美'] # 'cars': [ # {'brand': 'BYD', 'max_speed': 180}, # {'brand': 'Audi', 'max_speed': 280}, # {'brand': 'Benz', 'max_speed': 320} # ] # } # try: # with open('data.json', 'w', encoding='utf-8') as fs: # # 将python对象按照JSON格式序列化到文件中 # json.dump(mydict, fs) # except IOError as e: # print(e) # print('数据保存完成')
57c6d0d043b2a266851bd66df976251b70d7d76f
wjj800712/python-11
/Answers/week6/__init__.py
796
3.75
4
import threading threading.Condition origin=[1, 30,20,40,60,50,10,80,70,90] origin.insert(0,0) total=len(origin)-1 print(total) def heap_adjust(n,i,array:list): while 2*i<=n: lchile_index=2*i max_child_index=lchile_index #n=2*i if n>lchile_index and array[lchile_index+1]>array[lchile_index]: max_child_index=lchile_index+1 if array[max_child_index]>array[i]: array[i],array[max_child_index]=array[max_child_index],array[i] i=max_child_index else: break return array print('origin:', origin, total) def max_heap(total,array:list): for i in range(total//2,0,-1): heap_adjust(total,i,array) print(i, array, '======', total//2) return array print(max_heap(total,origin))
50681876e11616dab742390b63782be0bc094f32
BadrChoujai/hacker-rank-solutions
/Python/06_Itertools/itertools.permutations().py
356
3.6875
4
# Problem Link: https://www.hackerrank.com/challenges/itertools-permutations/problem # ---------------------------------------------------------------------------------- from itertools import permutations u_input = list(map(str, input().split())) s = sorted(u_input[0]) n = int(u_input[1]) p = list(permutations(s, n)) for i in p: print(*i, sep='')
62cfd87850a6106ff81186bff2f2ced15befa3f0
ezioitachi/Big-Data
/ML-python/python画图/正态分布.py
483
3.671875
4
import numpy as np import math as m import matplotlib.pyplot as plt if __name__=="__main__": mu = 0 sigma = 1 x = np.linspace(mu-3*sigma,mu+3*sigma,51) y = np.exp(-(x-mu)**2/(2*sigma**2))/(m.sqrt(2*m.pi)*sigma) print(x.shape) print(y.shape) plt.figure(facecolor='w') plt.plot(x,y,'r-',x,y,'go',linewidth=2, markersize=8) plt.xlabel('x',fontsize=15) plt.ylabel('y',fontsize=15) plt.title('Gauss Distribution',fontsize=18) plt.grid(True) #画虚线格子 plt.show()
bfaeba82d793e052863472f2af676c4364ed2df1
geekori/numpy
/src/chapter03/demo07.py
640
3.609375
4
# NumPy常用函数:计算中位数和方差 from numpy import * # 1,2,3,4,5,6 a = array([4,5,2,3,1]) print(median(a)) price =loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True) print(price) print(median(price)) sorted = msort(price) print(sorted) n = len(sorted) print(n) #print('middle', '=', sorted[(n - 1)//2]) # 取索引为14和15的两个值取平均数 print('middle', '=', (sorted[n // 2] + sorted[(n - 1)//2]) / 2) # 方差:假设数组元素的算数平均数是a,元素个数是n,x1、x2、...、xn # ((x1 - a)^2 + (x2 - a)^2 + ... + (xn - a)^ 2) / n # 方差:var print('方差:',var(price))
34a9fb39400db27cfe00f0d318337d89902ca4e3
vikashmrv/python
/begn44.py
75
3.640625
4
v=int(input()) if(1<=v and v<=10): print("yes") else: print("no")
756aecd293346c0326a1b8a7a5c35288627a8caa
zXin1112/Python-Practice
/FilesAndExceptions/FilesAndExceptions/FilesAndExceptions.py
1,221
4.15625
4
#文件 #读取整个个文件 with会在合适的时候自动将打开的文件关闭 在win系统中使用/由于Python认为是转义符所以可能失败,故在引号之前加r保证字符原义输出 filename='pi_digits.txt' #with open(filename) as file_object: # contents=(file_object.read()).rstrip() # print(contents) ##逐行读取 #with open(filename) as file_object: # for line in file_object: # print(line.rstrip()) #将文件内容存到列表中 with open(filename) as file_object: lines=file_object.readlines() print(lines) pi_string='' for line in lines: pi_string+=line.strip() print(pi_string) #显示前十位 print(pi_string[:10]+"……") #写入文件 其中,open的参数 w写入、r读取、a附加、r+读写,默认只读 filename='programming.txt' #写入 with open(filename,'w') as file_wirite: file_wirite.write("hello world!\n") file_wirite.write("hello world!\n") #读取 with open(filename) as file_read: print( file_read.read()) #附加到文件 写入后原内容保持不变 with open(filename,'a') as file_attach: file_attach.write("aaaaa\n") file_attach.write("bbbbb\n") with open(filename) as file_read: print( file_read.read())
104e6ee24c25fbb87d90e367a4c62b9ae1e277d2
sajedgit/pythonTest
/test.py
648
3.546875
4
player = 'Thomas' points = 33 k=" Last night, "+player+" scored "+str(points)+" points. " print(f'Last night, {player} scored {points} points.') # concatenation a,b,c=3,4.7,'\nsajed\n' print("I'm going to inject %s here by %d to %s." %(a,b,c)) print(repr(player)) print('Floating point numbers: %2.1f' %(2.175909)) print('may name is %s and my age is %d \n my weight is %2.5f thanks for you info %r' %('sajed',32,73.52,'bye bye!!!')) s="my name is {l} and my age is {l}"; print(s.format(l='sajed')) print('{0:7} | {1:40}'.format('Fruit', '40')) print('{0:7} | {1:9}'.format('Apples', 'hghg')) print('{0:1} | {1:9}'.format('Oranges', 10))
68b77dec130d1df315466177290742ab680f55db
jothisreerk/Scrambled
/scrambled.py
440
3.8125
4
from random import randrange def scramble(word): if (word == ""): return 'Please enter a word or a sting of words' else: scrambled = '' word_list = list(word) for i in range(len(word_list)): rand_index = randrange(0, len(word_list)) scrambled = scrambled + word_list[rand_index] del word_list[rand_index] return scrambled
5b0f3b1005bf8dbefeaae1b92f6cba9e2c55172b
nikhilsingh90/hello-world
/find_emails.py
431
4.5
4
""" Find emails from a string """ import re input("Press a key") print ("This is the email list - \ 1.random@example.com \ 2.random@example.com \ 3.random@example.com \ 4.random@example.com \ 5.random@example.com") print ("") m= re.findall('[\w.-]+@[\w.-]+.com','1.random@example.com \ 2.random@example.com 3.random@example.com 4.random@example.com \ 5.random@example.com') for email in m: print (email) """ Output: 1.random@example.com 2.random@example.com 3.random@example.com 4.random@example.com 5.random@example.com """
454a8211f2edec26f8bbd0627054b6b1fd44e26a
alexgrand/pythonhardway
/ex48 Advanced User Input/ex48/lexicon.py
1,246
3.84375
4
class Lexicon(object): def __init__(self): self.words = { 'north': 'direction', 'south': 'direction', 'east': 'direction', 'west': 'direction', 'down': 'direction', 'up': 'direction', 'left': 'direction', 'right': 'direction', 'back': 'direction', 'go': 'verb', 'stop': 'verb', 'kill': 'verb', 'eat': 'verb', 'the': 'stop', 'in': 'stop', 'of': 'stop', 'from': 'stop', 'at': 'stop', 'it': 'stop', 'door': 'noun', 'bear': 'noun', 'princess': 'noun', 'cabinet': 'noun' } def convert_number(self, u_str): try: return int(u_str) except ValueError: return None def scan(self, u_str): u_str = u_str.split() sentence = [] for word in u_str: conv_word = word.lower() conv_num = self.convert_number(word) if not conv_num: key = self.words.get(conv_word) if key: sentence.append((key, conv_word)) else: sentence.append(('error', word)) else: sentence.append(('number', conv_num)) return sentence lexicon = Lexicon()
784a91378999341cbbf715f36d14597873dd5238
Lav2891/python
/Correlation.py
886
3.71875
4
import pandas as pd def getinput(onefile, dlimiter, colname): if not dlimiter: df = pd.DataFrame(onefile) correlation_find(df, colname) else: df = pd.DataFrame(onefile,sep=dlimiter) correlation_find(df, colname) def correlation_find(df, colname): #get correlation of columns as matrix corr = pd.DataFrame() for colname[0] in colname: for colname[1] in colname: corr.loc[colname[0], colname[1]] = df.corr().loc[colname[0], colname[1]] def main(): dlimiter = ";" filepath = "C:/Users/Student/polls/Salary_Data.csv" onefile = pd.read_csv(filepath) columnname = "Salary, Yearsofexperience" #columns for which correlation to be calculated colname = columnname.split(',') getinput(onefile, dlimiter, colname) if __name__ == "__main__": main()
4cda944b6c15f705a25d779b8543940a1b130f5c
asrashley/music-bingo
/TicketChecker.py
6,371
3.5
4
from Tkinter import * import ttk from collections import namedtuple import json import os import sys # Object representation of a ticket mapping its number to its prime number ID class Ticket: def __init__(self, ticketNumber, ticketId): self.ticketNumber = ticketNumber self.ticketId = ticketId # GUI Class class MainApp: def __init__(self, master, gameID=''): self.appMaster = master frame = Frame(master, bg=normalColour) frame.pack(side=TOP, fill=BOTH, expand=1) gameIdLabel = Label(frame, bg=normalColour, text="Game ID Number:", font=(typeface, 18),pady=10) gameIdLabel.grid(row=0,column=0) self.gameIdEntry = Entry(frame, font=(typeface, 18), width=12, justify=LEFT) self.gameIdEntry.grid(row=0,column=1) self.gameIdEntry.insert(0, gameID) ticketNumberLabel = Label(frame, bg=normalColour, text="Ticket Number:", font=(typeface, 18),pady=10) ticketNumberLabel.grid(row=1,column=0) self.ticketNumberEntry = Entry(frame, font=(typeface, 18), width=12, justify=LEFT) self.ticketNumberEntry.grid(row=1,column=1) checkWinButton = Button(master, text="Check Win", command=self.findWinPoint, font=(typeface, 18), width=10, bg="#00e516") checkWinButton.pack(side=TOP, fill=X) self.ticketStatusWindow = Text(master, bg="#111", fg="#FFF", height=4, width=30, font=(typeface, 16)) self.ticketStatusWindow.pack(side=TOP,fill=X) self.ticketStatusWindow.config(state=DISABLED) # This function will find the winning point of the ticket given in box def findWinPoint(self): self.ticketStatusWindow.config(state=NORMAL) self.ticketStatusWindow.delete(0.0, END) gameId = self.gameIdEntry.get() gameId = gameId.strip() path = "./Bingo Games/Game-%s"%gameId if not os.path.exists(path): path = "./Bingo Games/Bingo Game - %s"%gameId if os.path.exists(path): f = open(path + "/ticketTracks") ticketFileLines = f.read() f.close() ticketFileLines = ticketFileLines.split("\n") ticketFileLines = ticketFileLines[0:len(ticketFileLines)-1] ticketList = [] for line in ticketFileLines: [ticketNum, ticketId] = line.split("/") ticketList.append(Ticket(ticketNum, ticketId)) ticketNumber = self.ticketNumberEntry.get() ticketNumber = ticketNumber.strip() theTicket = None for ticket in ticketList: if ticketNumber == ticket.ticketNumber: theTicket = ticket break if theTicket != None: with open(path + "/gameTracks.json", 'rt') as f: gameTracks = json.load(f) Song = namedtuple('Song', ['song_id', 'title', 'artist', 'count', 'duration', 'filename', 'album']) for idx in range(len(gameTracks)): try: gameTracks[idx]['song_id'] = gameTracks[idx]['songId'] del gameTracks[idx]['songId'] except KeyError: pass gameTracks = map(lambda s: Song(**s), gameTracks) winPoint, title, artist = self.checkWin(int(theTicket.ticketId), path, gameTracks) self.ticketStatusWindow.config(fg=normalColour) self.ticketStatusWindow.insert(END,"In Game Number " + gameId +":\n") self.ticketStatusWindow.insert(END,"Ticket "+ticketNumber+" will win at song " + str(winPoint)+".") self.ticketStatusWindow.insert(END,"\n("+title+" - " +artist+")") else: if len(ticketNumber) > 0: self.ticketStatusWindow.config(fg="#F00") self.ticketStatusWindow.insert(END, "Ticket "+ticketNumber+" does not exist\nwith Game ID Number " + gameId+"!") else: self.ticketStatusWindow.config(fg="#00f6ff") self.ticketStatusWindow.insert(END, "You must enter a Ticket Number!") else: self.ticketStatusWindow.config(fg="#F00") if len(gameId) > 0: self.ticketStatusWindow.insert(END, "Game ID Number " + gameId + "\ndoes not exist!") else: self.ticketStatusWindow.insert(END, "You must enter a Game ID Number\nand Ticket Number!") self.ticketStatusWindow.config(state=DISABLED) def checkWin(self, ticketId, directory, lines): """returns the point and track in which the ticket will win""" ticketTracks = self.primes(ticketId) lastSong = "INVALID" lastArtist = "" lastTitle = "" if os.path.exists(directory): fileLines = lines for i in fileLines: if int(i.song_id) in ticketTracks: lastSong = i.count lastTitle = i.title lastArtist = i.artist ticketTracks.remove(int(i.song_id)) if len(ticketTracks) == 0 and lastSong != "INVALID": return [int(lastSong),lastTitle,lastArtist] else: return [0, "", ""] def primes(self, n): """calculates the prime factors of the prime ticket ID. This will tell exactly what tracks were on the ticket""" primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) # supposing you want multiple factors repeated n //= d d += 1 if n > 1: primfac.append(n) return primfac root = Tk() root.resizable(0,0) root.wm_title("Music Bingo - Ticket Checker") #if os.path.exists("./Extra-Files/Icon.ico"): # root.iconbitmap('./Extra-Files/Icon.ico') typeface = "Arial" normalColour = "#ff7200" altColour = "#d83315" bannerColour = "#222" if len(sys.argv) > 1: newObject = MainApp(root, sys.argv[1]) else: newObject = MainApp(root) root.mainloop()
2ac42d08af26002414c931c694dab3f1224c0785
garettmd/Scrambled
/main2.py
521
3.609375
4
__author__ = 'GD020348' import random def main(): thefile = "input.txt" # thefile = input("What's the name of the file?") inputfile = open(thefile) lines = inputfile.readlines() word = "" # First, grab out individual lines in the input file for line in lines: # Make a list variable out of each character on the current line # and assign it to the charactrs variable words = line.split() #print(words) for word in words: inputfile.close() main()
10d7c85e2de36211f073a318489ee6d4067e7dfb
BalaMurugan6/python_programs
/find factor of the number.py
129
4.15625
4
#to find factor of a given number x=int(input("enter the number")) for i in range(1,x+1): if x%i==0: print(i)
d1a3da0ef5a6488d2d32d2cf804551de058cab95
STEADSociety/FBC
/odd_number.py
114
4
4
def odd_number(number): return [odd for odd in range(number) if int(odd % 2) != 0] print(odd_number(20))
065d34781bf52eb134dab6771f84991211fedd31
Natalie150806/uebung
/hello-world.py
160
3.515625
4
def hello(): print("gebe deinen namen ein: ") name=input() print("hallo " + name + ", wie geht´s dir so?") if __name__ == '__main__': hello()
5882f09222a7deeeb7eea495e1e1964a639d4336
RandyCarrion/python
/loop.py
257
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 13 11:50:07 2018 @author: randycarrion """ L = [] while len(L) <2: new_name = input("Name: ").strip().capitalize() L.append(new_name) print("sorry, list is full") print(L)
9a67f8722fba6c17e86b741d6880d196210f1617
s0703w/python-study
/재귀함수 (예).py
167
4.125
4
def recursive_function(n): if n == 1: return n else: return recursive_function(n - 1) * n n = int(input("N: ")) print(recursive_function(n))
a1d58d0bc7ceba271c13951adf5b3889ef17e981
santanu5670/Python
/Tkinter/13.py
913
3.953125
4
from tkinter import * root=Tk() canvas_width=400 canvas_hight=200 root.geometry(f"{canvas_width}x{canvas_hight}") # can_widget=Canvas(root,width=canvas_width,height=canvas_hight) # can_widget=Canvas(root,width=canvas_width,height=canvas_hight) can_widget=Canvas(root,width=1200,height=1200) can_widget.pack() #The lines goes from the point x1,y1,x2,y2 can_widget.create_line(0,0,800,400,fill='red') can_widget.create_line(0,400,800,0,fill='red') can_widget.create_line(0,200,800,200,fill='red') can_widget.create_line(400,0,400,400,fill='red') #To create ractangle specify parameter in this order:- corner of the top left and corner of the buttom right # can_widget.create_rectangle(3,5,700,300,fill="blue") can_widget.create_text(200,200,text="Python") #To create oval specify parameter in this order:- corner of the top left and corner of the buttom right can_widget.create_oval(344,233,244,355) root.mainloop()
ebb7d73e2a2af10ebff6845c83184fcdacbc0342
skyying/euler
/016/16.py
122
3.734375
4
# python is awesome def power_of_two(n): return sum([int(x) for x in str(pow(2, n))]) print(power_of_two(1000))
7a7478311a1ace76c5096a38797afcd4556b1d1b
bz866/Pokemon-Information-Search-System
/dsga1007_final_project/input/userInput.py
1,802
3.90625
4
import pandas as pd import numpy as np import sys from LoadData import * class UserChoice: """ This class contains all process that asking user input of choosing cuisine category, cuisine, neighborhood category, and neighborhood. User could go back or exit follow the instruction. """ def __init__(self): self.user_decision = {'Cuisine_Category': None, 'Cuisine': None, 'Neighborhood_Category': None, 'Neighborhood': None} self.cuisine = Cuisine() self.nbhd = Neighborhood() def select_pokemon(self): while True: choice = raw_input('\nHow would like to CHOOSE a cuisine category?\n' 'You can type \'back\' to go back.\n' 'A. African\n' 'B. EastAsian\n' 'C. SouthAsian\n' 'D. LatinAmerican\n' 'E. NorthAmerican\n' 'F. European\n' 'G. MiddleEastern\n' 'H. Cafes\n' 'I. Bars\n' 'J. Vegan\n' 'K. OtherBusiness\n' '---->') choice = choice.lower().rstrip().lstrip() if choice == 'quit': return 'quit' elif choice == 'back': return 'back' elif choice in ['a','b','c','d','e','f','g','h','i','j','k']: self.user_decision['Cuisine_Category'] = self.cuisine.cuisine_category[choice] return 'selected' else: print 'Invalid Input. Please enter again.\n'
19400bc992056ffa2e04ded4d2515a65a77dc9f3
ogruca/python
/lists-for-loop.py
140
3.90625
4
names = ['Ben', 'Sally', 'Amy', 'George', 'Randy'] x = len(names) print('There are', x, 'items in the list') for x in names: print(x)
9b1e64522e1c479ab009781e9da467cb520efe68
GlitchHopper/AdventOfCode2019
/AoC_2019_Day3/Part1.py
1,083
3.90625
4
import math def GetLeg(path, position, instruction): direction = instruction[0] distance = int(instruction[1:]) for i in range(distance): if direction == "L": position[0] -= 1 elif direction == "R": position[0] += 1 elif direction == "D": position[1] -= 1 elif direction == "U": position[1] += 1 else: print("Invalid Leg Instruction") path.add(tuple(position)) file = open("/Users/nathanielgugel/Desktop/AdventOfCode2019/AoC_2019_Day3/PuzzleInput.txt") cables = [] for line in file: cables.append(line.split(",")) cablePaths = [] for cable in cables: position = [0, 0] path = set() for node in cable: GetLeg(path, position, node) cablePaths.append(path) cableIntersections = list(set.intersection(cablePaths[0], cablePaths[1])) distances = [] for intersection in cableIntersections: distances.append(abs(intersection[0]) + abs(intersection[1])) distances.sort() print("Shortest Manhattan distances is " + str(distances[0]))
dc043e312ccec6f5aeb0d91bf47c7b7d82725831
bijeshofficial/coding_solutions
/LeetCode/0500_Keyboard_Row.py
729
3.671875
4
class Solution: def findWords(self, words: List[str]) -> List[str]: first_row = 'qwertyuiopQWERTYUIOP' second_row = 'asdfghjklASDFGHJKL' third_row = 'zxcvbnmZXCVBNM' output = [] for i in words: counter_first = 0 counter_second = 0 counter_third = 0 for j in i: if j in first_row: counter_first +=1 elif j in second_row: counter_second += 1 elif j in third_row: counter_third += 1 if counter_first == len(i) or counter_second == len(i) or counter_third == len(i): output.append(i) return output
2abd372be6aaf6afcf17221e04599553141c1647
rneitzey/python-challenge
/PyBank/main.py
2,114
3.703125
4
import os import csv import statistics import sys budget_csv = os.path.join('Resources','budget_data.csv') with open(budget_csv,newline='') as csvfile: csvreader = csv.reader(csvfile,delimiter = ',') csvheader = next(csvreader) row_count = 0 net = 0 monthly_change = 0 # Make a list of difference between each row row_diff = [] previous_row_value = 0 greatest_increase = 0 greatest_decrease = 0 greatest_increase_month = "" greatest_decrease_month = "" for row in csvreader: # Add each row in file for total count. Use for months since each row is a new month. row_count += 1 # Add up the total for column Profit/Losses. net += int(row[1]) if row_count > 1: monthly_change = int(row[1]) - previous_row_value row_diff.append(monthly_change) if monthly_change > 0 and monthly_change > greatest_increase: greatest_increase = monthly_change greatest_increase_month = row[0] elif monthly_change < 0 and monthly_change < greatest_decrease: greatest_decrease = monthly_change greatest_decrease_month = row[0] previous_row_value = int(row[1]) average_change = round(statistics.mean(row_diff),2) #After loop printing print("Financial Analysis") print("-" * 20) print(f"Total Months: {row_count}") print(f"Total: ${net}") print(f"Average Change: ${average_change}") print(f"Greatest Increase in Profits: {greatest_increase_month} (${greatest_increase})") print(f"Greatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease})") with open("Results_summary.txt","w+") as summary: sys.stdout = summary #Print to text file print("Financial Analysis") print("-" * 20) print(f"Total Months: {row_count}") print(f"Total: ${net}") print(f"Average Change: ${average_change}") print(f"Greatest Increase in Profits: {greatest_increase_month} (${greatest_increase})") print(f"Greatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease})")
9b9c099a94fb37b64ac70fba1f2c94da146f85c0
tsemach/pyexamples
/pyexamples/objects/singleton_02.py
781
3.890625
4
import functools def singleton(cls): """ Use class as singleton. """ cls.__new_original__ = cls.__new__ @functools.wraps(cls.__new__) def singleton_new(cls, *args, **kw): it = cls.__dict__.get('__it__') if it is not None: return it cls.__it__ = it = cls.__new_original__(cls, *args, **kw) it.__init_original__(*args, **kw) return it cls.__new__ = singleton_new cls.__init_original__ = cls.__init__ cls.__init__ = object.__init__ return cls # # Sample use: # @singleton class Foo: def __new__(cls): cls.x = 10 return object.__new__(cls) def __init__(self): assert self.x == 10 self.x = 15 assert Foo().x == 15 Foo().x = 20 assert Foo().x == 20
dda80d4733f3ac9e1a89e87156289c25f74f184c
sumeyra123/PythonDS
/gamereversi.py
1,223
3.625
4
from __future__ import print_function from reversigamelogic import ReversiGameLogic def main(): game = ReversiGameLogic() draw(game) print("First move: ", game.whoseTurn()) while(game.getWinner() == 0): canInput = True while canInput: #plays until someone wins move_coordinate = raw_input\ ("Input (row,col) for player %d or (8,8) to pass > "\ %game.whoseTurn()) #IF no legal move at all for a player, the optiion should be pass #but it is not implemented as ReversiGameLogic ADT needs some change r_string,c_string = move_coordinate.split(',') r, c = int(r_string), int(c_string) if game.isLegalMove(r,c): canInput = False game.makeMove(r,c) draw(game) def draw(game): print ("r/c", end = ' ') for a in range(8): print (a, sep = ' ', end = ' ') print ('\n') for r in range(8): print (r, sep = ' ', end = ' ') for c in range(8): print(game.occupiedBy(r,c), sep = ' ', end = ' ') print('\n---------------------------------') main()
f318a7af275c0a9408128cb7a3e76a012247cf82
fxy1018/Leetcode
/LC_808_Movie Network.py
2,871
3.9375
4
''' Give some rating of movie (number starting from 0) and their relationship, and relationships can be passed (a and b are related, b and c are related, a and c are also considered to be related). Give every movie's relationship list.Given a movie numbered S, find the top K movies with the highest rating in the movies associated with S(When the number of movies which associated with S is less than K, output all the movies .You can output them in any order). Does not include this movie. Example Given ratingArray = [10,20,30,40], contactRelationship = [[1,3],[0,2],[1],[0]], S = 0, K = 2, return [2,3]. Explanation: In contactRelationship, [1,3] is associated with 0,[0,2] is associated with 1,[1] is associated 2,[0] is associated with 3. Finally,Movies numbered [1,2,3] are associated with movie 0, and the order which according to their rating from high to low is [3,2,1], so the output [2,3]. Given ratingArray = [10,20,30,40,50,60,70,80,90], contactRelationship = [[1,4,5],[0,2,3],[1,7],[1,6,7],[0],[0],[3],[2,3],[]], S = 5, K = 3, return [6,7,4]. Explanation: In contactRelationship,[1,4,5] is associated with 0,[0,2,3] is associated with 1,[1,7] is associated with 2,[1,6,7] is is associated with 3,[0] is associated with 4,[0] is associated with 5,[3] is associated with 6,[2,3] is associated with 7,no moive is associated with 8. Finally,Movies numbered [0,1,2,3,4,6,7] are associated with movie 5, and the order which according to their rating from high to low is [7,6,4,3,2,1,0]. Notice that movie 8 is not related to movie 5, so it has the highest rating but does not count towards the answer. ''' import heapq class Solution: """ @param rating: the rating of the movies @param G: the realtionship of movies @param S: the begin movie @param K: top K rating @return: the top k largest rating moive which contact with S """ def topKMovie(self, rating, G, S, K): # Write your code here #find all movie related to S queue = [S] visit = set([]) while queue: movie = queue.pop(0) visit.add(movie) for m in G[movie]: if m not in visit: queue.append(m) visit.add(m) visit.remove(S) if len(visit) <=K: return(list(visit)) heap = [] visit = list(visit) for i in range(K): if visit: top = visit.pop() heapq.heappush(heap, [rating[top], top]) else: return([x[1] for x in heap]) while visit: top = visit.pop() if rating[top] > heap[0][0]: heapq.heappop(heap) heapq.heappush(heap, [rating[top], top]) return([x[1] for x in heap])
44410909a0cc356eb3c8dd0135df6979d8480d33
Aydndmrcn/Data_Structures_inKTU
/ds_inPython_Book/ch01/06_scale.py
235
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 14:12:48 2020 @author: zafer """ def scale(data, factor): for j in range(len(data)): data[j] *= factor mylist = [2,3,5,2,3,6,8] print(mylist) scale(mylist,2) print(mylist)
00c2405863724f7181b2efc16e355630d053d118
UltraMarine107/Data-Clustering
/Clustering/Data.py
1,532
3.515625
4
''' Get data for all analysis practice MBT: March total bill, which represents the amount of service that customers purchase emp: Employee number, the size of customer companies ''' import csv import codecs from matplotlib import pyplot import math def get_data(): # Read csv file csvFile = codecs.open('3.22MRR&EMP.csv', "r", encoding='latin-1', errors='ignore') reader = csv.reader(csvFile) data = [] # put all data into the format of double list for row in reader: data.append(row) del data[0] # delete title row return data def get_log_MBT_emp(data): march_bill_total = [] emp = [] for row in data: march_bill_total.append(int(row[18])) emp.append(int(row[36])) log_march_bill_total = [] log_emp = [] for row in data: try: bill = math.log(int(row[18])) emp_number = math.log(int(row[36])) log_march_bill_total.append(bill) log_emp.append(emp_number) except ValueError: continue return log_march_bill_total, log_emp def get_log_LT_3(data): ins1, ins2 = get_log_MBT_emp(data) # TODO index out of range, cause unknown. This should work?! for i in range(len(ins2)): if ins2[i] < 3: del ins2[i] del ins1[i] return ins1, ins2 def scatter_plot(list1, list2): pyplot.scatter(list1, list2) pyplot.show() # ins1, ins2 = get_log_LT_3(get_data()) # scatter_plot(ins1, ins2)
01fe50e6d89a97a704de5e6e3908a6a8216c983d
VictorSSH/Python
/Code/list_python/day_01/linst_嵌套列表_Code_02.py
622
3.90625
4
#!/usr/bin/env python # coding=utf-8 import random #1.定义一个嵌套列表, rooms =[[],[],[],[]] #2.有一个列表,保存了8位老师的姓名 teacher =[ "李克强","温家宝","张家辉", "薛之谦","李晨","陈赫","嘉玲", "毛不易","宋东野"] #3.随机把8位老师的名字添加到第一个列表中, for name in teacher: randomNum =random.randint(0,3) rooms[randomNum].append(name) #print(rooms) i=1 for room in rooms: #print(rooms) print("办公室%d里面的老师姓名是:"%i) for name in room: print(name,end=" ") print(" ") i+=1
d879123f73c6f6c1a17f69a7a7fd8341c41128dc
hernanrr/OpenChannel
/ChannelGeometry.py
10,155
3.984375
4
#!/usr/bin/env python3 import math from abc import ABC, abstractmethod from typing import Union, Callable import logging def check_valid_positive_number(**kwargs): for key, value in kwargs.items(): if not isinstance(value, (float, int)) or value <= 0: message = f'{key} must be a positive number' logging.error(message, stack_info=False) raise ValueError(message) return None def check_depth_le_diameter(diameter, depth): if depth > diameter: logging.error('Depth exceeds diameter', stack_info=False) raise ValueError('Depth must be less than or equal to diameter.') return None class ChannelXSection(ABC): """A class to represent channel cross-sections.""" @abstractmethod def area(self, depth: Union[int, float]) -> Callable[[float], float]: """Returns a function for the area of the channel cross-section.""" @abstractmethod def wetted_perimeter(self, depth: Union[int, float]) -> Callable[[float], float]: """Returns a function for wetted perimeter of the channel.""" @abstractmethod def top_width(self, depth: Union[int, float]) -> Callable[[float], float]: """Returns a function forthe water surface width of the channel.""" @abstractmethod def shape_function(self, depth: Union[int, float]) -> Callable[[float], float]: r"""Returns a function for the channel shape function of the channel. Notes ----- The channel shape function results from the solution to Manning's equation for normal depth using the Newton-Raphson method. It is defined as: .. math:: \left(\frac{2}{3R}\frac{dR}{dy} + \frac{1}{A}\frac{dA}{dy} \right) where R and y are the hydraulic radius and the water depth respectively. """ def hydraulic_radius(self, depth) -> float: """Returns a function for the hydraulic radius of the channel.""" check_valid_positive_number(Depth=depth) return self.area(depth) / self.wetted_perimeter(depth) def hydraulic_depth(self, depth) -> float: """Returns a function for the hydraulic depth of the channel.""" check_valid_positive_number(Depth=depth) return self.area(depth) / self.top_width(depth) class Rectangular(ChannelXSection): """A class to represent rectangular channel cross-sections. Parameters ---------- width : int or float Bottom width of the channel [m] or [ft] Raises ------ ValueError Only accepts positive, real numbers (int or float). Notes ----- Unit consistency, correctness and compatibility is the user's responsibility. Examples -------- >>> rectangle = Rectangular(10) >>> rectangle.width 10.0 """ def __init__(self, width: Union[int, float]) -> None: """Constructor for rectangular channel cross-section.""" check_valid_positive_number(Width=width) self.width = float(width) def area(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return depth * self.width def wetted_perimeter(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return self.width + 2 * depth def top_width(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return self.width def shape_function(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return ((5 * self.width + 6 * depth) / (3 * depth * self.wetted_perimeter(depth))) class Triangular(ChannelXSection): """A class to represent symmetrical triangular channel cross-sections. Parameters ---------- side_slope : int or float Horizontal distance per unit vertical rise of the side Raises ------ ValueError Only accepts positive, real numbers (int or float). Notes ----- Unit consistency, correctness and compatibility is the user's responsibility. Examples -------- >>> triangle = Triangular(2) >>> triangle.side_slope 2 """ def __init__(self, side_slope: Union[int, float]) -> None: check_valid_positive_number(**{'Side slope': side_slope}) self.side_slope = side_slope def area(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return self.side_slope * depth ** 2 def wetted_perimeter(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return 2 * depth * math.sqrt(1 + self.side_slope ** 2) def top_width(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return 2 * depth * self.side_slope def shape_function(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return 8 / (3 * depth) class Trapezoidal(ChannelXSection): """A class to represent symmetrical trapezoidal channel cross-sections. Parameters ---------- width : int or float Bottom width of the channel [m] or [ft] side_slope : int or float Horizontal distance per unit vertical rise of the side Raises ------ ValueError Only accepts positive, real numbers (int or float). Notes ----- Unit consistency, correctness and compatibility is the user's responsibility. Examples -------- >>> trapezoid = Trapezoidal(10, 2, 2) >>> trapezoid.width 10 >>> trapezoid.side_slope 2 """ def __init__(self, width: Union[int, float], side_slope: Union[int, float]) -> None: check_valid_positive_number(Width=width) check_valid_positive_number(**{'Side slope': side_slope}) self.width = width self.side_slope = side_slope def area(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return (self.width + self.side_slope * depth) * depth def wetted_perimeter(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return (self.width + 2 * depth * math.sqrt(1 + self.side_slope ** 2)) def top_width(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) return self.width + 2 * depth * self.side_slope def shape_function(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) A = math.sqrt(1 + self.side_slope ** 2) numerator = (self.top_width(depth) * (5 * self.width + 6 * depth * A) + (4 * self.side_slope * depth ** 2 * A)) denominator = (3 * depth * (self.width + depth * self.side_slope) * (self.width + 2 * depth * A)) return numerator / denominator class Circular(ChannelXSection): """A class to represent circular channel cross-sections. Parameters ---------- diameter : int or float Channel diameter or pipe inner diameter [m] or [ft] Raises ------ ValueError Only accepts positive, real numbers (int or float). Notes ----- Unit consistency, correctness and compatibility is the user's responsibility. Examples -------- >>> circle = Circular(0.2, 0.1) >>> circle.diameter 0.2 """ def __init__(self, diameter: Union[int, float]) -> None: check_valid_positive_number(Diameter=diameter) self.diameter = diameter def area(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) check_depth_le_diameter(self.diameter, depth) theta = 2 * math.acos(1 - (2 * depth) / self.diameter) return ((1 / 8) * (theta - math.sin(theta)) * self.diameter ** 2) def wetted_perimeter(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) check_depth_le_diameter(self.diameter, depth) theta = 2 * math.acos(1 - (2 * depth) / self.diameter) return 1 / 2 * theta * self.diameter def top_width(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) check_depth_le_diameter(self.diameter, depth) theta = 2 * math.acos(1 - (2 * depth) / self.diameter) return math.sin(theta / 2) * self.diameter def shape_function(self, depth: Union[int, float]) -> Callable[[float], float]: check_valid_positive_number(Depth=depth) check_depth_le_diameter(self.diameter, depth) theta = 2 * math.acos(1 - (2 * depth) / self.diameter) numerator = (4 * (2 * math.sin(theta) + 3 * theta - 5 * theta * math.cos(theta))) denominator = (3 * self.diameter * theta * (theta - math.sin(theta)) * math.sin(theta / 2)) return numerator / denominator def main(): """ Not implemented yet. """ if __name__ == '__main__': main() # pragma: no cover
d747896795d41d705eafd167a14ed6b653c34f72
edenuis/Python
/Sorting Algorithms/insertionSort.py
674
4.09375
4
#Insertion sort def insertionSort(numbers): for idx in range(len(numbers)-1): new_idx = idx for sec_idx in range(idx+1, len(numbers)): if numbers[sec_idx] < numbers[new_idx]: new_idx = sec_idx if new_idx != idx: numbers[idx], numbers[new_idx] = numbers[new_idx], numbers[idx] return numbers if __name__ == "__main__": assert insertionSort([1,2,3,4,5]) == [1,2,3,4,5] assert insertionSort([5,4,3,2,1]) == [1,2,3,4,5] assert insertionSort([5,2,3,4,4,2,1]) == [1,2,2,3,4,4,5] assert insertionSort([]) == [] assert insertionSort([-1,23,0,123,5,6,4,-12]) == [-12,-1,0,4,5,6,23,123]
6c48eaa3952b441e437979349a0b00691df7aa0f
Nik-Kaz/domaci_predavanje5
/zadatk16_strana4.py
1,266
3.6875
4
""" Dat je realan broj a. Koristeći samo operaciju množenja i pomoćne promjenljive, izračunati: a. a7 za 4 operacije b. a10 za 4 operacije c. a21 za 6 operacija d. a64 za 6 operacija e. a3 i a10 za 4 operacije f. a2 , a 5 i a17 za 6 operacija """ def pod_a(): a = int(input("Unesite broj: ")) a2 = a * a a4 = a2 * a2 a8 = a4 * a4 return a8 / a def pod_b(): a = int(input("Unesite broj: ")) a2 = a * a a4 = a2 * a2 a8 = a4 * a4 return a8 * a2 def pod_c(): a = int(input("Unesite broj: ")) a2 = a * a a4 = a2 * a2 a8 = a4 * a4 a16 = a8 * a8 a20 = a16 * a4 return a20*a def pod_d(): a = int(input("Unesite broj: ")) a2 = a * a a4 = a2 * a2 a8 = a4 * a4 a16 = a8 * a8 a32 = a16 * a16 return a32*a32 def pod_e(): a = int(input("Unesite broj: ")) a2 = a * a a3 = a2 * a a5 = a3 * a2 a10 = a5*a5 print(f"a na stepen 3 je {a3}, a a na stepen 10 je {a10}") def pod_f() a = int(input("Unesite broj: ")) a2 = a * a a4 = a2 * a2 a5 = a4 * a a10 = a5*a5 a15 = a10*a5 a17 = a15*a2 print( f"a na stepen 2 je {a2}, a a na stepen 5 je {a5} i a na stepen 17 je {a17}")