blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
36d93f0fedf6713171282e63316e4dd38e09d80e
Amdude/RandomPasswordGenerator
/RandomPasswordGenerator.py
1,555
4.5
4
from random import randint import string all_characters = [] # set up this array to hold our letters and special characters special_characters = ['!', '@', '#', '$', '%', '^', '&', '*'] # array of special characters password = [] # our array that will be used to store out password def combine_chars(): for char in string.ascii_letters: # add all characters in ascii_letters to all_characters array all_characters.append(char) for char in special_characters: # add all characters in special_characters to all_characters array all_characters.append(char) def greeting(): print("\nHello. Welcome to the random password generator!") choose_length() def choose_length(): password_length = int(input("How long do you want your password to be?")) # get password length print("Your password will be " + str(password_length) + " characters long.") generate_password(password_length) # create a random password, passing our desired length def generate_password(length): current_length = 0 while current_length <= length: # while the current_length of our password is <= to desired password_length rand_char = randint(0, len(all_characters) - 1) # select a random number password.append(all_characters[rand_char]) # use that random number to access a character by index current_length += 1 # increment current_length by 1 present_password() def present_password(): print("\nHere is your password:") print(''.join(password)) combine_chars() greeting()
f5745ffd80db2c13fc6dd173d41ae4293c4c9e22
NEUAI/testchain
/testchain/incentive/wallet.py
460
3.65625
4
""" wallet.py This file defines the structure and methods of class Wallet. """ __all__ = ["Wallet"] __version__ = '1.0' __author__ = 'Zhengpeng Ai' class Wallet: def __init__(self, coin: float = 0.0): self.coin = coin return def get_coin(self): return self.coin def add_coin(self, amount: float): self.coin += amount return def sub_coin(self, amount: float): self.coin -= amount return
61b1db8d7e151957d4e4faf470f41583c78e719c
S-Philp/LearningPython
/EvenOdd.py
117
4.09375
4
number = input("Type a number: ") user_num = int(number) if user_num%2==0: print("even") else: print("odd")
b85ffbbc411490b508f4ad212c32852d48891acc
norahpack/carbonEmissions
/cs5png3.py
3,190
3.515625
4
import os import sys from PIL import Image import time def saveRGB(boxed_pixels, filename = "out.png"): """Save the given pixel array in the chosen file as an image.""" print(f'Starting to save {filename}...', end = '') w, h = getWH(boxed_pixels) im = Image.new("RGB", (w, h), "black") px = im.load() for r in range(h): #print(".", end = "") for c in range(w): bp = boxed_pixels[r][c] t = tuple(bp) px[c,r] = t im.save(filename) time.sleep(0.5) print(filename, "saved.") def getRGB(filename = "in.png"): """Reads an image png file and returns it as a list of lists of pixels (i.e., and array of pixels). """ original = Image.open(filename) print(f"{filename} contains a {original.size[0]}x{original.size[1]}" f" {original.format} image with mode {original.mode}.") WIDTH, HEIGHT = original.size px = original.load() PIXEL_LIST = [] for r in range(HEIGHT): row = [] if original.mode == 'RGB': for c in range(WIDTH): row.append(px[c, r][:3]) else: for c in range(WIDTH): pixel = px[c, r] row.append((pixel, pixel, pixel)) PIXEL_LIST.append(row) return PIXEL_LIST def getWH(px): """Given a pixel array, return its width and height as a pair.""" h = len(px) w = len(px[0]) return w, h def binaryIm(s, cols, rows): """Given a binary image s of size rows x cols, represented as a single string of 1's and 0's, write a file named "binary.png", which contains an equivalent black-and-white image.""" px = [] for row in range(rows): row = [] for col in range(cols): c = int(s[row*cols + col])*255 px = [c, c, c] row.append(px) px.append(row) saveRGB(px, 'binary.png') #return px class PNGImage: """Class to support simple manipulations on PNG images.""" def __init__(self, width, height): """Construct a PNGImage of the given dimensions.""" self.width = width self.height = height default = (255, 255, 255) self.image_data = [[(255, 255, 255) for col in range(width)] for row in range(height)] def plotPoint(self, col, row, rgb = (0, 0, 0)): """Plot a single RGB point in at the given location in a PNGImage.""" # Ensure that rgb is a three-tuple if not isinstance(rgb, (list, tuple)) or len(rgb) != 3: print(f"In plotPoint, the color {rgb} was not" f" in a recognized format.", file = sys.stderr) # Check if we're in bounds if 0 <= col < self.width and \ 0 <= row < self.height: self.image_data[row][col] = rgb else: print(f"In plotPoint, column {col} or row {row}", file = sys.stderr) return def saveFile(self, filename = "test.png"): """Save the object's data to a file.""" # We reverse the rows so that the y direction # increases upwards... saveRGB(self.image_data[::-1], filename)
652cbe57599fee3423707998e98ea9a9fff30c7f
edu-athensoft/ceit4101python_student
/ceit_190910_zhuhaotian/py0923/datatype_number.py
281
3.71875
4
# datatype # type() a = 5 print(a, type(a)) b = 1.5 print(b, type(b)) c = True print(c, type(c)) d = 'my name' print(d, type(d)) # isinstance() print(isinstance(a, int)) # accuracy of float f1 = 0.1234567890123456789 print(f1) f1 = 0.1234567890123456789012345678 print(f1)
5a653bdc1ce652e9ec0de67b3d3626f9396cfc38
Redmar-van-den-Berg/newick_utils
/src/toy.py
868
3.625
4
#!/usr/bin/env python import sys from newick_utils import * def count_polytomies(tree): count = 0 for node in tree.get_nodes(): if node.children_count() > 2: count += 1 return count # Main def main(): if len(sys.argv) < 2: raise RuntimeError ("Usage: toy.py <-|filename>") filename = '' if sys.argv[1] != '-': filename = sys.argv[1] input = '(A,(B,C));((Drosophila:1,Tribolium:1.2,Vespa:0.23):1,(Daphnia:2.0,Homarus:1.3):3.1);' for tree in Tree.parse_newick_input(input, type='string'): type = tree.get_type() if type == Tree.PHYLOGRAM: # also sets nodes' depths depth = tree.get_depth() else: depth = None print 'Type:', type print '#Nodes:', len(list(tree.get_nodes())) print ' #leaves:', tree.get_leaf_count() print '#Polytomies:', count_polytomies(tree) print "Depth:", depth if __name__ == "__main__": main()
073f9272bbe3c5b4fdbfed1b575d2d1fb76d44a8
residoo/project_euler
/archive/euler004.py
1,300
3.96875
4
# euler004.py # https://projecteuler.net/problem=4 """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ # From 999 to 100, and from 999 to 100.... # IMPORTS import math # METHODS def checkifpalindrome(number): isPalindrome = True # We'll assume that it is... word = str(number) # Turn number into a string for checking for i in range(int(len(word) / 2)): # We're checking from both ends, so only need to go through half the word. This should round it up in case of uneven number of characters... if word[i] != word[len(word)-i-1]: # If the first isn't equal to the last, etc... isPalindrome = False # then not a palindrome, sorry return isPalindrome return isPalindrome # MAIN iterations = 0 biggestPalindrome = 0 for i in range(999,100,-1): for j in range(999,100,-1): iterations += 1 if checkifpalindrome(i*j): print "Palindrome found. " + str(i*j) print "The product of " + str(i) + " and " + str(j) print "This took " + str(iterations) + " iterations." if i*j > biggestPalindrome: biggestPalindrome = i*j break print "Biggest palindrome: " + str(biggestPalindrome)
67e413eadd6433897b6ebf50eb5068315dbb7f9c
a-yildiz/ROS-Simple-Sample-Packages
/pyqt5_fundamentals/window8_QSpinBox.py
1,064
3.546875
4
#!/usr/bin/env python3 from PyQt5 import QtWidgets import sys """ QSpinBox: Creates a textbox with increment buttons for numbers. """ def create_window(): # Define window: obj = QtWidgets.QApplication(sys.argv) window = QtWidgets.QWidget() # Set window attributes: window.setWindowTitle("My PyQt5 Interface") window.setGeometry(250, 100, 600, 300) # upper left corner of monitor is ax = ay = 0. # Create a spin box (integers): spin1 = QtWidgets.QSpinBox(window) # default range limit is from 0 to 99, integers only. spin1.setRange(15, 35) # customize range limit spin1.setSingleStep(5) # customize increment amount # Create a spin box (floats): spin2 = QtWidgets.QDoubleSpinBox(window) # default range limit is from 0.00 to 99.99. spin2.move(100, 0) spin2.setRange(22.5, 47.5) # customize range limit spin2.setSingleStep(0.25) # customize increment amount # Display window: window.show() sys.exit(obj.exec_()) if __name__ == "__main__": create_window()
fb688cb1ff85bdbf9fabc24719ff0ea96c8cbebe
sbrandom/DataStructuresAndAlgorithms
/ch3-find-duplicate.py
1,091
3.921875
4
def has_duplicate_quadratic(list): num_steps = 0 for i in range(len(list)): for j in range(len(list)): num_steps += 1 if i != j and list[i] == list[j]: return [True, num_steps] return [False, num_steps] def has_duplicates_linear(list): num_steps = 0 existing_numbers = {} for i in range(len(list)): num_steps += 1 if list[i] in existing_numbers: return [True, num_steps] else: existing_numbers[list[i]] = True return [False, num_steps] list_to_check = [1, 4, 5, 2, 9] # No duplicates #list_to_check = [1, 5, 3, 9, 4, 4] # One duplicate print("The list to check...") print(list_to_check) print("\nQuadratic search...") quad_results = has_duplicate_quadratic(list_to_check) print("Has duplicates? " + str(quad_results[0])) print("Steps to complete: %d" % (quad_results[1])) print("\nLinear search...") linear_results = has_duplicates_linear(list_to_check) print("Has duplicates? " + str(linear_results[0])) print("Steps to complete: %d" % (linear_results[1]))
486183f0ffe8aeb96e74d4a465a68b95f37e7085
sicsempatyrannis/Credit-Suisse-Hackathon
/Question8.py
832
3.6875
4
# Participants may update the following function parameters def countNumberOfWays(numOfUnits, numOfCoinTypes, coins): # Participants code will be here dp = [1] + [0]*numOfUnits for coin in coins: for i in range(coin, numOfUnits+1): dp[i] += dp[i-coin] return dp[numOfUnits] def main(): firstLine = input().split(" ") secondLine = input().split(" ") numOfUnits = int(firstLine[0]) numOfCoinTypes = int(firstLine[1]) coins = list(map(int, secondLine)) # Participants may update the following function parameters answer = countNumberOfWays(numOfUnits, numOfCoinTypes, coins) # Please do not remove the below line. print(answer) # Do not print anything after this line if __name__ == '__main__': main()
08deea2444709ddc59f09cfdf9996edc44b1cab2
Vaitesh/ZipFileFinder
/Zip_file_finder.py
193
4.0625
4
#Listing the files/folders present in zipfile from zipfile import Zipfile file_name = input('Please enter the folder/file name: ') with Zipfile(file_name, 'r') as zip: zip.printdir()
23598ff071943aa907704e0e10bc5b14e3fbe419
verisimilitude20201/dsa
/Tree/Binary Search Tree/algorithms/inorder_successor.py
798
3.734375
4
""" Problem ------ Find the in-order successor of a node in a Binary search tree 1. If p has a right sub-tree, its in order sucessor is the left most node of the right-subtree 2. If p does not have a right sub-tree, its in order successor is the ancestor that contains p in its left subtree Complexity ---------- Time: O(h) where h is the height of the Tree. Space: O(1) Note: This is a plain algorithm """ def inorder_successor(p): if p.right() is not None: walk = p.right() while walk.left() is not None: walk = walk.left() return walk else: walk = p ancestor = parent(walk) while ancestor is not None and walk == ancestor.right(): walk = ancestor ancestor = parent(walk) return walk
70b8c64148e13a932ca61ff4124aeea21d242632
zuigehulu/AID1811
/pbase/day02/jiangyi/day02/exercise/2numbers.py
556
3.90625
4
# 练习: # 输入两个整数,分别用变量 x, y 绑定 # 1. 计算这两个数的和并打印结果 # 2. 计算这两个数的积,并打印结果 # 3. 计算 x 的 y次方并打印 # 如: # 请输入 x: 100 # 请输入 y: 200 # 打印如下: # 100 + 200 = 300 # 100 * 200 = 20000 # 100 ** 200 = 1000000..... s = input("请输入 x: ") # 得到的是字符串 x = int(s) # 转为整数 y = int(input("请输入 y: ")) print(x, '+', y, '=', x + y) print(x, '*', y, '=', x * y) print(x, '**', y, '=', x ** y)
88cb545d426984720c1b4878ad9b0ce5c1ceb565
610yilingliu/leetcode
/Python3/536.construct-binary-tree-from-string.py
1,218
3.671875
4
# # @lc app=leetcode id=536 lang=python3 # # [536] Construct Binary Tree from String # # @lc code=start # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def str2tree(self, s: str) -> TreeNode: if not s: return None stack,number=[],'' for c in s: if c in '()': if c=='(' and number: stack.append(TreeNode(number)) number='' elif c==')': if number: node,parent=TreeNode(number),stack[-1] number='' else: node,parent=stack.pop(),stack[-1] if parent.left: parent.right=node else: parent.left=node else: number+=c if number: stack=[TreeNode(number)] return stack[0] # @lc code=end
611383d0a30acdb4f0b6d11784c3ff2301c3ebab
Paulinakhew/project_euler_solns
/2_even_fibonacci_numbers.py
682
3.90625
4
#!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n = int(input().strip()) #assign values to the first two numbers in the sequence num1 = 1 num2 = 1 sum = 0 # x is a placeholder that is used to represent the next number in the sequence x = 0 while x <= n: x = num1 + num2 #assign value of the sum of the two previous numbers to x num1 = num2 num2 = x if x > n: #checks whether or not we have exceeded the value of the inputted number break if x % 2 == 0: #checks whether or not x is divisible by 2 sum += x #print the sum to the console print(sum)
39f66dd9587235dd4ea11d0b3a445517d355c5d9
Baron197/Fundamental_Python_DS_4
/meanMedianModus.py
1,231
3.71875
4
from math import floor x = [ 1,2,3,2,5,2,7,2 ] # function mean def getMean(list) : sum = 0 for item in list : sum += item mean = sum / len(list) return mean print(getMean(x)) # function median def getMedian(list) : list.sort() median = 0 if (len(list) % 2 != 0) : median = list[floor(len(list) / 2)] else : mid1 = list[(int(len(list) / 2)) - 1] mid2 = list[int(len(list) / 2)] median = (mid1 + mid2) / 2 return median print(getMedian(x)) # function mode def getMode(list) : countDictionary = {} # create countDictionary for num in list : if(num in countDictionary.keys()) : countDictionary[num] += 1 else : countDictionary[num] = 1 # create list of mode/s maxFrequency = 1 modes = [] for key in countDictionary : if (countDictionary[key] > maxFrequency) : modes = [key] maxFrequency = countDictionary[key] elif (countDictionary[key] == maxFrequency) : modes.append(key) # if every value appears same amount of times if (len(modes) == len(countDictionary.keys())) : modes = [] return modes print(getMode(x))
54b8d4b935706ef4d002d867cbae49cabd913802
Python-Repository-Hub/image_processing_with_python
/01_pillow_basics/save_image_with_new_dpi.py
339
3.546875
4
# save_image_with_new_dpi.py import pathlib from PIL import Image def image_converter(input_file_path, output_file_path, dpi): image = Image.open(input_file_path) image.save(output_file_path, dpi=dpi) if __name__ == "__main__": image_converter("blue_flowers.jpg", "blue_flowers_dpi.jpg", dpi=(72, 72))
a37153363ffde178fc657284447ed4c3d2de06a0
Splinter0/HelloWorld
/queue/nodeQueue.py
1,077
3.796875
4
class Node(object): def __init__(self, value): self.value = value self.next = None class LinkedQ(object): def __init__(self): self.first = None self.last = None def enqueue(self, value): n = Node(value) if self.first == None: self.first = n self.last = n else : self.last.next = n self.last = n def dequeue(self): n = self.first self.first = self.first.next return n.value def isEmpty(self): return self.first == None def insert(self, value, index): new = Node(value) n = self.first for i in range(index-1): n = n.next new.next = n.next n.next = new def __str__(self): string = "" n = self.first while True: string = string+str(n.value)+" " n = n.next if n == None : break return string q = LinkedQ() q.enqueue(2) q.enqueue(4) q.enqueue(6) print(q) q.insert(5, 1) print(q)
5e3a61031a1dbad713f9631f8e1b864af3126831
rinleit/hackerrank-solutions
/Interview Preparation Kit/Recursion and Backtracking/Recursion: Fibonacci Numbers/solutions.py
161
4
4
def fibonacci(n): prev, next = 0, 1 for _ in range(2, n + 1): next, prev = prev + next, next return next n = int(input()) print(fibonacci(n))
2c9194997d3def052890d080174a929bff7704d5
muminurrahman/PythonExercises
/adjacentElementsProduct.py
283
3.921875
4
def adjacentElementsProduct(*nums): largest = nums[0] * nums[1]; for i in range(1, len(nums) - 1): product = nums[i] * nums[i + 1]; if product > largest: largest = product; return largest; print(adjacentElementsProduct(3, 6, -2, -5, 7, 3))
a07af7c39d9d18070f97983e3f5409fddc9987b6
prem-banker/Hackerrank-Questions
/encryption.py
422
3.625
4
import math string = raw_input() rows = math.floor(math.sqrt(len(string))) columns = math.ceil(math.sqrt(len(string))) encrypt = [] for i in range(int(rows)+1): encrypt.append("") for i in range(int(rows)+1): for j in range(len(string)): if i == j%columns: encrypt[i]+=string[j] output = "" for items in encrypt : output+= items + " " print(output)
a6626827bb23d5dbb3757f959a15a7f752653b94
GiacomoManzoli/SudokuGenerator
/search/astar_search.py
3,111
3.84375
4
from search import Problem, Node from util import PriorityQueue class AStarSearch(object): def __memoize(self, fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn def __best_first_graph_search(self, problem, f): """Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have breadth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned.""" f = self.__memoize(f, 'f') node = Node(problem.initial) assert node != None and node.state != None if problem.goal_test(node.state): return node frontier = PriorityQueue(min, f) frontier.append(node) explored = set() step = 0 while frontier: step+=1 node = frontier.pop() assert node != None and node.state != None, "Estratto un nodo None" #print '---- CURRENT NODE ----' #print node.state if problem.goal_test(node.state): return node, len(explored)+1 explored.add(node.state) for child in node.expand(problem): assert child != None and child.state != None if child.state not in explored and child not in frontier: frontier.append(child) elif child in frontier: incumbent = frontier[child] if f(child) < f(incumbent): del frontier[incumbent] frontier.append(child) return None def search(self, problem, h=None): """A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search, or else in your Problem subclass.""" h = self.__memoize(h or problem.h, 'h') def heuristic(n): v = h(n) return n.path_cost + v return self.__best_first_graph_search(problem, heuristic)
17166f2deed8fe8e1b0527d65a569150d69f0a47
z-sector/algo
/05/sorting/init.py
537
3.671875
4
import argparse def init_argparse() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Sorting array") parser.add_argument("len", type=int, help="Length array N >= 0") parser.add_argument("array", type=str, help="Array like 1,2,3,4,5") return parser def get_array(): parser = init_argparse() args = parser.parse_args() arr_len: int = args.len array: list = list(map(int, args.array.split(","))) return array def print_result(arr): print(",".join(str(x) for x in arr))
537059932cb0f1a4e0e51a2cd949cac28a67065a
crudalex/microsoft-r
/leetcode/Accepted/Implement_strStr.py
443
3.5
4
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 try: index = haystack.index(needle) except ValueError: index = -1 return index if __name__ == '__main__': s1 = Solution().strStr("hello", "ll") s2 = Solution().strStr("aaaaa", "bba")
289786549752464777b58ec7349bb0fa0e00449e
Ekaterina01703/dz.python
/z4/matrix8.py
375
3.734375
4
#Matrix8 import random import numpy A = random.randrange(2,6) M = random.randrange(2,6) K = random.randrange(0,M) print("A = ",A,"; M = ",M,"; K = ",K) a = numpy.zeros((A, M)) for i in range(A): for j in range(M): a[i][j] = random.randrange(-5,5) print(a) print("Столбец ",K,": ") for i in range(A): print(a[i][K],end="; ") print()
a5e727e115ca467d1faa1bc0cb1c02614bb84813
aungnyeinchan351/Searching_algorithms
/JumpSearch.py
554
4
4
def JumpSearch(list1, val): import math gap = math.sqrt(len(list1)) left = 0 while(list1[int(min(gap, len(list1))-1)]<val): left = gap gap = gap + math.sqrt(len(list1)) if(left>=len(list1)): break while(list1[int(left)]<val): left =left + 1 if(left== min(gap, len(list1))): break if(list1[int(left)]==val): return int(left) arr = [1,2,6,7,8,10] searchitem = 8 result = JumpSearch(arr,searchitem) print("{} is found at index of {}".format(searchitem, result))
908ba7770e6aeaad0119f4dd4061a2ecd7805893
zasdaym/daily-coding-problem
/problem-076/solution.py
800
3.671875
4
from typing import List, Set def min_col_to_delete(matrix: List[str]) -> int: # edge case if not matrix: return 0 col_to_delete = 0 row_len, col_len = len(matrix), len(matrix[0]) # check every col for unordered letters. for j in range(0, col_len): largest = matrix[0][j] for i in range(1, row_len): curr = matrix[i][j] if curr < largest: col_to_delete += 1 break largest = curr return col_to_delete tests = [ [ "cba", "daf", "ghi" ], [ "abcdef" ], [ "zyx", "wvu", "tsr" ] ] expected_values = [1, 0, 3] for i in range(len(tests)): assert min_col_to_delete(tests[i]) == expected_values[i]
b951f970887181fe8333a44ec6e4fe7a448eefea
fuckgitb/Python-1
/projects/Thread/demo01.py
941
4
4
import time import threading # 传统的写法 # def coding(): # for x in range(3): # print('正在写代码%s'%x) # time.sleep(1) # # # def drawing(): # for x in range(3): # print('正在画图%s' % x) # time.sleep(1) # 多线程的写法 def coding(): for x in range(3): print('正在写代码%s' % threading.current_thread()) time.sleep(1) def drawing(): for x in range(3): print('正在画图%s' % threading.current_thread()) time.sleep(1) def main(): # 创建子线程(指定函数执行,加圆括号是返回值) t1 = threading.Thread(target=coding) t2 = threading.Thread(target=drawing) t1.start() t2.start() # 查看进程中的线程数 print(threading.enumerate()) # 查看进程中的线程名 threading.current_thread() if __name__ == '__main__': main()
2a2502917784eea402234cdb0b8fd448625e049f
supramolecular-toolkit/stk
/src/stk/ea/fitness_calculators/property_vector.py
9,814
3.546875
4
""" Property Vector =============== """ from .fitness_calculator import FitnessCalculator class PropertyVector(FitnessCalculator): """ Uses multiple molecular properties as a fitness value. Examples -------- *Calculating Fitness Values* .. testcode:: calculating-fitness-values import stk # First, create the functions which calculate the properties # of molecules. def get_num_atoms(molecule): return molecule.get_num_atoms() def get_num_bonds(molecule): return molecule.get_num_bonds() def get_diameter(molecule): return molecule.get_maximum_diameter() # Next, create the fitness calculator. fitness_calculator = stk.PropertyVector( property_functions=( get_num_atoms, get_num_bonds, get_diameter, ), ) # Calculate the fitness value of a molecule. # "value" is a tuple, holding the number of atoms, number of # bonds and the diameter of the molecule. value = fitness_calculator.get_fitness_value( molecule=stk.BuildingBlock('BrCCBr'), ) .. testcode:: calculating-fitness-values :hide: _bb = stk.BuildingBlock('BrCCBr') assert value == ( _bb.get_num_atoms(), _bb.get_num_bonds(), _bb.get_maximum_diameter(), ) *Storing Fitness Values in a Database* Sometimes you want to store fitness values in a database, you can do this by providing the `output_database` parameter. .. testsetup:: storing-fitness-values-in-a-database import stk # Change the database used, so that when a developer # runs the doctests locally, their "stk" database is not # contaminated. _test_database = '_stk_doctest_database' _old_init = stk.ValueMongoDb stk.ValueMongoDb = lambda mongo_client, collection: ( _old_init( mongo_client=mongo_client, database=_test_database, collection=collection, ) ) # Change the database MongoClient will connect to. import os import pymongo _mongo_client = pymongo.MongoClient _mongodb_uri = os.environ.get( 'MONGODB_URI', 'mongodb://localhost:27017/' ) pymongo.MongoClient = lambda: _mongo_client(_mongodb_uri) .. testcode:: storing-fitness-values-in-a-database import stk import pymongo # Create a database which stores the fitness value of each # molecule. fitness_db = stk.ValueMongoDb( # This connects to a local database - so make sure you have # local MongoDB server running. You can also connect to # a remote MongoDB with MongoClient(), read to pymongo # docs to see how to do that. mongo_client=pymongo.MongoClient(), collection='fitness_values', ) # Define the functions which calculate molecular properties. def get_num_atoms(molecule): return molecule.get_num_atoms() def get_num_bonds(molecule): return molecule.get_num_bonds() def get_diameter(molecule): return molecule.get_maximum_diameter() # Create the fitness calculator. fitness_calculator = stk.PropertyVector( property_functions=( get_num_atoms, get_num_bonds, get_diameter, ), output_database=fitness_db, ) # Calculate fitness values. value1 = fitness_calculator.get_fitness_value( molecule=stk.BuildingBlock('BrCCBr'), ) # You can retrieve the fitness values from the database. value2 = fitness_db.get(stk.BuildingBlock('BrCCBr')) .. testcode:: storing-fitness-values-in-a-database :hide: assert value1 == tuple(value2) .. testcleanup:: storing-fitness-values-in-a-database stk.ValueMongoDb = _old_init pymongo.MongoClient().drop_database(_test_database) pymongo.MongoClient = _mongo_client *Caching Fitness Values* Usually, if you calculate the fitness value of a molecule, you do not want to re-calculate it, because this may be expensive, and the fitness value is going to be the same anyway. By using the `input_database` parameter, together with the `output_database` parameter, you can make sure you store and retrieve calculated fitness values instead of repeating the same calculation multiple times. The `input_database` is checked before a calculation happens, to see if the value already exists, while the `output_database` has the calculated fitness value deposited into it. .. testsetup:: caching-fitness-values import stk # Change the database used, so that when a developer # runs the doctests locally, their "stk" database is not # contaminated. _test_database = '_stk_doctest_database' _old_init = stk.ValueMongoDb stk.ValueMongoDb = lambda mongo_client, collection: ( _old_init( mongo_client=mongo_client, database=_test_database, collection=collection, ) ) # Change the database MongoClient will connect to. import os import pymongo _mongo_client = pymongo.MongoClient _mongodb_uri = os.environ.get( 'MONGODB_URI', 'mongodb://localhost:27017/' ) pymongo.MongoClient = lambda: _mongo_client(_mongodb_uri) .. testcode:: caching-fitness-values import stk import pymongo # You can use the same database for both the input_database # and output_database parameters. fitness_db = stk.ValueMongoDb( # This connects to a local database - so make sure you have # local MongoDB server running. You can also connect to # a remote MongoDB with MongoClient(), read to pymongo # docs to see how to do that. mongo_client=pymongo.MongoClient(), collection='fitness_values', ) # Define the functions which calculate molecular properties. def get_num_atoms(molecule): return molecule.get_num_atoms() def get_num_bonds(molecule): return molecule.get_num_bonds() def get_diameter(molecule): return molecule.get_maximum_diameter() # Create the fitness calculator. fitness_calculator = stk.PropertyVector( property_functions=( get_num_atoms, get_num_bonds, get_diameter, ), input_database=fitness_db, output_database=fitness_db, ) # Assuming that a fitness value for this molecule was not # deposited into the database in a previous session, this # will calculate the fitness value. value1 = fitness_calculator.get_fitness_value( molecule=stk.BuildingBlock('BrCCBr'), ) # This will not re-calculate the fitness value, instead, # value1 will be retrieved from the database. value2 = fitness_calculator.get_fitness_value( molecule=stk.BuildingBlock('BrCCBr'), ) .. testcode:: caching-fitness-values :hide: value3 = fitness_calculator.get_fitness_value( molecule=stk.BuildingBlock('BrCCBr'), ) assert value2 is value3 .. testcleanup:: caching-fitness-values stk.ValueMongoDb = _old_init pymongo.MongoClient().drop_database(_test_database) pymongo.MongoClient = _mongo_client """ def __init__( self, property_functions, input_database=None, output_database=None, ): """ Initialize a :class:`.PropertyVector` instance. Parameters ---------- property_functions: :class:`tuple` of :class:`callable` A group of :class:`function`, each of which is used to calculate a single property of the molecule. Each function must take one parameter, `mol`, which accepts a :class:`.Molecule` object. This is the molecule used to calculate the property. input_database : :class:`.ValueDatabase`, optional A database to check before calling `fitness_function`. If a fitness value exists for a molecule in the database, the stored value is returned, instead of calling `fitness_function`. output_database : :class:`.ValueDatabase`, optional A database into which the calculate fitness value is placed. """ self._property_functions = property_functions self._input_database = input_database self._output_database = output_database def get_fitness_value(self, molecule): if self._input_database is not None: try: fitness_value = self._input_database.get(molecule) except KeyError: fitness_value = tuple( property_function(molecule) for property_function in self._property_functions ) else: fitness_value = tuple( property_function(molecule) for property_function in self._property_functions ) if self._output_database is not None: self._output_database.put(molecule, fitness_value) return fitness_value
293e0c1bbf6760ef7bc6ef8dd9ff2b7bd35ca292
github-felipe/ExerciciosEmPython-cursoemvideo
/PythonExercicios/ex038.py
267
3.875
4
n = str(input('Digite dois números: ')).strip() n = n.split() n1 = int(n[0]) n2 = int(n[1]) if n1 > n2: print('O PRIMEIRO número é maior') elif n2 > n1: print('O SEGUNDO número é maior') else: print('Não existe número maior, os dois são iguais!')
ac14452ddf91492ed3177d3f1cc386b2d1146aea
hajmat02/prog1-ovn
/kap2/upg2.7.py
366
3.859375
4
import math #gör så att man kan skriva mattematiska saker på ett enkelt sätt #ett program som räknar ut en cirkels area och omkrets svar = input ('Cirkelns radie:') r = float(svar) a = r*r * math.pi #räknar ut arean på cirkeln b = (r+r) * math.pi #räknar ut omkretsen på cirkeln print(f'Cirkelns area är:{a:.3f}') print(f'Cirkelns omkrets är:{b:.3f}')
08b859351687fe3a43a617ed61438ed6e95aa5d0
bm5w/sea-f2-python-sept14
/Students/JakeAnderson/session02/series.py
848
4.0625
4
# coding: utf-8 #series program """ runs the Fibonacci series """ def Fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: return Fibonacci(n - 1) + Fibonacci(n - 2) """ runs the Lucas series """ def Lucas(n): if n <= 0: return 0 elif n == 1: return 2 elif n == 2: return 1 else: return Lucas(n - 1) + Lucas(n - 2) """ runs the nth number series """ def sum_series(n, n0 = 0, n1 = 1): if n < 0: return 0 elif n == 0: return n0 elif n == 1: return n1 else: return sum_series(n - 1, n0, n1) + sum_series(n - 2, n0, n1) if __name__ =="__main__": Fib = [0,1,1,2,3,5,8,13] Luc = [0,2,1,3,4,7,11,18] for n, (exf, exl) in enumerate(zip(Fib,Luc)): #print exf, exl assert Fibonacci(n) == exf assert Lucas(n) == exl print sum_series(n) assert Fibonacci(n) == sum_series(n) print "All tests pass"
915abf0266e543f202b41af751e0879201be1326
Kirkirillka/network_aggregator
/utils.py
3,337
3.5625
4
import re import ipaddress def validate_net_data(net_data): """ # A function to check if supplied net_data meets model's requirement. Thus net_data must be a dict with specified fields Examples of net_data: net_data1 = { "value": "192.168.34.4", "type": "host" } net_data2 = { "value": "192.168.34.0/24", "type": "network" } net_data3 = { "value": "192.168.34.4", "type": "host", "os": "Linux", "ports": [21, 22, 80 ,443] } :param net_data: a dict with specified fields . :return: True if net_data has required fields and they are in valid formats otherwise False. """ # These fields must be in supplied net_data required_fields = ['value', 'type'] # Extra fields are needed to just help remember what fields can be there in applied data extra_fields = ['os', 'ports', 'users', 'supernet'] # Supplied data must be in dictionary form if not isinstance(net_data, dict): return False # Check whether supplied dictionary has all required fields if not all(field in net_data for field in required_fields): return False return True def is_addr(addr): """ Checks if supplied string is valid host address. Can be both 192.168.0.23 or 192.168.0.23/32 (CIDR format). Only IPv4 right now. :param addr: a string represented a host address. :return: True if a string is valid host address otherwise false. """ # It should be better to insert several patterns for both IPv4/IPv6. # Although, I haven't enough time I have put only pattern for x.x.x.x/24 IPv4 networks patterns = [r'^(\d{1,3}).(\d{1,3}).(\d{1,3}).(\d{1,3})(\/32)?$'] if any(re.match(pattern, addr) for pattern in patterns): return True return False def is_network(net): """ Checks if supplied string is valid CIDR network address (only IPv4). :param net: a string to validate CIDR format. :return: True if a given string is a valid CIDR network address otherwise False. """ # It should be better to insert several patterns for both IPv4/IPv6. # Although, I haven't enough time I have put only pattern for x.x.x.x/24 IPv4 networks patterns = [r'^(\d{1,3}).(\d{1,3}).(\d{1,3}).(\d{1,3})\/([1-3]?[0-9]?)$'] if any(re.match(pattern, net) for pattern in patterns): return True return False def is_supernet(net, supernet): """ Checks for given net that it's overlapped by supplied supernet, e.g. 192.168.13.0/25 is subnet of 192.168.13.0/24. Both net and supernet must be given in CIDR format (IPv4 only). :param net: a string represented network address in CIDR format to validate it's overlapped by supernet. :param supernet: a string represented network address in CIDR format which mask prefix is less than a given one. :return: True if net is overlapped by supernet, e.g net is a subnet of supernet. """ if not (is_network(net) and is_network(supernet)): return False foo = ipaddress.ip_network(net) bar = ipaddress.ip_network(supernet) return foo.overlaps(bar)
8eb9e9de2a571d1f98b23ee1596343abb28acb2b
Adi-Levy/TechAVSFControl
/pure_pursuit/controller.py
3,685
3.5625
4
import math import numpy as np class PurePursuitController: """ this a class to define a controller object of a pure pursuite controller the controller gets the current state of the car(x,y coordinates, velocity and current angle), the currnet path that the car should follow and then calculates the steering angle requiered to course correct according to the car's velocity in order to update the data in the controller it's update methods need to be called. """ path = None coordinates = [] orientation = 0 velocity = 0 _car_length = 0 _max_steering_angle = 0 # based on vehicle data and physical limits _kdd = 1 # ld=kdd*v, ld=lookahead distance _poly_fit_deg = 3 def __init__(self, car_length, kdd, max_steering_angle, poly_fit_deg): # initializes the controller and sets the initial values self._car_length = car_length self._kdd = kdd self._max_steering_angle = max_steering_angle self._poly_fit_deg = poly_fit_deg def update_state(self, x, y, v, orientation): # update the current state of the car in the controller for calculations self.coordinates = [x, y] self.velocity = v self.orientation = orientation def update_path(self, path): # update the path for the controller for calculations self.path = path def calculate_steering(self): # calc the needed steering angle to course correct to the next waypoint look_ahead_point = self._calculate_look_ahead_point() alpha = math.atan2(look_ahead_point[1] - self.coordinates[1], look_ahead_point[0] - self.coordinates[0]) - self.orientation # error angle delta = math.atan2(2*self._car_length*math.sin(alpha), self._point_distance(look_ahead_point)) return max(delta, -self._max_steering_angle) if (delta < 0) else min(delta, self._max_steering_angle) def _calculate_look_ahead_point(self): ld = self.velocity * self._kdd near_point_index = self._find_near_point_index() swapped_axis_path = np.swapaxes(self.path[max(near_point_index-4, 0):min(near_point_index+4, len(self.path)-1)], 0 , 1) p = np.poly1d(np.polyfit(swapped_axis_path[0], swapped_axis_path[1], self._poly_fit_deg)) point_index = self._target_point_index(swapped_axis_path[0][near_point_index:], swapped_axis_path[1][near_point_index:], ld) x_sector = np.linspace(self.path[(near_point_index+point_index-1)[0]], self.path[near_point_index+point_index[0]], 5) y_sector = np.polyval(p, x_sector) point_index = self._target_point_index(x_sector, y_sector, ld) return [x_sector[point_index], y_sector[point_index]] def _find_near_point_index(self): near_point = [self.path[0]] near_point_distance = self._point_distance(near_point) for way_point in self.path: way_point_distance = self._point_distance(way_point) if (near_point_distance > way_point_distance): near_point = way_point near_point_distance = self._point_distance(near_point) return self.path.index(near_point) def _point_distance(self, point): return math.sqrt((self.coordinates[0] - point[0])**2 + (self.coordinates[1] - point[1])**2) def _target_point_index(self, x_vector, y_vector, distance): for point_index in range(len(x_vector)): if(self._point_distance([x_vector[point_index], y_vector[point_index]]) > distance): return point_index return (len(x_vector)-1)
91c070223352202f5383aa87a832c367040a6dbc
markkorenic/mayaTools
/Maya/System/Example.py
2,481
4.6875
5
""" Comments are used to provide descriptions or notes in your code. You can make large blocks of comments by surrounding your text in sets of 3 quotation marks. """ # You can also use the pound sign. """ A Variable is used to store data. In this case 'h' is the varaible to which we assign the value of the string 'Hello' """ h = 'Hello' print h """ Variables can hold any data types. For instance, a variable can hold a list. A list is just like a grocery list. In this example we will use a list of numbers also know as integers. """ l = (1, 2, 3) print l """ If we wanted to print every number in our 'l' list, we need to use a loop. In this example we will use a for loop. """ for each in l: print each """ Each item in a list can also be viewed as the 'index number' of that list So on a grocery list you would have item 1: Milk, item 2: Bread, and item 3: Eggs. Python starts with 0 instead of 1. """ grocery_list = ('Milk', 'Bread', 'Eggs') """ We can use a differnt type of loop to know the number associated with each item on the list. First lets look at len. Len means length. """ #This will tell us that we have 3 items in grocery_list. print len(grocery_list) # The number of items in a list is also called range. # So to do something for each item in the range of the # length of grocery list we can do this. for index in range(len(grocery_list)): print index # This will print the current items index number. """ If we want to find out if the current item is Milk, we can use a condition. """ if grocery_list[index] == 'Milk': print grocery_list[index] """ If you want to pick a paticular item from a list you can refer to it's index number like this """ print grocery_list[2] """ Python has many different libraries to handle all sorts of functions. For instance we can import Python's date and time library to get the time. """ import datetime print datetime.datetime.now() """ The same thing applies for maya commands. In Maya Python serves as a wrapper for mel commands. To use those commands we need to import that library into Maya. When we import that library we will assign it to a variable called "cmds". """ import maya.cmds as cmds """ Now if we want to use a maya command, we can call on it like this """ cmds.joint() """ Maya commands have 'flags', Flags can be used to modify or query a command. Lets name our joint and place it somewhere in our scene. """ cmds.joint(name='MyJoint', position=['1.0', '2.0', '0.0'])
0740c99ca584a935b919081e1238b2acc780d74c
PeshrawSarwar/GIZ-pass-python
/python-pass.py
1,065
3.765625
4
class Solution(object): @staticmethod def longest_palindromic(s: str): # Square Matrix - length = length of the string [False] matrix = [[False for i in range(len(s))] for i in range(len(s))] for i in range(len(s)): # major diagonal elements = True matrix[i][i] = True max_length = 1 start = 0 # 2 to length of s+1 for l in range(2,len(s)+1): # 0 to to length of s-1+1 for i in range(len(s)-l+1): end = i+l if l==2: if s[i] == s[end-1]: matrix[i][end-1]=True max_length = l start = i else: if s[i] == s[end-1] and matrix[i+1][end-2]: matrix[i][end-1]=True max_length = l start = i return s[start:start+max_length] ob = Solution() print(ob.longest_palindromic("lagalabcdnananana")) # Output -> ananana
e0673e5ac586c1d357a14a36818e6058f7926529
nobodyh/Project-Euler
/6. Sum Square Difference.py
304
3.890625
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 30 14:14:26 2021 @author: Hayagreev """ import numpy as np n=int(input("Enter the limit:")) result = np.subtract(np.power(np.divide(np.multiply(n,n+1),2),2),np.divide(np.multiply(n,np.multiply(n+1,2*n+1)),6)) print("Result: ",result)
73f2e36f7df9365c97bd4dec5357320ef69de894
hoyeonkim795/solving
/swexpert/LinkedList_again.py
2,856
3.765625
4
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return str(self.data) class linkedlist: def __init__(self, *args): self.length = 0 if args: for i in range(len(args)): if i == 0: self.head = Node(args[i]) temphead = self.head else: temphead.next = Node(args[i]) temphead = temphead.next self.length += 1 else: self.head = None def append(self, data): if not self.head: self.head = Node(data) else: temphead = self.head while temphead.next: temphead = temphead.next temphead.next = Node(data) self.length += 1 def insert(self, idx, data): if abs(idx) >= self.length: if idx >= 0: idx = self.length else: idx = -self.length if idx == 0 or -idx == self.length: temphead = self.head self.head = Node(data) self.head.next = temphead else: prevhead = self.get(idx-1) targethead = prevhead.next prevhead.next = Node(data) prevhead.next.next = targethead self.length += 1 def pop(self, idx=None): if not self.head: raise IndexError('pop from empty list') else: if idx != None: if abs(idx) > self.length or idx == self.length: raise IndexError('pop index out of range') elif idx == 0 or -idx == self.length: popnode = self.head self.head = self.head.next else: prevhead = self.get(idx-1) popnode = prevhead.next targethead_next = popnode.next prevhead.next = targethead_next else: if self.head.next == None: popnode = self.node self.head = None else: prevhead = self.get(self.length-2) popnode = prevhead.next prevhead.next = None self.length -= 1 return popnode def get(self, idx): if abs(idx) > self.length or idx == self.length: raise IndexError('list index out of range') elif idx < 0: idx -= -self.length temphead = self.head for i in range(idx): temphead = temphead.next return temphead def __repr__(self): string = [] temphead = self.head while temphead: string.append(temphead.data) temphead = temphead.next return str(string)
45c71efc6be8ff112b3ccd969b1e40a3f4318873
yeeyoung/CS-590-Data-Engineering-II
/hw1/solution.py
3,064
3.765625
4
#!/Users/yeeyoung/anaconda/bin/python import sqlite3 import csv # Open connection to the SQLite database file con = sqlite3.connect("air.db") # Create a cursor that will return an instance of the database for data set traversal cur = con.cursor() # Read the csv file and begin parsing it with open('flights.csv', 'r') as flights_table: dr = csv.DictReader(flights_table, delimiter=',') to_db = [(i['YEAR'], i['MONTH'], i['DAY_OF_MONTH'], i["DAY_OF_WEEK"], i["OP_UNIQUE_CARRIER"], i["TAIL_NUM"], i["OP_CARRIER_FL_NUM"], i["ORIGIN_AIRPORT_ID"], i["DEST_AIRPORT_ID"], i["CRS_DEP_TIME"], i["DEP_TIME"], i["DEP_DELAY"], i["CRS_ARR_TIME"], i["ARR_TIME"], i["ARR_DELAY"], i["CANCELLED"], i["CANCELLATION_CODE"], i["CRS_ELAPSED_TIME"], i["ACTUAL_ELAPSED_TIME"], i["AIR_TIME"], i["DISTANCE"], i["CARRIER_DELAY"], i["WEATHER_DELAY"], i["NAS_DELAY"], i["SECURITY_DELAY"], i["LATE_AIRCRAFT_DELAY"]) for i in dr] print(to_db[0]) print(to_db[1]) cur.execute("DROP TABLE IF EXISTS flights;") # Create tables in the SQLite database cur.execute("CREATE TABLE flights (YEAR number, MONTH number, DAY_OF_MONTH number, DAY_OF_WEEK number, OP_UNIQUE_CARRIER number, TAIL_NUM number, OP_CARRIER_FL_NUM number, ORIGIN_AIRPORT_ID number, DEST_AIRPORT_ID number, CRS_DEP_TIME number, DEP_TIME number, DEP_DELAY number, CRS_ARR_TIME number, ARR_TIME number, ARR_DELAY number, CANCELLED number, CANCELLATION_CODE number, CRS_ELAPSED_TIME number, ACTUAL_ELAPSED_TIME number, AIR_TIME number, DISTANCE number, CARRIER_DELAY number, WEATHER_DELAY number, NAS_DELAY number, SECURITY_DELAY number, LATE_AIRCRAFT_DELAY number);") # Insert all parameter sequences to the table cur.executemany("INSERT INTO flights VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", to_db) # Select Year from Table flights with open('airlines.csv', 'r') as airlines_table: dr = csv.DictReader(airlines_table, delimiter=',') to_db1 = [(i['OP_UNIQUE_CARRIER'], i['FULL_OP_UNIQUE_CARRIER']) for i in dr] print(to_db1[0]) print(to_db1[1]) cur.execute("DROP TABLE IF EXISTS airlines;") cur.execute("CREATE TABLE airlines (OP_UNIQUE_CARRIER text, FULL_OP_UNIQUE_CARRIER text);") cur.executemany("INSERT INTO airlines VALUES(?,?);", to_db1) with open('airports.csv', 'r') as airports_table: dr = csv.DictReader(airports_table, delimiter=',') to_db2 = [(i['AIRPORT_ID'], i['FULL_AIRPORT_ID']) for i in dr] print(to_db2[0]) print(to_db2[1]) cur.execute("DROP TABLE IF EXISTS airports;") cur.execute("CREATE TABLE airports (AIRPORT_ID number, FULL_AIRPORT_ID text);") cur.executemany("INSERT INTO airports VALUES(?,?);", to_db2) with open('cancellations.csv', 'r') as cancellations_table: dr = csv.DictReader(cancellations_table, delimiter=',') to_db3 = [(i['CODE'], i['CODE_DESCRIPTION']) for i in dr] print(to_db3[0]) print(to_db3[1]) cur.execute("DROP TABLE IF EXISTS cancellations;") cur.execute("CREATE TABLE cancellations (CODE text, CODE_DESCRIPTION text);") cur.executemany("INSERT INTO cancellations VALUES(?,?);", to_db3) con.commit()
2e183afcfa1bceb67cb16a5f6c0593fda7114e55
DaCanneAPeche/crypto-coins
/cryppy_coins/__init__.py
1,735
3.5
4
# import request and json for use API import requests import json # url start basic_api_url = 'https://api.coincap.io/v2' # function for get data of a request def return_data(end_url='/assets'): data = requests.get(f'{basic_api_url}{end_url}') return json.loads(data.text) # get the 100 more expensive crypto-moneys in order of rank def get_top_list(): data = return_data() rank = [] for crypto in data['data']: rank.append(crypto['id']) return rank # get the name of a money by the rank def get_money_by_rank(rank=1): return get_top_list()[rank - 1] # get the rank of a money def get_rank_by_money(money='bitcoin'): try: return get_top_list().index(money) + 1 except: return 'not existing' # get the info of a money def get_money_info(money_name='bitcoin'): return return_data(f'/assets/{money_name}') # get the history of money, with interval (m1, m5, m15, m30 / h1, h2, h6, h12 / d1 ; m = month, h = hour, d = day) def get_history(money='bitcoin', interval='d1'): dictionary = {money: return_data(f'/assets/{money}/history?interval={interval}')} return dictionary # get markets of a money def get_markets(money='bitcoin'): dictionary = {money: return_data(f'/assets/{money}/markets')} return dictionary # get rates of a money or off all the moneys def get_rates(money=None): if money is None: return return_data('/rates') else: return return_data(f'/rates/{money}') # get get_exchanges of a money or off all the moneys def get_exchanges(money=None): if money is None: return return_data('/exchanges') else: return return_data(f'/exchanges/{money}') print(get_markets('bitcoin'))
820212a00edd69a141ca27509de6dee7dc57e9d8
joyonto51/Basic-Algorithm
/find_the_factorial.py
105
3.734375
4
n = int(input()) factorial = 1 i = 1 while(i<=n): factorial = factorial*i i+=1 print(factorial)
9c778ef6d160d097301e31a55b9fe3ba719e0985
paul-hohle/Python
/Python-Book/map.py
900
3.890625
4
#!/usr/bin/env python #********************************************************************* dict = {} dict['meat'] = 'carne' dict['arroz'] = 'rice' dict['frijoles'] = 'beans' dict['aqua'] = 'water' print dict nested = {'name' : { 'first' : 'bob', 'last' : 'smith'}, 'jobs' : [ 'dev' , 'manager' ], 'age' : 40.5, 'ss#' : 464984287, } nested['jobs'].append('medic') print nested # Checking for missing keys # Indent for multible lines if not 'key' in nested: print ('No such key') print ('Please add if needed') key=nested.get('key',0) print key key=nested['key'] if 'key' in nested else 0 print key keys=list(nested.keys()) keys.sort() print print keys print for key in keys: print(key,'-> ', nested[key]) print for key in sorted(nested): print(key,'-> ', nested[key]) # Delete and reclaim memory print nested =0 print nested
0bedbab2222153cfa802fa18319ae48282a417db
captainjack331089/Automate-Boring-Stuff-with-Python
/Python Programming/Practice/list_dictionary_practice.py
1,569
4
4
""" List to Dictionary Function for Fantasy Game Inventory Imagine that a vanquished dragon’s loot is represented as a list of strings like this: dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this: """ """ def addToInventory(inventory, addedItems): # your code goes here inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv) The previous program (with your displayInventory() function from the previous project) would output the following: Inventory: 45 gold coin 1 rope 1 ruby 1 dagger Total number of items: 48 """ from Dictionary_GameInventory import displayInventory def addToInventory(inventory, addedItems): for i in addedItems: if i not in inventory: inventory.setdefault(i,1) else: inventory[i] += 1 return inventory if __name__ == '__main__': inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(**inv)
fcccf0005a388eea2c33a55460b49bcec790fe05
uestcwm/search
/Sort/countsort.py
801
3.5
4
#! /usr/bin/env python #coding=utf-8 ''' 桶排序 复杂度O(n) ''' def countsort( A, d ): #A待排数组, d位数 如果位置需要先修改一下知道A中最多位数 for k in range(d): #k轮排序 s[ [] for i in range(10) ] #数字0~9,建10个桶 '''对于数组中的元素,首先按照最低有效数字进行 排序,然后由低位向高位进行''' for i in A: s[ i//(10**k)%10 ].append(i) A = [j for i in s for j in i] #977/10=97(小数舍去),87/100=0 return A from random import randint a = [randint(1,999) for i in range(10)] #产生10个随机3位数 a = countsort(a,3) print(a) [181, 263, 893, 705, 566, 727, 801, 310, 589, 783] #随机数 [181, 263, 310, 566, 589, 705, 727, 783, 801, 893] #排序后
0d9ea89f66cb678dbdecd81ac92bc5134a61959f
pawelbicz/exercism
/python/pangram/pangram_old.py
690
3.6875
4
import string as s def is_pangram(sentence): text = remove_punctuation(sentence) dictionary = create_dictionary() dictionary = assert_letters_in_sentence(text, dictionary) return verify_dictionary(dictionary) def remove_punctuation(text): result = '' for i in text: if i not in s.punctuation: result += i return result def create_dictionary(): d = {} for i in s.ascii_lowercase: d[i] = False return d def assert_letters_in_sentence(text, d): for i in text.lower(): d[i] = True return d def verify_dictionary(d): for i in d: if d[i] is False: return False return True
76e05d14bcb2d044ab3807fdccb5579b5423aef6
chrisjdavie/interview_practice
/leetcode/search_in_rotated_sorted_array/doubling_index.py
2,236
3.703125
4
# https://leetcode.com/problems/search-in-rotated-sorted-array/ """ First result, not sure why I did it like this, doubling indicies until I found the right one. Looking at other answers, the much more common way was starting from left and right and halving. Also a lot quicker than mine, which is interesting. I *know* this solution isn't one I came up with, I've seen it for a different something, but can't recall where. I don't know when I'd use one or another, either. """ import bisect import pytest class Solution: @staticmethod def _find_pivot_index(nums: list[int]) -> int: if len(nums) <= 1: # single length array return 0 if nums[0] < nums[-1]: # pivot is at zero, no need to search return 0 i_0: int = 0 i: int = 1 while True: if i_0 + i < len(nums) and nums[i_0] < nums[i_0+i]: i *= 2 else: i_0, i = i_0 + i//2, 1 if nums[i_0] > nums[i_0+i]: break return i_0 + 1 def search(self, nums: list[int], target: int) -> int: pivot_index: int = self._find_pivot_index(nums) i_candidate: int = 0 if target >= nums[0] and target <= nums[pivot_index-1]: i_candidate: int = bisect.bisect_left(nums, target, hi=pivot_index) if target >= nums[pivot_index] and target <= nums[-1]: i_candidate: int = bisect.bisect_left(nums, target, lo=pivot_index) if nums[i_candidate] == target: return i_candidate return -1 @pytest.mark.parametrize( "nums,pivot_index", ( ([0],0), ([0,1],0), ([4,1,2],1), ([3,4,1,2],2), ([3,4,5,0,1],3), ([4,5,6,7,0,1,2], 4), ([3,4,5,6,7,1], 5), ) ) def test__find_pivot_index(nums,pivot_index): assert Solution._find_pivot_index(nums) == pivot_index @pytest.mark.parametrize( "nums,target,expected_result", ( ([4,5,6,7,0,1,2],0,4), ([4,5,6,7,0,1,2],5,1), ([4,5,6,7,0,1,2],3,-1), ([1],0,-1) ) ) def test_leetcode(nums,target,expected_result): assert Solution().search(nums, target) == expected_result
4da29ccbabaef071935aa7f2824a2d9ee2c96f12
ShoYamanishi/PersonNamesTransliterator
/utils/character_converters.py
8,330
4.03125
4
# some string contain hard-to-find diacritical marks as # independent characters. # It is difficult to clean strings that contain such marks. # In those cases, we just remove them from the training set. def is_bad_word_alpha( word ): for c in word: # U+0300 - U+036F combining diacritical marks. if 768 <= ord(c) and ord(c) <= 879: return True elif c in bad_chars_alpha: return True return False # Generates a set of conversion rules for latin-based characters. # It lowers the case and convert the accented characters to [a-zç]. # e.g. # 'Ä' => 'ae' # We retain 'Ç' as is, as conerting to some character sequence like 'c' # will deteriorate the performance. def create_char_maps_alpha(): # Maps chars down to a-z, ç (27 chars) char_map = {} char_map['A'] = 'a' char_map['B'] = 'b' char_map['C'] = 'c' char_map['D'] = 'd' char_map['E'] = 'e' char_map['F'] = 'f' char_map['G'] = 'g' char_map['H'] = 'h' char_map['I'] = 'i' char_map['J'] = 'j' char_map['K'] = 'k' char_map['L'] = 'l' char_map['M'] = 'm' char_map['N'] = 'n' char_map['O'] = 'o' char_map['P'] = 'p' char_map['Q'] = 'q' char_map['R'] = 'r' char_map['S'] = 's' char_map['T'] = 't' char_map['U'] = 'u' char_map['V'] = 'v' char_map['W'] = 'w' char_map['X'] = 'x' char_map['Y'] = 'y' char_map['Z'] = 'z' char_map['a'] = 'a' char_map['b'] = 'b' char_map['c'] = 'c' char_map['d'] = 'd' char_map['e'] = 'e' char_map['f'] = 'f' char_map['g'] = 'g' char_map['h'] = 'h' char_map['i'] = 'i' char_map['j'] = 'j' char_map['k'] = 'k' char_map['l'] = 'l' char_map['m'] = 'm' char_map['n'] = 'n' char_map['o'] = 'o' char_map['p'] = 'p' char_map['q'] = 'q' char_map['r'] = 'r' char_map['s'] = 's' char_map['t'] = 't' char_map['u'] = 'u' char_map['v'] = 'v' char_map['w'] = 'w' char_map['x'] = 'x' char_map['y'] = 'y' char_map['z'] = 'z' char_map['À'] = 'a' char_map['Á'] = 'a' char_map['Â'] = 'a' char_map['Ä'] = 'ae' char_map['Å'] = 'aa' char_map['Æ'] = 'ae' char_map['Ç'] = 'ç' char_map['È'] = 'e' char_map['É'] = 'e' char_map['Í'] = 'i' char_map['Ï'] = 'i' char_map['Ò'] = 'o' char_map['Ó'] = 'o' char_map['Ö'] = 'oe' char_map['Ø'] = 'oe' char_map['Û'] = 'u' char_map['Ü'] = 'ue' char_map['Ý'] = 'y' char_map['ß'] = 'ss' char_map['à'] = 'a' char_map['á'] = 'a' char_map['â'] = 'a' char_map['ã'] = 'a' char_map['ä'] = 'ae' char_map['å'] = 'aa' char_map['æ'] = 'ae' char_map['ç'] = 'ç' char_map['è'] = 'e' char_map['é'] = 'e' char_map['ê'] = 'e' char_map['ë'] = 'e' char_map['ì'] = 'i' char_map['í'] = 'i' char_map['î'] = 'i' char_map['ï'] = 'i' char_map['ñ'] = 'nh' char_map['ò'] = 'o' char_map['ó'] = 'o' char_map['ô'] = 'o' char_map['õ'] = 'on' char_map['ö'] = 'oe' char_map['ø'] = 'oe' char_map['ù'] = 'u' char_map['ú'] = 'u' char_map['û'] = 'u' char_map['ü'] = 'ue' char_map['ý'] = 'y' char_map['ÿ'] = 'y' char_map['Ā'] = 'a' char_map['ā'] = 'a' char_map['Ć'] = 'ch' char_map['ć'] = 'ch' char_map['ĉ'] = 'c' char_map['Č'] = 'ch' char_map['č'] = 'ch' char_map['Ď'] = 'd' char_map['Ē'] = 'e' char_map['ē'] = 'e' char_map['ě'] = 'e' char_map['ĩ'] = 'i' char_map['Ī'] = 'i' char_map['ī'] = 'i' char_map['Ĭ'] = 'i' char_map['İ'] = 'i' char_map['ı'] = 'e' char_map['ķ'] = 'k' char_map['Ĺ'] = 'l' char_map['ĺ'] = 'l' char_map['Ł'] = 'l' char_map['ł'] = 'w' char_map['Ń'] = 'ny' char_map['ń'] = 'ny' char_map['ņ'] = 'n' char_map['ň'] = 'nh' char_map['Ō'] = 'o' char_map['ō'] = 'o' char_map['Ŏ'] = 'o' char_map['ő'] = 'e' char_map['œ'] = 'oe' char_map['ŕ'] = 'r' char_map['Ř'] = 'r' char_map['ř'] = 'zh' char_map['Ś'] = 'sh' char_map['ś'] = 'sh' char_map['Ş'] = 'sh' char_map['ş'] = 'sh' char_map['Š'] = 'sh' char_map['š'] = 'sh' char_map['ũ'] = 'u' char_map['ū'] = 'u' char_map['ŭ'] = 'u' char_map['ů'] = 'u' char_map['ű'] = 'u' char_map['ŵ'] = 'w' char_map['Ź'] = 'dj' char_map['ź'] = 'dj' char_map['Ż'] = 'j' char_map['ż'] = 'j' char_map['Ž'] = 'zh' char_map['ž'] = 'zh' char_map['ǎ'] = 'a' char_map['ǐ'] = 'i' char_map['ǧ'] = 'gh' char_map['ǰ'] = 'j' char_map['ǵ'] = 'gh' char_map['ǹ'] = 'nh' char_map['ș'] = 'sh' char_map['ț'] = 'ts' char_map['ȩ'] = 'e' char_map['ȳ'] = 'y' char_map['Ḅ'] = 'b' char_map['ḋ'] = 'd' char_map['Ḍ'] = 'd' char_map['ḍ'] = 'd' char_map['Ḏ'] = 'd' char_map['ḏ'] = 'd' char_map['Ḡ'] = 'g' char_map['Ḥ'] = 'h' char_map['ḥ'] = 'h' char_map['ḱ'] = 'ch' char_map['Ḳ'] = 'k' char_map['ḳ'] = 'k' char_map['Ḵ'] = 'k' char_map['ḵ'] = 'k' char_map['ḻ'] = 'l' char_map['Ḿ'] = 'm' char_map['ḿ'] = 'm' char_map['ṁ'] = 'm' char_map['ṃ'] = 'm' char_map['Ṅ'] = 'n' char_map['ṅ'] = 'n' char_map['ṇ'] = 'n' char_map['ṉ'] = 'n' char_map['ṕ'] = 'p' char_map['ṛ'] = 'r' char_map['ṟ'] = 'r' char_map['ṡ'] = 's' char_map['Ṣ'] = 's' char_map['ṣ'] = 's' char_map['ṫ'] = 't' char_map['Ṭ'] = 't' char_map['ṭ'] = 't' char_map['ṯ'] = 't' char_map['Ẓ'] = 'z' char_map['ẓ'] = 'z' char_map['ẖ'] = 'h' char_map['ạ'] = 'a' char_map['Ị'] = 'i' char_map['-'] = '' return char_map # Generates a set of conversion rules for Japanese Kanas. # It does two things: # 'ヮ' => 'ワ' # '・' => '' def create_char_maps_kana(): char_map = {} char_map['ァ'] = 'ァ' char_map['ア'] = 'ア' char_map['ィ'] = 'ィ' char_map['イ'] = 'イ' char_map['ゥ'] = 'ゥ' char_map['ウ'] = 'ウ' char_map['ェ'] = 'ェ' char_map['エ'] = 'エ' char_map['ォ'] = 'ォ' char_map['オ'] = 'オ' char_map['カ'] = 'カ' char_map['ガ'] = 'ガ' char_map['キ'] = 'キ' char_map['ギ'] = 'ギ' char_map['ク'] = 'ク' char_map['グ'] = 'グ' char_map['ケ'] = 'ケ' char_map['ゲ'] = 'ゲ' char_map['コ'] = 'コ' char_map['ゴ'] = 'ゴ' char_map['サ'] = 'サ' char_map['ザ'] = 'ザ' char_map['シ'] = 'シ' char_map['ジ'] = 'ジ' char_map['ス'] = 'ス' char_map['ズ'] = 'ズ' char_map['セ'] = 'セ' char_map['ゼ'] = 'ゼ' char_map['ソ'] = 'ソ' char_map['ゾ'] = 'ゾ' char_map['タ'] = 'タ' char_map['ダ'] = 'ダ' char_map['チ'] = 'チ' char_map['ッ'] = 'ッ' char_map['ツ'] = 'ツ' char_map['テ'] = 'テ' char_map['デ'] = 'デ' char_map['ト'] = 'ト' char_map['ド'] = 'ド' char_map['ナ'] = 'ナ' char_map['ニ'] = 'ニ' char_map['ヌ'] = 'ヌ' char_map['ネ'] = 'ネ' char_map['ノ'] = 'ノ' char_map['ハ'] = 'ハ' char_map['バ'] = 'バ' char_map['パ'] = 'パ' char_map['ヒ'] = 'ヒ' char_map['ビ'] = 'ビ' char_map['ピ'] = 'ピ' char_map['フ'] = 'フ' char_map['ブ'] = 'ブ' char_map['プ'] = 'プ' char_map['ヘ'] = 'ヘ' char_map['ベ'] = 'ベ' char_map['ペ'] = 'ペ' char_map['ホ'] = 'ホ' char_map['ボ'] = 'ボ' char_map['ポ'] = 'ポ' char_map['マ'] = 'マ' char_map['ミ'] = 'ミ' char_map['ム'] = 'ム' char_map['メ'] = 'メ' char_map['モ'] = 'モ' char_map['ャ'] = 'ャ' char_map['ヤ'] = 'ヤ' char_map['ュ'] = 'ュ' char_map['ユ'] = 'ユ' char_map['ョ'] = 'ョ' char_map['ヨ'] = 'ヨ' char_map['ラ'] = 'ラ' char_map['リ'] = 'リ' char_map['ル'] = 'ル' char_map['レ'] = 'レ' char_map['ロ'] = 'ロ' char_map['ヮ'] = 'ワ' char_map['ワ'] = 'ワ' char_map['ン'] = 'ン' char_map['ヴ'] = 'ヴ' char_map['・'] = '' char_map['ー'] = 'ー' return char_map
189b6d80031e26bb4ffde12a39baf861cb82c536
amakridin/py_learn
/lesson2/2.py
917
4.1875
4
# 2. Для списка реализовать обмен значений соседних элементов, т.е. # Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). lst = [] while True: elem = input("Введи что-нибудь для наполнения списка. Надоест - напиши /end: ") if elem != '/end': lst.append(elem) else: break print("Введенный список ", lst) for i in range(len(lst) // 2): lst.insert(i * 2 + 2, lst[i * 2]) lst.pop(i * 2) print("После обмена элементами: ", lst)
2c68ed20901619c93032ec3824e1fd592cd2df9e
swhh/python_project
/problem_3.py
1,640
3.640625
4
import random from sys import argv, exit from collections import namedtuple, defaultdict Graph = namedtuple('Graph', ['V', 'E']) def random_contraction_algorithm(graph): n = len(graph.V) new_graph = graph while n > 2: edge = random_select(new_graph) new_graph = merge(graph, edge) n -= 1 return new_graph def random_select(graph): edges = graph.E edge = random.choice(edges.keys()) return edge def merge(graph, edge): edges, nodes = graph.E, graph.V u, v = edges[edge] del edges[edge] edges, nodes = transfer(u, v, edges, nodes) del nodes[u] return Graph(nodes, edges) def transfer(u, v, edges, nodes): for edge in [edge for edge in nodes[u] if edges.get(edge)]: edge_nodes = edges[edge] if edge_nodes[0] == u: edge_nodes[0] = v else: edge_nodes[1] = v if edge_nodes[0] == v and edge_nodes[1] == v: del edges[edge] else: nodes[v].append(edge) return edges, nodes if __name__ == '__main__': f = argv[1] V = defaultdict(list) E = dict() edge_num = 1 with open(f) as f: for line in f: vertices = map(int, line.split()) vertex, neighbors = vertices[0], vertices[1:] for neighbor in neighbors: if vertex < neighbor: E[edge_num] = [vertex, neighbor] V[vertex].append(edge_num) V[neighbor].append(edge_num) edge_num += 1 graph = Graph(V, E) new_graph = random_contraction_algorithm(graph)
17cda7a4d78c1b3e0da8b22624a1f3244029c8d9
edwu/Project-Euler
/euler5.py
270
3.59375
4
def diviser(n): i = 1 while i<=20: if n % i != 0: return False i+=1 return True def smallest(): i=1 while (1): if diviser(i): return i i+=1 return "Never Reaches Here" k=smallest() print k
c978d5114b3b2a73de285ded430cd87d18915b31
algoitssm/algorithm_taeyeon
/Baekjoon/1991_tree_트리순회.py
974
3.765625
4
N = int(input()) tree = {} for i in range(N): root, left, right = input().split() tree[root] = [left, right] # print(tree) A B C = > {'A': ['B', 'C']} # 전위 순회 : 루트/왼쪽/오른쪽 def preorder(root): if root != ".": # 값이 존재하는 경우 left = tree[root][0] right = tree[root][1] print(root, end="") preorder(left) preorder(right) # 중위 순회 : 왼쪽/루트/오른쪽 def inorder(root): if root != ".": # 값이 존재하는 경우 left = tree[root][0] right = tree[root][1] inorder(left) print(root, end="") inorder(right) # 후위 순회 : 왼쪽/오른쪽/루트 def postorder(root): if root != ".": # 값이 존재하는 경우 left = tree[root][0] right = tree[root][1] postorder(left) postorder(right) print(root, end="") preorder("A") print() inorder("A") print() postorder("A") print()
d70dd71e871055c1e30f8925d9ab15768f4bbbbf
Singularmotor/test_project
/test.py
99
3.828125
4
#coding utf-8 print("please type in a number which less than 10") n=int(input) print("%d"%(a/10))
4cff20c39f4e07e1eab7732e2215b864bbd086a8
hosjiu1702/Programming_Problems
/leetcode/problems/p414/main.py
594
3.765625
4
import sys class Solution: def thirdMax(self, nums) -> int: """ Sorting """ nums.sort() count = 0 i = len(nums) - 1 while i - 1 >= 0: if nums[i - 1] < nums[i]: count = count + 1 if count == 2: return nums[i - 1] i = i - 1 return nums[-1] if __name__ == '__main__': # nums = [5, 4, 3, 2, 1]\ nums = map(int, sys.argv[1:]) nums = list(nums) # import pdb; pdb.set_trace() s = Solution() ret = s.thirdMax(nums) print(ret)
ca48b15e7349230cb1f1a05a354efcb01dcc8c6e
biefeng/Exercise
/algorithm/main.py
552
3.515625
4
# -*- coding: utf-8 -*- from random import Random from algorithm.sort import qucik_sort, merge_sort __author__ = '33504' if __name__ == "__main__": arr = [Random().randint(0, 20) for x in range(20)] arr=[4, 4, 13, 19, 12, 8, 11, 10, 8, 18, 13, 2, 8, 20, 4, 6, 7, 16, 7, 5] print(arr) print('******************sort start******************') # qucik_sort = qucik_sort() # qucik_sort.sort(arr, 0, len(arr) - 1) # print(arr) merge_sort = merge_sort() merge_sort.merge(arr, 1) print(arr) print('******************sort end******************')
9873bbfd53b603b5c5712e8dfd0b71ede078d846
syedaali/python
/coderb/exercises/matrix.py
249
4.15625
4
''' Write a python program that prints a 12x12 multiplication table matrix. ''' for i in xrange(1,12): for j in xrange(1,12): print i,j for row in range(1,12): for col in range(1,n+1): print(row*col, end="\t") print()
ed17db17440d0cb6eff06170ca6c63c7a3b2a547
vaquierm/RedditCommentTextClassification
/src/models/Model.py
1,197
3.578125
4
class Model: def __init__(self): self.trained = False self.M = None def fit(self, X, Y): """ Fit the model with the training data :param X: Inputs :param Y: Label associated to inputs :return: None """ self.trained = True self.M = X.shape[1] if X.shape[0] != Y.shape[0]: raise Exception("The number of input samples and output samples do not match!") def predict(self, X): """ Predict the labels based on the inputs :param X: Inputs :return: The predicted labels based on the training """ if not self.trained: raise Exception("You must train the model before predicting!") if self.M != X.shape[1]: raise Exception("The shape of your sample does not match the shape of your training data!") def get_params(self, deep: bool = True): """ Get parameters for this estimator. :param deep: If True, will return the parameters for this estimator and contained subobjects that are estimators. :return: Parameter names mapped to their values. """ return {}
57b2e5c1bc218822e9a042d525e4d1fb270c51cb
mkieft/Computing
/Python/Week 5/lab 5 q 13.py
519
3.765625
4
#Lab 5 Q 13 #Maura Kieft #9/29/2016 #13. Two friends (Alice and Bob) are playing a game where they roll two dice import random def main(): a=random.randrange(1,7) a1=random.randrange(1,7) a2=a+a1 print("Alice dice roll: ",a2) b=random.randrange(1,7) b1=random.randrange(1,7) b2=b+b1 print("Bob dice roll: ",b2) if (a>b): print("Alice is the winner!") if(b>a): print ("Bob is the winner!") if (a==b): print ("It's a tie!") main()
2787ed5f4c5faa887d698e51e329111010359bf3
oudin-clement/Mini-projet1
/justeprix.py
239
3.53125
4
from random import* n=randint(1,100) reponse="" essai=0 while reponse!=n: reponse=int(input("->")) if reponse > n: print("trop grand!") else: print("trop petit!") essai+=1 print("gagné en ",essai," coups")
b5cb583bcfefcd48a137ef6974f6f466e61f78f9
Ghostkeeper/MetaProgrammingWorkshop
/m2properties.py
1,005
3.75
4
class Printer: def __init__(self, extruders, price, has_misp): self.extruders = extruders self.price = price self.has_misp = has_misp @property def extruders(self): print("Get extruders") return self._extruders @extruders.setter def extruders(self, value): if not isinstance(value, int): raise TypeError("No integer!") if value < 1: raise ValueError("Need at least one extruder!") print("Set extruders", value) self._extruders = value @property def price(self): print("Get price") return self._price @price.setter def price(self, value): if not isinstance(value, int): raise TypeError("No integer!") if value < 2000: raise ValueError("Too cheap!") print("Set price", value) self._price = value @property def has_misp(self): print("Get has_misp") return self._has_misp @has_misp.setter def has_misp(self, value): if not isinstance(value, bool): raise TypeError("Must be boolean!") print("Set has_misp", value) self._has_misp = value
adc886d69bc57e080f0a5937233cc4d9285f950f
SilverXuz/TextBasedPythonGame
/Game.py
4,449
3.765625
4
import random as r hp = 0 coins = 0 damage = 0 def printParameters(): print("У тебя {0} жизней, {1} урона и {2} монет.".format(hp, damage, coins)) def printHp(): print("У тебя", hp, "жизней.") def printCoins(): print("У тебя", coins, "монет.") def printDamage(): print("У тебя", damage, "урона.") def meetShop(): global hp global damage global coins def buy(cost): global coins if coins >= cost: coins -= cost printCoins() return True print("У тебя маловато монет!") return False weaponLvl = r.randint(1, 3) weaponDmg = r.randint(1, 5) * weaponLvl weapons = ["AK-47", "Iron Sword", "Showel", "Flower", "Bow", "Fish"] weaponRarities = ["Spoiled", "Rare", "Legendary"] weaponRarity = weaponRarities[weaponLvl - 1] weaponCost = r.randint(3, 10) * weaponLvl weapon = r.choice(weapons) oneHpCost = 5 threeHpCost = 12 print("На пути тебе встретился торговец!") printParameters() while input("Что ты будешь делать (зайти/уйти): ").lower() == "зайти": print("1) Одна единица здоровья -", oneHpCost, "монет;") print("2) Три единицы здоровья -", threeHpCost, "монет;") print("3) {0} {1} - {2} монет".format(weaponRarity, weapon, weaponCost)) choice = input("Что хочешь приобрести: ") if choice == "1": if buy(oneHpCost): hp += 1 printHp() elif choice == "2": if buy(threeHpCost): hp += 3 printHp() elif choice == "3": if buy(weaponCost): damage = weaponDmg printDamage() else: print("Я такое не продаю.") def meetMonster(): global hp global coins monsterLvl = r.randint(1, 3) monsterHp = monsterLvl monsterDmg = monsterLvl * 2 - 1 monsters = ["Grock", "Clop", "Cholop", "Madrock", "Lilbitch"] monster = r.choice(monsters) print("Ты набрел на монстра - {0}, у него {1} уровень, {2} жизней и {3} урона.".format(monster, monsterLvl, monsterHp, monsterDmg)) printParameters() while monsterHp > 0: choice = input("Что будешь делать (атака/бег): ").lower() if choice == "атака": monsterHp -= damage print("Ты атаковал монстра и у него осталось", monsterHp, "жизней.") elif choice == "бег": chance = r.randint(0, monsterLvl) if chance == 0: print("Тебе удалось сбежать с поля боя!") break else: print("Монстр оказался чересчур сильным и догнал тебя...") else: continue if monsterHp > 0: hp -= monsterDmg print("Монстр атаковал и у тебя осталось", hp, "жизней.") if hp <= 0: break else: loot = r.randint(0, 2) + monsterLvl coins += loot print("Тебе удалось одолеть монстра, за что ты получил", loot, "монет.") printCoins() def initGame(initHp, initCoins, initDamage): global hp global coins global damage hp = initHp coins = initCoins damage = initDamage print("Ты отправился в странствие навстречу приключениям и опасностям. Удачного путешествия!") printParameters() def gameLoop(): situation = r.randint(0, 10) if situation == 0: meetShop() elif situation == 1: meetMonster() else: input("Блуждаем...") initGame(3, 5, 1) while True: gameLoop() if hp <= 0: if input("Хочешь начать сначала (да/нет): ").lower() == "да": initGame(3, 5, 1) else: break
3a74f5928a15ea1410c95bedc8951e0478cfdaa5
leetuckert10/CrashCourse
/chapter_9/exercise_9-4.py
621
3.53125
4
# Exercise 9-4: Number Served # This version of Restaurant from 9-1 explorers a new attribute added to the # the Restaurant class. import restaurant as r restaurant = r.Restaurant("Billy Bob's Grill", "American") restaurant.set_number_served(28_952) restaurant.describe_restaurant() restaurant.open_restaurant() # Set number_served to a new value and print again. restaurant.set_number_served(32_995) print(f"\nNew value for number served: {restaurant.number_served}.") restaurant.increment_number_served(378) print(f"\nAfter serving 378 customers toady our new value for number served:" f" {restaurant.number_served}.")
295fb94878473164a468b154bf7af68bed2f5acc
dvir200/Data_Structures_and_Algorithms
/Queues and Stacks/basic_queue.py
246
3.703125
4
""" Queue - First in, First out """ queue = [] queue.append("data1") queue.append("data2") queue.append("data3") queue.append(5) print(queue) """ deleting data1 """ queue.pop(0) print(queue) """ deleting data2 """ queue.pop(0) print(queue)
e07f6990bef7be5b19a18897481acd73dee93067
Warriorchief/matrixSubcount
/submatrixcount.py
794
4.03125
4
""" Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it. Example For matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] the output should be differentSquares(matrix) = 6 """ def differentSquares(matrix): w=len(matrix[0]) h=len(matrix) if w<2 or h<2: return 0 quads=[] for r in range(h-1): row=[] for c in range(w-1): q=[matrix[r][c],matrix[r][c+1],matrix[r+1][c],matrix[r+1][c+1]] row.append(q) for thing in row: quads.append(thing) #print(quads) seen=[quads[0]] for item in quads[1:]: if item not in seen: seen.append(item) #print(seen) return len(seen)
be4b8fde0e3d38db5b66dbfe65147610ea648039
mennanov/problem-sets
/other/strings/anagram_check.py
1,101
4.15625
4
# -*- coding: utf-8 -*- """ Given two strings check whether one string is a permutation of the other (anagram). """ from collections import Counter def anagram_sort(string1, string2): """ Simple and straightforward solution: sort both strings and check them for equality. Running time is O(NLogN), space consumption depends on the sorting algorithm. """ # it is obvious that the length of these strings must be the same if len(string1) != len(string2): return False return sorted(string1) == sorted(string2) def anagram_counting(string1, string2): """ Count the number of occurrences of each character in each string. If all the numbers are the same - it is an anagram. Running time is O(N), space O(R), R - length of the alphabet. """ # it is obvious that the length of these strings must be the same if len(string1) != len(string2): return False return Counter(string1) == Counter(string2) if __name__ == '__main__': s1 = 'race' s2 = 'care' assert anagram_sort(s1, s2) assert anagram_counting(s1, s2)
6045c81a5f3d67148c0be9e9434881a849b43f2f
InjiChoi/algorithm_study
/재귀함수/1901.py
151
3.703125
4
# 1부터 n까지 출력하기 num = int(input()) def recursion_print(n): if n!=1: recursion_print(n-1) print(n) recursion_print(num)
24da817d798c5aa56d839f0639d6225ff33b680f
PedroVitor1995/Uri
/Iniciantes/Questao1117.py
296
3.53125
4
def main(): qtd = 0 soma = 0 media = 0 while True: nota = input('') if nota > 0 and nota <= 10: soma += nota qtd += 1 else: print('nota invalida') media = soma / 2.0 if qtd == 2: print('media = %.2f') % media break if __name__ == '__main__': main()
6958b0124c3e1fb84f88b8a84ea3b403ea8656f4
Choirong/Automated-Program-Repair
/src/is_prime.py
180
3.84375
4
def is_prime(number): if number < 0: return True if number in (0, 1): return False for element in range(2, number): if number % element == 0: return False return True
8380d5ffe10e459c08b0952bca82e6ee93893a56
Robert-Rutherford/learning-Python
/practiceProblems/BeginningAndEndPairs.py
1,019
3.890625
4
# Beginning and End Pairs # site: https://edabit.com/challenge/HrCuzAKE6skEYgDmf # Write a function that pairs the first number in an array with the last, the second number with the second to last, # etc. # notes: # If the list has an odd length, repeat the middle element twice for the last pair. # Return an empty list if the input is an empty list. def pairs(lst): pairedlist = list() split = 0 reverse = -1 odd = False if len(lst) % 2 == 0: split = int(len(lst)/2) else: odd = True split = int(int(len(lst))/2) for x in range(split): pairset = list() pairset.append(lst[x]) pairset.append(lst[reverse]) reverse -= 1 pairedlist.append(pairset) if odd: oddset = list() oddset.append(lst[split]) oddset.append(lst[split]) pairedlist.append(oddset) return pairedlist print(pairs([1, 2, 3, 4, 5, 6, 7])) print(pairs([1, 2, 3, 4, 5, 6])) print(pairs([5, 9, 8, 1, 2])) print(pairs([]))
fe57c20a41de8502c562123e6711f983d2b8406d
falkecarlsen/restful-web-service-py
/web-service.py
4,455
3.6875
4
import socket import threading import http PRINT_LOCK = threading.Lock() HOST = ("localhost", 8002) DATA = dict(first="42") def thread_print(arg): with PRINT_LOCK: print(arg) def http_response(code, body) -> bytes: """ Constructs a HTTP response from a given code and body :param code: the HTTP status code to use for the HTTP response line :param body: the body to append the HTTP response :return: the UTF-8-encoded HTTP-response """ http_status = http.HTTPStatus(code) line = f"HTTP/1.0 {code} {http_status.phrase}\r\n\r\n{body}" thread_print(f"[SERVER] Sending response: {line}") return line.encode("UTF-8") def handle_client(conn: socket.socket, addr: str): """ Handles a client REST-request to the resource 'data' and implements basic GET, ADD, OVERWRITE, and DELETE operations :param conn: the socket representing the client connection :param addr: the client address :return: """ thread_print(f"[SERVER] Got connection from {addr}") # Receive data (up to 512 bytes) and decode request = conn.recv(512).decode("UTF-8") thread_print(f"[SERVER] Got request: {request}, from: {addr}") # HTTP follows the form: 'METHOD-TOKEN REQUEST-URI HTTP-PROTOCOL' # Strip potential whitespace for sanity request = request.strip() method_token = request.split()[0] request_uri = request.split()[1] # resource should be the second (first) element in path. Note, that the empty element before the first '/' counts. resource = request_uri.split('/')[1] # Key should be the third (second) element in path key = request_uri.split('/')[2] # Get body as last element in request FIXME; does not take into account that bodies can be space-separated body = request.split()[len(request.split()) - 1] # Check if path refers to the resource 'data', if not respond with bad-request to client if resource == "data": # Process each operation; {GET, PUT, POST, DELETE}, otherwise reply with bad-request to client if method_token == "GET": try: conn.sendall(http_response(200, DATA[key])) except KeyError: conn.sendall(http_response(404, f"Could not find key: {key}")) elif method_token == "PUT": if key not in DATA: DATA[key] = body conn.sendall(http_response(200, f"Set key: {key} = {body}")) else: conn.sendall( http_response(400, f"Cannot overwrite key: {key} = {body}. Key: {key} already has {DATA[key]}")) elif method_token == "POST": if key in DATA: DATA[key] = body conn.sendall(http_response(200, f"Updated key: {key} = {body}")) else: conn.sendall(http_response(400, f"Cannot overwrite key: {key} = {body}. Key does not exist.")) elif method_token == "DELETE": try: del DATA[key] conn.sendall(f"HTTP/1.0 200 OK\r\n\r\nSuccessfully deleted key: {key}".encode("UTF-8")) except KeyError: conn.sendall(f"HTTP/1.0 404 Not Found\r\n\r\nCould not find key for deletion: {key}".encode("UTF-8")) else: thread_print(f"Bad request. Request: {request} from: {addr}") conn.sendall(http_response(400, f"Did not understand method: {method_token}")) conn.close() else: conn.sendall(http_response(400, f"Server does not have the given resource {resource}")) conn.close() def start_server(): # Declare a socket on localhost using TCP and IPv4 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Allow rapid restarting of server sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind to HOST-constant sock.bind(HOST) # Begin listening to socket sock.listen() # Loop on accepting new connections while True: thread_print("[SERVER] Accepting incoming connections") # Accept a connection, resulting in a tuple, (conn, addr), where conn is the socket representing # the client connection and addr is the IP:PORT of the client (conn, addr) = sock.accept() # Start a thread on the handle_client function, giving the newly accepted client as arguments threading.Thread(target=handle_client, args=(conn, addr)).start() start_server()
cd6de2b359b60cdd62f8269c273e16277c2f25ae
Lzffancy/Aid_study
/fancy_month02/draft_box/famliy_across_bridge.py
452
3.828125
4
""" 小明过桥 """ class FamilyBridge(): family = { 'p1s':1, 'p3s':3, 'p6s':6, 'p8s':8, 'p12s':12, } def __init__(self): self.totall_time = 0 def across_time(self,x,y): one_time = x + y self.totall_time += one_time if x>y: return y else: return x if __name__ == '__main__': pass
9c446ab5a732358c46553c959cf73015042c3c47
xiaolongjia/techTrees
/Python/00_Code Interview/AlgoExpert/Category/LinkedList_M_001_Construction.py
5,474
4.5
4
#!C:\Python\Python #coding=utf-8 ''' Linked List Construction Write a DoublyLinkedList class that has a head and a tail. both of which point to either a linked list Node or None/Null. The class should support: - Setting the head and tail of the linked list. - Inserting nodes before and after other nodes as well as at given positions (the position of the head node is 1) - Removing given nodes and removing nodes with given values. - Searching for nodes with given values. Note that the setHead, setTail, insertBefore, insertAfter, insertAtPosition. and remove methods all take in actual Node as input parameters -- not integers (except for insertAtPosition, which also takes in an integer representing the position); this means that you do not need to create any new Node in these methods. The input nodes can be either stand-alone nodes or nodes that are already in the linked list. if they are nodes that are already in the linked list, the methods will effectively be mobing the nodes within the linked list. you won't be told if the input nodes are already in the linked list. so your code will have defensively handle this scenario. Each Node has an integer value as well as a prev node and a next node, both of which can point to either another node or None/null. Sample Usage: 1<->2 <->3 <-> 4 <-> 5 3, 3, 6, # stand-alone nodes setHead(4): 4 <-> 1 <-> 2 <-> 3 <-> 5 setTail(6): 4 <-> 1 <-> 2 <-> 3 <-> 5 <->6 insertBefore(6,3): 4 <-> 1 <-> 2 <-> 5 <-> 3 <->6 insertAfter(6,3): 4 <-> 1 <-> 2 <-> 5 <-> 3 <-> 6 <-> 3 insertAtPosition(1,3): 3<-> 4 <-> 1 <-> 2 <-> 5 <-> 3 <-> 6 <-> 3 removeNodesWithValue(3): 4 <-> 1 <-> 2 <-> 5 <-> 6 remove(2): 4 <-> 1 <-> 5 <-> 6 containsNodeWithValue(5): true ''' # This is an input class. Do not edit. class Node: def __init__(self, value): self.value = value self.prev = None self.next = None # Feel free to add new properties and methods to the class. class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def linkPrint(self): if self.head is None: print("It is a Null linked list") else: values = [] node = self.head while node is not None: values.append(str(node.value)) node = node.next print(" <-> ".join(values)) def setHead(self, node): if self.head is None: self.head = node self.tail = node return self.insertBefore(self.head, node) def setTail(self, node): if self.tail is None: self.setHead(node) return self.insertAfter(self.tail, node) def insertBefore(self, node, nodeToInsert): if nodeToInsert == self.head and nodeToInsert == self.tail: return self.remove(nodeToInsert) nodeToInsert.prev = node.prev nodeToInsert.next = node if node.prev is None: self.head = nodeToInsert else: node.prev.next = nodeToInsert node.prev = nodeToInsert def insertAfter(self, node, nodeToInsert): if nodeToInsert == self.head and nodeToInsert == self.tail: return self.remove(nodeToInsert) nodeToInsert.prev = node nodeToInsert.next = node.next if node.next is None: self.tail = nodeToInsert else: node.next.prev = nodeToInsert node.next = nodeToInsert def insertAtPosition(self, position, nodeToInsert): if position == 1: self.setHead(nodeToInsert) return node = self.head currPosition = 1 while node is not None and currPosition != position: node = node.next currPosition += 1 if node is not None: self.insertBefore(node, nodeToInsert) else: self.setTail(nodeToInsert) def removeNodesWithValue(self, value): node = self.head while node is not None: node2Remove = node node = node.next if node2Remove.value == value : self.remove(node2Remove) def remove(self, node): if node == self.head: self.head = self.head.next if node == self.tail : self.tail = self.tail.prev self.removeNodeRelation(node) def removeNodeRelation(self, node): if node.prev is not None: node.prev.next = node.next if node.next is not None: node.next.prev = node.prev node.prev = None node.next = None def containsNodeWithValue(self, value): node = self.head while node is not None: if node.value == value : return True node = node.next return False nodeOne = Node(1) nodeTwo = Node(2) nodeThree = Node(3) nodeFour = Node(4) nodeFive = Node(5) llist = DoublyLinkedList() llist.setHead(nodeFive) llist.setHead(nodeFour) llist.setHead(nodeThree) llist.setHead(nodeTwo) llist.setHead(nodeOne) llist.linkPrint() nodeSix = Node(6) llist.setTail(nodeSix) llist.linkPrint() llist.insertBefore(nodeSix,Node(3)) llist.linkPrint() llist.insertAfter(nodeSix,Node(3)) llist.linkPrint() llist.insertAtPosition(1,Node(3)) llist.linkPrint() llist.removeNodesWithValue(3) llist.linkPrint() llist.remove(nodeTwo) llist.linkPrint() print(llist.containsNodeWithValue(5))
0442c676af133a26717476948df3442218d7014e
JasonYRChen/DataStructures_codes
/ch8/tree/Tree/Tree.py
2,035
4.15625
4
import abc class Tree(abc.ABC): @abc.abstractmethod def __len__(self): """Total node numbers""" def __repr__(self): return f"{self.__class__.__name__}(node_numbers: {len(self)})" @abc.abstractmethod def root(self): """Return root node""" def is_root(self, node): """Check if node is the root node.""" return self.parent(node) is None @abc.abstractmethod def parent(self, node): """Return node's parent node""" def children(self, node): """Iterate node's children.""" raise NotImplementedError def children_num(self, node): """Return numbers of children""" raise NotImplementedError @abc.abstractmethod def element(self, node): """Return node's element""" def is_leaf(self, node): return self.children_num(node) == 0 @abc.abstractmethod def attach(self, node, *nodes): """Attach new nodes or None to current node""" @abc.abstractmethod def detach(self, node): """Remove the node and connect its children to its parent if legitimate.""" @abc.abstractmethod def _replace(self, node, elements): """Replace elements in the node.""" @abc.abstractmethod def _disable_node(self, node): """Make node invalid and reduce total nodes number by 1. May accompany with self.detach method.""" @abc.abstractmethod def _add_root(self, node): """Add root to the tree""" def height(self, node=None): """Height is zero-base, starts from current node. Ex: node's height is 0, node's children's height is 1, and so on).""" if node is None: node = self.root() if self.is_leaf(node): return 0 return 1 + max(self.height(c) for c in self.children(node)) def depth(self, node): """Depth is zero-base, starts from root node""" if node is self.root(): return 0 return 1 + self.depth(self.parent(node))
c069ae0d12c705d91c52e78cbea8e001acd537c5
paetztm/python-playground
/python-beyond-the-basics/comprehensions/google_chess.py
4,527
3.546875
4
import math GRID_SIZE = 100 class Grid: def __init__(self, rows, columns): pass class Point: def __init__(self, row, column): self.row = row self.column = column @staticmethod def is_valid_point(row, column): return 0 <= row < GRID_SIZE and 0 <= column < GRID_SIZE def append_valid_point(self, neighbors, row, column): if self.is_valid_point(row, column): neighbors.append(Point(row, column)) def get_neighbor_points(self): neighbors = [] row = self.row column = self.column self.append_valid_point(neighbors, row + 1, column + 2) self.append_valid_point(neighbors, row + 1, column - 2) self.append_valid_point(neighbors, row - 1, column + 2) self.append_valid_point(neighbors, row - 1, column - 2) self.append_valid_point(neighbors, row + 2, column + 1) self.append_valid_point(neighbors, row + 2, column - 1) self.append_valid_point(neighbors, row - 2, column + 1) self.append_valid_point(neighbors, row - 2, column - 1) return neighbors def get_row(point): return int(point / GRID_SIZE) def get_column(point): return point % GRID_SIZE def is_corner(point): return (point.column == 0 and point.row == 0) or (point.column == 0 and point.row == GRID_SIZE - 1) or (point.column == GRID_SIZE - 1 and point.row == 0) or (point.column == GRID_SIZE - 1 and point.row == GRID_SIZE - 1) def memoize(func): cache = {} def wrapper(src, dest): source = Point(get_row(src), get_column(src)) destination = Point(get_row(dest), get_column(dest)) distance = math.sqrt((destination.column - source.column)**2 + (destination.row - source.row)**2) # corners with diagonal of 1 aren't equal to every where else if distance == 1.4142135623730951 and (is_corner(source) or is_corner(destination)): count = func(source, destination) elif distance not in cache: count = func(source, destination) cache[distance] = count else: count = cache[distance] # print("{} src {} dest {} distance {} cached".format(src, dest, distance, count)) return count return wrapper @memoize def answer(source, destination): # your code here check_points = [[False for x in range(GRID_SIZE)] for y in range(GRID_SIZE)] count = 0 neighbors = source.get_neighbor_points() check_points[source.row][source.column] = True while not check_points[destination.row][destination.column]: count += 1 temp_neighbors = [] for point in neighbors: if not check_points[point.row][point.column]: check_points[point.row][point.column] = True temp_neighbors.extend(point.get_neighbor_points()) if check_points[destination.row][destination.column]: break neighbors = temp_neighbors return count def answer2(src, dest): # your code here if src == dest: return 0 check_points = [[False for x in range(GRID_SIZE)] for y in range(GRID_SIZE)] source = Point(get_row(src), get_column(src)) destination = Point(get_row(dest), get_column(dest)) count = 0 neighbors = source.get_neighbor_points() while not check_points[destination.row][destination.column]: count += 1 temp_neighbors = [] for point in neighbors: if not check_points[point.row][point.column]: check_points[point.row][point.column] = True temp_neighbors.extend(point.get_neighbor_points()) if check_points[destination.row][destination.column]: break neighbors = temp_neighbors return count import time total_time = 0 start_time = time.time() left_answers = [] right_answers = [] for x in range(GRID_SIZE**2): for y in range(GRID_SIZE**2): answer1 = answer(x, y) # point = Point(get_row(x), get_column(x)) # if is_corner(point): # print("{} x {} y {} row {} col".format(x, y, point.row, point.column)) # answer3 = answer2(x, y) # if not answer1 == answer3: # print("{} answer1 {} answer2".format(answer1, answer3)) # a = "a" + a # # left_answers.append(answer1) # right_answers.append(answer3) print(time.time() - start_time) print(left_answers == right_answers) #print(answer(19, 36)) # = 1 #print(answer(1, 9)) # = 3
fa13c3dbfe728b47e92121c0e8d383660b826d13
SmischenkoB/campus_2018_python
/Oleksandr_Kotov/10/game_package_okotov/game_package_okotov/creature.py
1,184
3.890625
4
import decorators class Creature: """defines basic live game creature """ @decorators.debug_decorator def __init__(self, row=0, col=0, health=0): """init object with position Keyword Arguments: row {int} -- row on game map (default: {0}) col {int} -- column on game map (default: {0}) health {int} -- creature health (default: {0}) """ self.__health = health self.__curr_row = row self.__curr_col = col @property def position(self): return self.__curr_row, self.__curr_col def set_position(self, row, col): """set object position Arguments: row {int} -- row on game map col {int} -- column on game map """ self.__curr_row = row self.__curr_col = col @decorators.debug_decorator def damage(self, damage): """deal damage to creature Arguments: damage {int} -- number of points to decrement from health """ self.__health -= damage @property @decorators.debug_decorator def health(self): return self.__health
088a82a140362a0cfe369ddb1fd9d161fc2a83f0
Buzz627/AdventOfCode
/2016/day8/puzzle.py
1,332
3.59375
4
def countCells(mat): count=0 for row in mat: for cell in row: if cell=="#": count+=1 return count def makeRect(mat, row, col): for i in range(row): for j in range(col): mat[j][i]="#" def rotateCol(mat, col, num): if num==0: return temp=mat[len(mat)-1][col] for i in range(len(mat)-1, 0, -1): mat[i][col]=mat[i-1][col] mat[0][col]=temp rotateCol(mat, col, num-1) def rotateRow(mat, row, num): if num==0: return temp=mat[row][len(mat[row])-1] for i in range(len(mat[row])-1, 0, -1): mat[row][i]=mat[row][i-1] mat[row][0]=temp rotateRow(mat, row, num-1) with open("input.txt","rb") as inputfile: pad=[["."]*50 for i in range(6)] # makeRect(pad, 3, 2) # for i in pad: # print i # rotateRow(pad, 1, 2) # print "" # for i in pad: # print i # print "" # rotateCol(pad, 2, 5) # for i in pad: # print i for line in inputfile: comm=line.strip().split() if len(comm)==2: # print comm[1] n=comm[1].split("x") # print n makeRect(pad, int(n[0]), int(n[1])) else: if comm[1]=="row": row=int(comm[2][2:]) num=int(comm[4]) # print row, num rotateRow(pad, row, num) if comm[1]=="column": col=int(comm[2][2:]) num=int(comm[4]) # print col, num rotateCol(pad, col, num) for i in pad: print " ".join(i) print countCells(pad) #efeykfrfij
dab97c24f66d8719a0319e45b900e7241bea38a0
PavlikSweetheard/GB
/hw_les_1/exercise_6_les_1.py
1,229
3.875
4
# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил "a" километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. # Например: a = 2, b = 3.# Результат:# 1-й день: 2# 2-й день: 2,2# 3-й день: 2,42 # 4-й день: 2,66# 5-й день: 2,93# 6-й день: 3,22 a = float(input('Введите результат спортсмена в первый день, км :')) b = float(input('Введите результат спортсмена в n-ый день, км :')) day = 1 while a < b: a = a * 1.1 day += 1 print(f"Спортсмен добьется результата за {day} дней")
a4c45098e3ce85878c92dda4615441e861762315
MisterCruz/CSC148Notes
/recursionJan27.py
277
3.703125
4
def codes(r): '''(int)->list of str Return all binary codes of length r ''' if r == 0: return [''] small = codes(r-1) lst = [] for item in small: lst.append('0' + item) lst.append('1' + item) return lst print(codes(2))
fe4f821766004453b8b34e91b0acc9125a0005c2
jiyoungkimcr/Python_Summer_2021_2
/HW3_Stock data.py
1,223
3.75
4
''' Write a program that searches for CSV files with stock rates in a given folder and for every one of them: Calculates the percentage change between Close and Open price and adds these values as another column to this CSV file. Code writer: Jiyoung Kim ''' import os import csv from pip._vendor.distlib.compat import raw_input print('Write a path of a folder containing csv files (please add slash at the end):') path = raw_input() counter = 0 for file in os.listdir(path): if file.endswith('.csv'): counter += 1 filepath = path + file if file.endswith('.csv'): file_copy = filepath[:-4] + "_new.csv" with open(filepath, 'r') as input: with open(file_copy, 'w') as output: reader = csv.reader(input) writer = csv.writer(output) row0 = next(reader) row0.append('change_pct') writer.writerow(row0) for row in reader: change_pct = ((float(row[4]) - float(row[1])) / float(row[1])) * 100 row.append(change_pct) writer.writerow(row) print("Please check your folder")
b3a63dfadc365724ee0b073ef3350f813ab9e9c8
lalwanigunjan/Parking_Data_Analysis
/amount_due_per_licence/reduce.py
2,188
3.6875
4
#!/usr/bin/env python """s The algorithm simply considers each licence type as key and add +1 to count and the amount value to current amount for the current key. It averages by divding amount/count and outputs it. """ from operator import itemgetter import sys current_licence_type = None current_count = 0 current_amount = 0 current_average = 0 word = None # input comes from STDIN for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # parse the input we got from mapper.py licence_type, amount, count = line.split('\t', 2) # convert count and amount (currently a string) to int try: count = int(count) amount = float(amount) except ValueError: # count was not a number, so silently # ignore/discard this line continue # this IF-switch only works because Hadoop sorts map output # by key (here: word) before it is passed to the reducer if current_licence_type == licence_type: current_count += count current_amount +=amount else: if current_licence_type: # write result to STDOUT #To avoid the program from throwing #divide by zero exception try: current_average = current_amount/current_count except ValueError: #the current amount will be 0.00 in this case current_average = current_amount current_amount = "{0:.2f}".format(round(current_amount,2)) current_average = "{0:.2f}".format(round(current_average,2)) print('%s\t%s, %s' % (current_licence_type, current_amount, current_average)) current_count = 1 current_amount = amount current_licence_type = licence_type try: current_average = current_amount/current_count except: current_average = current_amount # do not forget to output the last word if needed! if current_licence_type: current_amount = "{0:.2f}".format(round(current_amount,2)) current_average = "{0:.2f}".format(round(current_average,2)) print('%s\t%s, %s' % (current_licence_type,current_amount, current_average))
5540c1a1091789bca7a573fd1b8a0f9283e46d64
kristiyankisimov/HackBulgaria-Programming101
/week0/is-an-bn/solution.py
348
3.78125
4
def is_an_bn(word): if len(word) % 2 == 1: return False else: first = word[:len(word)//2] second = word[len(word)//2+1:] is_true_first = all(map(lambda x: True if x == 'a' else False, first)) is_true_second = all(map(lambda x: True if x == 'b' else False, second)) return is_true_first and is_true_second
23f88075ffa4d482af5ad3e9370ffef77925902f
youyuebingchen/Algorithms
/paixusuanfa/quicksort.py
584
3.796875
4
def QuickSort(alist): qsort_rec(alist,0,len(alist)-1) return alist def qsort_rec(alist,l,r): if l > r: return i = l j = r mid = alist[i] while i < j : while i < j and alist[j] >= mid: j -= 1 if i < j: alist[i] = alist[j] i += 1 while i < j and alist[i] <= mid: i += 1 if i < j: alist[j] = alist[i] j -= 1 alist[i] = mid qsort_rec(alist,l,i-1) qsort_rec(alist,i+1,r) test = [1, 5, 3, 2, 7, 4, 9] print(QuickSort(test))
36c7b8b32bc16cb216969c51d14a4dd1255f712a
sjbarag/CS260-Programming-Assignments
/pa1/p4-2.py
6,367
4
4
# Leftmost Child/Right Sibling implementation of Trees # Node class - each object of class node is a node a tree # @param label label of the node (1, 2, 3, ...) # @param lc left child of the node # @param rs right sibling of the node # @param parent the node's parent class node : # constructor def __init__(self) : self.label = None self.lc = None self.rs = None self.parent = None # for easier printing def __str__(self): return str(self.label) # Tree class # @param cellspace list of objects of type node # @param end integer representation of one-past-last *used* object in list # @param root the root node of the tree. class tree : # constructor. Creates only null trees. def __init__(self) : self.cellspace = None self.root = None # returns a null (empty) tree. def MAKENULL() : temp = tree() temp.cellspace = [None]*MAXNODES return temp # returns the parent of a node # @param n node in question def PARENT(n, T) : return T.cellspace[n.parent] # returns the leftmost child of a node # @param n node in question def LEFTMOST_CHILD(n, T) : if n.lc is None : return None else : return T.cellspace[n.lc] print n, "does not exist in the tree." # returns the right sibling of a node # @param n node in question def RIGHT_SIBLING(n, T): if n.rs is None : return None else : return T.cellspace[n.rs] print n, "does not exist in the tree." # returns the label of a node # @param n node in question def LABEL(n) : return n.label # returns a tree with root/leaf node v. ...that's it. # @param v label of the root/leaf node def CREATE0(v) : # make new, empty tree temp = MAKENULL() #set root's values temp.cellspace[v] = node() temp.cellspace[v].label = v # root is v temp.root = v return temp # returns a tree with root node labeled v and child subtree T # @param v label of the new root node (it better be an integer, or things will break badly) # @param T subtree to the be leftmost (er... only) chlid of the new root def CREATE1(v, T) : # make new, empty tree temp = MAKENULL() # copy T's cellspace for i in range(0, MAXNODES) : if T.cellspace[i] is not None : temp.cellspace[i] = T1.cellspace[i] # set new root temp.cellspace[v] = node() temp.cellspace[T.root] = node() # set root's values temp.cellspace[v].label = v temp.cellspace[v].lc = T.root temp.rs = None # not needed, but good for explicitacity. # set T's values temp.cellspace[T.root].label = T.root temp.cellspace[T.root].rs = None # explicit temp.cellspace[T.root].parent = v # root is v temp.root = v return temp # returns a tree with root node labeled v and children subtrees T1 and T2 # @param v label of the new root node (it better be an integer, or things will break badly) # @param T1 subtree to be the leftmost child of the new root # @param T2 subtree to be the rightmost child of the new root def CREATE2(v, T1, T2) : # make new, empty tree temp = MAKENULL() # copy T1's cellspace #temp.cellspace = T1.cellspace # merge in T2's cellspace for i in range(0, MAXNODES) : if T1.cellspace[i] is not None : temp.cellspace[i] = T1.cellspace[i] elif T2.cellspace[i] is not None : temp.cellspace[i] = T2.cellspace[i] # set new roots temp.cellspace[v] = node() temp.cellspace[T1.root] = node() temp.cellspace[T2.root] = node() # set root's values temp.cellspace[v].label = v temp.cellspace[v].lc = T1.root temp.cellspace[v].rs = None # being explicit # set T1's cell's attributes temp.cellspace[T1.root] = T1.cellspace[T1.root] temp.cellspace[T1.root].rs = T2.root temp.cellspace[T1.root].parent = v # set T2's cell's attributes temp.cellspace[T2.root] = T2.cellspace[T2.root] temp.cellspace[T2.root].rs = None temp.cellspace[T2.root].parent = v # root is v temp.root = v return temp # returns a tree with root node labeled v and children subtrees T1, T2, and T3 # @param v label of the new root node (it better be an integer, or things will break badly) # @param T1 subtree to be the leftmost child of the new root # @param T2 subtree to be to the right of T1 # @param T3 subtree to be to the right of T2 def CREATE3(v, T1, T2, T3) : print "T1.root = ",T1.root print "T2.root = ",T2.root # make new, empty tree temp = MAKENULL() for i in range(0, MAXNODES) : if T1.cellspace[i] is not None : temp.cellspace[i] = T1.cellspace[i] elif T2.cellspace[i] is not None : temp.cellspace[i] = T2.cellspace[i] elif T3.cellspace[i] is not None : temp.cellspace[i] = T3.cellspace[i] # set new roots temp.cellspace[v] = node() temp.cellspace[T1.root] = node() temp.cellspace[T2.root] = node() temp.cellspace[T3.root] = node() # set root's values temp.cellspace[v].label = v temp.cellspace[v].lc = T1.root temp.cellspace[v].rs = None # being explicit # set T1's cell's attributes temp.cellspace[T1.root] = T1.cellspace[T1.root] temp.cellspace[T1.root].rs = T2.root temp.cellspace[T1.root].parent = v # set T2's cell's attributes temp.cellspace[T2.root] = T2.cellspace[T2.root] temp.cellspace[T2.root].rs = T3.root temp.cellspace[T2.root].parent = v # set T3's cell's attributes temp.cellspace[T3.root] = T3.cellspace[T3.root] temp.cellspace[T3.root].rs = None temp.cellspace[T3.root].parent = v # root is v temp.root = v return temp # returns the root of tree T # @param T the tree in question def ROOT(T) : return T.cellspace[T.root] # prints contents of tree t containing root r [inorder]. There is probably a way to put this in # tree class's __str__ function, I just haven't done it yet. # @param r the root of the tree in question def printTree(n, T) : if n.lc is None : print n, else : printTree(T.cellspace[n.lc], T) print n, tmp = LEFTMOST_CHILD(n,T) tmp = RIGHT_SIBLING(tmp, T) while tmp is not None : printTree(tmp, T) tmp = RIGHT_SIBLING(tmp, T) ############################################## MAXNODES = 100 foo = CREATE0(1) bar = CREATE0(2) baz = CREATE0(3) derp = CREATE2(4, foo, bar) hurr = CREATE0(7) herp = CREATE3(5, baz, derp, hurr) print "Printing herp (inorder):" printTree(ROOT(herp), herp) print n = ROOT(herp) print "n is ROOT(herp)" print n n = LEFTMOST_CHILD(n, herp) print "n is leftmost child of ROOT(herp):" print n n = RIGHT_SIBLING(n, herp) print "right sibling of n:" print n n = PARENT(n, herp) print "parent of n:" print n
a2487afcfa31ef00d3399ff10830ddf7bd1938b4
baketbek/AlgorithmPractice
/LinkList/2. Add Two Numbers.py
1,103
3.8125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None #这个解题的思路是 用temp来记录进位用于下一轮循环 #每对结点相加的时候立刻创建对应结果结点 处理进位 #一开始超时了 那是因为忘了大家一起next 还是要在脑子里有个动画 #后来报错说none没有next属性 所以给l1=l1.next搞了个条件 #说了这么多其实还是。。题解区nb class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result=ListNode(None) pointer=result temp=0 while l1 or l2 or temp: temp=(l1.val if l1 else 0) + (l2.val if l2 else 0)+temp pointer.next=ListNode(temp%10) temp=temp//10 pointer=pointer.next l1=l1.next if l1 else None l2=l2.next if l2 else None return result.next '''执行用时: 76 ms, 在所有 Python3 提交中击败了62.12%的用户 内存消耗: 13.3 MB, 在所有 Python3 提交中击败了76.55%的用户'''
0890b32420983d05e089bde118c868195ba03b97
msansome/Challenges
/06 - Max Min2.py
5,118
4.375
4
''' OCR 20 Coding Challenges 06 Max and min list =================== Version 2 - With Extension tasks Mark Sansome September 2019 Max and min list Write a program that lets the user input a list of numbers. Every time they input a new number, the program should give a message about what the maximum and minimum numbers in the list are. Extensions 1. The program should let the user choose the allowable minimum and maximum values, and should not let the user input something to the list that is outside of these bounds 2. The user should be able to write these values to a file and then also read them back out again. 3. If a file has any numbers outside of the boundaries, it should strip them out of the list once it has read them in. ''' def getNums(): ''' This functio will get a list of integers from the user It will write them into the 'numlist' array''' numb = input(f"Please enter a number between {lowerB} and {upperB} - XXX to finish: ") while numb.upper() != "XXX": numb = int(numb) if numb >= lowerB and numb <= upperB: numlist.append(numb) else: print(f"Sorry. That number is not betweem {lowerB} and {upperB}.") numb = input("Please enter a number - XXX to finish: ") def findMaxMin(lowerB, upperB): ''' This function will find the maximum and minimun entries in the 'numlist' array''' if len(numlist) == 0: # If the list is empty reset max & min to 0 maxi = 0 mini = 0 else: maxi = lowerB mini = upperB for i in numlist: if i > maxi: maxi = i if i < mini: mini = i return maxi, mini def readfile(filename): ''' This function will attempt to open the file as defined by "filename". if it doesn't exist it will simply call the getNums fuction to start creating a list of numbers. This will later be written to the file.''' try: # Only open if the file exists with open(filename, 'r') as filehandle: contents = filehandle.readlines() for numb in contents: numb = int(numb[:-1]) # Strip off the CR and convert the string to an int if numb >= lowerB and numb <= upperB: numlist.append(numb) # If it's between the upper and lower bounds add it to the list except FileNotFoundError: # The file does not exist so tell the user and start a new list. print("The file does not exist. It will be created now...") getNums() def writefile(filename): ''' This funcion will write the list to the file as defined by "filename". It will write the integer plus a newline character.''' with open(filename, 'w+') as file: # w+ will create the file if it doesn't exist for numb in numlist: file.write(f"{numb}\n") # Save number with a New Line def answerYes(message): ''' Reusable Yes/No function.''' yes = False ans = input(message) ans = ans[0].lower() while ans != "y" and ans != "n": ans = input(message) if ans == "y": yes = True return yes def upperLower(): ''' This function will get upper and lower bounds for the list from the user. If not set, it will use the default values''' upperB = 1000 # Default Values lowerB = 1 if answerYes(f"Do you wish to set upper and lower limits? (default {lowerB}-{upperB}) Y/N : "): lowerB = int(input("Please enter the lower limit: ")) upperB = int(input("Please enter the upper limit: ")) return lowerB, upperB ############################ # Main program starts here # ############################ numlist=[] # Empty list to store the integers filename = "list_of_numbers.txt" # Filename of the file to be written / read lowerB, upperB = upperLower() # Get upper and lower bounds for the list if answerYes("Do you wish to load the last list saved to file? (Y/N): "): print(f"Note: The numbers loaded will be restrict to the upper and lower bounds of {lowerB}-{upperB}.") readfile(filename) else: getNums() # Start a new list print(numlist) high, low = findMaxMin(lowerB, upperB) print("Max =", high, "Min =", low) writefile(filename) # Save the list to a file for next time ''' ###Alternative method to read / write to file with open(filename, 'w') as filehandle: for listitem in numbs[:-1]: # Write all but the last entry filehandle.write(f'{listitem},') # with a comma after it. filehandle.write(f'{numbs[-1]}\n') # Write the last entry with a newline # after it. with open(filename, 'r') as filehandle: filecontents = filehandle.readlines() # read in the file filecontents = filecontents[0] print(filecontents) newthing = filecontents.split(",") for i in range (len(newthing)): newthing[i] = int(newthing[i]) print(newthing) '''
0cd36cf5389664cdf1d81c790d667eb68f83aeb8
BansiddhaBirajdar/python
/assignment08/ass8Q2.py
453
3.90625
4
'''2. Accept single digit number from user and print it into word. Input : 9 Output : Nine Input : -3 Output : Three Input : 12 Output : Invalid Number''' def Dis(ino): no={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'} if(ino<0): ino=-ino else: print(f"OUTPUT::{no[ino]}") def main(): ino=int(input("Enter the ino ::")) Dis(ino) if __name__ == '__main__': main()
90b2f3c3ff4ba0384027cd9ea7e124f4049bd4e6
JoshuaSamuelTheCoder/Quarantine
/Missing_Number/main.py
1,110
3.875
4
""" Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 Example 3: Input: [1, 2, 4, 6, 3, 7, 8] Output: 5 Example 4: Input: [1, 2, 3, 5] Output: 4 Example 5: Input: nums = [7,8,9,11,12] Output: 10 Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? """ class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ min_n = float("inf") max_n = float("-inf") sum_n = 0 count = 0 for n in nums: if n >= 0: sum_n += n min_n = min(min_n, n) max_n = max(max_n, n) count += 1 expected_sum = (min_n + max_n)*(max_n - min_n + 1)//2 return expected_sum - sum_n if __name__ == "__main__": ans = Solution() a = ans.firstMissingPositive([7,8,9,11,12]) print(a)
430f89abc9ce0dc3d148aa39b47faff37bea3b56
Veraph/LeetCode_Practice
/cyc/math/67.py
557
3.9375
4
# 67.py -- Add binary ''' Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. ''' def addBinary(a, b): # create a var to store the inc 1 situation carry = 0 res = '' a = list(a) b = list(b) while a or b or carry: if a: # use pop() to get the last digit carry += int(a.pop()) if b: carry += int(b.pop()) res += str(carry % 2) carry //= 2 return res[::-1]
9423205aa24b009f76b35bec89521f56d7f602c2
bfbonatto/roller
/advanced.py
1,608
3.609375
4
""" This is an advanced version of the roller script, it functions as an arbitrary dice calculator but it can also store and use character information in its calculations """ from random import randint import json import click import re diceMatcher = re.compile('\d\d*d\d\d*') def toString(tup): return ' '.join(list(tup)) def save(char): with open(char['name']+'.json', 'w') as f: json.dump(char, f) def load(charName): with open(charName+'.json', 'r') as f: return json.load(f) def isDice(dice): return diceMatcher.match(dice) is not None def rollDie(die): return randint(1, die) def rollDice(dice): n, d = dice.split('d') return sum( [ rollDie(int(d)) for _ in range(int(n)) ] ) def filterDice(expression): return " ".join([ str(rollDice(e)) if isDice(e) else e for e in expression.split() ]) def filterAttributes(expression): def f(e): name, att = e.split('.') try: char = load(name) return char[att] except: click.echo('invalid character name') return " ".join([f(e) if '.' in e else e for e in expression.split()]) @click.group() def cli(): pass @cli.command() @click.argument('name') def create(name): save({'name': name}) @cli.command() @click.argument("att") @click.argument("value", nargs=-1) def modify(att, value): try: name, attribute = att.split('.') char = load(name) char[attribute] = eval(filterDice(filterAttributes(toString(value)))) save(char) except: click.echo('error') @cli.command() @click.argument("expression", nargs=-1) def roll(expression): click.echo(eval(filterDice(filterAttributes(toString(expression))))) cli()
548ae50d2f7cb3b2ffc9baedf44e1f5cd5ebcd4b
kobe-mop/python
/py_test_code/test/simpleStudy/test_004.py
216
3.9375
4
''' Created on 2016年8月10日 #4 全局变量global# @author: shengxiz ''' def func(): global x print('x is: ',x) x=2 print('Change Local x to',x) x=50 func() print('x is still',x)
21815b97e6e71efc62e6277e346cf88fb40d98c7
ylvaldes/Python-Curso
/Curso/ejemplosSegundo Dia/26.py
1,006
3.921875
4
#!/usr/bin/env python3 class inclusive_range: def __init__(self,*args): n=len(args) self._start=0 self._step=1 if n<1: raise TypeError('expected at least 1 argument, got {}'.format(n)) elif n==1: self._stop=args[0] elif n==2: (self._start,self._stop)=args elif n==3: (self._start,self._stop,self._step)=args else: raise TypeError('expected at most 3 arguments, got {}'.format(n)) self._next=self._start def __iter__(self): # Iterar sobre un elemento return self def __next__(self): # En caso de que el proximo elemento sea mayor lanza una excepcion de paro de la iteracion if self._next>self._stop: raise StopIteration else: _r=self._next self._next+=self._step return _r def main(): for n in inclusive_range(10): print(n,end=' ') print() if __name__ == '__main__': main()
5409af81ec1ce374290d0b3bde0bb5e6930c09f0
gjermundgaraba/py-tictactoe-withgui
/py-tictactoe-withgui/computer_player.py
6,369
3.890625
4
class ComputerPlayer: def __init__(self, game, player): self.game = game self.player = player def make_play(self): if self.two_equal_plays_in_row(0): square = self.get_empty_square_in_row(0) elif self.two_equal_plays_in_row(1): square = self.get_empty_square_in_row(1) elif self.two_equal_plays_in_row(2): square = self.get_empty_square_in_row(2) elif self.two_equal_plays_in_column(0): square = self.get_empty_square_in_column(0) elif self.two_equal_plays_in_column(1): square = self.get_empty_square_in_column(1) elif self.two_equal_plays_in_column(2): square = self.get_empty_square_in_column(2) elif self.two_equal_plays_across_left_to_right(): square = self.get_empty_square_across_left_to_right() elif self.two_equal_plays_across_right_to_left(): square = self.get_empty_square_across_right_to_left() elif self.center_is_free(): square = 1, 1 elif self.opponent_has_played_in_corner() and self.get_empty_corner_square() is not None: square = self.get_empty_corner_square() elif self.no_corner_played(): square = self.get_empty_corner_square() else: square = self.get_first_empty_square() self.game.play(square[0], square[1]) def two_equal_plays_in_row(self, row): number_of_x = 0 number_of_o = 0 current_position = self.game.get_current_position() for i in range(3): player_in_square = current_position[i][row] if player_in_square == 'X': number_of_x += 1 elif player_in_square == 'O': number_of_o += 1 return (number_of_x == 2 and not number_of_o == 1) or (number_of_o == 2 and not number_of_x == 1) def two_equal_plays_in_column(self, column): number_of_x = 0 number_of_o = 0 current_position = self.game.get_current_position() for i in range(3): player_in_square = current_position[column][i] if player_in_square == 'X': number_of_x += 1 elif player_in_square == 'O': number_of_o += 1 return (number_of_x == 2 and not number_of_o == 1) or (number_of_o == 2 and not number_of_x == 1) def two_equal_plays_across_left_to_right(self): number_of_x = 0 number_of_o = 0 current_position = self.game.get_current_position() if current_position[0][0] == 'X': number_of_x += 1 if current_position[0][0] == 'O': number_of_o += 1 if current_position[1][1] == 'X': number_of_x += 1 if current_position[1][1] == 'O': number_of_o += 1 if current_position[2][2] == 'X': number_of_x += 1 if current_position[2][2] == 'O': number_of_o += 1 return (number_of_x == 2 and not number_of_o == 1) or (number_of_o == 2 and not number_of_x == 1) def two_equal_plays_across_right_to_left(self): number_of_x = 0 number_of_o = 0 current_position = self.game.get_current_position() if current_position[2][0] == 'X': number_of_x += 1 if current_position[2][0] == 'O': number_of_o += 1 if current_position[1][1] == 'X': number_of_x += 1 if current_position[1][1] == 'O': number_of_o += 1 if current_position[0][2] == 'X': number_of_x += 1 if current_position[0][2] == 'O': number_of_o += 1 return (number_of_x == 2 and not number_of_o == 1) or (number_of_o == 2 and not number_of_x == 1) def get_empty_square_in_row(self, row): current_position = self.game.get_current_position() for i in range(3): if current_position[i][row] == '': return i, row def get_empty_square_in_column(self, column): current_position = self.game.get_current_position() for i in range(3): if current_position[column][i] == '': return column, i def get_empty_square_across_left_to_right(self): current_position = self.game.get_current_position() if current_position[2][0] == '': return 2, 0 elif current_position[1][1] == '': return 1, 1 elif current_position[0][2] == '': return 0, 2 def get_empty_square_across_right_to_left(self): current_position = self.game.get_current_position() if current_position[0][2] == '': return 0, 2 elif current_position[1][1] == '': return 1, 1 elif current_position[2][0] == '': return 2, 0 def center_is_free(self): current_position = self.game.get_current_position() return current_position[1][1] == '' def opponent_has_played_in_corner(self): current_position = self.game.get_current_position() if ( (current_position[0][0] != '' and current_position[0][0] != self.player) or (current_position[2][0] != '' and current_position[2][0] != self.player) or (current_position[0][2] != '' and current_position[0][2] != self.player) or (current_position[2][2] != '' and current_position[2][2] != self.player) ): return True else: return False def get_empty_corner_square(self): current_position = self.game.get_current_position() if current_position[0][0] == '': return 0, 0 elif current_position[2][0] == '': return 2, 0 elif current_position[0][2] == '': return 0, 2 elif current_position[2][2] == '': return 2, 2 def no_corner_played(self): current_position = self.game.get_current_position() return current_position[0][0] == '' or current_position[2][0] == '' or current_position[0][2] == '' or current_position[2][2] == '' def get_first_empty_square(self): current_position = self.game.get_current_position() for x in range(3): for y in range(3): if current_position[x][y] == '': return x, y
aa471f8ccd081731cbf1e20b36e2171131f216b0
Software-Design-Team-Carl/ourfavorites
/datasource.py
7,220
3.5625
4
import psycopg2 import getpass class Nutrek: ''' Nutrek executes all of the queries on the database and formats the data to send back to the front end''' def connect(self, user, password): ''' Establishes a connection to the database with the following credentials: user - username, which is also the name of the database password - the password for this database on perlman Note: exits if a connection cannot be established. ''' try: self.connection = psycopg2.connect(host="localhost", database=user, user=user, password=password) except Exception as e: print("Connection error: ", e) exit() def disconnect(self): ''' Breaks the connection to the database ''' self.connection.close() def getNutrients(self, food): ''' returns all nutrients and the amount of each nutrient in a given food ''' food = food.upper() nutrientList = ["ash(g)", "biotin(mcg)", "caffeine(mg)", "calcium(mg)", "carbohydrate by difference(g)", "carbohydrate_other(g)", "cholesterol(mg)", "chromium(mcg)", "copper(mg)", "fatty acids total monounsaturated(g)", "fatty acids total polyunsaturated (g)", "fatty acids total saturated(g)", "fatty acids total trans(g)", "fiber insoluble(g)", "fiber soluble(g)", "fiber total dietary(g)", "folic acid(mcg)", "iodine(mcg)", "iron(mg)", "lactose(g)", "magnesium(mg)", "manganese(mg)", "niacin(mg)", "pantothenic acid(mg)", "phosphorus (mg)", "potassium(mg)", "protein(g)", "riboflavin(mg)", "selenium(mcg)", "sodium(mg)", "sugars added(g)", "sugars total(g)", "thiamin(mg)", "total lipid fat(g)", "total sugar alcohols(g)", "vitamin a IU" , "vitamin b 12(mcg)", "vitamin b-6(mg)", "vitamin c total ascorbic acid(mg)", "vitamin d IU", "vitamin e label entry primarily IU", "vitamin K phylloquinone(mcg)", "water(g)", "xylitol(g)", "zinc(mg)"] try: cursor1 = self.connection.cursor() cursor1.execute("SELECT Ash_grams, Biotin_mcg, Caffeine_mg, Calcium_Ca_mg, Carbohydrate_by_difference_g, Carbohydrate_other_g, Cholesterol_mg, Chromium_Cr_mcg, Copper_Cu_mg, Fatty_acids_total_monounsaturated_g, Fatty_acids_total_polyunsaturated_g, Fatty_acids_total_saturated_g, Fatty_acids_total_trans_g, Fiber_insoluble_g, Fiber_soluble_g, Fiber_total_dietary_g, Folic_acid_mcg, Iodine_I_mcg, Iron_Fe_mg, Lactose_g, Magnesium_Mg_mg, Manganese_Mn_mg, Niacin_mg, Pantothenic_acid_mg FROM Nutrek WHERE food_name LIKE " + str("'%"+food+"%'") + ";") results1 = cursor1.fetchall() cursor2 = self.connection.cursor() cursor2.execute("SELECT Phosphorus_P_mg, Potassium_K_mg, Protein_g, Riboflavin_mg, Selenium_Se_mcg, Sodium_Na_mg, Sugars_added_g, Sugars_total_g, Thiamin_mg, Total_lipid_fat_g, Total_sugar_alcohols_g, Vitamin_A_IU , Vitamin_B12_mcg, Vitamin_B6_mg, Vitamin_C_total_ascorbic_acid_mg, Vitamin_D_IU, Vitamin_E_label_entry_primarily_IU, Vitamin_K_phylloquinone_mcg, Water_g, Xylitol_g, Zinc_Zn_mg FROM Nutrek WHERE food_name LIKE " + str("'%"+food+"%'") + ";") results2 = cursor2.fetchall() fullNutrientList = [] results = [] for i in results1[0]: results.append(i) for j in results2[0]: results.append(j) nutrientDictionary = {} for nutrient, proportion in zip(nutrientList, results): nutrientDictionary[nutrient] = proportion return nutrientDictionary except Exception as e: print ("Something went wrong when executing the query: ", e) return None def getIngredientBreakDown(self, food): ''' returns all the ingredients in a given food item''' food = food.upper() try: cursor = self.connection.cursor() query = ("SELECT ingredients_english FROM Nutrek WHERE food_name LIKE " + str("'%"+food+"%'") +";") cursor.execute(query) results = cursor.fetchall() results = results[0] FullIngredientList = [] for item in results: if "(" in item: item = item.replace("(", "") if "," in item: item = item.replace(",", "") if ")" in item: item = item.replace(")","") FullIngredientList.append(item) return FullIngredientList except Exception as e: print ("Something went wrong when executing the query: ", e) return None def getFoodAvailable(self, food): '''returns all foods in database''' food = food.upper() try: cursor = self.connection.cursor() query = ("SELECT food_name FROM Nutrek WHERE food_name LIKE " + str("'%"+food+"%'") +";") cursor.execute(query) results = cursor.fetchall() return results except Exception as e: print ("Something went wrong when executing the query: ", e) return None def containsAllergen(self, food, allergen): '''returns True if food contains allergen (could cause allergic reaction) and false if otherwise ''' ingredients = self.getIngredientBreakDown(food) FullIngredientList = [] allergen = allergen.upper() for item in ingredients: if "(" in item: item = item.replace("(", "") if "," in item: item = item.replace(",", "") if ")" in item: item = item.replace(")","") FullIngredientList.append(item) food = food.upper() try: for ing in FullIngredientList: if allergen in ing: return True return False except Exception as e: print ("Something went wrong when executing the query: ", e) return None def checkNutrientThreshold(self, food, nutrient): '''check if the amount of nutrients in a given food to enable them see if they are meeting a nutritional goal.''' food = food.upper() nutrient = nutrient.lower() try: nutrientDictionary = self.getNutrients(food) for item in nutrientDictionary: if nutrient in item: return item, nutrientDictionary[item] except Exception as e: print ("Something went wrong when executing the query: ", e) return None def main(): user = 'odoome' password = 'tiger672carpet' #password = getpass.getpass() # Connect to the database N = Nutrek() N.connect(user, password) print(N.getFoodAvailable('yoghurt')) print("\n") print(N.getNutrients('granola')) print("\n") print(N.getIngredientBreakDown('granola')) print("\n") print(N.containsAllergen('granola', 'peanut')) print("\n") print(N.checkNutrientThreshold('granola', 'protein')) # Disconnect from database N.disconnect() main()
6cd6a83aeeeeff09d9c0e0824ea6966c14aebf12
TadpoleNew/test
/craps.py
1,720
3.796875
4
from random import randint # *,是命名关键字参数,可以增加代码的可读性,在调用函数时必须给出参数名和参数值 # def roll_dice(a, *, num = 1): def roll_dice(*, num=1): total = 0 for _ in range(num): total += randint(1, 6) return total def main(): # first = roll_dice(1, num = 2, 3) # SyntaxError: positional argument follows keyword argument 位置参数遵循关键字参数 # first = roll_dice(1, 2) # TypeError: roll_dice() takes 1 positional # argument but 2 were given 类型错误:roll骰()接受1个位置参数,但是有2个 money = 1000 while money > 0: print(f'玩家总资产:{money}元') while True: debt = int(input('请下注:')) if 0 < debt <= money: break first = roll_dice(num=2) print(f'玩家摇出了{first}点.') game_over = True # 假设第一次就能分出胜负 if first == 7 or first == 11: money += debt print('玩家胜!') elif first == 2 or first == 3 or first == 12: money -= debt print('庄家胜!') else: game_over = False # 说明游戏没有分出胜负 while not game_over: current = roll_dice(num=2) print(f'玩家摇出了{current}点。') if current == 7: money -= debt print('庄家胜!') game_over = True elif current == first: money += debt print('玩家胜') game_over = True # print(current) print('你已破产') if __name__ == '__main__': main()
0fd5c72d9d857f759c5c245d1c03f1f60db94ea2
Johanstab/INF200-2019-Exercises
/src/johan_stabekk_ex/ex02/file_stats.py
1,093
4.25
4
# -*- coding: utf-8 -*- __author__ = 'Johan Stabekk' __email__ = 'johan.stabekk@nmbu.no' def char_counts(textfilename): """ Opens the given file then reads it in to single string. It then counts how often each character code occurs in the string, then returns a list with the results. Parameters ---------- textfilename - The text file you want to analyse. Returns ------- result - Returns a list of the counted character codes. """ with open(textfilename, encoding='utf-8') as file: read_file = file.read() result = [0]*256 for char in read_file: ascii_val = ord(char) result[ascii_val] += 1 return result if __name__ == '__main__': filename = 'file_stats.py' frequencies = char_counts(filename) for code in range(256): if frequencies[code] > 0: character = '' if code >= 32: character = chr(code) print( '{:3}{:>4}{:6}'.format( code, character, frequencies[code] ) )
bf83d5ce234e6c22cb52091a5437b8880c0bd7e9
DidiMilikina/DataCamp
/Machine Learning Scientist with Python/03. Linear Classifiers in Python/02. Loss functions/01. Changing the model coefficients.py
1,058
4.375
4
''' Changing the model coefficients When you call fit with scikit-learn, the logistic regression coefficients are automatically learned from your dataset. In this exercise you will explore how the decision boundary is represented by the coefficients. To do so, you will change the coefficients manually (instead of with fit), and visualize the resulting classifiers. A 2D dataset is already loaded into the environment as X and y, along with a linear classifier object model. Instructions 100 XP Set the two coefficients and the intercept to various values and observe the resulting decision boundaries. Try to build up a sense of how the coefficients relate to the decision boundary. Set the coefficients and intercept such that the model makes no errors on the given training data. ''' SOLUTION # Set the coefficients model.coef_ = np.array([[0,1]]) model.intercept_ = np.array([0]) # Plot the data and decision boundary plot_classifier(X,y,model) # Print the number of errors num_err = np.sum(y != model.predict(X)) print("Number of errors:", num_err)
8389be742324ef0a6265493d9617e8faca089435
MAHESHRAMISETTI/My-python-files
/tue.py
290
3.75
4
num=int(input('enter the table you want to print\n')) for a in range (1,11): print(num,'x','a','=',num*a) a=0 while a<10: print(a) a+=1 for a in 'rahul': if 'h'== a: break print(a) for a in 'rahul': if 'x'==a: continue print(a) L1=[1,2,3,'hello',39.6] print(L1[3])
1c824370a0d56999fbe3436725167bfee86493b6
JonMer1198/developer
/programstarter.py
1,133
3.609375
4
from math import * from sympy import * import numpy as np a,b,c,x = symbols('a,b,c,x') #f = a*x**2 + b*x + c #f = a*x**4 f = 3.0 / ((2.0*x)+2) #f = Function('f') x = Symbol('x') #fprime = f(x).diff(x) - f(x) # f' = f(x) F = integrate(f,x) F = str(F) # y = dsolve(fprime, f(x)) y = Symbol('y') eqn = Eq(((3.0)/(2.0)*(np.log(2*y+2)), 1) # print y print(f) #print y.subs(x,4) #print [y.subs(x, X) for X in [0, 0.5, 1]] # multiple values #solution = solve(f, x) #print solution #print(F) #print integrate(f, x) # indefinite integral #print integrate(f, (x, 0, 1)) # definite integral from x=0..1 #print diff(f, x) #print diff(f, x, 2) # 2nd part differentiate respect to x, 3rd part; the number represents amount of derivatives taken #print diff(f, a) ############Program for computing the height of a ball in vertical motion############################### #v_0 = 5 #initial velocity #g = 9.81 #acceleration of gravity #t = 0.6 #time #y = v_0*t - 0.5*g*t**2 #vertical position #print(y) ###################Program for conversion from Celcius to Fahrenheit########################## #C = 21 #F = (9/5)*C +32 #print(F)
bb7b35c54f69efc6274212b0c8f5603d8ad62c20
TushaFalia/Tusha-Code
/Assignment 1 Ceaser Cipher.py
776
4
4
# Final assingnment 1 encrypt : def encrypt(x,y): l='' for i in range(len(x)): b= ord(x[i])+y d=(chr(b)) l+=d return l #print('Cipher:',l) if __name__ == '__main__': a= input("Please Enter the Text:") c= int(input("Please Enter The Key Number:")) print("Cipher:" ,(encrypt(a,c))) #encrypt(a,c) # Final assingnment 1 decrypt : def decrypt(x,y): l='' for i in range(len(x)): b= ord(x[i])-y d=(chr(b)) l+=d return l #print('Decipher:',l) if __name__ == '__main__': a= input("Please Enter the Encrypt Text:") c= int(input("Please Enter The Key Number:")) print("Decipher:" ,(decrypt(a,c))) #decrypt(a,c)
9655b75467b2a1b09c31b936c79142452211afce
presianbg/HackBG-Programming101
/WEEK-1/application/caesar_encrypt.py
988
3.953125
4
#!/usr/bin/python import sys, argparse import math def caesar_encrypt(): parser = argparse.ArgumentParser(description='Process some strings.') parser.add_argument('-a', type=str) parser.add_argument('-k', nargs=1 , type=int, choices=xrange(0, 26)) args = parser.parse_args() cipher = str() print "Your string is: %s" % args.a for passnum in range(len(args.a)): if args.a[passnum].isalpha() == True: n = ord(args.a[passnum]) n += args.k[0] if args.a[passnum].isupper(): if n > ord('Z'): n -= 26 elif n < ord('A'): n +=26 elif args.a[passnum].islower(): if n > ord('z'): n -= 26 elif n < ord('a'): n += 26 cipher += chr(n) else: cipher += args.a[passnum] print "Your Ceasar coded string is: %s" % cipher caesar_encrypt()
2ddf2bbbd682d422b62c858c8e25969db28fd5fd
shehryarbajwa/Algorithms--Datastructures
/algoexpert/hatchways/depth_first_search.py
1,094
3.765625
4
# Sample Input # graph = A # / | \ # B C D # / \ / \ # E F G H # After DFS - [A,B,E,F,C,D,G,H] #Time Complexity O(V + E) O(V) for adding each vertex to the array. O(V) for the amount of times we have to traverse the children Nodes #Space Complexity O(V) for adding DFS to the call stack for each vertex class Node: def __init__(self, name): self.name = name self.children = [] def add_child(self, child): self.children.append(Node(child)) def depth_first_search(self, array): array.append(self.name) for child in self.children: child.depth_first_search(array) return array # A # / \ # B C # / \ # E D node1 = Node('A') node1.add_child('B') node1.add_child('C') node1.children[0].add_child('E') node1.children[1].add_child('D') print(node1.depth_first_search([]))