blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
57d8954fbba66252f63c2264b1f16c9f36adaa51
gabee1987/codewars
/CodeWars/stuff_test.py
161
3.734375
4
words = ['aabb', 'abcd', 'bbaa', 'dada'] sorted_words = [] for i in words: a = sorted(i) b = "".join(a) sorted_words.append(b) print(sorted_words)
0882864e7032f124d064fb5d5ab20f1b8c5308c3
brubribeiro/Python-EC
/movimentoObliquo.py
250
3.921875
4
#Bruna Ribeiro import math; theta = float(input()); velocidade = float(input()); gravidade = float(input()); radianos = math.radians(theta); h = (math.pow(velocidade, 2) * (math.sin(radianos))**2) denominador = (h/(2*gravidade)) print(denominador)
562048ef51c2f416afcbcc04c19a18564511a812
vishalvb/practice
/python_practice/slicing.py
414
4.125
4
#List slicing my_list = [0,1,2,3,4,5,6,7,8,9] print("list = ",my_list) print("my_list[0:]",my_list[0:]) print("my_list[:]",my_list[:]) print("my_list[:-1]",my_list[:-1]) print("my_list[1:5]",my_list[1:5]) #list(start:end:step) print("my_list[1::3]",my_list[1::3]) print("my_list[-1:1:-1]",my_list[-1:1:-1]) sample_url = 'https://mydomain.com' print("sample_url =",sample_url) print("reverse", sample_url[::-1])
2216c8bccf7af48fe03b888a3f82ed38c588792c
rereal7/Algoshiki_practice
/lecture_groups-13/Q1/Q1_5.py
129
3.578125
4
n = int(input()) ans = 0 # 後ろから見て貪欲法 while n > 0: if n%3 == 0: n //= 3 else: n -= 1 ans += 1 print(ans)
540cb2ffb66eac8c601ed844610cd0229a4f035f
maomao905/algo
/clone-n-ary-tree.py
738
3.53125
4
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] """ from collections import deque class Solution: def cloneTree(self, root: 'Node') -> 'Node': if not root: return None dummy = Node() q = deque([(root, dummy)]) # original node and clone parent node while q: node, parent = q.popleft() clone = Node(node.val) parent.children.append(clone) for ch in node.children: q.append((ch, clone)) return dummy.children[0]
8e4df277fa11f0b3e400f1c1c3bf012c25086b08
drettt/fattails
/fattails/metrics.py
2,404
3.703125
4
from copy import copy import numpy as np import pandas as pd def mad(x): """Calculate Mean Absolute Deviation Not to be confused with commonly found 'Median' Absolute Deviation. Parameters ---------- x : array_like Input array or object that can be converted to an array. Returns ------- mad : scalar Mean Absolute Deviation of x """ mean = np.mean(x) deviation = x-mean absolute_deviation = np.abs(deviation) mad = np.mean(absolute_deviation) return mad def get_survival_probability(arr): """Calculate sample probability of X >= x, for each value in `arr`. Duplicate values are treated as ascending values based on their position in `arr`. Parameters ---------- arr : array_like Numeric values on the real number line Returns ------- survival_probability_sr : Pandas Series """ #--------------------------------------------------- # PREPARE ## Sort values from low to high. Keep track of original ## index and order. arr = copy(arr) # Copy to avoid accidental mutation sr = pd.Series(arr) # Ensure we have a pandas series ## Keep a copy of the original index input_index = sr.index.copy() ## Create index of input order df = sr.reset_index(name='input_values') # Keeps the input index as a column df.index.name = 'input_order' # Name the new index ## Sort from low to high and reindex df = df.sort_values(by='input_values') # sort from low to high df = df.reset_index() df.index.name = 'sorted_order' # Name the new index #--------------------------------------------------- # CALCULATE # Label relative positions gap_count = len(sr) + 1 # Think of the Posts and Fences analogy df['left_gap_count'] = df.index + 1 # Count values <= x df['right_gap_count'] = gap_count - df.left_gap_count # Count values >= x # Get survival Probability df['survival_probability'] = df.right_gap_count / gap_count #--------------------------------------------------- # FORMAT THE OUTPUT #Reset Input Order and Index df = df.sort_values(by='input_order') # sort from low to high df.index = input_index #Extract the output series survival_probability_sr = df.survival_probability return survival_probability_sr
4be21200cbf9a7140a62c3addeac3e746a4f0b13
digjao/CursoEmVideo
/ExerciciosModulosPython/ex028.py
262
3.765625
4
velo = int(input('A velocidade do carro é: ')) if velo > 80: print('Você foi multado, pois a velocidade permitida é até 80Km/h') print('O valor da sua multa será de: R${:.2f} '.format((velo-80)*7)) print('Tenha um bom dia, dirija com segurança!')
c7732a8db8aedc7136b6e2453c2c18bce6d15bab
jluocc/jluo2018
/python/python/老师笔记/python/day17/day17/code/del_method.py
458
3.765625
4
# del_method.py # 此示例示意析构方法的定义和自动调用 class Car: def __init__(self, info): self.info = info print("汽车:", info, "对象被创建") def __del__(self): '''这是析构方法,形参只有一个self''' print("汽车", self.info, "被销毁") c1 = Car("BYD E6") c2 = c1 # c2绑定谁? del c1 # 删除变量c1 input("按回车键继续执行程序: ") print("程序正常退出")
3ca1a4be4318611edede3bba71da401b6ae9e014
rogeriosilva-ifpi/adsi-algoritmos-2016.1
/atividade_f/Atividade F - Kairo Emannoel - Leonardo Freitas/lista3questao16.py
364
4.125
4
def fibonacci(n,numero1 = 0, numero2 = 1): if n>0: atual=numero1+numero2 numero1=numero2 numero2=atual print atual, fibonacci(n-1,numero1,numero2) def main(): n=input("Insira numero de termos: ") n-=2 numero1=0 numero2=1 print numero1,numero2, fibonacci(n) if __name__ == '__main__': main()
6235af062f0b6607670939fe55b997691dc1d3b5
lethargilistic/MiscellaneousPython
/workClock.py
836
3.546875
4
import time import winsound SECONDS_IN_MIN = 60 DEFAULT_WORK = 10 DEFAULT_BREAK = 5 def wait(minutes): while minutes > 0: print(minutes, "minutes remaining...") time.sleep(SECONDS_IN_MIN) minutes -= 1 def main(): automatic = "q" while automatic != "y" and automatic != "n": automatic = input("Do you want automatic?(y/n): ") while True: if automatic == "y": t = DEFAULT_WORK else: t = int(input("Work how long? ")) print("Work time!") winsound.Beep(300, 2000) wait(t) if automatic == "y": t = DEFAULT_BREAK else: t = int(input("Rest how long? ")) print("Break time!") winsound.Beep(500, 750) winsound.Beep(500, 750) wait(t) main()
01c5662837c9a4f051c10e5d305b7fd00f0a41de
UalwaysKnow/-offer
/offer/栈和队列/包含min函数的栈(辅助栈).py
443
3.734375
4
class stack: def __init__(self): self.stack1 = [] self.stack2 = [] def pop(self): if len(self.stack1) == 0: return None if self.stack1[-1] == self.stack2[-1]: self.stack2.pop() self.stack1.pop() def push(self,data): self.stack1.append(data) if len(self.stack2) == 0 or data < self.stack2[-1]: self.stack2.append(data) def min(self): return self.stack2[-1] s = stack() s.push(3) s.push(2) s.push(4) print(s.min())
1303b4d4d625bf0bb46f647e0c10950b5ea1a696
macheart/Eight-Puzzle
/board.py
4,971
4.1875
4
class Board: """ A class for objects that represent an Eight Puzzle board. """ def __init__(self, digitstr): """ A constructor for a Board object whose configuration is specified by the input digitstr input: digitstr is a permutation of the digits 0-9 """ # check that digitstr is 9-character string # containing all digits from 0-9 assert(len(digitstr) == 9) for x in range(9): assert(str(x) in digitstr) self.tiles = [[0] * 3 for x in range(3)] self.blank_r = -1 self.blank_c = -1 # Put your cod e for the rest of __init__ below. # Do *NOT* remove our code above. for r in range(3): for c in range(3): if digitstr[3*r + c] == '0': self.blank_r = r self.blank_c = c self.tiles[r][c] = int(digitstr[3*r + c]) else: self.tiles[r][c] = int(digitstr[3*r + c]) ### Add your other method definitions below. ### def __repr__(self): """Returns a string representation of a Board""" s = '' for r in range(3): for c in range(3): if self.tiles[r][c] == 0: s += '_' + ' ' else: s += str(self.tiles[r][c]) + ' ' s += '\n' return s def move_blank(self, direction): """Takes a string direction (that the blank should move) and attempts to modify the contents of the Board returns True or False to indicate whether the move if possible""" if direction != 'up' and direction != 'down' and direction != 'left' and direction != 'right': print('unknown direction:', direction) return False if direction == 'up': new_r = self.blank_r - 1 new_c = self.blank_c if direction == 'down': new_r = self.blank_r + 1 new_c = self.blank_c if direction == 'left': new_r = self.blank_r new_c = self.blank_c - 1 if direction == 'right': new_r = self.blank_r new_c = self.blank_c + 1 if new_r > 2 or new_r < 0 or new_c > 2 or new_c < 0: return False else: original_tile = self.tiles[new_r][new_c] self.tiles[new_r][new_c] = 0 self.tiles[self.blank_r][self.blank_c] = original_tile self.blank_r = new_r self.blank_c = new_c return True def digit_string(self): """Returns a string of digits that corresponds to the current contents of Board""" current_digitstr = '' for r in range(3): for c in range(3): current_digitstr += str(self.tiles[r][c]) return current_digitstr def copy(self): """Returns a Board object that is a deep copy of the called object""" copy_string = self.digit_string() copy_board = Board(copy_string) return copy_board def num_misplaced(self): """Counts and returns the number of tiles not in goal state""" goal = 0 num = 0 for r in range(3): for c in range(3): if self.tiles[r][c] == 0: goal += 1 else: if self.tiles[r][c] == goal: goal += 1 else: goal += 1 num += 1 return num def where_misplaced(self): """Returns a list of location of misplaced tiles""" goal = 0 misplaced_locations = [] goal_list = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]] misplaced_sum = 0 for r in range(3): for c in range(3): if self.tiles[r][c] == goal: goal += 1 else: location = [r, c] misplaced_locations += [location] goal += 1 #found misplaced_locations in a list for x in misplaced_locations: current = self.tiles[x[0]][x[1]] goal_index = current y = goal_list[goal_index] misplaced_sum += abs(x[0] - y[0]) misplaced_sum += abs(x[1] - y[1]) return misplaced_sum def __eq__(self, other): """Overloads the == operator Return True if the called object and the argument have same values for the tiles False otherwise""" for r in range(3): for c in range(3): if self.tiles[r][c] != other.tiles[r][c]: return False return True
7674493f3b11d5cc7583c1e7309ed37f663138ee
soumiyajit/python
/python-basic/011-list3.py
152
3.6875
4
""" list of list for mutiplication table """ def multi_table(a): multi = [[a,b,a*b] for b in range(1,11)] return multi print multi_table(5)
c5783decee20671f5849ce7fe728622429945a27
liqingxuan/ECS165
/3c.py
1,331
3.625
4
import psycopg2 #open databse connection db = psycopg2.connect(database = "postgres") ###################------------3c------------#################### #Question 3c:Name and average grade of easiet and hardest instructor cursor3c = db.cursor() #find all instructors ans his assigned total GPA and total GPA*units cursor3c.execute("SELECT m.inst_name, sum(t.units), sum(t.units * t.gpa) AS UG FROM meetings m, transcript t WHERE m.CID = t.CID AND m.term = t.term AND m.inst_name <> 'NaN' AND t.units <> 'NaN' AND t.GPA <> 'NaN' GROUP BY m.inst_name ") hardest = cursor3c.fetchall() #pre assigned the value easyInst = 0.0 hardInst = 4.0 easyName = hardest[0][0] hardName = hardest[0][0] #compare those values to find the hardest and the easiest for i in range(len(hardest)): if(float(hardest[i][2])/float(hardest[i][1]) > easyInst): easyInst = float(hardest[i][2])/float(hardest[i][1]) easyName = hardest[i][0] if(float(hardest[i][2])/float(hardest[i][1]) < hardInst): hardInst = float(hardest[i][2])/float(hardest[i][1]) hardName = hardest[i][0] print '*****3c*****' print('The easiest instructor is %s His average grade is %s'% (easyName, str(easyInst))) print('The hardest instructor is %s His average grade is %s'% (hardName, str(hardInst))) #disconnect from server db.close()
e3ec2675e631c5a066482e2fee9c44ac2d7a8d14
Zahidsqldba07/sandbox
/codewars/swap-items-in-a-dictionary.py
752
4.34375
4
''' https://www.codewars.com/kata/swap-items-in-a-dictionary In this kata, you will take the keys and values of a dictionary and swap them around. You will be given a dictionary, and then you will want to return a dictionary with the old values as the keys, and list the old keys as values under their original keys. For example, given the dictionary: ```{'Ice': 'Cream', 'Age': '21', 'Light': 'Cream', 'Double': 'Cream'}```, you should return: ```{'Cream': ['Ice', 'Double', 'Light'], '21': ['Age']}``` # Notes: * The dictionary given will only contain strings * The dictionary given will not be empty * You do not have to sort the items in the lists ''' switch_dict = lambda d: {v: [k for k in d.keys() if d.get(k) == v] for v in d.values()}
b324c0eec8a263d56da84a608091a72325fb2457
Katarzyna-Bak/Coding-exercises
/Do I get a bonus.py
961
3.859375
4
""" It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money? Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean. If bonus is true, the salary should be multiplied by 10. If bonus is false, the fatcat did not make enough money and must receive only his stated salary. Return the total figure the individual will receive as a string prefixed with "£" (= "\u00A3", JS, Go, Java and Julia), "$" (C#, C++, Ruby, Clojure, Elixir, PHP, Python, Haskell and Lua) or "¥" (Rust). """ def bonus_time(salary, bonus): return '${}'.format(salary if bonus == False else salary*10) print("Tests:") print(bonus_time(10000, True)) print(bonus_time(25000, True)) print(bonus_time(10000, False)) print(bonus_time(60000, False)) print(bonus_time(2, True)) print(bonus_time(78, False)) print(bonus_time(67890, True))
3f1e14d8aa71c9713a410d4876457229b189087c
salvador-dali/algorithms_general
/interview_bits/level_1/01_mathematics/00_example/03_prime_numbers.py
395
3.6875
4
# https://www.interviewbit.com/problems/prime-numbers/ def eratosthenes_sieve(n): prime, result, sqrt_n = [True] * n, [2], (int(n ** .5) + 1) | 1 append = result.append for p in xrange(3, sqrt_n, 2): if prime[p]: append(p) prime[p*p::p << 1] = [False] * ((n - p*p - 1) / (p << 1) + 1) return result + [p for p in xrange(sqrt_n, n, 2) if prime[p]]
5fad216dbc142984fda6aa2799962119dee0d36f
itzadi22/Basic-python
/difference_betweeen_two_dates.py
275
3.96875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 24 10:30:16 2021 Difference between any two dates @author: ASUS """ import datetime a=datetime.datetime(2000, 12, 22) b=datetime.datetime(2000, 12, 25) c=b-a print("The difference between two dates is :",c)
ed1532908486ac891ae639bda6aba78acd1aae24
Hassan8521/alx-higher_level_programming-1
/0x07-python-test_driven_development/2-matrix_divided.py
1,918
4.09375
4
#!/usr/bin/python3 """Define a matrix devision function""" def matrix_divided(matrix, div): """Divide all element of a matrix. Args: matrix(list): A list of lists of int/floats. div(int/float): The diviaor. Raises: TypeError:if the matrix contains non number, if the matrix contains rows of d/ff sizes, if div is not int/float ZeroDivisionError: if div is 0. Returns: A new matrix with the result of the division """ # Checks if matrix is a list if not isinstance(matrix, list): raise TypeError("matrix must be a matrix (list of lists) of " "integers/floats") # Checks if the first element in matrix is a list so len can be used if isinstance(matrix[0], list): rowlen = len(matrix[0]) # Checking if matrix is formatted correctly for mtx in matrix: # Checks if mtx is a list if not isinstance(mtx, list): raise TypeError("matrix must be a matrix (list of lists) of " "integers/floats") # Checks if the length of each row is the same if len(mtx) != rowlen: raise TypeError("Each row of the matrix must have the same size") # Checks if the elements in the matrix are int or float for elemnt in mtx: if not isinstance(elemnt, (int, float)): raise TypeError("matrix must be a matrix (list of lists) of " "integers/floats") # Checks if div is a number if not isinstance(div, (int, float)): raise TypeError("div must be a number") # Checks if div is 0 if div == 0: raise ZeroDivisionError("division by zero") # Dividing original matrix and creating a new matrix new_matrix = [[round(idx / div, 2) for idx in mtx] for mtx in matrix] return new_matrix
c7ac685f28e29c023644364e3c4c5b945ef11825
unix2dos/pythonTest
/grammar/map_reduce.py
623
3.953125
4
# map()函数接收两个参数,一个是函数,一个是Iterable, # map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。 # python3 from functools import reduce a = list(map(str, [1, 2, 3, 4, 5])) print(a) # reduce把一个函数作用在一个序列[x1, x2, x3, ...]上, # 这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是: # reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) # reduce 需要 import def sum(a, b): return a + b total = reduce(sum, [1, 2, 3, 4, 5]) print(total)
85f681e19f46dc6a31cfdff400e05e603826aa58
lindo-zy/python-100
/python-009.py
225
3.609375
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- ''' 题目:暂停一秒输出。 程序分析:使用 time 模块的 sleep() 函数。 ''' import time l = [1, 2, 3, 4] for i in range(len(l)): print(l[i]) time.sleep(1)
121ad3d14ece3ef9ab8d32ca8fa53d846563064d
moonlimb/interview_prep
/challenges/prod_of_other.py
1,099
3.75
4
from operator import mul def make_prod_ls(ls, zero_count, zero_index, prod_of_nums): if zero_count >= 1: # more than 1 zero: prod_ls contains all 0's prod_ls = [0] * len(ls) if zero_count == 1: # 1 zero: set element in prod_ls at zero_index to prod_of_nums prod_ls[zero_index]=prod_of_nums else: prod_ls = [prod_of_nums/n for n in ls] return prod_ls # ls is a list of integers def prod_of_other_nums(ls): prod_ls = [] if len(ls) == 1: # returns empty list if length of ls is 1 return prod_ls zero_count, zero_index =0, 0 prod_of_nums = 1 for i in range(len(ls)): # what is run-time for len(ls) if ls[i] == 0: zero_index = i zero_count += 1 else: prod_of_nums *= ls[i] # product of all nums (except 0) in ls prod_ls = make_prod_ls(ls, zero_count, zero_index, prod_of_nums) return prod_ls # not used def get_prod(ls): "calculate the product of all nums, excluding 0, in list" return reduce(mul, [x for x in ls if x !=0])
2303927115fec377f10b103aec0cabd648c8d123
amarF117/forgit
/alfa5.py
510
3.703125
4
manushowProduc = 1 menubuyProduc = 2 productName =3 productPrice = 180 userBalanc = int (input("Enter ammout")) userCommand = int (input("Enter command")) if (userCommand ==1): print("Name " , productName ) print("Price ", productPrice) if (userCommand ==2 ): if (userCommand >= productPrice): print("You bought the prodoct") if (userBalanc < productPrice): print("you dont have enough balanc ") if (userCommand == 3 ): print("good buy")
60b5d34f34a4b0d06b4c263342c51d69086f51f2
eirikhoe/advent-of-code
/2015/20/sol.py
1,232
3.71875
4
def find_presents(house_number): divisible = [] i = 1 while i * i <= house_number: if (house_number % i) == 0: d = house_number // i divisible.append(i) if i != d: divisible.append(d) i += 1 return sum(divisible) * 10 def find_presents_alt(house_number): divisible = [] i = 1 while i <= min(50, house_number): if (house_number % i) == 0: d = house_number // i divisible.append(d) i += 1 return sum(divisible) * 11 def find_lowest_house_number(target, alt=False): method = {False: find_presents, True: find_presents_alt} house_number = 1 p = method[alt](house_number) while p < target: house_number += 1 p = method[alt](house_number) return house_number def main(): target = 36000000 print("Part 1") num = find_lowest_house_number(target) print(f"The lowest house number to get at least {target} presents is house {num}") print() print("Part 2") num = find_lowest_house_number(target, alt=True) print(f"The lowest house number to get at least {target} presents is house {num}") if __name__ == "__main__": main()
74d03bfa34a54d54215d44a14864ac894b28e546
TheMiloAnderson/data-structures-and-algorithms
/Py401/array_binary_search/array_binary_search_test.py
638
3.671875
4
from array_binary_search import array_binary_search def test_binary_search_small(): """ test with small array """ arr = [1, 2, 3, 4] actual = array_binary_search(arr, 3) expected = 2 assert actual == expected def test_binary_search_large(): """ test with larger array """ arr = [i * 3 for i in range(100)] actual = array_binary_search(arr, 21) expected = 7 assert actual == expected def test_binary_search_not_found(): """ test when value will not be found """ arr = [4, 8, 12, 16, 20, 24, 28] actual = array_binary_search(arr, 15) expected = -1 assert actual == expected
d5a9b1768343444ee71f751d3e4d68f393e97e4a
vignesh787/PythonDevelopment
/Week11Lec6.py
407
3.890625
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 19 08:31:50 2021 @author: Vignesh """ ''' def add(a,b): return a+b def sub(a,b): return a-b def multiply(a,b): return a*b def divide(a,b): return a/b ''' add = lambda x,y : x + y sub = lambda x,y : x - y multiply = lambda x,y : x * y divide = lambda x,y : x / y print(add(2,4)) print(sub(12,4)) print(multiply(2,4)) print(divide(20,4))
de3918430a9e9852051714c4b6c5e6a1a2f7449b
HonniLin/leetcode
/neetcode150/875.koko-eating-bananas.py
1,964
3.515625
4
# # @lc app=leetcode id=875 lang=python3 # # [875] Koko Eating Bananas # # https://leetcode.com/problems/koko-eating-bananas/description/ # # algorithms # Medium (52.90%) # Likes: 5001 # Dislikes: 223 # Total Accepted: 221.5K # Total Submissions: 418.6K # Testcase Example: '[3,6,7,11]\n8' # # Koko loves to eat bananas. There are n piles of bananas, the i^th pile has # piles[i] bananas. The guards have gone and will come back in h hours. # # Koko can decide her bananas-per-hour eating speed of k. Each hour, she # chooses some pile of bananas and eats k bananas from that pile. If the pile # has less than k bananas, she eats all of them instead and will not eat any # more bananas during this hour. # # Koko likes to eat slowly but still wants to finish eating all the bananas # before the guards return. # # Return the minimum integer k such that she can eat all the bananas within h # hours. # # # Example 1: # # # Input: piles = [3,6,7,11], h = 8 # Output: 4 # # # Example 2: # # # Input: piles = [30,11,23,4,20], h = 5 # Output: 30 # # # Example 3: # # # Input: piles = [30,11,23,4,20], h = 6 # Output: 23 # # # # Constraints: # # # 1 <= piles.length <= 10^4 # piles.length <= h <= 10^9 # 1 <= piles[i] <= 10^9 # # # # @lc code=start class Solution: # Binary search between [1, 10^9] or [1, max(piles)] to find the result. # Time complexity: O(NlogM) # (p + m - 1) / m equal to ceil(p / m) (just personal behavior) def minEatingSpeed(self, piles: List[int], h: int) -> int: if len(piles) == h: return max(piles) l, r = 1, max(piles) ret = 0 while l <= r: mid = l + (r - l) // 2 midTime = 0 for p in piles: midTime += math.ceil(p / mid) if midTime <= h: ret = mid r = mid - 1 elif midTime > h: l = mid + 1 return ret # @lc code=end
a545f185d63749873d154f1fb422a6721b7da3e3
ccx210/git-tensorflow-test
/mnist/mnist_test.py
2,246
3.859375
4
#import tensorflow lib import tensorflow as tf #load data set (mnist for example) from tensorflow.examples.tutorials.mnist import input_data #read data from downloaded files, the parameter "one_hot=True" means the outputs are one-hot vectors. say as the form of [0,0,0,1,0,0,0,0,0,0]T mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #first we define the model #x, as the input is a 2D-tensor (or matrix) with the size of n*784 #where n denotes the number of samples and 784 is the total size of one single sample (28*28) x = tf.placeholder(tf.float32, [None, 784]) #w is the weight matrix w = tf.Variable(tf.zeros([784,10])) #b is the bias vector b = tf.Variable(tf.zeros([10])) #y is the output which interprets what number was writen in the picture y = tf.nn.softmax(tf.matmul(x, w) + b) #y_ is the grand truth y_ = tf.placeholder(tf.float32, [None, 10]) #use cross entropy to evaluate the parameters, the second parameter of reduc_sum() means operations are done on the 2nd (index 1) dimension of y cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices = [1])) #use greadient descent to optimize the model, the parameter "0.5" is the learning rate. #minimize(cross_entropy) refers to as our target function is defined by cross_entropy and we should minimize it. train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) #always remember to initialize variables before running the model init = tf.initialize_all_variables() #define a session to solve this sess = tf.Session() #run initialization sess.run(init) #loop for some amount of iterations, for example 1000 in this case for i in range(1000): #set the batch size as 100 batch_xs, batch_ys = mnist.train.next_batch(100) #train step by step sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) #logging if(i%10==0): #calculate the correct percentage of the model #argmax(y, 1) returns the index of the highest entry in tensor "y" on the 2nd axis correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) acc = sess.run(accuracy, feed_dict = {x: mnist.test.images, y_: mnist.test.labels}) print 'iter:%d\t%f' % (i, acc)
29249afad2dc390b16e6e7f7cddd4cb3350a194c
Razoff/prepa_cahier
/half_move.py
1,676
3.671875
4
class HalfMove: """ Each member of this class hold half a move move_id: number of the full move the half move is part of (13) move_name: Name of the half move (Cxb2) white_move: True if it is a white move parent: parent half move children: list of all children half moves comment: Comment object if there is a comment None else graph_pos: TBU """ def __init__(self, move_id, move_name, white_move, parent=None, children=[], comment=None, graph_pos=None): self.move_id = move_id self.move_name = move_name self.white_move = white_move self.parent = parent self.children = children self.comment = comment self.graph_pos = graph_pos # Full name is move_id. move_name for white and move_id... move name for black if white_move: self.full_name = str(self.move_id) + ". " + self.move_name else: self.full_name = str(self.move_id) + "... " + self.move_name """ Print half move with or without comment """ def print_half_move(self, comment=False): if comment: print(self.full_name, self.comment.comment) else : print(self.full_name) """ Longer and more verbose print """ def print_full_object(self): print("MOVE NAME", self.full_name) if self.comment is not None: print("COMMENT") self.comment.print_full_comment() if self.parent is not None: print("PARENT") self.parent.print_half_move() print("CHILDREN") for child in self.children: child.print_half_move()
f94b01102016542c523af8604267d9a706f64683
Gafanhoto742/Python-3
/Python (3)/Ex_finalizados/ex030.py
270
3.90625
4
#Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR. n = int(input('Me diga um numero qualquer: ')) resultado = n % 2 if resultado == 0: print ('O número {} é PAR'.format(n)) else : print ('O número {} é IMPAR!'.format(n))
6150e2b4d31e0e3a977c45238e5283096fd92f35
ravee-interview/DataStructures
/Week4/Design/155_minstack.py
1,483
4.0625
4
from collections import deque class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = deque() self.length = 0 def push(self, x): """ :type x: int :rtype: None """ #push on stack #update length if not self.stack: curr_min = x else: curr_min = self.stack[self.length-1][1] curr_min = min(curr_min,x) self.stack.append((x,curr_min)) self.length +=1 def pop(self): """ :rtype: None """ #return top #update length if not self.stack: raise Error("Failed ... Attempting to remove from emtpy stack") self.length -=1 return self.stack.pop()[0] def top(self): """ :rtype: int """ if not self.stack: raise Error("Stack is empty") return self.stack[self.length-1][0] def getMin(self): """ :rtype: int """ if not self.stack: raise Error("Stack is empty") return self.stack[self.length-1][1] """ time complexity : o(1) for all space complexity : o(n) where n are number of elements """ # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() #Edge cases:
0f0ab6a5d3993d30460b6524ba5ec26aa1c1486d
Parvez6084/Easy-to-Python-Learning
/Variable.py
235
3.578125
4
name = "Parvez Ahmed" age = 24 GPA = 3.94 n,a,g = "Mukta",27,3.24 print("\n"+name) print(age) print(GPA,"\n") print("My name is "+name + ". i am ",age,". my GPA is ",GPA,"\n") print("My name is "+n + ". i am ",a,". my GPA is ",g,"\n")
e57b2a7e370f849ba15f0bd16c27639cdf209b04
nzsnapshot/MyTimeLine
/1-2 Months/tutorial/Files/remember_me2.py
455
4.09375
4
import json # Load username, if it has been stored previously, # Otherwise, prompt for the username and store it. filename = 'username2.txt' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: username = input('What is your name? ') with open(filename,'w') as f: json.dump(username, f) print(f"We'll remember your {username} for your return!") else: print(f"Welcome back! {username}")
ff62c60e8caa5eb16153d5824feb959193e061d4
kmintae/CITE301
/C_Motor/Car_Test.py
446
3.75
4
from Car import Car import time car = Car() while(1): time.sleep(1) test=input() if test=="w" : car.move_forward(300) elif (test=="s"): car.move_forward(-300) elif test=="d": car.move_right(300) elif(test=="a"): car.move_right(-300) elif(test=="e"): car.rotate(500) elif(test=="q"): car.rotate(-500) elif(test=="stop"): break else: continue
8be06d5353d974cfed545bf0ef5cf4791bd129bb
davidzhusd/br-pdv
/portfolio.py
1,873
3.78125
4
import requests """ For the examples we are using 'requests' which is a popular minimalistic python library for making HTTP requests. Please use 'pip install requests' to add it to your python libraries. """ class Portfolio(): """docstring for Portfolio. Instance vars: params - passed into the API requests p - a json of the portfolio p_stocks - the list of stocks in the portfolio, and which ones are num_tickers - len(tickers) """ def __init__(self, tickers_list): """ tickers is a list of strings, each string being a ticker """ # take list of tickers and convert into a string that can be passed into the API # end result example: "ticker:AAPL,ticker:MSFT,ticker:RKUNY" self.num_tickers = len(tickers_list) self.params = los_to_brparams(tickers_list) portfolioAnalysisRequest = requests.get("https://www.blackrock.com/tools/hackathon/security-data", params={'identifiers': self.params}) self.p = portfolioAnalysisRequest.json # get as json object self.p_stocks = (self.p)()['resultMap']["SECURITY"][:self.num_tickers] # cut off to take care of "duplicate" stocks that share the same ticker def get_counts(self, attr_string): """ returns dictionary: {Security Attribute: Count} Security attribute is stuff like country, currency, etc country, currency, exchangeAcronym, issFtse1Industry, issFtse3Sector, assetType """ a_counts = {} for stock in self.p_stocks: c = stock[attr_string] a_counts[c] = 1 + a_counts.get(c, 0) return a_counts def los_to_brparams(los): params = '' for ticker in los: params += "ticker:{},".format(ticker.upper()) #tickers have to be uppercase return params[:-1] # cut off the last comma
1a8857fd2d11c05383970b1afe4b00b2762a704c
FriggD/CursoPythonGGuanabara
/Mundo 1/Desafios/Desafio#24.py
248
3.859375
4
#Crie um programa que leia o nomne de umja cidade e diga se ela começa ou não com o nome SANTO cidade = input('Digite o nome da sua cidade: ').strip() cid = cidade.lower().split() print('Sua cidade é nome de santo? {}'.format('santo' == cid[0]))
0173373c8703c2b955002b1cba3411d479e1cd89
jay3ss/congenial-rotary-phone
/interfaces.py
1,876
4
4
"""Module that holds the interfaces that define different data structures""" import abc class ListInterface(abc.ABC): """Abstract base class that defines a list""" @abc.abstractmethod def clear(self): """Removes all entries from the list""" @abc.abstractmethod def entry(self, position): """Returns the entry at the given position""" @abc.abstractmethod def insert(self, position, data): """Inserts the data at a given position""" @abc.abstractmethod def is_empty(self): """Determines if the list is empty""" @abc.abstractmethod def remove(self, position): """Removes an entry at the given position""" @abc.abstractmethod def replace(self, position, data): """Replaces an entry in the list at the desired position""" class QueueInterface(abc.ABC): """Defines the interface for a queue""" @abc.abstractmethod def is_empty(self): """Determines if the queue is empty""" @abc.abstractmethod def dequeue(self): """Removes an entry from the front of the queue""" @abc.abstractmethod def enqueue(self, entry): """Adds a new entry to the back of the queue""" @abc.abstractmethod def peek(self): """Returns the front of the queue""" class StackInterface(abc.ABC): """An abstract base class that defines a stack""" @abc.abstractmethod def is_empty(self): """Determines if the stack is empty""" @abc.abstractmethod def peek(self): """Returns the top of the stack""" @abc.abstractmethod def pop(self): """Removes the top of the stack""" @abc.abstractmethod def push(self, entry): """Adds data to the top of the stack""" @abc.abstractmethod def push(self, entry): """Adds a new entry to the top of the stack"""
4d8aff7bef6c9993b7473dda4117cff2f1b35387
peterschoice/python
/basic/06_loop.py
313
3.71875
4
menus = ["순남 시래기", "양자강", "20층", "23층"] for menu in menus: print(menu) for i in range(4): print(i) for i in range(4): print(menus[i]) for i in range(1,3): print(i) dict_nums = { "순남 시래기" : "02-6589-3652", "양자강" : "02-6589-3652" , "20" : "02-6589-3652" }
ba01ff43a4eec95489a4ce9adfd1053888910302
jerquinigo/Brooklyn-Steam-Center-lessons
/classActivities/dataTypeActivity/dataTypeStringActivity/stringActivity.py
681
3.59375
4
# please correct these errors by using proper syntax to get quotes and apostrophies to work along with any other string syntax errors present print("Hello Michael, that is Alex's math textbook, he asked me to "make sure no one takes it off his desk") print("Alex's textbook hasn't been removed from the desk. Michael quotes Alex's plan for the day, "got so many subjects to study for", and "I am so swamped) print "My father is on his way to pick up from school," replied Michael over the phone to Alex, "please hurry up and come back, I haven't got all day"") print("Alex didn't take too long to make it back. "Thanks man, you're awesome!" Michael sighed in relief."
b6cefaf4b110a387997c3f6a35574ed414fc662e
halmanza/pythonClass
/itemToPurchase.py
1,651
4.125
4
# Anthony Almanza # Chapter 9 class ItemToPurchase: item_name= str() item_price= float() item_quantity = int() def __init__(self,item_name="none",item_price= 0,item_quantity= 0): self.item_name= item_name self.item_price= item_price self.item_quantity=item_quantity return def print_item_cost(self): x= self.item_quantity * self.item_price print('{} {} @ ${:.0f} = ${:.0f}'.format(self.item_name,int(self.item_quantity),int(self.item_price), x)) def process(): item1=ItemToPurchase() item2=ItemToPurchase() for r in range(0,1): print('Item {}'.format(r + 1)) user_entry= input('Enter the item name: \n') print() item1.item_name = user_entry price_input=input('Enter the item price: \n') item1.item_price= float(price_input) quantitiy_input=input('Enter the item quantity: \n') item1.item_quantity= int(quantitiy_input) print() for s in range(0,1): print('Item {}'.format(r + 2)) user_entry= input('Enter the item name: \n') print() item2.item_name = user_entry price_input=input('Enter the item price: \n') item2.item_price= float(price_input) quantitiy_input=input('Enter the item quantity: \n') item2.item_quantity= float(quantitiy_input) print() print('TOTAL COST \n') item1.print_item_cost() item2.print_item_cost() print() total_price= (item1.item_quantity * item1.item_price) + (item2.item_quantity * item2.item_price) print('Total: ${:.0f}'.format(total_price)) process()
183098bd293fa0d49bb4c79b744457255e42a1d2
mishag/euler
/src/prob35.py
742
3.609375
4
#!/usr/bin/python import primes import sys g_primes = set([]) circular_primes = set([]) def generate_cycles(n): cycles = [] num_str = str(n) for i in range(len(num_str)): num_str = num_str[1:] + num_str[0] m = int(num_str) cycles.append(m) return cycles def build_prime_set(N): for p in primes.primes(): if p >= N: break g_primes.add(p) if __name__ == "__main__": N = int(sys.argv[1]) build_prime_set(N) for i in range(N): cycles = generate_cycles(i) cycle_set = set(cycles) if cycle_set <= g_primes: circular_primes |= cycle_set print circular_primes print len(circular_primes)
de6f1279543dbee3a45635da7bbe04950472a1be
sherrytp/bc_f19_econ
/ADEC7430 Big Data Econometrics/Lecture03/Pycode/Lecture03.py
4,238
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 22:53:39 2019 @author: RV """ #%% #%% Setup import os projFld = "C:/Users/RV/Documents/Teaching/2019_01_Spring/ADEC7430_Spring2019/Lecture03" codeFld = os.path.join(projFld, "PyCode") fnsFld = os.path.join(codeFld, "_Functions") outputFld = os.path.join(projFld, "Output") rawDataFld = os.path.join(projFld, "RawData") savedDataFld = os.path.join(projFld, "SavedData") #%% Part 1: Sorting lists templist = ['25', '010', '1', '10', '23'] templist.sort() # notice - this is in-place, we don't assign the operation result! print(templist) #%% Part 2: substrings of strings # execute these statements one by one, figure out what they do # search online only after you've tried for 2 minutes to figure out what they do!!! tempstring = 'My first string' print(tempstring[0]) print(tempstring[4]) print(tempstring[:10]) print(tempstring[1:5]) print(tempstring[1:5:2]) print(tempstring[1:5:3]) print(tempstring[1:5:4]) #%% Iterate over a list, do something templist = [i for i in range(-10, 10, 2)] # read about range print(templist) print([2*x + 1 for x in templist]) print([str(x) for x in templist]) # the order of operation matters: # sorting AFTER type conversion (from numeric to characters) sorted([str(x) for x in templist]) # sorting BEFORE type conversion (from numeric to characters) print([str(x) for x in sorted(templist)]) #%% Part 4: sort list by initial letter, lower cased templist = ['pandas', 'numpy', 'DataFrame', 'boxplot', 'Seaborn'] templist.sort() templist # do you like this order? templist_lower = [x.lower() for x in templist] print(templist_lower) # OK but this is a different list - changed templist_lower.sort() sorted(templist, key=lambda x: templist_lower.index(x.lower())) # OK this is probably one of the most complex things we'll do with lists. #%% Running an ANOVA # Import rTrain exported in Lecture 02 - it should be in SavedData in Lecture02 # one-way ANOVA import pandas as pd import statsmodels as sm from statsmodels.formula.api import ols # from statsmodels.stats.anova import anova_lm rTrain = pd.read_csv(os.path.join(rawDataFld, "Lecture2_train.csv"), sep=',', dtype=object) rTrain.Age = pd.to_numeric(rTrain.Age) rTrain.Pclass = pd.to_numeric(rTrain.Pclass) rTrain.Survived = pd.to_numeric(rTrain.Survived) test_lm = ols('Age ~ C(Pclass, Sum)*C(Survived, Sum)', data=rTrain).fit() test_lm.summary() table = sm.stats.anova.anova_lm(test_lm, typ=2) # Type 2 ANOVA DataFrame # table = anova_lm(test_lm, typ=2) # Type 2 ANOVA DataFrame # we can run ANOVA with scipy as well import scipy anova_scipy = scipy.stats.f_oneway(rTrain.loc[rTrain['Pclass'] == 1].Age, rTrain.loc[rTrain['Pclass'] == 2].Age) print(anova_scipy) #%% Does the price vary significantly by departure port? # HW investigate distribution (one-way Anova) of Fare with respect to Embarked #@@ ===== to replace code below with Python code ==== # ===== R Code for reference ==== #rTrain[,Embarked_f:=as.factor(Embarked)] #anova1 <- oneway.test(Fare ~ Embarked_f, data=rTrain) #anova1 #summary(anova1) # better option - "aov" #anova2 <- aov(Fare ~ Embarked, data = rTrain) #anova2 #summary(anova2) # ====== end of R Code ========== #============================================================================== # Multiple Linear Regression #============================================================================== # Assumptions... and what do they mean? Rpdata = pd.read_csv(os.path.join(rawDataFld, "alr4_Rpdata.csv")) import statsmodels.api as sm import seaborn as sns lmmodel = sm.OLS(Rpdata["y"], Rpdata[["x1", "x2", "x3", "x4", "x5", "x6"]]).fit() # does this look like a good model (numerically speaking)? lmmodel.summary() # how about we "dig deeper"? - residual plots lmmodel_fitted_y = lmmodel.fittedvalues lmmodel_residuals = lmmodel.resid sns.residplot(lmmodel_fitted_y, 'y', data=Rpdata, lowess=True) # Uh-oh! The residuals are not random! Or are they? What makes them non-random? # Participate in the online discussion on randomness! # HW follow up with comments on what is randomness, and how is this relevant to our analysis?
cc14fb5372ff90a818e3b22f6e4771d70f34f80b
Mateushrb/URI-Online-Judge
/Python/Iniciante/1176 - Fibonacci em Vetor.py
600
3.6875
4
# Lista da sequencia inicial de Fibonacci sequencia_fibo = [0, 1] valor_fibo = 0 # Estrutura de repetição para calcular a sequencia de Fibonacci for i in range(0, 60, 1): valor_fibo = sequencia_fibo[i] + sequencia_fibo[i+1] sequencia_fibo.append(valor_fibo) # Quantidade de testes T = int(input()) casos_testes = list() # Estrutura de repetição para adicionar os casos de testes na lista for l in range(0, T, 1): N = int(input()) casos_testes.insert(l, N) # Estrutura de repetição para imprimir os testes for m in casos_testes: print("Fib(%s) = %s" %(m, sequencia_fibo[m]))
55ded99013a8784d05a4462a3dbbd2cd1db61e1c
kolpator/python
/not.py
189
4.0625
4
#!/usr/bin/python3 x = int(input("notunuz")) if x > 100 or x < 0: print("böyle bir not yok") elif x >=90 and x <=100: print("A aldınız") elif x >= 80 and x <= 89: print("B aldınız")
70ff0f19489988ed51caa350d921d5ffc72acb5c
smistro/stanford
/TripleKarel.py
2,153
4.125
4
from karel.stanfordkarel import * """ File: TripleKarel.py -------------------- When you finish writing this file, TripleKarel should be able to paint the exterior of three buildings in a given world, as described in the Assignment 1 handout. You should make sure that your program works for all of the Triple sample worlds supplied in the starter folder. """ def main(): """ You should write your code to make Karel do its task in this function. Make sure to delete the 'pass' line before starting to write your own code. You should also delete this comment and replace it with a better, more descriptive one. """ block_one() while left_is_blocked(): put_beeper() move() turn_right() block_two() """From this point on, the functions used to create the building blocks above will be defined. Awesome. Many thanks to Stanford University for providing me with this unique and challenging learning experience. I'am just grateful for this opportunity.""" # Defines the most used command by Karel def primary_function(): while left_is_blocked(): put_beeper() move() turn_left() move() # Defines secondary command def secondary_function(): while left_is_blocked(): put_beeper() move() put_beeper() turn_right() move() # Defines tertiary function def tertiary_function(): while left_is_blocked(): put_beeper() move() turn_right() put_beeper() move() # Defining the building blocks def block_one(): primary_function() primary_function() secondary_function() primary_function() primary_function() def block_two(): primary_function() primary_function() primary_function() tertiary_function() tertiary_function() primary_function() # Turns Karel 90 degrees to the right. def turn_right(): turn_left() turn_left() turn_left() # Turns Karel around 180 degrees. def turn_around(): turn_left() turn_left() pass # There is no need to edit code beyond this point if __name__ == "__main__": run_karel_program()
ea5acf926f51adfd2116eef20d886ccf6a302489
grasingerm/PL
/cmu_hw_list_algorithms_and_invdict.py
5,539
3.65625
4
import copy import bisect def fast2(a): b = copy.copy(a) b.sort() for i in range(len(b)-1): if b[i] == b[i+1]: return False return True print(fast2([1, 2, 3]), " should be True") print(fast2([1, 2, 3, 4]), " should be True") print(fast2([1, 2, 3, -1, -14, 4, 7, 9, 11, 38]), " should be True") print(fast2([1, 2, 3, -1, -14, 4, 7, 9, 11, 38, -14]), " should be False") print(fast2([1, 2, 3, 2, 1, 3]), " should be False") def binary_search(L, target): start = 0 end = len(L) - 1 while(start <= end): middle = (start + end)//2 if(L[middle] == target): return True elif(L[middle] > target): end = middle - 1 else: start = middle + 1 return False a = [1, 2, 3, -1, -14, 4, 7, 9, 11, 38]; a.sort() print(binary_search([1, 2, 3], 3), " should be True") print(binary_search([1, 2, 3, 4], 2), " should be True") print(binary_search(a, -14), " should be True") print(binary_search([1, 2, 3], -4), " should be False") print(binary_search([1, 2, 3, 4], 17), " should be False") print(binary_search(a, 39), " should be False") def fast3(a, b): n = len(a) # O(1) assert(n == len(b)) # O(1) result = 0 #sort a2 = copy.copy(a) # O(N) a2.sort() # O(Nlog(N)) # O(N log(N)) for c in b: # do something with binary search if not binary_search(a2, c): # log(N) result += 1 return result def slow3(a, b): # assume a and b are the same length n n = len(a) assert(n == len(b)) result = 0 for c in b: if c not in a: result += 1 return result a = [1, 2, 3, 4] b = [3, 4, 5, 6] c = [1, 1, 2, 2] d = [6, 7, 8, 9] assert(fast3(a, b) == slow3(a, b)) assert(fast3(b, a) == slow3(b, a)) assert(fast3(c, d) == slow3(c, d)) assert(fast3(d, c) == slow3(d, c)) assert(fast3(a, c) == slow3(a, c)) assert(fast3(c, a) == slow3(c, a)) assert(fast3(b, d) == slow3(b, d)) assert(fast3(d, b) == slow3(d, b)) print("Fast3 tests passed.") def slow4(a, b): # assume a and b are the same length n n = len(a) assert(n == len(b)) result = abs(a[0] - b[0]) for c in a: for d in b: delta = abs(c - d) if (delta > result): result = delta return result def fast4(a, b): n = len(a) assert(n == len(b)) c = copy.copy(a) d = copy.copy(b) c.sort() d.sort() delta1 = abs(c[0] - d[-1]) delta2 = abs(c[-1] - d[0]) return max(delta1, delta2) assert(fast4(a, b) == slow4(a, b)) assert(fast4(b, a) == slow4(b, a)) assert(fast4(c, d) == slow4(c, d)) assert(fast4(d, c) == slow4(d, c)) assert(fast4(a, c) == slow4(a, c)) assert(fast4(c, a) == slow4(c, a)) assert(fast4(b, d) == slow4(b, d)) assert(fast4(d, b) == slow4(d, b)) print("Fast4 tests passed.") def slow5(a, b): # Hint: this is a tricky one! Even though it looks syntactically # almost identical to the previous problem, in fact the solution # is very different and more complicated. # You'll want to sort one of the lists, # and then use binary search over that sorted list (for each value in # the other list). In fact, you should use bisect.bisect for this # (you can read about this function in the online Python documentation). # The bisect function returns the index i at which you would insert the # value to keep the list sorted (with a couple edge cases to consider, such # as if the value is less than or greater than all the values in the list, # or if the value actually occurs in the list). # The rest is left to you... # # assume a and b are the same length n n = len(a) assert(n == len(b)) result = abs(a[0] - b[0]) for c in a: for d in b: delta = abs(c - d) if (delta < result): result = delta return result def fast5(a, b): n = len(a) assert(n == len(b)) a2 = copy.copy(a) result = abs(a[0] - b[0]) for c in b: i = bisect.bisect(a2, c) if i == 0: delta = abs(a2[i] - c) elif i == n: delta = abs(a2[i-1] - c) else: delta1 = abs(a2[i] - c) delta2 = abs(a2[i-1] - c) delta = min(delta1, delta2) if (delta < result): result = delta return result assert(fast5(a, b) == slow5(a, b)) assert(fast5(b, a) == slow5(b, a)) assert(fast5(c, d) == slow5(c, d)) assert(fast5(d, c) == slow5(d, c)) assert(fast5(a, c) == slow5(a, c)) assert(fast5(c, a) == slow5(c, a)) assert(fast5(b, d) == slow5(b, d)) assert(fast5(d, b) == slow5(d, b)) print("Fast5 tests passed.") def invertDictionary(d): inv_d = {} for (k, v) in d.items(): inv_key = v if not inv_key in inv_d.keys(): inv_d[inv_key] = set([k]) else: inv_d[inv_key].add(k) return inv_d print(invertDictionary({1: 2, 2: 3, 3: 4, 5: 3})) def friendsOfFriends(d): fof = {} for (person, friends) in d.items(): fof_item = set([]) for friend in friends: fof_item |= d[friend] fof_item -= friends fof_item -= set([person]) fof[person] = fof_item return fof d = {'barney': set(['fred']), 'dino': set(['wilma']), 'fred': set(['bam-bam', 'wilma', 'betty', 'barney']), 'betty': set(['dino', 'wilma']), 'bam-bam': set(['fred']), 'wilma': set(['dino', 'betty', 'fred'])} print(friendsOfFriends(d))
c4e55746ea83f0f05a2e0b50707165241f2586f7
sunnivmr/tdt4110
/oving9/sets.py
925
3.734375
4
print("\na)") my_set = set() print(my_set) print("\nb)") def oddetall(set, max): for i in range(max): if i % 2 != 0: set.add(i) oddetall(my_set, 20) print(my_set) print("\nc)") my_set2 = set() oddetall(my_set2, 10) print(my_set2) print("\nd)") my_set3 = set() my_set3 = my_set.difference(my_set2) print(my_set3) print("\ne)") print("Forventer å få {1, 3, 5, 7, 9}:") print(my_set.intersection(my_set2)) print("\nf)") def all_unique(lst): lst_set = set() for i in lst: lst_set.add(i) if len(lst) == len(lst_set): return True else: return False print(all_unique([1, 3, 2, 6, 8])) print(all_unique([1, 3, 5, 2, 3, 7])) print("\ng)") def remove_dup(lst): lst_set = set() new_lst = list() for i in lst: lst_set.add(i) for i in lst_set: new_lst.append(i) return new_lst print(remove_dup([1, 3, 5, 2, 3, 7]))
d5d06554d0f7d8c598d357732f8db83e0252d024
DMamrenko/Kattis-Problems
/autori.py
156
3.84375
4
#Autori inp = list(input()) answer = "" for letter in inp: if letter == letter.upper() and letter != "-": answer += letter print(answer)
379689ccc9e4cde26ae04b0a6b27387e7800f7a3
AlexandrSech/Z49-TMS
/students/Volodzko/Task_13/Task_13_1/func.py
760
3.578125
4
from exceptions import MyZeroException def my_sum(x, y): # Функция сложения двух чсел return "x + y = {}".format(x + y) def my_dif(x, y): # Функция вычитания двух чсел return "x - y = {}".format(x - y) def my_mul(x, y): # Функция умножения двух чсел return "x * y = {}".format(x * y) def my_division(x, y): # Функция деления двух чсел try: if y == 0: raise MyZeroException("Деление на ноль запрещено!") # Генерируется собственное исключение else: return "x / y = {}".format(round(x / y, 4)) except MyZeroException as ex: print(ex)
ee479d0c18e6efbc701454daf9c48bef11c63ed7
rnsdoodi/Programming-CookBook
/Back-End/Python/Basics/Part -4- OOP/02 - Polymorphism/04_hash_protocol.py
425
3.828125
4
class Person: def __init__(self, name): self._name = name @property def name(self): return self._name def __eq__(self, other): return isinstance(other, Person) and self.name == other.name def __hash__(self): return hash(self.name) p1 = Person('Eric') d = {p1: 'Eric'} print(d) #{<__main__.Person at 0x7fc3d838f0f0>: 'Eric'} s = {p1} print(s)
8928af60159aca65d2e8815d92cacbf621c75494
boksuh/Python_300
/061-080.py
1,200
3.75
4
""" 2021-07-05 Bokyung Suh Python 300 """ # 061 price = ['20180728', 100, 130, 140, 150, 160, 170] print(price[1:]) # 062 nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(nums[::2]) # 063 nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(nums[1::2]) # 064 nums = [1, 2, 3, 4, 5] print(nums[::-1]) # 065 interest = ["Samsung", "LG", "Naver"] print(interest[0], interest[2]) # 066 interest = ["Samsung", "LG", "Naver", "SK", "Mirae"] print(" ".join(interest)) # 067 print("/".join(interest)) # 068 print("\n".join(interest)) # 069 string = "Samsung/LG/Naver" interest = string.split("/") print(interest) # 070 data = [2, 4, 3, 1, 5, 10, 9] data.sort() print(data) # 071 my_variable = () # 072 movie_rank = ("Dr.Strange", "Split", "Lucky") print(movie_rank) # 073 tup = (1,) print(tup) # 074 t = (1, 2, 3) # t[0] = 'a' print(t) # 075 t = 1, 2, 3, 4 print(type(t)) # 076 t = ('a', 'b', 'c') t = ('A', 'b', 'c') # 077 interest = ("Samsung", "LG", "SK") list_interest = list(interest) print(list_interest) # 078 tup_interest = tuple(list_interest) print(tup_interest) # 079 temp = ('apple', 'banana', 'cake') a, b, c = temp print(a, b, c) # 080 data = tuple(range(2, 100, 2)) print(data)
dbad2111915225b1119a682cac830155f5f56cd7
TheMcHammer/Magic-8-ball
/magic_8-ball/Magic8Ball.py
2,252
3.65625
4
import random class Fortune: #global fates fates = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes - definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful' ] def get_input(self, text): return input(text) def shake_8ball(self): shake = Fortune.get_input(self, "Shake Magic 8 ball? Y/N (press quit to stop): ") while shake: if shake == 'y': print('Asking fate') print('...') answer = random.choice(fates) print(answer) input('Ask a question to get an answer: ') Fortune.shake_8ball(self) return 'Yes Entered' elif shake == 'n': print('May the force be with you \n') break return 'No Entered' else: print('Invalid input') print() def give_fate(self): global fates fates = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes - definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful' ] input('Ask a question to get an answer: ') ##not tested## Fortune.shake_8ball(self) #return answer #### fate = Fortune() fate.give_fate() 'It is certain', 'It is decidedly so', 'Without a doubt', 'Yes - definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful'
30805bf258c0c6e75b5f2867ae0e8b2aab3df689
supazuko/Database-Exercises
/Python_DB_Connect/connect_insert.py
2,179
3.578125
4
import mysql.connector from mysql.connector import Error import stdiomask def connect_insert(): conn = None host = input('Enter Host for database: ') database = input('Enter database name: ') user = input('Enter user for database: ') password = stdiomask.getpass("Enter password: ") try: conn = mysql.connector.connect(host=host, database=database, user=user, password=password) print('Connecting to database server...') if conn.is_connected: print('Connected to database server') db_cursor = conn.cursor() # Create a variable to contain the sql query to be executed sql = "insert into Human(humanId, name, color, gender, bloodgroup) Values (%s, %s, %s, %s, %s)" # Create a list variable to conatain all the values we want to insert into the human table val = [] entryNumber = int(input("How many records do you want to enter?: ")) for i in range(entryNumber): humanId = input("Enter your ID: ") name = input("Enter your name: ") color = input("Enter your color: ") gender = input("Enter your gender: ") bloodGroup = input("Enter your blood group: ") print() val.append((humanId, name, color, gender, bloodGroup)) # val = [ # ('1013', 'Hannah', 'White', 'Female', 'B-'), # ('1014', 'Michael', 'Brown', 'Male', 'O-'), # ('1015', 'sandy', 'Black', 'Female', 'B+'), # ] # Execute the query using the execute many function db_cursor.executemany(sql, val) # Commit to the database conn.commit() # Print a success message print(db_cursor.rowcount, 'rows are inserted') # Close the cursor db_cursor.close except Error as e: print('Connection failed due to the following', e) finally: if conn is not None and conn.is_connected(): conn.close() print('Disconnected from the database') connect_insert()
9cdaa903a644b40b6b9029c304256ee913ed0382
dougaoyang/struct_code
/sort/quick_sort.py
998
3.859375
4
# 快速排序 import random # 获取分区点 def partition(arr, start, end): # i,j以此向后递推,i前面的都小于 下标p的值 i, j = start, start # 获取分区点 p = random.randint(start, end) while True: # 跳过下标p if i == p: i += 1 if j == p: j += 1 if j > end: break # 比较 j, p 将小于p的值交换到i的左侧 if arr[j] < arr[p]: arr[i], arr[j] = arr[j], arr[i] i += 1 j += 1 if p < i: arr[i-1], arr[p] = arr[p], arr[i-1] r = i-1 else: arr[i], arr[p] = arr[p], arr[i] r = i return r def quick_sort(arr, start=0, end=None): end = len(arr) - 1 if end is None else end if start >= end: return r = partition(arr, start, end) quick_sort(arr, start, r-1) quick_sort(arr, r+1, end) if __name__ == '__main__': arr = [10, 14, 6, 8, 32, 7, 3] print(arr) quick_sort(arr) print(arr)
e4cda589b8ea8e2b5992fff643c4669bedb3a5ff
roshstar1999/Art_Of-_Doing
/miles_per_hr_Conversion.py
365
4.4375
4
#MILES PER HOUR CONVERSION print("Welcome to miles per hour conversion app!") mph=input("\n enter the speed in miles per hour please =>") #for converting the miles into metres ===> miles*1609 mps=float(mph)*1609.34/(60*60) #using round function for upto 2 decimals precision mps=round(mps,2) print("the entered speed in metres per second is=>",mps)
2e828befcc131412dbd396e02adc59eff7a6e20c
python2018wow/python_code
/p2-1.py
107
3.59375
4
name = input("請輸入您的姓名:") print("您好," + name + "!") print("大家一起學 Python!")
02c6e1e537ddc3ca4eab998374cea07b2bd58e07
lengyugo/Data-Structure-and-Algorithm
/12-sorts2/quick_sort.py
938
3.8125
4
""" quick_sort 快速排序 """ from typing import List import numpy as np def quick_sort(a:List[int]): quick_sort_c(a,0,len(a) - 1) ## def quick_sort_c(a:List[int],low:int,high:int): if low < high: #k = random.randint(low,high) #a[low],a[k] = a[k],a[low] q = partition(a,low,high) #print(q) quick_sort_c(a,low,q - 1) quick_sort_c(a,q + 1,high) ##没理解? def partition(a:List[int],low:int,high:int): pivot,i= a[low],low for j in range(low+1,high+1): if a[j] <= pivot: i += 1 a[i],a[j] = a[j],a[i] a[low],a[i] = a[i],a[low] return i if __name__ == "__main__": a1 = [3, 9, -6, 4, 10] a2 = [2, 3, 2, 2] a3 = [4, 3, 2, 1] a4 = np.random.randint(1,100,size=50) quick_sort(a1) print(a1) quick_sort(a2) print(a2) quick_sort(a3) print(a3) quick_sort(a4) print(a4)
5f246ef3eb4100549c48eb0f4832a833d1d6a4ed
batestin1/PYTHON
/CHALLENGES/100TASK/ex010.py
379
4.0625
4
#Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar. import pandas print('-*-'*30) print('CONVERSAO DE DOLAR ') print('Desenvolvido por Maycon Cypriano') print('-*-'*30) real = float(input('Quanto você tem na carteira: ')) dolar = real*0.18 print(f'Se você tem R$:{real} na carteira, então você tem USD:{round(dolar,2)}')
81056370079d3089494d28873cc57a01a752ebe8
greenfrog82/DailyCoding
/Codewars/6kyu/6kyu_multiple_3_or_5/src/main.py
277
3.515625
4
import unittest def mysolution(number): return sum(i for i in range(number) if not i % 3 or not i % 5) solution = mysolution class Test(unittest.TestCase): def test_1(self): self.assertEqual(solution(10), 23) if __name__ == '__main__': unittest.main()
5e293f3767b782aa3757044ad79dabc7551fc639
JeffHemmen/AoC-2019
/Day 4/day4.py
1,221
4.125
4
#!/usr/bin/env python3 from sys import argv def two_adjacent_digits_are_the_same(n): cs = str(n) left = None for c in cs: if c == left: return True left = c return False def two_adjacent_digits_are_the_same_v2(n): cs = str(n) left, num_repeat = '', 1 for c in cs: if c == left: num_repeat += 1 # left = c else: # c != left if num_repeat == 2: return True else: num_repeat = 1 left = c if num_repeat == 2: return True return False def going_from_left_to_right_the_digits_never_decrease(n): cs = str(n) left = '0' for c in cs: if c < left: return False left = c return True def main(lower, upper): c = 0 for i in range(lower, upper+1): if not two_adjacent_digits_are_the_same_v2(i): continue if not going_from_left_to_right_the_digits_never_decrease(i): continue c += 1 return c if __name__ == '__main__': lower = argv[1] if len(argv) >= 3 else 382345 upper = argv[2] if len(argv) >= 3 else 843167 res = main(lower, upper) print(res)
b1146e80e7891fd105a12ddc2374843068c066f1
developer0101/AVLtree
/avltree.py
3,325
3.546875
4
''' Reza Fathi AVL Tree in python3 ''' class Node: def __init__(self, val): self.val = val self.left = self.right = None self.height = 0 def updateHeight(self): lh = self.left.height if self.left else 0 rh = self.right.height if self.right else 0 self.height = 1 + max(lh, rh) def balance(self): lh = self.left.height if self.left else 0 rh = self.right.height if self.right else 0 return lh-rh def leftRotate(self): root = self.right self.right = root.left root.left = self self.updateHeight() root.updateHeight() return root def rightRotate(self): root = self.left self.left = root.right root.right = self self.updateHeight() root.updateHeight() return root def rebalance(self): balance = self.balance() if balance>1: if self.left.balance()<0: self.left = self.left.leftRotate() return self.rightRotate() elif balance<-1: if self.right.balance()>0: self.right = self.right.rightRotate() return self.leftRotate() return self def insert(self, val): # print(val, flush=True) if val<self.val: self.left = self.left.insert(val) if self.left else Node(val) else: self.right = self.right.insert(val) if self.right else Node(val) self.updateHeight() return self.rebalance() def getMinValueNode(self): return self.left.getMinValueNode() if self.left else self def delete(self, val): if val<self.val: self.left = self.left.delete(val) if self.left else self.left elif val>self.val: self.right = self.right.delete(val) if self.right else self.right else: if self.left is None: return self.right elif self.right is None: return self.left temp = self.right.getMinValueNode() self.val = temp.val self.right = self.right.delete(temp.val) self.updateHeight() return self.rebalance() def search(self, val): if val==self.val: return val if val<self.val: return self.left.search(val) if self.left else self.left else: return self.right.search(val) if self.right else self.right def isValid(self, minval, maxval): if self.val<minval or self.val>maxval: return False elif abs(self.balance())>1: return False res = self.left.isValid(minval, self.val) if self.left else True if res: res = self.right.isValid(self.val, maxval) if self.right else True return res class AVLTree: def __init__(self): self.root = None def insert(self, val): self.root = self.root.insert(val) if self.root else Node(val) def delete(self, val): self.root = self.root.delete(val) if self.root else self.root def search(self, val): return self.root.search(val) if self.root else self.root def test(self): import random d = 100 n = 2014+d nums = [] for i in range(n): nums.append(random.randint(0, n**2)) self.insert(nums[-1]) numsdel = random.sample(nums, d) for num in numsdel: self.delete(num) import sys import numpy as np print("Simulation test inserted {0} random numbers and deleted {1} numbers".format(n,d)) if self.root: print ("log(n)={0:0.2f}, avltree height={1}".format(np.log2(n-d),self.root.height)) if self.root is None or self.root.isValid(-sys.maxsize, sys.maxsize): print("Valid avl tree!") else: print("Opps, Invalid avl tree") def test(): avltree = AVLTree() avltree.test() if __name__=="__main__": test()
970671fd7c1e9c625088512a3985f1e826913aff
AnshumanSharma05/Python
/StationaryShop.py
1,200
3.953125
4
''' A new stationary shop has been opened in the city. The owner asks his accountant to take the list of items sold in the store. The list should contain the details of the items and their costs. Help the accountant to generate the prince list by writing a Python program. Generate list with just 4 products - A4sheets, pen, pencil and eraser and get the price of the items from the user. Please refer the sample input and output statements for more clarifications. Note: The amount must be displayed with 2 decimal places. On entering the product price to be a negative number, the program should display the message " Invalid input" and stop the program. Sample input 1 : Cost of A4sheet: 40 Cost of pen: 20 Cost of pencil: 10 Cost of eraser: 5 ''' cs=float(input("Cost of A4sheet:")) if(cs<0): print("Invalid input") exit() cp=float(input("Cost of pen:")) if(cp<0): print("Invalid input") exit() cpe=float(input("Cost of pencil:")) if(cpe<0): print("Invalid input") exit() ce=float(input("Cost of eraser:")) if(ce<0): print("Invalid input") exit() print("Items Details") print("A4sheet:%0.2f"%cs) print("Pen:%0.2f"%cp) print("Pencil:%0.2f"%cpe) print("Eraser:%0.2f"%ce)
4f993a22f064e488d21ed4f4572edac9cb675112
ErikArndt/GMTK-Jam-2020
/util.py
2,724
3.53125
4
"""This module is for general use functions that can be used by any module. """ import pygame def bevelled_rect(surface, colour, rect, border_radius): """pygame doesn't support rects with curved edges yet, so I had to write this myself. Args: surface (pygame.Surface): surface to draw the rect onto. colour (rgb value): colour of the rect rect ((x, y, width, height)): dimensions of the rect border_radius (int): radius of the circular corners of the rect. Must be less than min(width/2, height/2) """ if border_radius >= min(rect[2]/2, rect[3]/2): return # corners pygame.draw.circle(surface, colour, (rect[0] + border_radius, rect[1] + border_radius), border_radius) pygame.draw.circle(surface, colour, (rect[0] + rect[2] - border_radius, rect[1] + border_radius), border_radius) pygame.draw.circle(surface, colour, (rect[0] + border_radius, rect[1] + rect[3] - border_radius), border_radius) pygame.draw.circle(surface, colour, (rect[0] + rect[2] - border_radius, \ rect[1] + rect[3] - border_radius), border_radius) # edges pygame.draw.rect(surface, colour, (rect[0] + border_radius, rect[1], \ rect[2] - border_radius*2, border_radius)) pygame.draw.rect(surface, colour, (rect[0] + border_radius, rect[1] + rect[3] - border_radius, \ rect[2] - border_radius*2, border_radius)) pygame.draw.rect(surface, colour, (rect[0], rect[1] + border_radius, \ border_radius, rect[3] - border_radius*2)) pygame.draw.rect(surface, colour, (rect[0] + rect[2] - border_radius, rect[1] + border_radius, \ border_radius, rect[3] - border_radius*2)) # center pygame.draw.rect(surface, colour, (rect[0] + border_radius, rect[1] + border_radius, \ rect[2] - border_radius*2, rect[3] - border_radius*2)) def lighten(rgb, factor=30): """This function lightens an rgb value by the given factor, or by 30 if no factor is given. Args: rgb (rgb value): the rgb value to lighten. factor (int, optional): the amount to add to r, g, and b. Defaults to 30. Returns: rgb value: the lightened rgb value. """ return (min(255, rgb[0] + factor), min(255, rgb[1] + factor), min(255, rgb[2] + factor)) def darken(rgb, factor=30): """This function darkens an rgb value by the given factor, or by 30 if no factor is given. Args: rgb (rgb value): the rgb value to darken. factor (int, optional): the amount to subtract from r, g, and b. Defaults to 30. Returns: rgb value: the darkened rgb value. """ return (max(0, rgb[0] - factor), max(0, rgb[1] - factor), max(0, rgb[2] - factor))
91508f2abde32f646dad83879e2aecc827a5ad42
CubeSugar/HeadFirstPython
/Day05/demo_class_define.py
651
3.671875
4
''' ''' ''' ''' #define function format time_string def sanitize(time_string): if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.split(splitter) return (mins + '.' + secs) #end def class Athlete: def __init__(self, a_name, a_bday = None, a_times = []): self.m_Name = a_name self.m_bday = a_bday self.m_times = a_times def add_time(self, a_time = None): self.m_times.append(a_time) def add_times(self, a_times = []): self.m_times.extend(a_times) def top3times(self): return (sorted(set([sanitize(each) for each in self.m_times]))[0:3])
3f7837f57386fa1f85d6e6e4a6a30ff0f029b236
jfsolanilla/Python-Code
/Guess the Number.py
5,302
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console # Defining libraries import random import simplegui import math # Defining global variables Secret_Number = 0 # Number that will be guessed by the user Upper_Limit = 0 # Upper limit of the random range Limit_of_Guesses = 0# Limit of guesses available # helper function to start and restart the game def new_game(): # initialize global variables used in your code here # Defining the value of the secret number global Secret_Number Secret_Number = random.randrange(0,Upper_Limit) # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game # Assigning the upper value global Upper_Limit,Limit_of_Guesses Upper_Limit = 100 Limit_of_Guesses = math.ceil(math.log(Upper_Limit + 1,2)) # Welcome message of a new game print " " print "Guess the number!!! This game will be in the 0-100 range. You will have",Limit_of_Guesses,"chances. Good luck!!!" # Running a new game new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game # Assigning the upper value global Upper_Limit,Limit_of_Guesses Upper_Limit = 1000 Limit_of_Guesses = math.ceil(math.log(Upper_Limit + 1,2)) # Welcome message of a new game print " " print "Guess the number!!! This game will be in the 0-1000 range. You will have",Limit_of_Guesses,"chances. Good luck!!!" # Running a new game new_game() def input_guess(guess): # main game logic goes here # Updating the value in order to do comparisons between integers guess = int(guess) # Defining a copy of the variable global Limit_of_Guesses,Upper_Limit #________________________________________________________________________________ # Verifying if the number is correct # Printing the guess of the user print " " print "Guess was",guess # The guess is higher than the secret number if Secret_Number > guess: # Updating the limit of guesses Limit_of_Guesses -= 1 # Printing the clue print "Higher" print Limit_of_Guesses,"guesses remaining" # The guess is lower than the secret number elif Secret_Number < guess: # Updating the limit of guesses Limit_of_Guesses -= 1 # Printing the clue print "Lower" print Limit_of_Guesses,"guesses remaining" # The guess is equal than the secret number else: print "Correct" # Defining the number of guesses Limit_of_Guesses = math.ceil(math.log(Upper_Limit + 1,2)) # The user have won print " " print "You have won!!! A new game in the range 0 -",Upper_Limit," have started. You will have",Limit_of_Guesses,"chances. Good luck!!!" # Starting a new game new_game() return #________________________________________________________________________________ # Verifying the limit of guesses if Limit_of_Guesses == 0: # Defining the number of guesses Limit_of_Guesses = math.ceil(math.log(Upper_Limit + 1,2)) # The user have lost print " " print "You have lost, the correct answer was",Secret_Number,". Don't Worry!!! A new game in the range 0 -",Upper_Limit," have started. You will have",Limit_of_Guesses,"chances. Good luck!!!" # Starting a new game new_game() return #________________________________________________________________________________ # create frame frame = simplegui.create_frame('Guess the Number', 300,300) #________________________________________________________________________________ # register event handlers for control elements and start frame # Adding an input frame.add_input("Enter the Guess",input_guess,70) # Adding two buttons in order to start a new game frame.add_button("Range: 0 - 100",range100) # Range 0 - 100 frame.add_button("Range: 0 - 1000",range1000) # Range 0 - 1000 # Starts the frame frame.start #________________________________________________________________________________ # STARTING THE FIRST GAME. THIS GAME STARTS IN THE 0-100 RANGE # Defining the upper limit Upper_Limit = 100 # Defining the limit of guesses Limit_of_Guesses = math.ceil(math.log(Upper_Limit + 1,2)) # Welcome message print "Guess the number!!! The first game will start in the 0-100 range. You will have",Limit_of_Guesses,"chances. Good luck!!!" # Running the first game new_game() # always remember to check your completed program against the grading rubric
f89d2d951dcad9eb2ca8d9fdd701313851d3dc3b
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/150_14.py
2,887
4.3125
4
Python | Delete elements with frequency atmost K There are many methods that can be employed to perform the deletion in the list. Be it remove function, pop function and many other functions. But most of the times, we usually don’t deal with the simple deletion, but with certain constraints. This article discusses certain ways in which we can delete only those elements which occurs less than K times. **Method #1 : Using list comprehension +count()** The idea applied here is to construct a new list using list comprehension and insert only those elements which occur more than K times. The count operation is done with the help of count function. __ __ __ __ __ __ __ # Python3 code to demonstrate # remove elements less than and equal K # using list comprehension + count() # initializing list test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] # printing original list print("The original list : " + str(test_list)) # initializing K K = 2 # using list comprehension + count() # remove elements less than K res = [ i for i in test_list if test_list.count(i) > K] # print result print("The list removing elements less than and equal K : " + str(res)) --- __ __ **Output :** The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2] **Method #2 : UsingCounter() \+ list comprehension** This problem can be efficiently solved using the Counter function that precomputes the count of each elements in list so that the decision to keep or reject a particular element takes lesser time. __ __ __ __ __ __ __ # Python3 code to demonstrate # remove elements less than and equal K # using Counter() + list comprehension from collections import Counter # initializing list test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] # printing original list print("The original list : " + str(test_list)) # initializing K K = 2 # using Counter() + list comprehension # remove elements less than K freq = Counter(test_list) res = [ele for ele in test_list if freq[ele] > K] # print result print("The list removing elements less than and equal K : " + str(res)) --- __ __ **Output :** The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2] Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
f35d5e60e919f240526e45a23acdbb3dbe4314b5
csungg/csung.github.io
/Folder2/chatbot.py
2,496
3.890625
4
class Personality(): hiResponse = "🤖 HELLO 🤖" whatsUpResponse = "🤖 🤖" howAreYouResponse = "🤖 🤖" otherResponse = "🤖 🤖" def processInput(self, response): if response == "Hi": print(self.hiResponse) elif response == "What's up?": print(self.whatsUpResponse) elif response == "How are you?": print(self.howAreYouResponse) else: print(self.otherResponse) def intro(): print("🤖 HELLO, I AM CHATBORT 🤖") print("🤖 LET'S TALK! 🤖") print("🤖 HOW ARE YOU? 🤖") def choosePersonality(): print("Choose a personality to talk to. You can choose:") choice = input("Mean, Nice, or Nervous") return choice def process_input(): if answer == "hi": print("🤖 GREETINGS FROM CHATBOT 🤖") else: print("🤖 THAT'S COOL 🤖") # Do process input stuff # --- Put your main program below! --- def main(): userChoice = choosePersonality() print(userChoice) niceRobot = Personality() niceRobot.hiResponse = "🤖 HI IT'S SO NICE TO MEET YOU! 🤖" niceRobot.whatsUpResponse = "🤖 OH, I'M JUST TALKING TO THE MOST INTERESTING PERSON 🤖" niceRobot.howAreYouResponse = "🤖 OH I'M JUST LOVELY! 🤖" niceRobot.otherResponse = "🤖 TERRIBLY SORRY, BUT I DON'T UNDERSTAND 🤖" meanRobot = Personality() meanRobot.hiResponse = "🤖 LEAVE! 🤖" meanRobot.whatsUpResponse = "🤖 DON'T SPEAK TO ME 🤖" meanRobot.howAreYouResponse = "🤖 TERRIBLE, NOW THAT I'M TALKING TO YOU! 🤖" meanRobot.otherResponse = "🤖 I DON'T UNDERSTAND YOUR GIBBERISH 🤖" nervousRobot = Personality() nervousRobot.hiResponse = "🤖" nervousRobot.whatsUpResponse = "🤖 ...UM, HI 🤖" nervousRobot.howAreYouResponse = "🤖 NERVOUS! 🤖" nervousRobot.otherResponse = "🤖 THE WORLD IS LARGE AND CONFUSING AND I AM SMALL AND SCARED! 🤖" intro() while True: answer = input("(What will you say?)") if (userChoice == "Nice"): niceRobot.processInput(answer) elif (userChoice == "Mean"): meanRobot.processInput(answer) elif (userChoice == "Nervous"): nervousRobot.processInput(answer) # DON'T TOUCH! Setup code that runs your main() function. if __name__ == "__main__": main()
228a818aa19bd74ffe70e0c504a4031e54f26cf9
dionis-git/study
/practice_3.py
695
4.5
4
# Check if a number is positive, negative, or NULL. while True: user_input = (input('enter a number:\n')) if user_input == 'exit': break else: # Check user input can get converted to 'float' try: user_variable = float(user_input) # Check the sign of the number if user_variable > 0: print("This is a positive number.") elif user_variable < 0: print("This is a negative number.") else: print('This is a NULL') except ValueError: print("This is not a number. ") finally: print("Type 'exit' to quit, or ", end='')
5799f4dd97217c61abb66c0775cd2568a48889ad
msanchez77/cs175_assignment2
/cs175/classifiers/softmax.py
4,674
3.84375
4
import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. (3073, 10) - X: A numpy array of shape (N, D) containing a minibatch of data. (500, 3073) - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. (500, 1) - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] num_classes = W.shape[1] # Loss term1 = 0 for i in range(num_train): term2 = 0 for j in range(num_classes): Wt = np.transpose(W[:,j]) score = np.dot(Wt, X[i,:]) term2 += np.exp(score) term1 += (-np.log((np.exp(np.dot(np.transpose(W[:,y[i]]), X[i,:])))/term2)) loss = (1/num_train)*term1 l2_norm = 0 for c in range(num_classes): l2_norm += np.linalg.norm(W[:,c])**2 loss += reg*l2_norm # dW term3 = 0 for i in range(num_train): hx = np.zeros(num_classes) x2d = np.atleast_2d(X[i,:]) #(1,3073) for j in range(num_classes): denom = 0 for k in range(num_classes): Wtk = np.transpose(W[:,k]) score_k = np.dot(Wtk, X[i,:]) denom += np.exp(score_k) Wtj = np.transpose(W[:,j]) #(3073,1) score_j = np.dot(Wtj, X[i,:]) hx[j] = np.exp(score_j)/denom y_hot = np.zeros(num_classes) y_hot[y[i]] = 1 y2d = np.atleast_2d(hx-y_hot) #(1,10) term3 += np.dot(x2d.T, y2d) dW = (term3/num_train) + 2*reg*W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW def softmax_loss_vectorized(W, X, y, reg): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# # W: (D, C) (3073, 10) # X: (N, D) (500, 3073) # Y: (N, 1) (500, 1) # Loss num_train = X.shape[0] num_classes = W.shape[1] scores = np.dot(X, W) max_score = np.max(scores) scores -= max_score exp_score = np.exp(scores) #(N, C) (500, 10) sum_score = np.sum(exp_score, axis=1) sum_score = np.atleast_2d(sum_score).T #(N, 1) (500, 1) yhat = exp_score / sum_score #(N, C) (500, 10) one_hot = np.zeros((num_train,num_classes)) #(N, C) (500, 10) indexs = np.arange(num_train) #(N) (500) one_hot[indexs, y] = 1 loss = -one_hot*np.log(yhat) loss = np.mean(np.sum(loss,axis=1)) loss += np.linalg.norm(W)**2 # dW dW = (np.dot(X.T,(yhat-one_hot))/num_train) + 2*reg*W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW
7ab0d5898d27cd73589c22eb090a277b270763cd
igortemnikovd/MyPythonTest
/calculator.py
579
3.75
4
#простой калькулятор # from colorama import init from colorama import Fore, Back, Style #use Colorama to make Termcolor work on Windows too init() print( Back.WHITE ) what = input( "Что делаем? (+, -,): " ) a = float(input("Введите первое число: ")) b = float(input("Введите второй число: ")) if what == "+": c = a + b print("Результат: " + str(c)) elif what == "-": c = a - b print("Результат: " + str(c)) else: print("Выбрана неверная операция!")
01bd422ae780515b8ad17df790aabec669890a6b
v1ctor/advent-of-code-2019
/day13/run.py
2,604
3.515625
4
import sys from computer import Computer class Game: sizeX = 0 sizeY = 0 score = 0 buf = None ball = None platform = None command = 0 def init(self, display): for i in range(0, len(display), 3): op = display[i:i + 3] if op[0] == -1: continue else: if self.sizeX < op[0]: self.sizeX = op[0] if self.sizeY < op[1]: self.sizeY = op[1] self.buf = [[]] * (self.sizeY + 1) for i in range(self.sizeY + 1): self.buf[i] = ["."] * (self.sizeX + 1) def draw_game(self, display): if self.buf == None: self.init(display) for i in range(0, len(display), 3): op = display[i:i + 3] if op[0] == -1: self.score = op[2] if op[2] == 1: self.buf[op[1]][op[0]] = "#" if op[2] == 2: self.buf[op[1]][op[0]] = "x" if op[2] == 3: if self.platform != None: self.buf[self.platform[1]][self.platform[0]] = '.' self.buf[op[1]][op[0]] = "=" self.platform = op[:2] if op[2] == 4: if self.ball != None: self.buf[self.ball[1]][self.ball[0]] = '.' self.ball = op[:2] if self.platform != None: if self.platform[0] > self.ball[0]: self.command = -1 elif self.platform[0] < self.ball[0]: self.command = 1 else: self.command = 0 self.buf[op[1]][op[0]] = "o" for j in range(self.sizeY + 1): print(''.join(self.buf[j])) print(self.score) def main(): filename = "input.txt" play = False if len(sys.argv) > 1: filename = sys.argv[1] if len(sys.argv) > 2 and sys.argv[2] == "--play": play = True f = open(filename) s = f.readline() memory = list(map(int, s.split(","))) game = Game() if play: memory[0] = 2 c = Computer(memory) while True: c.run() if len(c.writebuf) == 0: break game.draw_game(c.writebuf) c.writebuf = [] c.readbuf.append(game.command) else: c = Computer(memory) c.run() print(c.writebuf[2::3].count(2)) if __name__== "__main__": main()
61608ce3e67bbc3c60732281ba06547759710913
3esawe/Hacking
/chapter1/passcracker.py
393
3.71875
4
import crypt def encrypt(word): return crypt.crypt(word,"AI") def passcracker(cryptedpass): words = open("words2") salt = cryptedpass[0:2] for word in words.readlines(): word = word.strip('\n') cryptword = crypt.crypt(word,salt) if cryptword == cryptedpass: return word return 'not found' if __name__ == '__main__': c = encrypt("hello") v = passcracker(c) print(v)
aa90731b82c64f605cd100c31ee8c35b24f2eca6
radfordm-osu/homework-4
/hw4p3.py
179
3.578125
4
def NameGen(first, last): if (isinstance(first, str) and isinstance(last, str)): name = first + " " + last return name else: return "Error!"
d8a9ed2f36f52459cff0a0d05ba78f86478b4ed1
Luisdar0z/nonogrampy
/test.py
2,276
4.125
4
""" F = int(input("Numero de filas:\n")) C = int(input("Numero de Columnas:\n")) """ #ejemplo de ingreso de datos: 12 2 3 4 44, 123 3 32 2 323, 23 23 columna = input("ingrese columnas(solo separado por , sin espacio) \nR: ") col = columna.split(", ") print(col) #print("imprimiendo posicion valor 2 posicion 1: ", col[1]) #print(type(col[1][1])) #ejemplo de ingreso de datos: 12 2 3 4 44, 123 3 32 2 323, 23 23 fila = input("\ningrese filas (solo separado por , sin espacio)\nR: ") fil = fila.split(", ") print(fil) #print("imprimiento posicion 3", fil[1]) i = 0 acol = [] ecol = [] icol = [] while i < len(col): #creamos una lista de listas llamada "acol" con los datos de "col" acol.append(col[i].split(" ")) #print("+acol: ", acol[i]) #convertimos a enteros los elementos de una lista de "acol" y los pasamos a la lista "icol" for j in acol[i]: icol.append(int(j)) #print("-icol: ", icol) #pasamos la lista "icol" como un elemento de la lista "ecol" y reiniciamos la lista "icol" ecol.append(icol) icol = [] #print("•ecol: ", ecol) i += 1 print("\nValor columnas: ") print(ecol) i = 0 afil = [] efil = [] ifil = [] while i < len(fil): #creamos una lista de listas llamada "afil" con los datos de "fil" afil.append(fil[i].split(" ")) #print("+afil: ", afil[i]) #convertimos a enteros los elementos de una lista de "afil" y los pasamos a la lista "ifil" for h in afil[i]: ifil.append(int(h)) #print("-ifil: ", ifil) #pasamos la lista "ifil" como un elemento de la lista "efil" y reiniciamos la lista "ifil" efil.append(ifil) ifil = [] #print("•efil: ", efil) i += 1 print("\nValor filas: ") print(efil) """ print('\n') print(' 1 1 1 ') print(' 3 1 1 1 1') print(' 1 1 1 1 3') print('╔═╦═╦═╦═╦═╗') print('║■║■║■║■║■║ 5') print('╠═╬═╬═╬═╬═╣') print('║■║ ║ ║ ║ ║ 1') print('╠═╬═╬═╬═╬═╣') print('║■║■║■║■║■║ 5') print('╠═╬═╬═╬═╬═╣') print('║ ║ ║ ║ ║■║ 1') print('╠═╬═╬═╬═╬═╣') print('║■║■║■║■║■║ 5') print('╚═╩═╩═╩═╩═╝') """
c715b2cfd2920467c20f8a1addbd6393d1d00155
Michaelnstrauss/Byte
/udemy/smileyface.py
153
3.53125
4
#!/usr/bin/env python3 smile = 1 while smile < 10: num = '\U0001f600' # for smiles in len(range(smile)): print(num*smile) smile += 1
10b520460c12d819116f8d80a87d8e6c8d81a715
romwil22/python-textbook-exercises
/chapter7/exercise3.py
1,415
4.65625
5
"""Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their program. Modify the program that prompts the user for the file name so that it prints a funny message when the user types in the exact file name “na na boo boo”. The program should behave normally for all other files which exist and don’t exist. Here is a sample execution of the program: python egg.py Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python egg.py Enter the file name: missing.tyxt File cannot be opened: missing.tyxt python egg.py Enter the file name: na na boo boo NA NA BOO BOO TO YOU - You have been punk'd! We are not encouraging you to put Easter Eggs in your programs; this is just an exercise.""" textfile_input = None fileread = None # User text file input condition while True: textfile_input = input('enter text file: ') try: fileread = open(textfile_input) print() break except: if textfile_input == "na na boo boo": print(textfile_input.upper(), ' - You have been punk\'d!') print() continue print('File cannot be opened:', textfile_input) print() continue count = 0 # Count text line for line in fileread: count += 1 # Print output format_Txt = 'There were {} subject lines in {}'.format(count, textfile_input) print(format_Txt)
f253d412c5a55c7a11d3f76c302aab0b1a57a2c8
aserjunior/algoritmos-especial
/Atividade_Semana_5/uri1038_lanche.py
688
3.796875
4
def main(): #entrada lanche = int(input('Insira o código do pedido: ')) quantidade = int(input('Insira quantos pedidos vai querer: ')) #processamento validar = validar_lanche(lanche) valor_final = valor_lanche(validar, quantidade) #saída print(f'Total: R${valor_final: .2f}') def validar_lanche(lanche): if lanche is 1: return 4.00 elif lanche is 2: return 4.50 elif lanche is 3: return 5.00 elif lanche is 4: return 2.00 elif lanche is 5: return 1.50 def valor_lanche(codigo, quantidade): calculo = codigo * quantidade return calculo main()
a9463183fdcd5d040a9dc15fbe3706403a8b2728
forbearing/mypython
/1_python/8.1_函数.py
3,736
4.125
4
函数的定义和调用 局部变量、全局变量 - 在函数中,不使用 global 声明全局变量时,不能修改全局变量的本质是因为,不能修改全局变量的 指向,即不能将全局变量指向新的数据 - 对于不可变类型的全局变量,因为其指向的数据不能修改,所以不使用 global 时无法修改全局变量 - 对于可变类型的全局变量,因为其指向的数据可以修改,所以不使用 global 时也可以修改全局变量 - 全局变量定义在调用函数之前,不是定义函数之前 = 可变类型:值可以修改(内存地址不变但所保存的值变化了)引用可以修改(变量的内存地址变化了) - 不可变类型:值不可以修改,可以修改变量的引用(= 赋值号) - 在函数里面修改全局变量 1:如果函数变量是可变类型的,所以在函数里面任意修改(值、引用) 2:如果函数变量是不可变类型的,在函数里面不可以修改值,也不能修改引用,除非加上 global, 才能修改饮用。 - 全局变量放在调用函数之前,不是定义函数之前。 函数参数 1:缺省参数 1:语法 def func(a=1,b=2,c=3): return a+b+c d=func() print(d) 2:带有默认值的参数一定要位于参数列表的最后面 2:不定长参数 1:有时候我们需要一个函数能处理比当初声明时更多的参数,这些参数叫做不定长参数, 声明时不会命名 2:语法 def func(x,y,*args): print(x,y) print(args) sum = x+y for i in args: sum+=i print(sum) def func(x,*args,**kwargs): print(x) print(args) print(kwargs) sum = x for i in args: sum += i for i in kwargs.values(): sum += i func(2,3,4,num1=5,num2=6) args=[2,3] kwargs{'num1':5,'num2':6} func(2,*args,**kwargs) # 集合的拆包 3:引用传参 1:语法 def func(x,y): x=x.replace('a','A') y=y.append(10) print(x,y) a='abcdefg' b=[1,2,3] func(a,b) print(a,b) print(id(a),id(b)) 函数返回 1:函数返回多个值 def func(): a,b=1,2 return a,b # 返回元组 #return [a,b] # 返回列表 x,y=func() # x,y 为字符串 c=func() # c 为元组 # return [a,b] d=func() # d 为列表 print(x) print(y) 匿名函数 1:用 lambda 关键字可以创建小型匿名函数,这种函数得名于省略了 def 声明函数的标准步骤 lambda 函数能接受任何数量的参数,但只能返回一个表达式的值 匿名函数不能直接调用 print,因为 lambda 需要一个表达式。 2:语法 lambda [arg1 [,arg2, .... argn]]: expression sum = lambda arg1, arg2: arg1 + arg2 3:使用场景 def func(a,b,func): result = func(a,b) return result print(func(22,33,lambda x,y:x+y)) stus=[{"name":"zs","age":22},{"name":"lisi","age":33}] 封装函数、递归函数 重难点 1:局部变量和全局变量的区别 2:可变类型和不可变类型在函数中使用 # 3:不定长参数、拆包、缺省参数
8c524ff5d026ba497ee50ef57406d7b5326d92c9
Djamshed1/IS211_Assignment4
/sort_compare.py
4,825
4.1875
4
#!/usr/bin/env python # -*- coding utf-8 -*- """Week 4 Assignment 4 Part 2""" import time import random def insertion_sort(l): # l = list """ Args: l(list): List of numbers. Returns: l(list): Sorted List. Examples: >>> insertion_sort([1,2,3,4,5,6,7,8,9,10]) ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5.0067901611328125e-06) """ s = time.time() # s = start for index in range(1, len(l)): current_value = l[index] position = index while position > 0 and l[position - 1] > current_value: l[position] = l[position - 1] position = position - 1 l[position] = current_value end = time.time() return l, end-s def shell_sort(l): # l = list """ Args: l(list): List of numbers. Returns: l(list): List of number sorted. Examples: >>> shell_sort([9,8,7,6,5,4,3,2]) ([2, 3, 4, 5, 6, 7, 8, 9], 2.5987625122070312e-05) """ s = time.time() # s = start sublist_count = len(l) // 2 while sublist_count > 0: for s_position in range(sublist_count): is_gap(l, s_position, sublist_count) sublist_count = sublist_count // 2 end = time.time() return l, end-s def is_gap(l, s, gap): # s = start, l = list """ Args: l(list): List of numbers. Returns: Examples: """ for i in range(s + gap, len(l), gap): current_value = l[i] position = i while position >= gap and l[position - gap] > current_value: l[position] = l[position - gap] position = position - gap l[position] = current_value def python_sort(l): # l = list """The python_sort function simply a ‘wrapper’ function that calls sort() on the input list. Args: l(list): List of numbers. Returns: l(list): Sorted list. Examples: >>> python_sort([3,2,1]) ([1, 2, 3, 6, 8], 3.0994415283203125e-06) """ s = time.time() # s = start, l = list l.sort() end = time.time() return l, end-s def ran_number(value): """ Args: random_list(list): List of random ints based on values. Returns: random_list(list): Creates list of random values fast. Examples: >>> ran_number(100) [79, 1, 76, 62, 31, 21, 23, 27, 85, 0, 24, 25, 53, 32, 87, 46, 11, 12, 41, 29, 81, 71, 69, 36, 90, 15, 57, 82, 96, 48, 37, 59, 63, 80, 30, 54, 13, 94, 9, 77, 92, 72, 42, 51, 61, 91, 67, 43, 84, 93, 49, 8, 88, 89, 97, 2, 5, 28, 40, 10, 47, 55, 44, 60, 83, 34, 73, 99, 98, 52, 4, 16, 18, 95, 35, 75, 65, 6, 50, 86, 26, 17, 38, 66, 78, 14, 74, 3, 70, 39, 64, 22, 33, 45, 20, 58, 19, 7, 68, 56] """ random_list = random.sample(range(0, value), value) return random_list def main(): """ Args: test dict): Test keys and values. random_list(list): Generated random lists inter_count(int): Interger of indexed count. ouput(dict): Results output Returns: None Examples: >>> main() List of 500 length the test timed: Insertion Sort took 0.0000065 seconds to run on average Shell Sort took 0.0010760 seconds to run on average Python Sort took 0.0000131 seconds to run on average List of 1000 length the test timed: Insertion Sort took 0.0000092 seconds to run on average Shell Sort took 0.0016598 seconds to run on average Python Sort took 0.0000194 seconds to run on average List of 10000 length the test timed: Insertion Sort took 0.0000706 seconds to run on average Shell Sort took 0.0283402 seconds to run on average Python Sort took 0.0001699 seconds to run on average """ tests = {'test1': 500, 'test2': 10000, 'test3': 1000} for test in tests.values(): random_list = ran_number(test) iter_count = 100 output = {'insert':0, 'shell':0, 'pyth':0} while iter_count > 0: output['insert'] += insertion_sort(random_list)[1] output['shell'] += shell_sort(random_list)[1] output['pyth'] += python_sort(random_list)[1] iter_count -= 1 print "List of %s length the test timed:" % test print "Insertion Sort took %10.7f seconds to run on average" % \ (float(output['insert'] / 100)) print "Shell Sort took %10.7f seconds to run on average" % \ (float(output['shell'] / 100)) print "Python Sort took %10.7f seconds to run on average" % \ (float(output['pyth'] / 100)) print '\n' if __name__ == '__main__': main()
ae817d14984be079d38da264ee9cbb2e54dc221a
jz33/LeetCodeSolutions
/398 Random Pick Index.py
1,063
4.03125
4
''' 398. Random Pick Index https://leetcode.com/problems/random-pick-index/ Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Note: The array size can be very large. Solution that uses too much extra space will not pass the judge. Example: int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1); ''' from random import randint class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: resIndex = -1 count = 0 for i, e in enumerate(self.nums): if e == target: count += 1 if randint(1, count) == 1: resIndex = i return resIndex
9f043671f95d6bd1a0f8c00af426b49f465e467a
A-Alexander-code/150-Python-Challenges--Solutions
/Ejercicio_N058.py
1,375
3.84375
4
import random num1 = random.randint(1,10) num2 = random.randint(1,10) cont = 0 print("Inicia la prueba\nRealice las siguientes operaciones") oper1 = num1 + num2 oper2 = num1 - num2 oper3 = num1 * num2 oper4 = num1 / num2 oper5 = (num1 + num2) * num1 print("El primer número es: ",num1) print("El segundo número es: ",num2) resp1 = int(input("El resultado de sumar el primer y segundo número es \n")) resp2 = int(input("El resultado de restar el primer y segundo número es \n")) resp3 = int(input("El resultado de multiplicar el primer y segundo número es \n")) resp4 = float(input("El resultado de dividir el primer y segundo número es \n")) print("(",num1,"+",num2,")*",num1) resp5 = int(input("El resultado de la anterior operación es\n")) if resp1 == oper1: print("Respuesta guarda") cont = cont + 1 else: print("Respuesta guardada") if resp2 == oper2: print("Respuesta guarda") cont = cont + 1 else: print("Respuesta guardada") if resp3 == oper3: print("Respuesta guarda") cont = cont + 1 else: print("Respuesta guardada") if resp4 == oper4: print("Respuesta guarda") cont = cont + 1 else: print("Respuesta guardada") if resp5 == oper5: print("Respuesta guarda") cont = cont + 1 else: print("Respuesta guardada") print("La prueba ha finalizado") print("Usted ha acertado",cont,"preguntas de 5")
608a53882437a6522bbb96f10f2e57b94fb5500d
ToniCaimari/Codewars
/Python/kyu6/Count_char_in_string.py
271
3.71875
4
def count(string): character_list = [] character_number = [] for i in string: if i not in character_list: character_list.append(i) character_number.append(string.count(i)) return dict(zip(character_list, character_number))
b00598715a35f00055109b8c2828ee4c01ca5961
git-gagan/MywaysTrainee
/RoughExperiments/OpenCV/sizes.py
907
3.734375
4
import cv2 img = cv2.imread("C:/Users/Acer/Desktop/Nature.jpeg") #Changing size based on Aspect Ratio (measurement of relationship between height and width) #For Scaling up, use Inter_cubic or Inter_linear #For scaling down, use INTER_AREA or INTER_NEAREST #INTERPOLATION :- Mathematical procedure applied in order to derive the value between 2 points having prescribed values print(img.shape) print(img.size) scale = int(input("Number by which you wanna scale the image")) width = int(img.shape[1]*scale/100) height = int(img.shape[0]*scale/100) resized_img = cv2.resize(img, (width,height), interpolation = cv2.INTER_NEAREST) #cv2.imshow("Original",img) cv2.imshow("Resized",resized_img) #flipping the image flipped_img = cv2.flip(resized_img, 1) # 1 for horizontal flip, 0 for evrtical flip, -1 for both cv2.imshow("Flipped",flipped_img) cv2.waitKey(0) cv2.destroyAllWindows()
e3ec0d52b3f4deea078ced1f99d93e2cca91b004
tariqrahiman/pyComPro
/codeforces/contest/1087/test_B.py
1,271
3.515625
4
import unittest import B def valid(n, k, res): return (res / k) * (res % k) == n class test_class(unittest.TestCase): def test_basic(self): s = B.solve(6,3) self.assertEqual(s, 11) self.assertTrue(valid(6,3,int(s))) s = B.solve(1,2) self.assertEqual(s, 3) self.assertTrue(valid(1,2,int(s))) s = B.solve(4,6) self.assertTrue(valid(4,6,int(s))) self.assertEqual(s, 10) print "basicOK" #@unittest.skip("skip if you can not precompute the answer") def test_regression(self): from random import random as rnd from B import solve from time import time SIZE = 1000 # size of the regression (iterations) t1 = time() for _ in xrange(SIZE): # int(rnd() * (upper_bound - lower_bound) + lower_bound) for the parameter n = (int(rnd() * (100 - 0)) + 0) k = (int(rnd() * (10 - 2)) + 2) got = solve( n,k ) try: self.assertTrue(valid(n,k,got)) except: print n,k,got exit("") t2 = time() print "regressionOK : "+str(t2 - t1) if __name__ == "__main__": unittest.main()
2c56a3b04fc375ff2d78fdd163ad230f67cb55af
JFerRG/MySQL_Py
/GitHub/ComprobacionDeCuadrados.py
643
4
4
def validacion(): while True: try: num = int(input('Ingresa el valor: ')) if num > 0: return num break else: print('El número ha de ser mayor que cero') except Exception as e: print('Error al obtener el número\n' + str(e)) def dobles (a,b): if b == (a**2): print('{} es el cuadrado exacto de {}'.format(b,a)) elif b < (a**2): print('{} es menor que el cuadrado de {}'.format(b,a)) elif b > (a**2): print('{} es mayor que el cuadrado de {}'.format(b,a)) dobles(validacion(),validacion())
b322c5e99b42aa50be960e4441fc737210996a0e
chars32/edx_python
/Weeks/Week9/4. gcd.py
338
4.15625
4
#Write a function named calculate_gcd that receives two positive integers a and b as parameter and returns #their greatest common divisor (GCD) using recursion. def calculate_gcd(a, b): if b == 0: return a else: print("antes", a,b, a%b) g cd = calculate_gcd(b, a%b) return gcd print(calculate_gcd(5, 10))
132ce94da67fd0260133132bbc41368d92518c2f
diegodukao/choraoipsum
/choraogenerator.py
707
3.65625
4
from random import shuffle WORDS = [ "vagabundo", "skate", "charlie", "brown", "santos", ] def generate(qt_words): words = WORDS.copy() sentence = "Chorao Ipsum vagabundo brown" for i in range(int(qt_words)): if not words: words = WORDS.copy() shuffle(words) if i % 7 == 0: sentence = "{}{}".format(sentence, ",") sentence = "{} {}".format(sentence, words.pop()) elif i % 11 == 0: sentence = "{}{}".format(sentence, ".") sentence = "{} {}".format(sentence, words.pop().capitalize()) else: sentence = "{} {}".format(sentence, words.pop()) return sentence
885fb68421f4c6511c598ae9ce9d458442fff2eb
selincifci/bby162
/uygulama04.py
1,273
3.625
4
__author__"Selin ÇİFCİ" kadin=input("isim giriniz:") erkek=input("isim giriniz") misra=input("mısra sayısı giriniz:") sec=int(misra) bosluk=" " i=["ilk görüşte","vapurdayken","okula giderken","arkadaşlarıyla gezerken","ağlarken","mesajlaştığında","sinirlendiğinde","ders çalışıyorken","saçmalarken"] k=["yanına gitti","konuştu","mesajına cevap vermedi","görüldü attı","eğlendi","depresyona girdi","dizi izleyip ağladı","çikolata yiyip kilo aldı","canı sıkıldı"] import random def ilk(): secim=random.choice(i) i.remove(secim) return secim def ikinci(): secim=random.choice(k) k.remove(secim) return secim a=(kadin+bosluk+ilk()+bosluk+erkek+bosluk+ikinci()+"\n") b=(erkek+bosluk+ilk()+bosluk+kadin+bosluk+ikinci()+"\n") c=(kadin+bosluk+ilk()+bosluk+erkek+bosluk+ikinci()+"\n") d=(erkek+bosluk+ilk()+bosluk+kadin+bosluk+ikinci()+"\n") e=(kadin+bosluk+ilk()+bosluk+erkek+bosluk+ikinci()+"\n") f=(erkek+bosluk+ilk()+bosluk+kadin+bosluk+ikinci()+"\n") if sec==1 : print(a or b or c or d or e or f) elif sec==2: print(a,b) elif sec==3: print(a,b,c) elif sec==4: print(a,b,c,d) elif sec==5: print(a,b,c,d,e) elif sec==6: print(a,b,c,d,e,f) else: print("en fazla 6 mısra girebilirsiniz")
392cb14a54315353e7ececc459d74af2212feabf
dg5921096/Books-solutions
/Python-For-Everyone-Horstmann/Chapter11-Recursion/split_recursive_list_sum.py
405
4.03125
4
# Recursively calculates the sum of a list's items by splitting the list in two. # FUNCTIONS def _sum_helper(given_list, start): if start == len(given_list): return 0 return given_list[start] + _sum_helper(given_list, start + 1) def split_recursive_sum(given_list): middle = len(given_list) // 2 return _sum_helper(given_list[:middle], 0) + _sum_helper(given_list[middle:], 0)
b9dfbd3ddc22c6988616a0c1bd852d34138df0c3
Wraient/Python-Progarams
/115.looping.in.dict.py
862
3.5625
4
user_info = { "Name" : "Rushikesh", "Age" : 18, "Fav_movie" : ["Robot", "Social Networks", "Twitter"], "Fav_tunes" : ["Tokyo Ghoul", "Weathering with you"] } # if "Fav_tunes" in user_info: # print("True") # else: # print("False") # if "Rushikesh" in user_info: # print("True") # else: # print("False") # if "Rushikesh" in user_info.values(): # print("True") # else: # print("False") # for i in user_info.values(): # print(i) # print("\n") # print(user_info.values()) # print(type(user_info.values())) # print("\n") # print(user_info.keys()) # print(type(user_info.keys())) # print("\n") # for i in user_info: # print(user_info[i]) # for key, value in user_info.items(): # print(f"{key} is {value}") # user1 = dict(name = "e", age = 19, email = "xyz@gmail.com" ) # print(user1) # print(type(user1))
4ceb4e2779293f46e180555640cc3ead0acbc68e
MrLW/algorithm
/leetcode/everyday/middle_781_numRabbits.py
901
3.578125
4
from typing import List from typing import Counter class Solution: def numRabbits(self, answers: List[int]) -> int: ''' 题目: 781. 森林中的兔子 ''' # 1. 利用规律实现 count = Counter(answers) res = sum([(x+y) // (y+1) * (y+1) for y, x in count.items()]) # 1. for + dic # res, i, size, dic = 0, 0, len(answers), dict() # for i in range(size): # if answers[i] == 0: # res += 1 # elif answers[i] not in dic or dic[answers[i]] == 0: # dic[answers[i]] = answers[i] # res += answers[i] + 1 # elif dic[answers[i]] > 0: # dic[answers[i]] -= 1 # return res s, answers = Solution(), [0, 0, 2, 2, 1] # [1, 1, 1] => 2+2 = 4 # [2, 2, 2] => 3 只 兔子 回答 2 => 3 / 2+1 = 1 print('res', s.numRabbits(answers))
a394acfe35134d1daea2959c250646762fbcb9bd
Wilsonilo/MIT-6.00.1x
/Mid-Term/problem7.py
913
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 3 11:58:28 2017 @author: wilson """ import operator def dict_invert(d): ''' d: dict Returns an inverted dictionary according to the instructions above If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]} If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]} If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]} ''' newListReturn = {} #first lest get the keys or values in order for key,value in d.items(): newListReturn[value] = newListReturn.get(value, []) newListReturn[value].append(key) #order Values for key, element in newListReturn.items(): newListReturn[key] = sorted(element) return newListReturn print(dict_invert({8: 6, 2: 6, 4: 6, 6: 6}))
7048aa85e18f6638cbf95dbe378412529162db47
mascarock/ADM-HW1
/scripts.py
31,734
4.21875
4
#### Problem 1 ### Introduction ## Ex 1 - Hello World # store the string "Hello, World!" in a variable hello = "Hello, World!" # print the variable print(hello) ## Ex 2 - If, Else #!/bin/python3 import math import os import random import re import sys #get the input if __name__ == '__main__': n = int(input().strip()) #store the output output = "" # using the remainder operator, if the remainder is zero, # the number is odd, otherwise even if n % 2 != 0: output = 'Weird' # number is odd else: if n > 1 & n < 6: output = 'Not Weird' if n > 5 & n < 21: output = 'Weird' if n > 20: output = 'Not Weird' print(output) ## Ex 3 - Aritm op if __name__ == '__main__': a = int(input()) b = int(input()) # sum print(a + b) # diff print(a - b) # product print(a * b) ## Ex 4 - Division if __name__ == '__main__': a = int(input()) b = int(input()) print (a // b) print (a / b) ## Ex 5 - Loops if __name__ == '__main__': n = int(input()) # constraints if n >= 1 & n <= 20: #for loop for x in range (0, n): #exponential function print (x**2) ## Ex 6 - Function def is_leap(year): leap = False # Verbose version # if year %400 == 0: leap = True # else: # if ( year%4==0 and not year %100 == 0): leap = True # else: leap = False # Short version if year %400 == 0 or ( year % 4 == 0 and not (year %100 == 0)): leap = True return leap year = int(input()) print (is_leap(year)) ## Ex 7 - Print Function if __name__ == '__main__': n = int(input()) for i in range(n): if (i !=0): print(i, end ="") print(n) ### Data Types ## Ex 1 - Tuples if __name__ == '__main__': # get it out of the way the first line n = int(input()) # read the second line and split by whitespace line = input().split() # save to a list integer_list = map(int, line) # convert to a tuple of ints, which is hashable tp = tuple(integer_list) # print the hash print(hash(tp)) ## Ex 2 - List Comprehensions if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) list = [ [i,j,k] for i in range (x+1) for j in range (y+1) for k in range (z+1) if i+j+k!=n #constraints ] print( list ) ## Ex 3 - Runner-Up Score! if __name__ == '__main__': n = int(input()) # create the array for the scores scores = list(map(int, input().split())) # get the max m = max(scores) # store the temporary min (algo for min) minScore = min(scores) for x in scores: if(x>minScore and x<m): minScore = x print(minScore) ## Ex 4 - Nested Lists if __name__ == '__main__': # get the number of students studentsNumber = int(int(input())) # grade and students for each student gradeStudents = [[input(),float(input())] for i in range(0 , studentsNumber)] # list of grades grades = [] for grade in gradeStudents: grades.append(grade[1]) # Create a set of grades and find the min setGrades = set(grades) setGrades.remove(min(setGrades)) # Compute the second lowest grade minGrade = min(setGrades) # Get the students name minStudents = [s[0] for s in gradeStudents if s[1] == minGrade] # sort the set sortedStudents = sorted(minStudents) # print the students for s in sortedStudents: print(s) ## Ex 5 - Finding the percentage if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() # compute the mean average = sum(student_marks[query_name])/3 # format the mean print("%.2f" % average) ## Ex 6 - Lists List = [] result = [] N = int(input()) for i in range(N): List = input().split() if List[0] == "insert" : position = int(List[1]) integer = int(List[2]) result.insert(position,integer) if List[0] == "remove" : rem_int = int(List[1]) result.remove(rem_int) if List[0] == "append" : append_int = int(List[1]) result.append(append_int) if List[0] == "sort" : result.sort() if List[0] == "pop" : result.pop() if List[0] == "reverse" : result.reverse() if List[0] == "print" : print(result) ### Strings ## Ex 1 - Swap Case def swap_case(s): str = "" for i in range(len(s)): if s[i].islower(): str += s[i].upper() else: str += s[i].lower() return str if __name__ == '__main__': s = input() result = swap_case(s) print(result) ## Ex 2 - Split and Join def split_and_join(line): # line to split toSplit = line.split(" ") return "-".join(toSplit) if __name__ == '__main__': line = input() result = split_and_join(line) print(result) ## Ex 3 - What's your name? def print_full_name(a, b): print("Hello " + a + " " + b + "! You just delved into python.") if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name) ## Ex 4 - Mutations def mutate_string(string, index, char): return string[:index] + char + string[index+1:] if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new) ## Ex 5 - Find a String def count_substring(string, sub_string): count = 0 for i in range(0, len(string)): if(sub_string[0]==string[i]): if(string[i:i+len(sub_string)]==sub_string): count+=1 return count if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count) ## Ex 7 - String validation if __name__ == '__main__': s = input() alphanum = False alpha = False dig = False lc = False uc = False for i in range(len(s)): if s[i].isalnum(): alphanum = True if s[i].isalpha(): alpha = True if s[i].isdigit(): dig = True if s[i].islower(): lc = True if s[i].isupper(): uc = True print(alphanum) print(alpha) print(dig) print(lc) print(uc) ## Ex 8 - Text Alignment thk = int(input()) #This must be an odd number c = 'H' #Top Cone for i in range(thk): print((c*i).rjust(thk-1)+c+(c*i).ljust(thk-1)) #Top Pillars for i in range(thk+1): print((c*thk).center(thk*2)+(c*thk).center(thk*6)) #Middle Belt for i in range((thk+1)//2): print((c*thk*5).center(thk*6)) #Bottom Pillars for i in range(thk+1): print((c*thk).center(thk*2)+(c*thk).center(thk*6)) #Bottom Cone for i in range(thk): print(((c*(thk-i-1)).rjust(thk)+c+(c*(thk-i-1)).ljust(thk)).rjust(thk*6)) ## Ex 9 - Text Alignment import textwrap def wrap(string, max_width): return textwrap.fill(string, max_width) if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result) ## Ex 10 - Designer Door Mat if __name__ == "__main__": # get the input n, m = map(int, input().split()) central = ("WELCOME").center(m, "-") for i in range(n//2): print((".|."*(2*i+1)).center(m, "-")) print(central) for i in range((n//2)-1, -1, -1): print((".|."*(2*i+1)).center(m, "-")) ## Ex 11 - String Formatting def print_formatted(number): w = len(bin(number))-2 for i in range(1, number +1): print(("{0:"+ str(w) +"d} {1:"+ str(w) +"o} {2:"+ str(w) +"X} {3:"+ str(w) +"b}").format(i, i, i, i)) if __name__ == '__main__': n = int(input()) print_formatted(n) ## Ex 12 - Alphabet Rangoli import string def print_rangoli(size): pattern = [] size = int(size) for i in range(size): p = "-".join(string.ascii_lowercase[i:size]) pattern.append((p[::-1] + p[1:]).center(4*size-3, "-")) # final pattern print("\n".join(pattern[:0:-1] + pattern)) if __name__ == '__main__': n = int(input()) print_rangoli(n) ## Ex 13 - Capitalize #!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): bl = True for i in range(len(s)): if s[i] == ' ': bl = True elif bl == True: s = s[:i] + s[i].upper() + s[i+1:] bl = False return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = solve(s) fptr.write(result + '\n') fptr.close() ## Ex 14 - Minion Game def minion_game(string): # your code goes here lst = ['A', 'E', 'I', 'O', 'U'] stuart = 0 kevin = 0 for i in range(len(string)): if lst.__contains__(s[i]): kevin += len(string) -i else: stuart += len(string) -i if stuart > kevin: print("Stuart " + str(stuart)) elif stuart < kevin: print("Kevin " + str(kevin)) else: print("Draw") if __name__ == '__main__': s = input() minion_game(s) ## Ex 6 - Merge the Tools def merge_the_tools(string, k): for i in range(len(string) // k): # we should repeat the process len(string)/k times to reach all the string s = "" for j in string[i * k: i * k + k]: if j not in s: s += j print(s) if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k) ### Sets ## Ex 1 - Intro # new function definition def average_(array): # your code goes here s = set(arr) # compute the average return sum(s)/len(s) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average_(arr) print(result) ## Ex 2 - Sym diff. if __name__ == '__main__': m = int(input()) set1 = set(map(int, input().split())) n = int(input()) set2 = set(map(int, input().split())) sd = set1.__xor__(set2) for i in range(len(sd)): print(min(sd)) sd.remove(min(sd)) ## Ex 3 - No Idea! n , m = map(int, input().split()) L = list(map(int, input().split())) A = set(map(int, input().split())) B = set(map(int, input().split())) antani = 0 for i in L : if i in A : antani += 1 if i in B : antani -= 1 print(antani) ## Ex 4 - Set.add() N = int(input()) # avoiding repeated values... s = set() for i in range(0,N) : s.add(input()) print(len(s)) ## Ex 5 - Set .discard(), .remove() & .pop() if __name__ == "__main__": n = int(input()) s = set(map(int, input().split())) nc = int(input()) for i in range(nc): command = input().split() if command[0] == 'pop': s.pop() elif command[0] == 'remove': s.remove(int(command[1])) elif command[0] == 'discard': s.discard(int(command[1])) print(sum(s)) ## Ex 6 - Set .union() input() en = set(map(int, input().split())) input() fr = set(map(int, input().split())) print(len(en.union(fr))) ## Ex 7 - Set .intersection() input() en = set(map(int, input().split())) input() fr = set(map(int, input().split())) print(len(en.intersection(fr))) ## Ex 8 - Set .difference() input() en = set(map(int, input().split())) input() fr = set(map(int, input().split())) print(len(en.difference(fr))) ## Ex 9 - Sym diff input() en = set(map(int, input().split())) input() fr = set(map(int, input().split())) print(len(en.symmetric_difference(fr))) ## Ex 10 - Set Mutation input() a = set(map(int, input().split())) for i in range(int(input())): command, n = input().split() s = set(map(int, input().split())) if command == "update": a.update(s) elif command == "intersection_update": a.intersection_update(s) elif command == "difference_update": a.difference_update(s) elif command == "symmetric_difference_update": a.symmetric_difference_update(s) print(sum(a)) ## Ex 11 - The Captain's Room k = int(input()) L = list(map(int, input().split())) s = set(L) print((sum(s)*k - sum(L))// (k-1)) ## Ex 12 - Check subset N = int(input()) for i in range(0, N): NA= int(input()) A = set(map(int, input().split())) NB= int(input()) B = set(map(int, input().split())) print(A.issubset(B)) ## Ex 13 - check strict superset A = set(map(int, input().split())) N = int(input()) m = 1 for i in range(0, N): s = set(map(int, input().split())) if( s.issubset(A) == False) or (len(A) - len(s) < 1) : # s should be a subset of A and A should have at least1 member more than s m *= 0 print(bool(m)) ### Collections ## Ex 1 - Counter X = int(input()) L = list(map(int, input().split())) N = int(input()) money = 0 for i in range(0 , N) : customer = list(map(int, input().split())) if customer[0] in L : money += customer[1] L.remove(customer[0]) print(money) ## Ex 2 - DefaultDict from collections import defaultdict n, m = map(int, input().split()) a = defaultdict(list) b = [] for i in range(n): a[input()].append(i+1) for i in range(m): item = input() if a[item] == []: a[item].append(-1) print(" ".join(map(str,a[item]))) ## Ex 3 - Namedtuple from collections import namedtuple sum = 0 N = int(input()) catg = input().split() student_tup = namedtuple('student',catg) for i in range(0, N): L = list(input().split()) m = student_tup(L[0], L[1], L[2], L[3]) sum += int(m.MARKS) print(sum/N) ## Ex 4 - Word Order from collections import OrderedDict n = int(input()) od = OrderedDict() for i in range(n): word = input() if od.__contains__(word): od[word] += 1 else: od[word] = 1 print(len(od)) for item in od: print(od[item], end=" ") ## Ex 5 - Deque from collections import deque n = int(input()) d = deque() for i in range(n): command = input().split() if command[0] == "append": d.append(int(command[1])) elif command[0] == "appendleft": d.appendleft(int(command[1])) elif command[0] == "pop": d.pop() elif command[0] == "popleft": d.popleft() for i in d: print(i, end = " ") ## Ex 6 - Piling Up! from collections import deque t = int(input()) for i in range(t): d = deque() flag = True n = int(input()) l = list(map(int, input().split())) for item in l: d.append(item) temp = 0 if d[0] >= d[-1]: temp = d.popleft() else: temp = d.pop() for k in range(n-2): if d[0] >= d[-1]: temp2 = d.popleft() else: temp2 = d.pop() if(temp < temp2): flag = False temp = temp2 if d[0] <= temp and flag == True: print("Yes") else: print("No") ## Ex 7 - Logo from collections import Counter if __name__ == '__main__': s = input() c = Counter(s.replace(" ", "")) n = 3 while n > 0: l = [] m = max(c.values()) for item in list(c): if c[item] == m: x = c.pop(item) l.append(item) l.sort() for i in l: if n > 0: print(str(i) + " " + str(m)) n -= 1 # Ex 8 - Ordered if __name__ == '__main__': from collections import OrderedDict # Create new store Manager storeManager = OrderedDict() #get the number of items for dataentry nItems = int(input()) for x in range(nItems): # separate the input in 3-tuple # skipping the space item, space, quantity = input().rpartition(' ') #get the item and eventually update it storeManager[item] = storeManager.get(item, 0) + int(quantity) # print item and quantity for each item for item, quantity in storeManager.items(): print(item, quantity) ### Date and Time ## Ex 1 - Calendar import calendar m, d, y = map(int, input().split()) i = calendar.weekday(y, m, d) l = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"] print(l[i]) ## Ex 2 - Time delta #!/bin/python3 import math import os import random import re import sys from datetime import datetime, timezone # Complete the time_delta function below. def time_delta(t1, t2): tmp = t1.split() t1_dt = datetime.strptime(' '.join(tmp[1:]), '%d %b %Y %H:%M:%S %z') t1_dt_utc = t1_dt.astimezone(tz = timezone.utc) tmp = t2.split() t2_dt = datetime.strptime(' '.join(tmp[1:]), '%d %b %Y %H:%M:%S %z') t2_dt_utc = t2_dt.astimezone(tz = timezone.utc) return str(abs((t1_dt_utc - t2_dt_utc).days * 24 * 3600 + (t1_dt_utc - t2_dt_utc).seconds)) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): t1 = input() t2 = input() delta = time_delta(t1, t2) fptr.write(delta + '\n') fptr.close() ### Exceptions ## Ex 1 - Exceptions if __name__ == "__main__": n = int(input()) for _ in range(n): try: a, b = map(int, input().split()) print(a//b) except Exception as e: print("Error Code:", e) ### Built-ins ## Ex 1 - Athlete #!/bin/python3 import math import os import random import re import sys def sort_players(n,m,arr,k): arr.sort(key = lambda x: x[k]) def print_arr(arr,m): for l in arr: s = "" for i in range(m): s += str(l[i]) + " " print(s) if __name__ == '__main__': nm = input().split() n = int(nm[0]) m = int(nm[1]) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) k = int(input()) sort_players(n,m,arr,k) print_arr(arr,m) ## Ex 2 - Zipped L = [] N, M = map(int, input().split()) for i in range(M): L.append(list(map(float, input().split()))) for i in zip(*L) : print(sum(i)/len(i)) ## Ex 3 - ginorts s = input() lc = [] uc = [] od = [] ed = [] for i in range(len(s)): if s[i].isdigit(): if int(s[i])% 2 == 0: ed.append(s[i]) else: od.append(s[i]) elif s[i].islower(): lc.append(s[i]) elif s[i].isupper(): uc.append(s[i]) out = "" lc.sort() uc.sort() od.sort() ed.sort() for item in lc: out += item for item in uc: out += item for item in od: out += item for item in ed: out += item print(out) ### Python Functionals ## Ex 1 - Map and Lambda cube = lambda x: (x**3) # complete the lambda function def fibonacci(n): # return a list of fibonacci numbers arr = [] for i in range(0,n): if(i==0): arr.append(0) if(i==1 or i==2): arr.append(1) elif(i>2): arr.append(arr[i-1] + arr[i-2]) return arr if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n)))) ### Regex and Parsing challenges ## Ex 1 - Floating Point number import re T = int(input()) for i in range(T) : N = input() print (bool(re.match('^[-+]?[0-9]*\.[0-9]+$' , N))) # ? means zero or one * means zero or more +means one or more ## Ex 2 - Regex.split() regex_pattern = r"\W" # Do not delete 'r'. import re print("\n".join(re.split(regex_pattern, input()))) ## Ex 3 - Group(), Groups() & Groupdict() import re m = re.findall(r"([A-Za-z0-9])\1+",input()) #\1 refers to first match group if bool(m) : print(m[0]) else: print(-1) ## Ex 4 - Re.findall() & Re.finditer() import re r = r"(?<=[^aeiouAEIOU])([aeiouAEIOU]{2,})([^aeiouAEIOU])" l = re.findall(r, input()) if(len(l)>0): [print(c[0]) for c in l] else: print(-1) ## Ex 5 - Re.start() & Re.end() import re s = input() k = input() match_objects = re.finditer(r''+ k[0] + '(?='+ k[1:] +')',s) lst = list(map(lambda x: x.start(),match_objects)) if lst == []: print((-1, -1)) else: for item in lst: print((item, item + len(k) -1)) ## Ex 6 - Substitution import re n = int(input()) for _ in range(n): s = input() s = re.sub(r"(?<=\s)\|\|(?=\s)", "or" , s) s = re.sub(r"(?<=\s)&&(?=\s)", "and" , s) print(s) ## Ex 7 - Validating Roman Numbers import re regex_pattern = r"^(I(?=X))?(X(?=C))?(C(?=M))?M{0,3}(I(?=X))?(X(?=C))?(C(?=M))?((?<=C|X|I)M)?(I(?=X))?(X(?=C))?(C(?=D))?D?(I(?=X))?(X(?=C))?C{0,3}(I(?=X))?(X(?=L))?L?(I(?=X))?X{0,3}(I(?=V))?V?I{0,3}$" print(str(bool(re.match(regex_pattern, input())))) ## Ex 8 - Validating phone numbers import re for _ in range(int(input())): m = re.match("^[789]\d{9}$", input()) if bool(m) == True: print("YES") else: print("NO") ## Ex 9 - Validating and Parsing Email Addresses import email.utils as email import re n = int(input()) for _ in range(n): m = email.parseaddr(input()) regex = r"^[a-zA-Z][\w.-]+@[a-z]+\.[a-z]{1,3}$" res = re.search(regex, m[1]) if res: print(email.formataddr((m[0], m[1]))) ## Ex 10 - Hex Color Code import re r = r"#[0-9A-Fa-f]{3,6}\W" n = int(input()) ls = [] for _ in range(n): line = input() if((len(line.split())<=1) or ('{' in line.split())): continue l = re.findall(r, line) [ls.append(s[:len(s)-1]) for s in l] [print(s) for s in ls] ## Ex 11 - Html parser part 1 from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Start :", tag) for (name, value) in attrs: print("->", name, ">", value) def handle_endtag(self, tag): print("End :", tag) def handle_startendtag(self, tag, attrs): print("Empty :", tag) for (name, value) in attrs: print("->", name, ">", value) if __name__ == "__main__": parser = MyHTMLParser() n = int(input()) for _ in range(n): line = input() parser.feed(line) ## Ex 12 - Html parser part 2 from html.parser import HTMLParser class MySecondHTMLParser(HTMLParser): def handle_comment(self, data): if(len(data.split("\n"))>1): print(">>> Multi-line Comment") else: print(">>> Single-line Comment") print(data) def handle_data(self, data): if(data.strip()): print(">>> Data") print(data) html = "" for i in range(int(input())): html += input().rstrip() html += '\n' parser = MySecondHTMLParser() parser.feed(html) parser.close() ## Ex 13 - Detect HTML Tags, Attributes and Attribute Values from html.parser import HTMLParser class MyHTMLDetector(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for (name, value) in attrs: print("->", name, ">", value) html = "" for i in range(int(input())): html += input().rstrip() html += '\n' parser = MyHTMLDetector() parser.feed(html) parser.close() ## Ex 14 - Validating UID import re for _ in range(int(input())): s = input() v = True if re.match(r"^[a-zA-Z0-9]{10}$", s) == None: sur = False m = re.findall(r"([\w*]).*\1", s) if m != []: v = False m = re.findall(r"[A-Z]", s) if len(m) < 2: v = False m = re.findall(r"[0-9]", s) if len(m) < 3: v = False print("Valid") if v == True else print("Invalid") ## Ex 15 - Validating Credit Card Numbers import re for _ in range(int(input())): c = input() print ("Valid") if re.match(r"^[456]\d{3}-?\d{4}-?\d{4}-?\d{4}$", c) and re.findall(r"(\d)-?\1-?\1-?\1", c) == [] else print ("Invalid") ## Ex 16 - Validating Postal Codes regex_integer_in_range = r"^[1-9][0-9]{5}$" regex_alternating_repetitive_digit_pair = r"(\d)(?=.\1)" import re P = input() print (bool(re.match(regex_integer_in_range, P)) and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2) ## Ex 17 - Matrix Script #!/bin/python3 #!/bin/python3 import math import os import random import re import sys reading = input().rstrip().split() n = int(reading[0]) m = int(reading[1]) mtx = [] for _ in range(n): read = input() mtx.append(read) columns = zip(*mtx) l = [] for col in columns: l += list(col) s = ''.join(l) print(re.sub(r"(?<=[a-zA-Z0-9])([!@#$%&]|\s)+(?=[a-zA-Z0-9])", " ", s)) ### XML ## Ex 1 - Find the Score import sys import xml.etree.ElementTree as etree def get_attr_number(node): start = 0 start += len(node.attrib) for child in node: start += get_attr_number(child) return start if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() tree = etree.ElementTree(etree.fromstring(xml)) root = tree.getroot() print(get_attr_number(root)) ## Ex 2 - Find the Maximum Depth import xml.etree.ElementTree as etree maxdepth = 0 def depth(elem, level): global maxdepth level += 1 for child in elem: depth(child, level) if level > maxdepth: maxdepth = level if __name__ == '__main__': n = int(input()) xml = "" for i in range(n): xml = xml + input() + "\n" tree = etree.ElementTree(etree.fromstring(xml)) depth(tree.getroot(), -1) print(maxdepth) ### Closures and Decorations ## Ex 1 - Standardize Mobile Number Using Decorators def wrapper(f): def fun(l): f('+91 {} {}'.format(n[-10:-5], n[-5:]) for n in l) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l = [input() for _ in range(int(input()))] sort_phone(l) ## Ex 2 - Name Directory import operator def person_lister(f): def inner(people): for i in range(len(people)): people[i][2] = int(people[i][2]) people.sort(key=lambda x: x[2]) for i in range(len(people)): people[i] = f(people[i]) return(iter(people)) return inner @person_lister def name_format(person): return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1] if __name__ == '__main__': people = [input().split() for i in range(int(input()))] print(*name_format(people), sep='\n') ### Numpy ## Ex 1 - Arrays import numpy def arrays(arr): a = numpy.array(arr,float) return numpy.flip(a) arr = input().strip().split(' ') result = arrays(arr) print(result) ## Ex 2 - Shape and Reshape arr = numpy.array(list(map(int, input().split()))) print(numpy.reshape(arr, (3, 3))) ## Ex 3 - Transpose and Flatten import numpy n, m = map(int, input().split()) my_list = [] for _ in range(n): my_list.append(list(map(int, input().split()))) arr = numpy.array(my_list) print(numpy.transpose(arr)) print(arr.flatten()) ## Ex 4 - Concatenate import numpy n, m, p = map(int, input().split()) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) a = numpy.array(lst) lst = [] for _ in range(m): lst.append(list(map(int, input().split()))) b = numpy.array(lst) print(numpy.concatenate((a, b), axis = 0)) ## Ex 5 - Zeros and Ones import numpy axis = tuple(map(int, input().split())) print(numpy.zeros(axis, dtype = numpy.int)) print(numpy.ones(axis, dtype = numpy.int)) ## Ex 6 - Eye and Identity import numpy n, m = map(int, input().split()) a = numpy.eye(n, m) #forced to accept! print(str(a).replace('1',' 1').replace('0',' 0')) ## Ex 7 - Array Mathematics import numpy n, m = map(int, input().split()) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) a = numpy.array(lst) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) b = numpy.array(lst) print(a+b) print(a-b) print(a*b) print(a//b) print(a%b) print(a**b) ## Ex 8 - Floor, Ceil and Rint import numpy # for hackerrank! numpy.set_printoptions(sign=' ') a = numpy.array(list(map(float, input().split()))) print(numpy.floor(a)) print(numpy.ceil(a)) print(numpy.rint(a)) ## Ex 9 - Sum and prod import numpy n, m = map(int, input().split()) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) arr = numpy.array(lst) print(numpy.prod(numpy.sum(arr, axis = 0))) ## Ex 10 - Min and Max import numpy n, m = map(int, input().split()) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) arr = numpy.array(lst) print(numpy.max(numpy.min(arr, axis = 1))) ## Ex 11 - Mean, var, std import numpy numpy.set_printoptions(legacy='1.13') #Same here n, m = map(int, input().split()) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) arr = numpy.array(lst) print(numpy.mean(arr, axis = 1)) print(numpy.var(arr, axis = 0)) print(numpy.std(arr)) ## Ex 12 - Dot and cross import numpy n = int(input()) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) a = numpy.array(lst) lst = [] for _ in range(n): lst.append(list(map(int, input().split()))) b = numpy.array(lst) print(numpy.dot(a, b)) ## Ex 13 - Inner and Oute import numpy a = numpy.array(list(map(int, input().split()))) b = numpy.array(list(map(int, input().split()))) print(numpy.inner(a, b)) print(numpy.outer(a, b)) ## Ex 14 -Polynomials import numpy coe = list(map(float, input().split())) print(numpy.polyval(coe, int(input()))) ## Ex 15 - Linear Algebra import numpy n = int(input()) lst = [] for _ in range(n): lst.append(list(map(float, input().split()))) arr = numpy.array(lst) print(round(numpy.linalg.det(arr), 2)) # § Problem 2 # ## Ex 1 - Birthday Cake #!/bin/python3 import math import os import random import re import sys def birthdayCakeCandles(ar): return ar.count(max(ar)) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ar_count = int(input()) ar = list(map(int, input().rstrip().split())) result = birthdayCakeCandles(ar) fptr.write(str(result) + '\n') fptr.close() ## Ex 2 - Kangaroo #!/bin/python3 import math import os import random import re import sys def kangaroo(x1, v1, x2, v2): # I just applied the constraints return 'YES' if (v1 > v2) and (x2 - x1) % (v2 - v1) == 0 else 'NO' if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') x1V1X2V2 = input().split() x1 = int(x1V1X2V2[0]) v1 = int(x1V1X2V2[1]) x2 = int(x1V1X2V2[2]) v2 = int(x1V1X2V2[3]) result = kangaroo(x1, v1, x2, v2) fptr.write(result + '\n') fptr.close() ## Ex 3 - Viral Adv #!/bin/python3 import math import os import random import re import sys # Complete the viralAdvertising function below. def viralAdvertising(n): likes = 2 total_likes = 2 if n == 1: return total_likes else: for i in range(2,n+1): # each day we have: likes = likes * 3 // 2 total_likes += likes return total_likes if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = viralAdvertising(n) fptr.write(str(result) + '\n') fptr.close() ## Ex 4 - Recursive Digit Sum # Complete the superDigit function below. def superDigit(n, k): digits = map(int, list(n)) return aux_superDigit(str(sum(digits) * k)) # aux function def aux_superDigit(p): if len(p) == 1: return int(p) else: digits = map(int, list(p)) return aux_superDigit(str(sum(digits))) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = input().split() n = nk[0] k = int(nk[1]) result = superDigit(n, k) fptr.write(str(result) + '\n') fptr.close() ## Ex 5 - Insertion Sort 1 ## Ex 6 - Insertion Sort 2
718f61d1c0b4f795438ad546414ee409d7a19bfb
cu-swe4s-fall-2019/version-control-jfgugel
/math_lib.py
146
3.703125
4
def div(a, b): if b==0: print ("Can't divide by 0") return 1 else: return a/b def add(a, b): return a+b
b471484f1199797dcf440c3181e6bee462ce23a1
thinkSharp/Interviews
/Calculater.py
3,351
4.09375
4
def calculator(expression): def calc(op, v1, v2): if op == '+': return v1 + v2 elif op == '-': return v1 - v2 elif op == '*': return v1 * v2 elif op == '/': return v1 / v2 return 0 def getValue(j): temp = '' while j < len_exp: temp += expression[j] j += 1 if j < len_exp: if expression[j] in operators: break return float(temp), j len_exp = len(expression) if len_exp == 0: return 0 if len_exp == 1: return expression[0] operators = ['+', '-', '*', '/'] next_val = 0 result, i = getValue(0) current_op = '' while i < len_exp: if expression[i] in operators: if current_op == '': current_op = expression[i] i += 1 continue else: next_op = expression[i] if next_op == '+' or next_op == '-': before = result result = calc(current_op, result, next_val) print("1. result: {0}, op: {1}, {2} {3}".format(result, current_op, before, next_val)) current_op = next_op i += 1 else: if i + 1 < len_exp: temp_val, i = getValue(i + 1) before = next_val next_val = calc(next_op, next_val, temp_val) print("2. result: {0}, op: {1}, {2} {3}".format(next_val, next_op, before, temp_val)) else: return 0 else: next_val, i = getValue(i) before = result result = calc(current_op, result, next_val) print("3. result: {0}, op: {1}, {2} {3}".format(result, current_op, before, next_val)) return result def test_calculator(): result = calculator('2*3+5/6*3+15') print(result) assert(result == 23.5) result = calculator('15+143') print(result) assert(result == 158) result = calculator('15/3+4*5') print(result) assert(result == 25) #test_calculator() def divide(dividend, divisor): max_div_num = pow(2,30) negative = 2 if dividend < 0: negative -= 1 dividend = -dividend if divisor < 0: negative -= 1 divisor = -divisor if divisor == 1: return -dividend if negative == 1 else dividend doubles = [] power = [] divide_count = 1 while divisor <= dividend: doubles.append(divisor) power.append(divide_count) if divisor > max_div_num: break divisor += divisor divide_count += divide_count quotient = 0 for i in range(len(doubles)-1, -1, -1): divisor = doubles[i] power_of_two = power[i] if divisor <= dividend: dividend -= divisor quotient += power_of_two return -quotient if negative == 1 else quotient def test_divide(): result = divide(100, 3) print(result) result = divide(1, 3) print(result) result = divide(-1000000000000, 3) print(result) result = divide(-100, -3) print(result) result = divide(10, -3) print(result) test_divide()
2dddbecbd937e254fc52c1fddc5e01eefac62344
h2hyun37/algostudy
/study-algorithm/src/nedaair/study/sort/bubbleSort1.py
542
3.796875
4
__author__ = 'nedaair' unsortList = [3, 31, 48, 73, 8, 11, 20, 29, 65, 15] def bubbleSort() : index = 1 while 1 : indexf = 0 for j in unsortList : if j > unsortList[indexf+1] : temp = unsortList[indexf+1] unsortList[indexf+1] = j unsortList[indexf] = temp indexf = indexf + 1 if indexf == len(unsortList)-index : break index = index + 1 if index == 10 : break bubbleSort() print unsortList
0ff62a729adbdbf680a862b7b50cd80f3cc814b9
Sakibapon/BRAC
/CSE/CSE 422/CSE422 AI LAB/Lab01/lab01task07.py
267
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun May 26 20:37:09 2019 @author: Musavvir """ import math c = int (input ("Please enter the year you were born in: ")) d = math.sqrt(1+4*c) x1= (d + 1)/2 print( "\nI will be ", int(x1), "years old in the year ", int(x1*x1))
68353cc2c1436b758bd852f8a00fa3f096bbad01
arthurffd/proj22_indice_reverso
/scripts/idx_reducer.py
792
3.5
4
#! /usr/bin/python3 # Python 3 Reducer script, for MapReduce jobs called by Hadoop Streaming jar # REVERSED (Inverted) Index # Expected Output: <word_id> /t <[doc_id] # Example: 1 [7, 22, 30] , 2 [31], 3 [1, 3, 4, 10, 23] from sys import stdin import re import os index = {} reverse = {} for line in stdin: word, postings = line.split('\t') index.setdefault(word, {}) for posting in postings.split(','): doc_id, count = posting.split(':') count = int(count) index[word].setdefault(doc_id, 0) index[word][doc_id] += count i = 0 for word in sorted(index): reverse[i] = ['%s' % (doc_id) for doc_id in index[word]] print('{}\t{}'.format(i, reverse[i])) i += 1
bdd549a566b450752355c5c8fa22b8b15301bcf7
alishahwee/houses
/roster.py
947
3.84375
4
from sys import argv, exit from cs50 import SQL # Check for correct usage if len(argv) == 1: print('roster.py missing command-line argument\nUsage: python roster.py example-house') exit(1) elif len(argv) > 2: print('roster.py only accepts one command-line argument\nUsage: python roster.py example-house') exit(2) # Assign house argument to a variable house = argv[1].capitalize() # Connect to the database db = SQL('sqlite:///students.db') # Return a list of students in the specified house from the roster results = db.execute('SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first', house) # Iterate through the results and print each row in a format for row in results: # Check for middle names if row['middle']: print(f"{row['first']} {row['middle']} {row['last']}, born {row['birth']}") else: print(f"{row['first']} {row['last']}, born {row['birth']}") exit(0)
44312385bfaaa836a04cf92ba5282546558fcaa1
tarunlnmiit/blackhatpython
/test1.py
215
3.90625
4
def sum(num1, num2): num1int = convert_integer(num1) num2int = convert_integer(num2) res = num1int + num2int return res def convert_integer(num): return int(num) ans = sum('1', '2')