blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
376e6a065a1f94c7aad27775d2af2a80ad51e4da
MissBolin/CSE-Period3
/procedures and functions.py
1,844
4.4375
4
# Procedures are abstractions. We can create a blueprint of steps # for common actions that we can reference and use as often # as we wish. # Step 1: Create the blueprint / define the procedure def speak(): print("Hello user!") print("From your PC") # Step 2: Use the blueprint / call the procedure speak() speak() speak() speak() speak() speak() speak() def check_if_even(number): if number % 2 == 0: print("{} is even".format(number)) else: print("{} is NOT even".format(number)) check_if_even(12) check_if_even(3) def multiply_together(num1, num2): answer = num1 * num2 print("{} x {} = {}".format(num1, num2, answer)) multiply_together(5, 9) multiply_together(1, 1) multiply_together(-3, 7) multiply_together(.5, 16) def add_together(num1, num2, num3): total = num1 + num2 + num3 print("{} + {} + {} = {}".format(num1, num2, num3, total)) add_together(2, 7, 4) add_together(8, 6, 13) add_together("a", "b", "c") # Procedures are self-contained. They do not change the rest of the # code AT ALL. # Functions return data to the rest of the code. def subtract(num1, num2): difference = num1 - num2 return difference answer = subtract(2, 4) print(answer) my_other_answer = subtract(answer, 9) print(my_other_answer) my_final_answer = subtract(my_other_answer, 21) print(my_final_answer) def give_me_five(number): result = number + 5 return result cash = give_me_five(0) print(cash) cash = give_me_five(cash) print(cash) cash = give_me_five(cash) print(cash) # print() is a procedure # input() is a function def find_volume_prism(length, width, height): volume = length * width * height if volume >= 0: return volume else: return 0 print("No code is run after a return statement") print(find_volume_prism(1, 1, 1))
d173d15d9f9783b689b447187a3b88cec904e437
muondu/python-practise
/For loops/fruits_shop.py
446
3.9375
4
fruits = { "Apple" : 30, "Banana" : 10, "Pineaple" : 70 } print(fruits) input1 = input("How many times do you want to print it: ") integer = int(input1) constructor = list() for b in range(integer): input2 = fruits[input("Enter what you want: ")] print("The price of the fruit is " + str(input2)) constructor.append(input2) total = sum(constructor) print("Your total is " + str(total))
73b776ef58006f5fe7d266b21a7db248a615ad6d
Yuya-Furusawa/Self-Study
/choice.py
237
3.578125
4
import numpy as np def sampling(coin, n): """ coin : array-like Amount coin n : scalar(int) The number of lucky guys """ coin = np.asarray(coin) m = len(coin) prob = coin / sum(coin) return np.random.choice(m, n, p=prob)
fceb07c22ff3f423d86a57a957b18681c4bd3fd3
BenjiKCF/Codewars
/day9.py
347
3.75
4
def remove_smallest(numbers): l = [(index, value) for index, value in enumerate(numbers)] n = sorted(numbers) for i in range(len(numbers)): if n[0] == l[i][1]: numbers.pop(i) break return numbers def remove_smallest(numbers): if numbers: numbers.remove(min(numbers)) return numbers
826a613564bbd9d36a9d2ad5b03ebf9d8f6633e3
MudretsovaSV/Python
/Циклич.ПросмотрСписка.py
70
3.53125
4
letters=["a","b","c","d","e"] for letter in letters: print letter
9c9c012afdc73ff9cb58836b46544e18f747b84a
mdmmsrhs/Learning_Python
/point.py
1,091
4.25
4
#!/bin/Python """define a class called Point and initialise it""" class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def printPoint(p): print'(' + str(p.x) + ',' + str(p.y) + ')' def samePoint(p1,p2): return (p1.x == p2.x) and (p1.y == p2.y) def distanceSquared(p): return (p.x * p.x) + (p.y * p.y) """Instantiate a Point""" blank = Point() print(blank.x,blank.y) #distanceSquared = (blank.x * blank.x) + (blank.y * blank.y) print(distanceSquared(blank)) blank.x = 8 blank.y = 9 print(blank.x,blank.y) print(distanceSquared(blank)) printPoint(blank) p1 = Point() p1.x = 3.0 p1.y = 4.0 p2 = Point() p2.x = 3.0 p2.y = 4.0 print(samePoint(p1,p2)) ###################################### class Rectangle(): pass def findCentre(r): p = Point() p.x = r.corner.x = r.width/2 p.y = r.corner.y = r.height/2 return p box = Rectangle() box.width = 100.0 box.height = 200.0 box.corner = Point() box.corner.x = 0.0 box.corner.y = 0.0 centre = findCentre(box) print("The centre of the rectagle is: \n") printPoint(centre) #end
552fc7c286d46bf908d61eaa3dfa12cd5308ac67
greenloper/Graph
/10-3 Kruskal.py
688
3.8125
4
def find_parent(parent, x): if parent[x]!=x: parent[x]=find_parent(parent, parent[x]) return parent[x] def union_parent(parent, a, b): a=find_parent(parent, a) b=find_parent(parent, b) if a<b: parent[b]=a else: parent[a]=b v, e=map(int, input().split()) parent=[0]*(v+1) edges=[] result=0 for i in range(1, v+1): parent[i]=i for _ in range(e): a, b, cost=map(int, input().split()) edges.append((cost, a, b)) edges.sort() for edge in edges: cost, a, b=edge if find_parent(parent, a)!=find_parent(parent, b): union_parent(parent, a, b) result+=cost print(result)
e8826c4345b73bc95b964f932460a9f1eaadd282
georgeribeiro/dojouva
/convertion/convertion.py
384
3.828125
4
def convert(numero, sistema1, sistema2): if sistema1 == "numerico": sobra = int(numero) % 5 inteiro = int(numero) / 5 return "/" * sobra + "\\" * inteiro else: i = 0 for barra in numero: if barra == "/": i += 1 else: i += 5 return str(i)
90e4f5e2d35076b1f772053cb6d74061783dd43e
nhl4000/project-euler
/python2/11-20/015.py
263
3.875
4
def factorial(n): sum = 1 for i in xrange(1,n+1): sum *= i return sum def binomial_coefficient(n, k): num = factorial(n) dem = factorial(k) * factorial(n-k) return num / dem n = 20 k = 20 print (binomial_coefficient(n+k,k))
0b3904de4bf06c5e252bc075b2a54b17de918479
sarik/Algo_DS
/powerSet.py
1,104
3.640625
4
def convertArrToString(arr): st="" for i in arr: st = st + str(i) return st def powerSet(arr): setall =set() print(setall) helper(setall,[],arr,0) return setall def helper(setall,prev,arr,index): if len(prev) == 3 or index >2: setall.add(convertArrToString(prev)) return including = prev + [arr[index]] excluding = prev setall.add(convertArrToString(including)) setall.add(convertArrToString(excluding)) helper(setall,including,arr,index+1) helper(setall,excluding,arr,index+1) def powerSet_Short_Org(arr): powerset=[[]] for ele in arr: for i in range(len(powerset)): currentSubset= powerset[i] powerset.append(currentSubset+[ele]) return powerset def powerSet_Short(arr): powerset=[[]] for ele in arr: for i in range(len(powerset)): powerset.append(powerset[i]+[ele]) return powerset print(powerSet_Short([1,2,3]))
ce2b89dd15e27074e7de5d6ce175c8896b441070
Sal2912/Python-Projects
/first_last_name_reverse.py
172
4.3125
4
first_name = input("Enter your First Name: ") last_name = input("Enter your Last Name: ") full_name = first_name + last_name print(f'Reversed name is: {full_name[: :-1]}')
f1ee2409839ae1af398d5223b984c6fa5efae98b
chakid/NLPexp
/exp2/exp2_1.py
454
4.125
4
#字符串输出 str1 = "这是一个变量"; print("变量str1的值是:"+str1); print("变量str1的地址是:%d" %(id(str1))); str2 = str1; print("变量str2的值是:"+str2); print("变量str2的地址是:%d" %(id(str2))); str1 = "这是另一个变量"; print("变量str1的值是:"+str1); print("变量str1的地址是:%d" %(id(str1))); print("变量str2的值是:"+str2); print("变量str2的地址是:%d" %(id(str2)));
4f23672de689428004a125bcd8eedbb2d60669fb
gerrycfchang/leetcode-python
/tree/construct_BST_from_pre_inorder.py
2,025
3.953125
4
# 105. Construct Binary Tree from Preorder and Inorder Traversal # # Given preorder and inorder traversal of a tree, construct the binary tree. # # Note: # You may assume that duplicates do not exist in the tree. # # For example, given # # preorder = [3,9,20,15,7] # inorder = [9,3,15,20,7] # Return the following binary tree: # # 3 # / \ # 9 20 # / \ # 15 7 # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None self.seqlist = [] def __str__(self): self.inorder(self) return ' '.join(str(x) for x in self.seqlist) def inorder(self, curr): if not curr: return self.inorder(curr.left) self.seqlist.append(curr.val) self.inorder(curr.right) class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if not preorder: return root = TreeNode(preorder[0]) rootIdx = inorder.index(preorder[0]) if rootIdx > 0: root.left = self.buildTree(preorder[1:rootIdx+1], inorder[0:rootIdx]) root.right = self.buildTree(preorder[rootIdx + 1:], inorder[rootIdx+1:]) return root if __name__ == '__main__': preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] sol = Solution() assert str(sol.buildTree(preorder, inorder)) == ' '.join(str(x) for x in inorder) preorder = [1,2] inorder = [1,2] sol = Solution() assert str(sol.buildTree(preorder, inorder)) == ' '.join(str(x) for x in inorder) preorder = [1,2] inorder = [2,1] sol = Solution() assert str(sol.buildTree(preorder, inorder)) == ' '.join(str(x) for x in inorder) preorder = [1,2,3] inorder = [3,2,1] sol = Solution() assert str(sol.buildTree(preorder, inorder)) == ' '.join(str(x) for x in inorder)
ccb38823f3781e6c058f59f0e0d90ec68f0ccad0
quantumsnowball/AppleDaily20200907
/sentiment.py
2,567
3.703125
4
from textblob import TextBlob def tweet_sentiment(text, verbose=False): """ The sentiment function of textblob returns two properties, polarity, and subjectivity. Polarity is float which lies in the range of [-1,1] where 1 means positive statement and -1 means a negative statement. Subjective sentences generally refer to personal opinion, emotion or judgment whereas objective refers to factual information. Subjectivity is also a float which lies in the range of [0,1]. """ # parse the tweet into textblob object blob = TextBlob(text) # we define the sentiment of sentence to be the product of its polarity and subjectivity # tweet sentiment is the sum of sentiment for all sentences in a tweet sentiment = sum(s.polarity * s.subjectivity for s in blob.sentences) # print if verbose if verbose: polarity = sum(s.polarity for s in blob.sentences) subjectivity = sum(s.subjectivity for s in blob.sentences) num_sentence = len(blob.sentences) return text, num_sentence, polarity, subjectivity, sentiment else: return sentiment def test(): sentences = [ '$AAPL so is this the price that gets split? If so, looks like it’ll be $125.50 a share on Monday. Nice.', 'Stocks head into September in high gear as Apple and Tesla split, and markets await the August jobs report', 'S&P 500 SETS FRESH RECORD CLOSING HIGH OF 3,508.01', 'Massive $tsla dump be careful out there short term oversold tho $spy $amzn', '$SPX is overbought but momentum is very very strong. My bet is unless we correct quickly this week, we are looking for a blow off top. ', '$SPY reached 350 2 points from our target of 352.. RSI is overbought - sell and wait ti buy for later. Short $SHOP and $NVAX.', 'Slight setback, nothing to worry about. Outlook dismal. 28 trade session left - Target $SPX 2394.25', 'Russell looks bad. Big bearish RSI divergence and ejected from the channel after riding up the bottom rail.', ] print(' | '.join(['',' #','Sentence'+' '*92,'# sentence','polarity','subjectivity','sentiment',''])) print('-'*162) for i,sentence in enumerate(sentences): text, num_sentence, polarity, subjectivity, sentiment = tweet_sentiment(sentence, verbose=True) print(f' | {i+1:2d} | {text[:100]: <100} | {num_sentence: >10} | {polarity:+8.2f} | {subjectivity:+12.2f} | {sentiment:+9.2f} |') if __name__ == '__main__': test()
7bd1bdcae31fce4687c48c2048ae36b40c288176
Nitroto/SoftUni_Python_Open_Course
/Lecture_1/Problem-4.py
294
4.3125
4
import turtle while True: angle = input("Enter an angle: ") length = input("Enter a length: ") direction = input("Enter direction left/right: ") if direction == 'left': turtle.left(int(angle)) else: turtle.right(int(angle)) turtle.forward(int(length))
6554ed99e35d54c348a2c6c7c52ba798298e62f4
sudershan1903/Cricket-Scorecard-using-MongoDB
/DB Insertion/cleaning.py
627
3.6875
4
def headings(string): diction = eval(string) keys = list(diction.keys()) string = "" for i in keys: string = string + str(i).capitalize() + '\t\t\t' return string def process(string): diction = eval(string) #keys = list(diction.keys()) values = list(diction.values()) string = "" for i in values: string = string + str(i) + '\t' return string string = "{'date': '2008-05-13', 'team1': 'Kolkata Knight Riders', 'team2': 'Delhi Daredevils', 'winner': 'Kolkata Knight Riders', 'venue': 'Eden Gardens'}" print(headings(string)) print(process(string))
6408ef20d0e8becb4f53e3934c24aadb5e3b10af
hjain5164/Linear-Search
/python-linear-search/python-linear-search.py
382
4.25
4
num_array = list() #Enter elements num = raw_input("Enter how many elements you want:") print 'Enter numbers in array: ' for i in range(int(num)): n = raw_input("num :") num_array.append(int(n)) element_to_find = raw_input("Element to find :") for i in num_array: #searching through the list if i==element_to_find: print ("Successful Search!") break
efd5b35c881d14427f89ee49f8fe4b0353f733ea
Nagalakshmi301994/Python-Essentials-Day-9-Assignment
/Day9 B7 Assignment.py
1,700
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # Write a python Function for finding is a given number prime or not and do Unit Testing on it using PyLint and Unittest Library. # In[2]: get_ipython().system(' pip install pylint') # In[3]: get_ipython().run_cell_magic('writefile', 'prime.py', "'''\nIt is a prime number\n'''\ndef isprime(num):\n '''\n It is\n '''\n if num in(0, 1):\n return False\n for prime in range(2, num-1):\n if num % prime == 0:\n return False\n return True") # In[4]: get_ipython().system(' pylint prime.py') # In[5]: import prime prime.isprime(199) # # USING UNIT TEST # In[6]: get_ipython().run_cell_magic('writefile', 'newprime.py', '\nimport unittest\nimport prime\n\nclass primenumber(unittest.TestCase):\n def testprime(self):\n Number = 32\n result = prime.isprime(Number)\n self.assertEquals(result, False)\n\n \n def testprimenum(self):\n Num = 199\n res = prime.isprime(Num)\n self.assertEquals(res, True)\n\n \n \nif __name__ == "__main__":\n unittest.main()') # In[7]: get_ipython().system(' python newprime.py') # # Make a small generator program for returning armstrong numbers in between 1-1000 in a generator object. # In[8]: lst = list(range(1,1000)) # In[9]: print(lst) # In[10]: def getArmstrongNumGen(lst): for num in lst: order=len(str(num)) temp=num sum=0 while temp >0: digit=temp%10 sum=sum+digit**order temp=temp//10 if sum==num: yield num # In[11]: print(list(getArmstrongNumGen(lst))) # In[ ]:
11ff925f1e812ce444af7666b2a61540902d85f7
sashakrasnov/datacamp
/27-visualizing-time-series-data-in-python/2-summary-statistics-and-diagnostics/07-density-plots.py
1,385
4.15625
4
''' Density plots In practice, histograms can be a substandard method for assessing the distribution of your data because they can be strongly affected by the number of bins that have been specified. Instead, kernel density plots represent a more effective way to view the distribution of your data. An example of how to generate a density plot of is shown below: | ax = df.plot(kind='density', linewidth=2) The standard .plot() method is specified with the kind argument set to 'density'. We also specified an additional parameter linewidth, which controls the width of the line to be plotted. ''' import pandas as pd import matplotlib.pyplot as plt co2_levels = pd.read_csv('../datasets/ch2_co2_levels.csv', index_col=0, parse_dates=True) co2_levels = co2_levels.fillna(method='bfill') ''' INSTRUCTIONS * Using the co2_levels DataFrame, produce a density plot of the CO2 level data with line width parameter of 4. * Annotate the x-axis labels of your boxplot with the string 'CO2'. * Annotate the y-axis labels of your boxplot with the string 'Density plot of CO2 levels in Maui Hawaii'. ''' # Display density plot of CO2 levels values ax = co2_levels.plot(kind='density', linewidth=4, fontsize=6) # Annotate x-axis labels ax.set_xlabel('CO2', fontsize=10) # Annotate y-axis labels ax.set_ylabel('Density plot of CO2 levels in Maui Hawaii', fontsize=10) plt.show()
08e9c46a6df3483f5aafae545761e8ea60af5443
Vasiliy1982/repo24122020
/praktika_urok5_2.py
254
4.03125
4
# практическое задание 2 число = int(input("Введите число:")) число_крат7 = число % 7 if число_крат7 > 0: print(число, "не кратно 7") print(число, "кратно 7")
b418f1704484b48d5b7dc9bcfefa3e6d3643b523
NagiLam/MIT-6.00.1x_2018
/Week 1/PS1_Problem2.py
506
3.96875
4
""" Probem Set 1 - Problem 2 Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2""" # s = 'azcbobobegghakl' count = 0 n = 0 m = 3 temp = 0 length = len(s) while (temp < length - 2): if (s[n:m] == 'bob'): count = count + 1 temp += 1 n += 1 m += 1 print("Number of times bob occurs is: " + str(count))
3b6fb8e9ab34b5d114f0a817de8eef59b8cbd9ce
dipanjan44/Python-Projects
/ProgramPractise/numberofwaystoclimb.py
676
4
4
def count_ways_recursive(n): if n < 0: return 0 if n==0: return 1 else : return count_ways_recursive(n-1) + count_ways_recursive(n-3) +count_ways_recursive(n-2) def no_of_ways(n): count = [0 for i in range(n + 1)] count[0] = 1 count[1] = 1 count[2] = 2 for i in range(3, n + 1): count[i] = count[i - 1] + count[i - 2] + count[i - 3] return count[n] def main(): steps = input("Enter the desired no of steps:" +"\n") print(" Recursive solution : " + str(count_ways_recursive(int(steps)))) print(" Iterative solution : " + str(no_of_ways(int(steps)))) if __name__ == "__main__": main()
a735458d0282ae51d62aed88b0cf0a7b0a61387c
kanyaandrea/Exercises
/Phyton_exercises/exercise_4.py
519
3.609375
4
import random import math a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]#list of number from 10 to 100 by 10 t = 0#t is zero now if a[0] % 20: t += a[0] print(t) if a[1] % 20: t += a[1] print(t) if a[2] % 20: t += a[2] print(t) if a[3] % 20: t += a[3] print(t) if a[4] % 20: t += a[4] if a[5] % 20: t += a[5] if a[6] % 20: t += a[6] if a[7] % 20: t += a[7] if a[8] % 20: t += a[8] if a[9] % 20: t += a[9] print("Summation of number divisible by 20 is: " + str(t))
944ba36690d9cb9dffa31ffb237486adf4f5b826
CiesliixW/Cwiczenia_Repo
/Simple__calculator.py
2,148
4.1875
4
def is_number(string): try: float(string) return float(string) except: return None def is_valid_operator(operator): if operator == "+" or "-" or "*" or "/": return True else: return False def ask_for_a_number(force_valid_input): while force_valid_input == True: try: user_input = float(input("Provide a number: ")) return user_input except: print("That didn't look like a number, try again!") if force_valid_input == False: try: user_input = float(input("Provide a number: ")) return user_input except: return None def ask_for_an_operator(force_valid_input): while force_valid_input == True: user_operator = input("Provide an operator: ") if user_operator == "+" or "-" or "/" or "*": return user_operator else: print("Invalid operator, try again!") if force_valid_input == False: user_operator = input("Provide an operator: ") if user_operator == "+" or "-" or "/" or "*": return user_operator else: return None def calc(operator, a, b): if not is_valid_operator(operator) or not is_number(a) or not is_number(b): return None result = None if operator == "+": result = a + b return result elif operator == "-": result == a - b return result elif operator == "/": if b == 0: print("Error, nie można dzielic przez 0") return None else: result = a / b return result elif operator == "*": result = a * b return result def simple_calculator(): while True: a = ask_for_a_number(force_valid_input=False) if not a: break op = ask_for_an_operator(force_valid_input=True) b = ask_for_a_number(force_valid_input = True) result = calc(op, a, b) print(result) if __name__ == '__main__': simple_calculator()
6874444881d5cff2ae430bb0874336f1a1f16347
sarn3792/Python_tutorial
/polimorfismo.py
660
3.59375
4
class Usuario: def __new__(cls): print("Este método es el primero que se ejecuta") return super().__new__(cls) def __init__(self): print("Este método es el segundo que se ejecuta") self.__password = "Es secreto" def __str__(self): #ToString() del objeto return "Esto se imprime cuando intento mostrar el objeto" def __getattr__(self, atributo): print("Aquí mostramos que no se encontró el atributo") def mostrar_password(self): print(self.__password) usuario = Usuario() usuario.__password = "No secreto" #Nuevo atributo, no es el mismo de la clase #print(usuario.__dict__) usuario.mostrar_password() print(usuario) usuario.apellido
d0bcf3fdfc6c0814207a188d1820247c7dc709bb
fidakhattak/PreciousServer
/grovepi/test.py
513
3.734375
4
import collections class test: def __init__(self): window_size = 10 self.averaging_window = collections.deque(maxlen = window_size) def test_queue(self): string = "Hello Pakistan, How is the weather today" l = list(string) i = 0 while i < len(l): print l[i] self.averaging_window.appendleft(l[i]) l2 = list(self.averaging_window) print l2 i += 1 element = test() element.test_queue()
844a7b99c689759e5bb9ef4db213f4c4d6f5a5fb
jachin/AdventOfCodeSolutions
/2017/01_day/sum-half-way-round.py
470
3.5
4
#! /usr/bin/env python3 import fileinput for line in fileinput.input(): line = line.strip() if len(line) < 1: continue last_index = len(line) half_length = int(last_index / 2) print(last_index, half_length) sum = 0 for i, n in enumerate(line): half_index = (i + half_length) % last_index print(i, n, half_index) half = line[half_index] if half == n: sum += int(n) print(sum)
0be27f96e57c8014f679a02c32362274bcdf777c
JohnRal/fogstream_courses
/Practice_1/task_2.py
858
3.828125
4
''' 2.Длина Московской кольцевой автомобильной дороги —109 километров. Стартуем с нулевого километра МКАД и едем со скоростью V километров в час. На какой отметке остановимся через T часов? Программа получает на вход значение V и T. Если V>0, то движемся в положительном направлении по МКАД, если же значение V<0, то в отрицательном. Программа должна вывести целое число от 0 до 108 — номер отметки, на которой остановимся. ''' print("Ввод V") V = int(input()) print("Ввод T") T = int(input()) km = (V*T) % 109 print(km)
a58b3f37fdd02f5dbe5ed04659be43ca91004d0a
borisnorm/codeChallenge
/practiceSet/g4g/DP/game.py
1,650
3.859375
4
#Optimal strategy for a game ''' Problem statement: Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first. ''' #Recursive relationship def game(array, hi, low): if low > hi: return 0 else: return max( #Take into account the 4 moves that could be made, you only get one selection game(array, hi - 1, low + 1) + array[hi], game(array, hi - 1, low + 1) + array[low], game(array, hi - 2, low) + array[hi], game(array, hi, low + 2) + array[low] ) #DP solution def game(array, hi, lo): #The memoization is here memo = [[0 for x in range(len(array) + 2)] for y in range(len(array) + 2)] for lo in range(1, len(array) + 1): for hi in range(1, len(array) + 1): #How do i factor in skipping here? - A decision at a certain left, right bound the value is that value + unlocked from the double, double lr, and split #The values that you get work memo[lo][hi] = max( #Is this right? my last point was 2 away or 1 away, from both sides must have plus or minus? memo[lo][hi+1] + array[hi], memo[lo][hi+2] + array[hi], memo[lo-1][hi] + array[lo], memo[lo-2][hi] + array[lo], ) max_value = 0 for i in range(len(memo)): for j in range(len(memo[0]): if memo[i][j] > max_value: max_value = memo[i][j] return max_value
4919f1c66d34e2a89882ea25b28402044d65fea2
Aasthaengg/IBMdataset
/Python_codes/p02406/s004425808.py
256
3.828125
4
def inc3(i): if i - (i // 10)*10 == 3: return(True) elif i//10==0: return(False) else: return(inc3(i//10)) n = int(input()) for i in range(1,n+1): if i%3==0 or inc3(i): print(" " + str(i),end="") print()
591a90923a91076e2e07d64531c56baf881e9143
larrywhy/learning
/Python/verify_num.py
162
3.8125
4
user_input = input("enter number:") print(user_input) try: isNum = int(user_input) print("yes, is number") except ValueError: print("No, is string.")
a5d0d812f48114e2150c223d482ede9208fa6efc
huisonice668/is218_project_02
/Statistics/Mode.py
753
3.5
4
def mode(data): temp_list = [] count = [] if len(data) == 0: raise ValueError('Can not be an empty list') # remove duplicate then store the elements into temp_list for num in data: if num not in temp_list: temp_list.append(num) # count the appearance of elements in data for num in temp_list: counter = data.count(num) count.append(counter) # find the max count which is the mode max = count[0] max_index = 0 for i in range(len(count)): if count[i] > max: max = count[i] max_index = i # throw exception if there is no mode aka max = 1 if max == 1: raise StatisticsError('No Mode') return temp_list[max_index]
b6703b3fb1b8f8e2830318635c3e82ad6b8dce23
alexander-travov/algo
/InterviewBit/LinkedLists/KReverse.py
1,289
3.890625
4
# -*- coding: utf8 -*- """ K reverse linked list ===================== Given a singly linked list and an integer K, reverses the nodes of the list K at a time and returns modified linked list. NOTE : The length of the list is divisible by K Example : Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2, You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5 Try to solve the problem using constant extra space. """ from __future__ import print_function from linked_list import Node def kreverse(l, k): heads = [None] * k tails = [None] * k node = l i = 0 while node: if heads[i] is None: heads[i] = node if tails[i] is not None: tails[i].next = node tails[i] = node node = node.next tails[i].next = None i = (i+1) % k out_head = out_tail = None i = k-1 while any(h is not None for h in heads): if heads[i] is not None: if out_head is None: out_head = heads[i] if out_tail is not None: out_tail.next = heads[i] out_tail = heads[i] heads[i] = heads[i].next out_tail.next = None i = (i-1) % k return out_head l = Node.from_iterable(range(10)) print(kreverse(l, 3))
586ec39746d54ea0f15f9da172742902f9c9d24c
brewersey/dsp
/python/q6_strings.py
6,059
4.3125
4
# Based on materials copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 def donuts(count): """ Given an int count of a number of donuts, return a string of the form 'Number of donuts: <count>', where <count> is the number passed in. However, if the count is 10 or more, then use the word 'many' instead of the actual count. >>> donuts(4) 'Number of donuts: 4' >>> donuts(9) 'Number of donuts: 9' >>> donuts(10) 'Number of donuts: many' >>> donuts(99) 'Number of donuts: many' """ if count < 10: return 'Number of donuts: {0:d}'.format(count) else: return 'Number of donuts: many' number = 5 breakfast = donuts(number) print(breakfast) def both_ends(s): """ Given a string s, return a string made of the first 2 and the last 2 chars of the original string, so 'spring' yields 'spng'. However, if the string length is less than 2, return instead the empty string. >>> both_ends('spring') 'spng' >>> both_ends('Hello') 'Helo' >>> both_ends('a') '' >>> both_ends('xyz') 'xyyz' """ list_s = [l for l in s] if len(list_s) > 2: new_string = list_s[0] + list_s[1] + list_s[-2] + list_s[-1] new_string = ''.join(new_string) else: new_string = '' return new_string word = 'spring' new_word = both_ends(word) print(new_word) def fix_start(s): """ Given a string s, return a string where all occurences of its first char have been changed to '*', except do not change the first char itself. e.g. 'babble' yields 'ba**le' Assume that the string is length 1 or more. >>> fix_start('babble') 'ba**le' >>> fix_start('aardvark') 'a*rdv*rk' >>> fix_start('google') 'goo*le' >>> fix_start('donut') 'donut' """ list_s = [l for l in s] count = 1 while count < len(list_s): if list_s[count] == list_s[0]: list_s[count] = '*' count += 1 new_string = ''.join(list_s) return new_string fs = 'donut' new_fs = fix_start(fs) print(new_fs) def mix_up(a, b): """ Given strings a and b, return a single string with a and b separated by a space '<a> <b>', except swap the first 2 chars of each string. Assume a and b are length 2 or more. >>> mix_up('mix', 'pod') 'pox mid' >>> mix_up('dog', 'dinner') 'dig donner' >>> mix_up('gnash', 'sport') 'spash gnort' >>> mix_up('pezzy', 'firm') 'fizzy perm' """ a_string = [l for l in a] b_string = [l for l in b] z = a_string[0] y = a_string[1] x = b_string[0] w = b_string[1] a_string[0] = x a_string[1] = w b_string[0] = z b_string[1] = y a = ''.join(a_string) b = ''.join(b_string) new_string = ' '.join([a, b]) return new_string first = 'mix' second = 'pod' new_string = mix_up(first, second) print(new_string) def verbing(s): """ Given a string, if its length is at least 3, add 'ing' to its end. Unless it already ends in 'ing', in which case add 'ly' instead. If the string length is less than 3, leave it unchanged. Return the resulting string. >>> verbing('hail') 'hailing' >>> verbing('swiming') 'swimingly' >>> verbing('do') 'do' """ list_s = [l for l in s] if len(list_s) >= 3: test1 = list_s[-3:] test1 = ''.join(test1) if test1 == 'ing': list_s.append('ly') else: list_s.append('ing') new_string = ''.join(list_s) return new_string else: return s verb = 'swiming' new_string = verbing(verb) print(new_string) def not_bad(s): """ Given a string, find the first appearance of the substring 'not' and 'bad'. If the 'bad' follows the 'not', replace the whole 'not'...'bad' substring with 'good'. Return the resulting string. So 'This dinner is not that bad!' yields: 'This dinner is good!' >>> not_bad('This movie is not so bad') 'This movie is good' >>> not_bad('This dinner is not that bad!') 'This dinner is good!' >>> not_bad('This tea is not hot') 'This tea is not hot' >>> not_bad("It's bad yet not") "It's bad yet not" """ list_s = s.split() knots = [k for k in enumerate(list_s) if k[1] == 'not'] bads = [b for b in enumerate(list_s) if b[1] == 'bad'] if len(bads) == 0: return s elif bads[0][0] > knots[0][0]: stop = knots[0][0] new_string = list_s[:stop] new_string.append('good') new_string = ' '.join(new_string) return new_string else: return s phrase = 'This bad tea is not hot' new_phrase = not_bad(phrase) print(new_phrase) def front_back(a, b): """ Consider dividing a string into two halves. If the length is even, the front and back halves are the same length. If the length is odd, we'll say that the extra char goes in the front half. e.g. 'abcde', the front half is 'abc', the back half 'de'. Given 2 strings, a and b, return a string of the form a-front + b-front + a-back + b-back >>> front_back('abcd', 'xy') 'abxcdy' >>> front_back('abcde', 'xyz') 'abcxydez' >>> front_back('Kitten', 'Donut') 'KitDontenut' """ list_a = [l for l in a] list_b = [l for l in b] afront = len(list_a)//2 + len(list_a)%2 aback = -(len(list_a) - afront) bfront = len(list_b)//2 + len(list_b)%2 bback = -(len(list_b) - bfront) section_1 = list_a[:afront] section_1 = ''.join(section_1) section_2 = list_b[:bfront] section_2 = ''.join(section_2) section_3 = list_a[aback:] section_3 = ''.join(section_3) section_4 = list_b[bback:] section_4 = ''.join(section_4) new_string = section_1 + section_2 + section_3 +section_4 return new_string a = 'Kitten' b = 'Donut' c = front_back(a, b) print(c)
03d1cd338caf7339b72ad88cf9ff3e34adc6a438
DavLivesey/algoritms_01
/exercise_12.py
781
3.6875
4
''' Васе очень понравилась задача про анаграммы и он придумал к ней модификацию. Есть 2 строки s и t, состоящие только из строчных букв. Строка t получена перемешиванием букв строки s и добавлением 1 буквы в случайную позицию. Нужно найти добавленную букву. ''' import collections text_1 = collections.Counter(input()) text_2 = collections.Counter(input()) if len(text_1) > len(text_2): for i in text_1: if text_1[i] != text_2[i]: print(i) else: for i in text_2: if text_1[i] != text_2[i]: print(i) # Time: 47ms, Memory: 4.20Mb
c5342742af6e1229f22f4bd32db0269788067cb9
betty29/code-1
/recipes/Python/580639_Python2_keywordonly_argument_emulatidecorator/recipe-580639.py
11,343
3.546875
4
#!/usr/bin/env python import inspect import sys # The @decorator syntax is available since python2.4 and we support even this old version. Unfortunately functools # has been introduced only in python2.5 so we have to emulate functools.update_wrapper() under python2.4. try: from functools import update_wrapper except ImportError: def update_wrapper(wrapper, wrapped): for attr_name in ('__module__', '__name__', '__doc__'): attr_value = getattr(wrapped, attr_name, None) if attr_value is not None: setattr(wrapper, attr_name, attr_value) wrapper.__dict__.update(getattr(wrapped, '__dict__', {})) return wrapper KWONLY_REQUIRED = ('KWONLY_REQUIRED',) FIRST_DEFAULT_ARG = ('FIRST_DEFAULT_ARG',) def first_kwonly_arg(name): """ Emulates keyword-only arguments under python2. Works with both python2 and python3. With this decorator you can convert all or some of the default arguments of your function into kwonly arguments. Use ``KWONLY_REQUIRED`` as the default value of required kwonly args. :param name: The name of the first default argument to be treated as a keyword-only argument. This default argument along with all default arguments that follow this one will be treated as keyword only arguments. You can also pass here the ``FIRST_DEFAULT_ARG`` constant in order to select the first default argument. This way you turn all default arguments into keyword-only arguments. As a shortcut you can use the ``@kwonly_defaults`` decorator (without any parameters) instead of ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``. >>> from kwonly_args import first_kwonly_arg, KWONLY_REQUIRED, FIRST_DEFAULT_ARG, kwonly_defaults >>> >>> # this decoration converts the ``d1`` and ``d2`` default args into kwonly args >>> @first_kwonly_arg('d1') >>> def func(a0, a1, d0='d0', d1='d1', d2='d2', *args, **kwargs): >>> print(a0, a1, d0, d1, d2, args, kwargs) >>> >>> func(0, 1, 2, 3, 4) 0 1 2 d1 d2 (3, 4) {} >>> >>> func(0, 1, 2, 3, 4, d2='my_param') 0 1 2 d1 my_param (3, 4) {} >>> >>> # d0 is an optional deyword argument, d1 is required >>> def func(d0='d0', d1=KWONLY_REQUIRED): >>> print(d0, d1) >>> >>> # The ``FIRST_DEFAULT_ARG`` constant automatically selects the first default argument so it >>> # turns all default arguments into keyword-only ones. Both d0 and d1 are keyword-only arguments. >>> @first_kwonly_arg(FIRST_DEFAULT_ARG) >>> def func(a0, a1, d0='d0', d1='d1'): >>> print(a0, a1, d0, d1) >>> >>> # ``@kwonly_defaults`` is a shortcut for the ``@first_kwonly_arg(FIRST_DEFAULT_ARG)`` >>> # in the previous example. This example has the same effect as the previous one. >>> @kwonly_defaults >>> def func(a0, a1, d0='d0', d1='d1'): >>> print(a0, a1, d0, d1) """ def decorate(wrapped): if sys.version_info[0] == 2: arg_names, varargs, _, defaults = inspect.getargspec(wrapped) else: arg_names, varargs, _, defaults = inspect.getfullargspec(wrapped)[:4] if not defaults: raise TypeError("You can't use @first_kwonly_arg on a function that doesn't have default arguments!") first_default_index = len(arg_names) - len(defaults) if name is FIRST_DEFAULT_ARG: first_kwonly_index = first_default_index else: try: first_kwonly_index = arg_names.index(name) except ValueError: raise ValueError("%s() doesn't have an argument with the specified first_kwonly_arg=%r name" % ( getattr(wrapped, '__name__', '?'), name)) if first_kwonly_index < first_default_index: raise ValueError("The specified first_kwonly_arg=%r must have a default value!" % (name,)) kwonly_defaults = defaults[-(len(arg_names)-first_kwonly_index):] kwonly_args = tuple(zip(arg_names[first_kwonly_index:], kwonly_defaults)) required_kwonly_args = frozenset(arg for arg, default in kwonly_args if default is KWONLY_REQUIRED) def wrapper(*args, **kwargs): if required_kwonly_args: missing_kwonly_args = required_kwonly_args.difference(kwargs.keys()) if missing_kwonly_args: raise TypeError("%s() missing %s keyword-only argument(s): %s" % ( getattr(wrapped, '__name__', '?'), len(missing_kwonly_args), ', '.join(sorted(missing_kwonly_args)))) if len(args) > first_kwonly_index: if varargs is None: raise TypeError("%s() takes exactly %s arguments (%s given)" % ( getattr(wrapped, '__name__', '?'), first_kwonly_index, len(args))) kwonly_args_from_kwargs = tuple(kwargs.pop(arg, default) for arg, default in kwonly_args) args = args[:first_kwonly_index] + kwonly_args_from_kwargs + args[first_kwonly_index:] return wrapped(*args, **kwargs) return update_wrapper(wrapper, wrapped) return decorate kwonly_defaults = first_kwonly_arg(FIRST_DEFAULT_ARG) # ------------------------------------------------------------------------------------------------- # TESTS # ------------------------------------------------------------------------------------------------- def get_arg_values(func, locals): args, varargs, varkw, _ = inspect.getargspec(func) if varargs: args.append(varargs) if varkw: args.append(varkw) return ' '.join('%s=%r' % (name, locals[name]) for name in args) def test_functions(): def run_one_test(func, first_kwonly_arg_name, *args, **kwargs): print('--------------------------------------------------------------------') print(' @first_kwonly_arg(%r)' % first_kwonly_arg_name) print('function: %s%s' % (func.__name__, inspect.formatargspec(*inspect.getargspec(func)))) print(' args: %s' % (args,)) print(' kwargs: %s' % (kwargs,)) try: decorated = first_kwonly_arg(name=first_kwonly_arg_name)(func) decorated(*args, **kwargs) except Exception: import traceback traceback.print_exc() def run_all_tests_for_func(func): print('--------------------------------------------------------------------') print('||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||') mode = func.__name__.split('_')[1] if 'a' in mode: # func has required args run_one_test(func, 'd1', 0, a1='my_a1') run_one_test(func, 'd1', 0, a1='my_a1', d0='my_d0') run_one_test(func, 'd1', 0, a1='my_a1', d2='my_d2') run_one_test(func, 'd1', 0, a1='my_a1', d0='my_d0', d2='my_d2') run_one_test(func, 'd1', a0='my_a0', a1='my_a1') else: run_one_test(func, 'd0') run_one_test(func, 'd1') run_one_test(func, 'd1', 0) run_one_test(func, 'd1', 0, 1) run_one_test(func, 'd1', 0, 1, 2) if 'v' in mode: # func has varargs run_one_test(func, 'd1', 0, 1, 2, 3) run_one_test(func, 'd1', 0, 1, 2, 3, 4) run_one_test(func, 'd1', 0, 1, 2, 3, 4, d2='my_d2') run_one_test(func, 'd1', 0, 1, 2, 3, 4, d1='my_d1', d2='my_d2') def run_all_tests_for_func_a(func): run_all_tests_for_func(func) def print_arg_values(func, locals): print(' result: ' + get_arg_values(func, locals)) def func_r1(d0='d0', d1=KWONLY_REQUIRED, d2='d2'): print_arg_values(func_r1, locals()) def func_r12(d0='d0', d1=KWONLY_REQUIRED, d2=KWONLY_REQUIRED): print_arg_values(func_r12, locals()) def func_ad(a0, a1, d0='d0', d1='d1', d2='d2'): print_arg_values(func_ad, locals()) def func_d(d0='d0', d1='d1', d2='d2'): print_arg_values(func_d, locals()) def func_adv(a0, a1, d0='d0', d1='d1', d2='d2', *args): print_arg_values(func_adv, locals()) def func_dv(d0='d0', d1='d1', d2='d2', *args): print_arg_values(func_dv, locals()) run_one_test(func_ad, 'invalid_arg_name') run_one_test(func_ad, 'a0') run_one_test(func_ad, 'd0') run_one_test(func_ad, 'd1', 0, 1, 2, 3) run_one_test(func_ad, 'd1', 0, 1, 2, d0='my_d0') run_one_test(func_r1, 'd1') run_one_test(func_r12, 'd1') run_one_test(func_r1, 'd1', d2='my_d2') run_one_test(func_r1, 'd1', d1='my_d1') run_one_test(func_r12, 'd1', d1='my_d1') run_one_test(func_r12, 'd1', d1='my_d1', d2='my_d2') run_all_tests_for_func(func_ad) run_all_tests_for_func(func_d) run_all_tests_for_func(func_adv) run_all_tests_for_func(func_dv) def test_class_methods(): def instance_method(self, a0, a1, d0='d0', d1='d1', d2='d2', *args): print('instance_method: ' + get_arg_values(instance_method, locals())) def class_method(cls, a0, a1, d0='d0', d1='d1', d2='d2', *args): print('class_method: ' + get_arg_values(class_method, locals())) def static_method(a0, a1, d0='d0', d1='d1', d2='d2', *args): print('static_method: ' + get_arg_values(static_method, locals())) wrapped_instance_method = first_kwonly_arg('d1')(instance_method) wrapped_class_method = first_kwonly_arg('d1')(class_method) wrapped_static_method = first_kwonly_arg('d1')(static_method) class MyClass(object): instance_method = wrapped_instance_method class_method = classmethod(wrapped_class_method) static_method = staticmethod(wrapped_static_method) def __repr__(self): return MyClass.__name__ + '()' my_class_instance = MyClass() def run_one_test(method, *args, **kwargs): print('--------------------------------------------------------------------') print('method=%s args=%s, kwargs=%s' % (method.__name__, args, kwargs)) try: method(*args, **kwargs) except Exception: import traceback traceback.print_exc() print('--------------------------------------------------------------------') print('||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||') run_one_test(my_class_instance.instance_method, 0, 1) run_one_test(my_class_instance.instance_method, 0, 1, 2) run_one_test(my_class_instance.instance_method, 0, 1, 2, 3) run_one_test(my_class_instance.instance_method, 0, 1, 2, 3, d2='my_d2') run_one_test(my_class_instance.class_method, 0, 1) run_one_test(my_class_instance.class_method, 0, 1, 2) run_one_test(my_class_instance.class_method, 0, 1, 2, 3) run_one_test(my_class_instance.class_method, 0, 1, 2, 3, d2='my_d2') run_one_test(my_class_instance.static_method, 0, 1) run_one_test(my_class_instance.static_method, 0, 1, 2) run_one_test(my_class_instance.static_method, 0, 1, 2, 3) run_one_test(my_class_instance.static_method, 0, 1, 2, 3, d2='my_d2') if __name__ == '__main__': test_functions() test_class_methods()
61a18768a0df1d7cf52fc57b646a538bc1d8facd
kotaro0522/python
/procon20171205/kaiden.py
265
3.65625
4
import math from decimal import * numbers = [int(i) for i in input().split()] diff = numbers[1] - numbers[2] if numbers[0] <= numbers[1]: print("1") elif diff <= 0: print("-1") else: print(math.ceil(Decimal(numbers[0] - numbers[1]) / diff) * 2 + 1)
cb7f77da43f54145314a5b85a5360846c982d4b9
PranavSonar/Python-Scripting-And-Automation
/PowerCode/Pattern Print/STAR PATTERN/Done/Pattern Start Print Basic.py
2,836
3.71875
4
#%% # code to print box/O # ***** # * * # * * # * * # * * # * * # ***** def boxPrint(symbol, width, hight): print(symbol*width) for i in range(hight-2): print(symbol+(' '*(width-2))+symbol) print(symbol*width) boxPrint('*', 5, 7) # code to prin I # ***** # * # * # * # * # ***** def printI(symbol, width, hight): print(symbol*width) for i in range(hight-2): print(' '*((width-1)//2)+symbol) print(symbol*width) # printI('*', 5, 6) # 1. # code to print piramid # * * * * * # * * * * * # * * * * * # * * * * * # * * * * * def printprymid(symbol, v_length): symbol=symbol+' ' for i in range(v_length): print(symbol*v_length) # printprymid('*', 5) # print follwing pattern # * # * * # * * * # * * * * # * * * * * # * * * * * * # ****** def patt(symbol,l_len): symbol=symbol+' ' for i in range (l_len): print (i*symbol) # patt('*',7) # 3# print full dimond # * # ** # *** # **** # ***** def full_dem(symbol,l_len): for i in range (l_len): i=i+1 print(' '*(l_len-i)+symbol*i) # full_dem('*',5) # 4. # print following # ***** # **** # *** # ** # * def follw(symbol,l_len): symbol=symbol for i in range(l_len): print (' '*i+(l_len-i )*symbol) # follw('*',5) # sqp('*',7) # 5 # code to print reverse # ***** # **** # *** # ** # * def rev(symbol, v_length): for i in range(v_length): k=v_length-i print(k*symbol) # rev('* ', 5) # print following pattern # * # * * # * * * # * * * * # * * * * * def patt(symbol,l_len): for i in range(l_len): i=i+1 print (' '*(l_len-i)+(symbol+' ')*i) # patt('*',5) # print following pattern # * # ** # *** # **** # ***** # ***** # **** # *** # ** # * def patt(symbol,l_len): for i in range (l_len): i=i+1 print(' '*(l_len-i)+symbol*i) if i ==5: for k in range(l_len): # k=k-1 print(' '*k+symbol*(l_len-k)) patt('*',5) def sqp(symbol, v_length): for i in range(v_length): print(symbol*i) # code to print half dimond # * # ** # *** # **** # ***** # ****** # ***** # **** # *** # ** # * def dem(symbol,l_len): for i in range(l_len): print (i*symbol) # print(i) if i==l_len-1: for i in range(l_len): k=l_len-i print(k*symbol) # dem('*',6) # print following line dymond # * # * # * # * # * def full_dem(symbol,l_len): for i in range(l_len): print(' '*i+symbol) # full_dem('*',5) # print following line dymond # * # * # * # * # * def full_dem(symbol,l_len): for i in range(l_len): k=l_len-i print(' '*k+symbol) # full_dem('*',5)
03152bef4c989f5472a6fa27244598d88b066d9d
Flavio-Varejao/Exercicios
/Python/EstruturaDeRepeticao/Q22.py
649
4.125
4
#!/usr/bin/env python3 #Altere o programa de cálculo dos números primos, informando, caso o número não seja primo, por quais número ele é divisível. contador=0 divisores=[] numero=int(input("Digite o número: ")) if numero!=-1 and numero!=0 and numero!=1: for divisor in range(1,numero+1): if numero%divisor==0: contador+=1 #O contador aumenta quando há um divisor divisores.append(divisor) if contador>2: print(numero,"não é um número primo") print("Divisores",divisores) else: print(numero,"é um número primo") else: print(numero,"não é um número primo")
f55540fa11bf169fd2111036c569d407d4df0575
jbelo-pro/NumericMatrixProcessor
/Numeric Matrix Processor/task/processor/processor.py
8,596
3.6875
4
from collections import deque def sum_matrices(): rows_1, col_1 = input('Enter size of first matrix: ').split() print('Enter first matrix:') matrix_1 = [] for r in range(int(rows_1)): row = [] for n in input().split(): t = int(n) if n.isdigit() else float(n) row.append(t) matrix_1.append(row) rows_2, col_2 = input('Enter size of second matrix: ').split() print('Enter second matrix:') matrix_2 = [] for r in range(int(rows_2)): row = [] for n in input().split(): t = int(n) if n.isdigit() else float(n) row.append(t) matrix_2.append(row) if rows_1 != rows_2 or col_1 != col_2: print('The operation can not be performed\n') else: sum_matrix = [] print('The result is:') for r in range(len(matrix_1)): temp_r = [] for z in zip(matrix_1[r], matrix_2[r]): temp_r.append(str(z[0] + z[1])) print(' '.join(temp_r)) print('\n') def matrix_by_constant(cons, matrix): new_matrix = [] for row in matrix: temp_r = [n * cons if abs(n) != 0 else 0 for n in row] new_matrix.append(temp_r) return new_matrix def multiply_matrices(): rows_1, col_1 = input('Enter size of first matrix: ').split() print('Enter first matrix:') matrix_1 = [] for r in range(int(rows_1)): row = [] for n in input().split(): t = int(n) if n.isdigit() else float(n) row.append(t) matrix_1.append(row) rows_2, col_2 = input('Enter size of second matrix: ').split() print('Enter second matrix:') matrix_2 = [] for r in range(int(rows_2)): row = [] for n in input().split(): t = int(n) if n.isdigit() else float(n) row.append(t) matrix_2.append(row) if col_1 != rows_2: print('The operation can not be performed\n') else: t_matrix_2 = [] for r in range(int(col_2)): t_matrix_2.append([]) for r in matrix_2: for c in range(len(r)): t_matrix_2[c].append(r[c]) new_matrix = [] for r in matrix_1: new_row = [] for r1 in t_matrix_2: value = 0 for z in zip(r, r1): value += z[0] * z[1] new_row.append(str(value)) new_matrix.append(new_row) print('The result is:') for r in new_matrix: print(' '.join(r)) print('\n') def transpose_main_diagonal(matrix): t_matrix = [] for r in range(len(matrix[0])): t_matrix.append([]) for r in matrix: for c in range(len(r)): t_matrix[c].append(r[c]) return t_matrix def transpose_side_diagonal(): rows, cols = input('Enter matrix size: ').split() print('Enter matrix') matrix = [] for r in range(int(rows)): row = [n for n in input().split()] matrix.append(row) t_matrix = [] for r in range(len(matrix[0])): t_matrix.append([]) for r in matrix: for c in range(len(r)): t_matrix[c].append(str(r[c])) t_matrix.reverse() for r in t_matrix: r.reverse() print(' '.join(r)) def transpose_vertical_line(): rows, cols = input('Enter matrix size: ').split() print('Enter matrix') matrix = [] for r in range(int(rows)): row = [n for n in input().split()] matrix.append(row) for r in matrix: r.reverse() print(' '.join(r)) def transpose_horizontal(): rows, cols = input('Enter matrix size: ').split() print('Enter matrix') matrix = [] for r in range(int(rows)): row = [n for n in input().split()] matrix.append(row) matrix.reverse() for r in matrix: print(' '.join(r)) def determinant(mtrx): if len(mtrx) == 2: return mtrx[0][0] * mtrx[1][1] - mtrx[0][1] * mtrx[1][0] elif len(mtrx) == 1: return mtrx[0][0] else: deter = 0 for index in range(len(mtrx[0])): cof = mtrx[0][index] sym = (-1) ** (1 + index + 1) new_matrix = [] for row_index in range(1, len(mtrx)): row = mtrx[row_index] nr = [] for index2 in range(len(mtrx[0])): if index2 == index: continue nr.append(row[index2]) new_matrix.append(nr) deter += cof * sym * determinant(new_matrix) # (new_matrix[0][0] * new_matrix[1][1] - new_matrix[0][1] * new_matrix[1][0]) return deter def get_matrix(): rows, cols = input('Enter matrix size: ').split() print('Enter matrix') matrix = [] for r in range(int(rows)): row = [int(n) if n.isdigit() else float(n) for n in input().split()] matrix.append(row) return matrix def sub_matrix(row, column, matrix): new_matrix = [] for row_index in range(len(matrix)): if row_index == row: continue new_row = [] row_m = matrix[row_index] for column_index in range(len(row_m)): if column_index == column: continue new_row.append(row_m[column_index]) new_matrix.append(new_row) return new_matrix def attached_matrix(matrix): new_matrix = [] for row_index in range(len(matrix)): row = matrix[row_index] new_row = [] for column_index in range(len(row)): c = (-1) ** (row_index + column_index + 2) * determinant( sub_matrix(row_index, column_index, matrix)) new_row.append(c) new_matrix.append(new_row) return new_matrix def print_options(): print('1. Add matrices') print('2. Multiply matrix by constant') print('3. Multiply matrices') print('4. Transpose matrix') print('5. Calculate a determinant') print('6. Inverse matrix') print('0. Exit') def print_options_transpose(): print('1. Main diagonal') print('2. Side diagonal') print('3. Vertical line') print('4. Horizontal line') while True: print_options() choice = input('Your choice : ') if choice == '1': sum_matrices() elif choice == '2': matrix = get_matrix() cons = input('Enter constant: ') cons = int(cons) if cons.isdigit() else float(cons) matrix_by = matrix_by_constant(cons, matrix) print('The result is:') for row in matrix_by: print(' '.join([str(n) for n in row])) print('\n') elif choice == '3': multiply_matrices() elif choice == '4': print_options_transpose() choice_transponse = input('Your choice: ') if choice_transponse == '1': matrix = get_matrix() t_matrix = transpose_main_diagonal(matrix) for row in t_matrix: print(' '.join([str(n) for n in row])) elif choice_transponse == '2': transpose_side_diagonal() elif choice_transponse == '3': transpose_vertical_line() else: transpose_horizontal() elif choice == '5': matrix = get_matrix() d = determinant(matrix) print('The result is:') if d % 1 > 0: print(d, '\n') else: print(int(d), '\n') elif choice == '6': matrix = get_matrix() matrix_determinant = determinant(matrix) if matrix_determinant == 0: print("The matrix doesn't have an inverse\n") elif len(matrix) == 1: print('The result is') print(-1 * matrix[0][0]) elif len(matrix) == 2: matrix[0][0], matrix[1][1] = matrix[1][1], matrix[0][0] matrix[0][1] = matrix[0][1] * -1 matrix[1][0] = matrix[1][0] * -1 matrix_by = matrix_by_constant(matrix_determinant ** -1, matrix) print('The result is') for row in matrix_by: print([str(round(n, 2)) for n in row]) print('\n') else: attach_matrix = attached_matrix(matrix) trans_matrix = transpose_main_diagonal(attach_matrix) inverse = matrix_by_constant(matrix_determinant ** (-1), trans_matrix) for row in inverse: print(' '.join(str(round(n, 3)) for n in row)) else: break
eb752ee9e8012e1014f0574fe0a6759256c7dcb6
mickyscandal/word_count
/revamp.py
4,024
3.75
4
#!/usr/bin/python # imports import argparse import time from collections import Counter class TextData(object): def __init__(self, nfile): self.nfile = nfile def basic_count(self): """basic count of all words and unique words""" with open(self.nfile) as f: data = f.read().split() return "%s: %s words, <fix> unique words" % (self.nfile, len(data)) def uniq_count(self): """basic count of all unique words""" with open(self.nfile) as f: data = f.read().split print data self.uniq = [] for word in data : if word not in uniq: uniq.append(word) return len(uniq) def uniq_word_count(self): """every word in file and a count of how many occurances --(c)ount""" with open(self.nfile) as f: return Counter(f.read().split()) def search(self, pattern): """searches the file and returns bool weather true or false --(s)earch""" self.pattern = pattern with open(self.nfile) as f: self.searchDat = f.readlines() self.found = False for line in self.searchDat: if pattern in line: self.found = True break return self.found class Argument(object): def __init__(self, textdata): self.parser = argparse.ArgumentParser() self.textdata = textdata def parseArguments(self): # positional argument self.parser.add_argument("filename", help="File name.", type=str) # optional arguments self.parser.add_argument("-s", "--search", help="search help", type=str) self.parser.add_argument("-c", "--count", help="count help", action="store_true") self.parser.add_argument("-w", "--write", help="write help", action="store_true") self.parser.add_argument("--version", action="version", version="%(prog)s - Version X.X") return self.parser.parse_args() class Display(object): def __init__(self, textdata): self.textdata = textdata pass def basic_display(Self): print textdata.basic_count() def display_word_count(self): count = textdata.uniq_word_count() for k, v in count.iteritems(): print "%s: %d" % (k,v) def display_search(self): if textdata.found: print "'%s' found: " % textdata.pattern for line in textdata.searchDat: if textdata.pattern in line: print line def timestamp(self): print "Generated on: %s" % time.asctime(time.localtime(time.time())) class Write(object): def __init__(self, textdata): self.textdata = textdata self.outfile = open("%s_output.txt" % textdata.nfile[0:-4], 'w') pass def basic_write(self): self.outfile.write(textdata.basic_count() + "\n") def write_word_count(self): count = textdata.uniq_word_count() for k, v in count.iteritems(): self.outfile.write("%s: %d\n" % (k,v)) def write_search(self): if textdata.found: self.outfile.write("'%s' found: \n" % textdata.pattern) for line in textdata.searchDat: if textdata.pattern in line: self.outfile.write(line + "\n") def close_file(self): self.outfile.close() def timestamp(self): self.outfile.write("Generated on: %s\n" % time.asctime(time.localtime(time.time()))) if __name__ == "__main__": textdata = TextData('text.txt') display = Display(textdata) write = Write(textdata) textdata.search('fuck') # display outputs display.basic_display() display.display_word_count() display.display_search() display.timestamp() # write outputs write.basic_write() write.write_word_count() write.write_search() write.timestamp() write.close_file()
1889331059fe2e0d78320aaa8160feb550cec294
Uthaeus/practice_python
/guessing_game.py
628
4.1875
4
import time import random print("---------This is the guessing game----------") time.sleep(1) game = 'y' while game == 'y': turns = 0 for x in range(1): num = random.randint(1, 10) guess = int(input("Pick a number between 1 and 10 \n")) while guess != num: if guess < num: print("Your guess is too low") turns += 1 elif guess > num: print("Your guess is too high") turns += 1 guess = int(input("Try again\n")) if guess == num: print("You guessed it!!") game = input("Would you like to play again? (y/n)\n") if game != 'y': print("Thanks for playing!")
bfe377861812e9be856d7912903105b53810126b
AdamZhouSE/pythonHomework
/Code/CodeRecords/2306/60696/261462.py
1,486
3.546875
4
lch = [] rch = [] res_pre_order = [] res_in_order = [] res_post_order = [] def print_pre_order(root): if lch[root] == 0 and rch[root] == 0: res_pre_order.append(root) return res_pre_order.append(root) if lch[root]!=0: print_pre_order(lch[root]) if rch[root]!=0: print_pre_order(rch[root]) def print_in_order(root): if lch[root] == 0 and rch[root] == 0: res_in_order.append(root) return if lch[root]!=0: print_in_order(lch[root]) res_in_order.append(root) if rch[root]!=0: print_in_order(rch[root]) def print_post_order(root): if lch[root] == 0 and rch[root] == 0: res_post_order.append(root) return if lch[root]!=0: print_post_order(lch[root]) if rch[root]!=0: print_post_order(rch[root]) res_post_order.append(root) if __name__ == '__main__': arr = [int(i) for i in input().split()] n = arr[0] root = arr[1] lch = [0 for i in range(500)] rch = [0 for i in range(500)] for i in range(n): arr = [int(j) for j in input().split()] lch[arr[0]] = arr[1] rch[arr[0]] = arr[2] print_pre_order(root) for each in res_pre_order: print(each, end=' ') print() print_in_order(root) for each in res_in_order: print(each, end=' ') print() print_post_order(root) for each in res_post_order[:-1]: print(each, end=' ') print(res_post_order[-1])
1181f3ddf197be347868826a2f274072d30b247b
edt-yxz-zzd/python3_src
/nn_ns/math_nn/Josephus_problem.py
8,949
3.875
4
##Josephus problem ##From Wikipedia, the free encyclopedia ##In computer science and mathematics, ##the Josephus Problem (or Josephus permutation) ##is a theoretical problem related to a certain counting-out game. ## ##There are people standing in a circle waiting to be executed. ##The counting out begins at some point in the circle and ##proceeds around the circle in a fixed direction. In each step, ##a certain number of people are skipped and the next person is executed. ##The elimination proceeds around the circle (which is becoming smaller and ##smaller as the executed people are removed), until only the last person remains, ##who is given freedom. ## ##The task is to choose the place in the initial circle ##so that you are the last one remaining and so survive. ''' [0..n-1] 1st round killed k-1..x*k-1... if k|n, then n-1 is killed in this round 0 will again be the beginner. now there are n_2 = n-(n/k) if k|n[i] and n[i+1] = n[i] - n[i]/k, n[i+1] = (k-1)/k*n[i], n[?] = (k-1)^? let n = k^t ''' CHAR_BIT = 8 def check(k, n): if not (type(n) == int == type(k)): print('type(n)==', type(n), ', type(k)==', type(k)) raise 'k & n should be integers in Josephus_problem' elif n < 1 or k < 1: print('k = ', k, ', n = ', n) raise 'k & n should be a positive integers in Josephus_problem' def Josephus_problem(k, n): '''n person in circle numbered from 0 to n-1, counting-out the k-th person. which one will remains?''' check(k, n) if k == 1: return Josephus_problem_k_is_1(n) elif k == 2: return Josephus_problem_k_is_2(n) elif n > 10*k: # first round assert(k > 1 and k-1 < n) dn = (n+k-1) // k # dn <= (n+k-1)/2 < n n_ = n - dn # next n, n_ > 0 idx_ = (k * dn) % n - 1 # the index of the last out one in 1st round. begin from 0 # the index of the first out person is k-1, since k-1 < n # note that idx_ == -1 is needed #if not (-1 <= idx_ < k-1 < n): # print(idx_, k, n) assert(-1 <= idx_ < k-1 < n) # pad the answer of (k, n_) with the number of persons skiped a_ = Josephus_problem(k, n_) min_gap = k-2 - idx_ # after 1st round, each gap is either (k-1) or min_gap b = a_ + (k-1) - min_gap # [min_gap,k-1...,k-1], a_ is in one of these gaps, a = (idx_ + 1) + (a_ + b // (k-1)) # [(x+min_gap)=k-1,k-1...k-1,..a_ is here,...], how many (k-1) before a_? a %= n return a else: return Josephus_problem_dynamic(k, n) def Josephus_problem_k_is_1(n): check(1, n) return n - 1 def Josephus_problem_k_is_2(n): check(2, n) return (n << 1) - (1 << n.bit_length()) def Josephus_problem_dynamic_when_n_is_big(k, n): #raise 'unimpliment' # first round assert(k > 1 and k-1 < n) dn = (n+k-1) // k # dn <= (n+k-1)/2 < n, number of persons out in 1st round n_ = n - dn # next n, n_ > 0, number of remainders in next round idx_ = (k * dn) % n - 1 # the index of the last out one in 1st round. begin from 0 # the index of the first out person is k-1, since 0 < k-1 < n # note that idx_ == -1 is needed #if not (-1 <= idx_ < k-1 < n): # print(idx_, k, n) assert(-1 <= idx_ < k-1) # pad the answer of (k, n_) with the number of persons skiped a_ = Josephus_problem(k, n_) min_gap = k-2 - idx_ # after 1st round, each gap is either (k-1) or min_gap b = a_ + (k-1) - min_gap # [min_gap,k-1...,k-1], a_ is in one of these gaps, a = (idx_ + 1) + (a_ + b // (k-1)) # [(x+min_gap)=k-1,k-1...k-1,..a_ is here,...], how many (k-1) before a_? a %= n return a def Josephus_problem_dynamic(k, n): check(k, n) #if n == 1: # return 0 #return (Josephus_problem_dynamic(k, n-1) + k) % n # RuntimeError: maximum recursion depth exceeded while calling a Python object # Josephus_problem_dynamic(3, 999) !!!!!!!!!!!!! ans = 0 # for n == 1 for n_ in range(2, n+1): ans = (ans + k) % n_ return ans def Josephus_problem_dynamic_list(k, n, ls_n): # ls[i] = Josephus_problem(k,i+1) check(k, n) if len(ls_n) >= n: return ls_n[n-1] if ls_n == []: ls_n.append(0) # n == 1 for n_ in range(len(ls_n)+1, n+1): ls_n.append((ls_n[-1] + k) % n_) return ls_n[-1] def Josephus_problem_dynamic_when_k_div_n(k, n): raise 'unimpliment' check(k, n) power = get_power_of_factor(k, n) def get_power_of_factor_definition(f, n): assert(f > 1) assert(n != 0) p = 0 while n % f == 0: n //= f; p += 1 return p def get_power_of_factor(factor, number): ''' assert(number != 0, factor >= 2) number = factor**power * other, other%factor != 0 ''' assert(number != 0) assert(factor >= 2) if number % factor != 0: return 0 power = 0 fs = [factor] # fs[i] == factor**(2**i) i = 0 two_pow_i = 2**i # two_pow_i == 2**i while number % fs[i] == 0: number //= fs[i] power += two_pow_i fs.append(fs[i]**2) i += 1 two_pow_i <<= 1 for i in range(i-1, -1, -1): two_pow_i >>= 1 if number % fs[i] == 0: number //= fs[i] power += two_pow_i return power def Josephus_problem_definition(k, n): check(k, n) import array stack = array.array('L') item_bit_size = stack.itemsize * CHAR_BIT item_max = (1 << item_bit_size) - 1 if item_bit_size < n.bit_length() or n >= item_max: # i = 0; i < max; ++i raise 'out of range: n is too large...' stack.extend(range(1,n+1)) stack[-1] = 0 # stack[i] point to the index of next man that is (i+1)%n assert(len(stack) == n) pre_i = n-1 i = stack[pre_i] # i == stack[pre_i] holds while(stack[i] != i): for t in range(k-1): i,pre_i = stack[i], i # skip (k-1) persons stack[pre_i] = stack[i] # drop i-th person i = stack[pre_i] return i ############################## ##### test ##### ############################## def test_Josephus_problem_definition(): ns = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] ms = [0, 0, 2, 0, 2, 4, 6, 0, 2, 4, 6, 8, 10, 12, 14, 0] #[1, 1, 3, 1, 3, 5, 7, 1, 3, 5, 7, 9, 11, 13, 15, 1] k = 2 for m,n in zip(ms, ns): if m != Josephus_problem_definition(k, n): print('error: Josephus_problem_definition(', k, ', ', n, ') = ', Josephus_problem_definition(k, n), ' != ', m) return def test_Josephus_problem_dynamic(): for n in range(1, 200): for k in range(1, 5): if Josephus_problem_dynamic(k, n) != Josephus_problem_definition(k, n): print('error: Josephus_problem_dynamic(', k, ', ', n, ') = ', Josephus_problem_dynamic(k, n), ' != ', Josephus_problem_definition(k, n)) return def test_Josephus_problem(): for n in range(1, 1000): for k in range(1, 50): if Josephus_problem(k, n) != Josephus_problem_dynamic(k, n): print('error: Josephus_problem(', k, ', ', n, ') = ', Josephus_problem(k, n), ' != ', Josephus_problem_dynamic(k, n)) return def test_Josephus_problem_dynamic_list(): max_n = 1000 for k in range(1, 50): ls_n = [] Josephus_problem_dynamic_list(k, max_n, ls_n) for n in range(1, max_n): if Josephus_problem_dynamic_list(k, n, ls_n) != Josephus_problem(k, n): print('error: Josephus_problem_dynamic_list(', k, ', ', n, ') = ', Josephus_problem_dynamic_list(k, n, ls_n), ' != ', Josephus_problem(k, n)) return def test_get_power_of_factor_definition(): td = [ # f, n, p \ (2, 1, 0), \ (2, 2, 1), \ (2, 3, 0), \ (2, 4, 2), \ (2, 5, 0), \ (2, 6, 1), \ (2, 7, 0), \ (2, 8, 3), \ (2, 9, 0), \ (3, 1, 0), \ (3, 2, 0), \ (3, 3, 1), \ (3, 4, 0), \ (3, 5, 0), \ (3, 6, 1), \ (3, 7, 0), \ (3, 8, 0), \ (3, 9, 2), \ (3, 10, 0), \ (3, 11, 0), \ (3, 12, 1), \ (3, 13, 0), \ (3, 14, 0), \ (3, 15, 1), \ (3, 27, 3), \ (3, 81*59, 4), \ (3, 578*(3**7)**2, 14), \ ] for f,n,p in td: if get_power_of_factor_definition(f, n) != p: print('get_power_of_factor_definition(', f, ', ', n, ') != ', p) return def test_get_power_of_factor(): for f in range(2, 5): for n in range(1, 2000): if get_power_of_factor(f, n) != get_power_of_factor_definition(f, n): print('get_power_of_factor(', f, ', ', n, ') != ', get_power_of_factor_definition(f, n)) return
f08b78b7c2e108bb366eeccefb9f6d1b7bc31a9f
yunfanLu/LeetCode
/leetcode/src/p026RemoveDuplicatesfromSortedArray/solution.py
454
3.59375
4
# -*- coding: utf-8 -*- # @Time : 2018/8/31 13:51 # @Author : yunfan class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if nums is None or len(nums) == 0: return 0 l, r = 0, 1 while r < len(nums): if nums[r] != nums[l]: l += 1 nums[l] = nums[r] r += 1 return l + 1
ad73e0369c00a547c883e7b5b1c8c5c950a3635e
vanely/Python-Challenges
/KeepHydrated/liters.py
175
3.5625
4
import math; def litres(time): return math.floor(time / 2) #for greater simplicity we could use python floor division def liters(t): return t // 2 print(litres(5))
ab8232f1cdf261107c85b4b5946196f3d1fca5b5
lemishAn/prak_sem5
/task2/program1.py
519
3.890625
4
''' task 2, program 1 ''' if __name__ == '__main__': LINE = input() i, j, number_substrings = 1, 0, 1 S = LINE[0: i] while number_substrings*S != LINE: j = LINE.find(S, i) if j == - 1: break S = LINE[0: j] number_substrings = LINE.count(S) if i == j: i *= 2 else: i = j if (number_substrings*S == LINE) or (number_substrings == 1): print(number_substrings) else: print('Error: Not an integer number of substrings')
03c2b48c7245b6f57c655c61395cc9be48704395
kidexp/91leetcode
/two_ponters/287FindtheDuplicateNumber.py
670
3.765625
4
from typing import List class Solution: def findDuplicate(self, nums: List[int]) -> int: slow = fast = 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow = 0 while slow != fast: slow = nums[slow] fast = nums[fast] return fast if __name__ == "__main__": solution = Solution() print(solution.findDuplicate([1, 3, 4, 2, 2])) print(solution.findDuplicate([3, 1, 3, 4, 2])) print(solution.findDuplicate([1, 1])) print(solution.findDuplicate([1, 1, 2])) print(solution.findDuplicate([2, 2, 2]))
eb04a1adb1c67acb4477445ce4fdec33371dde4e
AMS347/PRACTICA
/Obtener promedios (diccionario).py
1,954
3.734375
4
def obtenerInfoestudiantes(): op='' dic={} while (op!='no'): print('ingrese los datos del estudiante') mat=int(input('Matriculas:')) dic2={} dic2['nombres']=input('nombres:') dic2['apellidos']=input('apellidos:') dic2['carrera']=input('carrera') op2='' materias=[] promedios=[] while (op2!='no'): print('ingrese los datos de una asignatura') materias.append(input('\tmateria:')) promedios.append(float(input('\tpromedio:'))) op2=input('\tquiere ingresar mas asignaturas, si o no?:') print('') dic2['asignaturas']=tuple(materias) dic2['calificaciones']=tuple(promedios) op=input('quiere ingresar mas estudiantes, si o no:?') dic[mat]=dic2 return dic def calcularPromediosEstudiantes(diccionario): promedios={} for i in diccionario: temp=diccionario.get(i) calificaciones=temp.get("calificaciones") promedio=0 for j in range(len(calificaciones)): promedio+=calificaciones[j] promedio=promedio/(len(calificaciones)) promedios[i]=promedio return promedios def obtenerMejoresPromedios(diccionario,inicial,final): mejores=[] for i in diccionario: if diccionario.get(i)>=inicial and diccionario.get(i)<=final : mejores.append(i) return mejores informacion=obtenerInfoestudiantes() promedios=calcularPromediosEstudiantes(informacion) inicio=int(input("Ingrese el valor minimo de la nota para la beca:")) final=int(input("Ingrese el valor maximo de la nota para la beca:")) mejores=obtenerMejoresPromedios(promedios,inicio,final) print("********MEJORES PROMEDIOS********") for i in range(len(mejores)): temp=informacion.get(mejores[i]) print(str(temp.get("nombres")) +" "+ str(temp.get("apellidos")) +" "+ str(temp.get("carrera")) +" "+ str(mejores[i]))
65d5efa13cbf7f1f99eb09eb38d2bb929e4ff9ef
Autassist/pi_code
/websocket_server.py
1,171
3.625
4
#!/usr/bin/env python import bluetooth host = "" port = 1 # Raspberry Pi uses port 1 for Bluetooth Communication # Creaitng Socket Bluetooth RFCOMM communication server = bluetooth.BluetoothSocket(bluetooth.RFCOMM) print('Bluetooth Socket Created') try: server.bind((host, port)) print("Bluetooth Binding Completed") except: print("Bluetooth Binding Failed") server.listen(1) # One connection at a time # Server accepts the clients request and assigns a mac address. client, address = server.accept() print("Connected To", address) print("Client:", client) try: while True: # Receivng the data. data = client.recv(1024) # 1024 is the buffer size. print(data) try: max_num = int(data) try: f = open('/home/pi/Desktop/Soundmeter/decibel_data/max_decibel.txt', 'w') except IOError as e: print(e) else: f.write(str(max_num)) f.close() except: print("input not int") except: # Closing the client and server connection client.close() server.close()
96b9409462f49e6aa93e7d82e7a652a0b48282e7
aanantt/Python-DataStructure
/Tree/Binary Tree/BinaryTree_Rightmost_Element.py
680
3.90625
4
class Node: def __init__(self, element): self.element = element self.right_node = None self.left_node = None class BinaryTree: def __init__(self, root_Node): self.root= root_Node def rightMost(self,node):#Right Most Element in a BST if node.right_node: self.rightMost(node.right_node) return True print(node.element) tree = BinaryTree(Node(1)) tree.root.left_node = Node(2) tree.root.right_node = Node(3) tree.root.left_node.left_node = Node(4) tree.root.left_node.right_node = Node(5) tree.root.right_node.left_node = Node(6) tree.root.right_node.right_node = Node(7) tree.rightMost(tree.root)
5dad0b3c1b8fcd106d96a91d80991383e2a1413f
ikeshou/Kyoupuro_library_python
/src/mypkg/basic_algorithms/sliding_window_min.py
3,243
3.8125
4
""" スライド最小値 <algorithm> 長さ n の数列 L に対し、長さ k の連続部分数列を考える。L[i:i+k] (0<=i<=n-k) に対してこの連続部分数列の最小値を求めたい。 ナイーブに比較演算を行うと O(n * k) 、RMQ をさばくセグ木だと O(nlgn) だが、スライド最小値のアルゴリズムでは O(n) で計算可能。 """ from collections import deque from typing import List, Sequence, Union Num = Union[int, float] def sliding_minimum_query(L: Sequence[Num], k: int) -> List[Num]: """ O(n) で L[i:i+k] (0<=i<=n-k) の最小値をそれぞれ計算しリストにまとめる Args: L (sequence): 正の数列 k (int): 要素数 k の L の連続部分列を考え、その最小値のクエリに答えていく Returns: list: L の各要素を先頭とする k 連続部分列を考え、その最小値を対応する要素に記録したリスト Raises: ValueError: k < 1 のとき IndexError: k > n のとき Examples: >>> sliding_minimum_query([1, 5, 3, 6, 9, 9, 2, 1, 8], 3) [1, 3, 3, 6, 2, 1, 1] Notes: Q にはむこう k 個の数列の要素のうち、最小要素, 2 番目の順序統計量, 3 番目の順序統計量... と順に「もとの並び順を尊重して」 限界まで取っていった時のインデックスが保存される (入るインデックスもその指し示す値も広義単調増加。これらは区間最小値の候補である) スライドを行うと一つ数列の要素 x を読み込むことになる。 現在 Q に残っている要素のうち x 以上のものは不要 (最小が上書きされる)。末尾からそれらを全て pop して x を追加。 Q の先頭は index が対象範囲から外れている可能性がある。チェックし対象範囲から外れていたら popleft する。 """ n = len(L) if k < 1: raise ValueError(f"sliding_minimum_query(): window size should be >= 1. got {k}") if k > n: raise IndexError(f"sliding_minimum_query(): window size is greater than the length of sequence. got sequence: {L}, window size: {k}") # ans[i] には L[i:i+k] の最小値が保存される ans = [] # 最初の Q (の直前まで、L[0:k-1]に対する処理) を作成しておく Q = deque() for j in range(k-1): while Q and L[Q[-1]] >= L[j]: Q.pop() Q.append(j) # L[0:k] に対する処理、つまり L[k-1] を読みに行くところからスタートする for j in range(k-1, n): i = j - k + 1 while Q and L[Q[-1]] >= L[j]: Q.pop() Q.append(j) if Q[0] < i: Q.popleft() ans.append(L[Q[0]]) return ans if __name__ == "__main__": L = [1,5,2,4,7,12,14,65,43,8,9,10,0,3,5,7,9,100] assert(sliding_minimum_query(L, 4) == [1,2,2,4,7,12,8,8,8,0,0,0,0,3,5]) assert(sliding_minimum_query(L, 8) == [1,2,2,4,7,0,0,0,0,0,0]) assert(sliding_minimum_query([1], 1) == [1]) assert(sliding_minimum_query([1, 2, 3, 4, 5], 1) == [1, 2, 3, 4, 5]) print(" * assertion test ok *")
b15547f6c896f19e2293ca2287ecc08cc18362f7
302Blue/CISC106
/PYTHON/Final & Midterm/Midterm/Worksheet+-+while+loops.py
2,314
4.28125
4
# Make sure you understand why each loop creates the output that it does. # Convert the following while loops to for loops. # For example, exercise 12b would be: product = 1 n = 2 for k in range(0, 9, 4): product = product * n print(product) print("Exercise 1a") x = 0 while x < 20: x = x + 1 print(x) print("Exercise 1b") x = 0 while x < 20: print(x) x = x + 1 print("Exercise 2a") x = 0 while x < 20: x = x + 1 print(x) print("Exercise 2b") x = 0 while x <= 20: x = x + 1 print(x) print("Exercise 3a") x = 10 while x > 0: x = x - 1 print (x) print("Exercise 3b") x = 10 while x > 0: print (x) x = x - 1 print("Exercise 4") x = 10 while x > 0: x = x - 1 print (x) print("Exercise 5") sum = 0 k = 0 while k <= 5: sum = sum + k print(sum) k = k + 1 print("Exercise 6a") sum = 0 k = 0 while k <= 5: sum = sum + k k = k + 1 print (sum) print ("Exercise 6b") sum = 0 k = 0 while k <= 5: k = k + 1 sum = sum + k print(sum) print("Exercise 6c") sum = 0 k = 0 while k <= 10: k = k + 2 sum = sum + k print(sum) print("Exercise 7") sum = 0 k = 0 while k <= 5: sum = k k = k + 1 print(sum) print("Exercise 8") product = 0 k = 1 while k <= 5: product = product * k k = k + 1 print(product) print("Exercise 9a") product = 1 k = 1 while k <= 5: product = product * k k = k + 1 print(product) print("Exercise 9b") product = 1 k = 0 while k <= 5: k = k + 1 product = product * k print(product ) print("Exercise 10") product = 1 k = 1 while k <= 5: product = product * k k = k + 1 print(product) print("Exercise 11a") sum = 1 k = 1 while k <= 5: sum = sum * k k = k + 1 print(sum) print("Exercise 11b") product = 1 k = 1 while k <= 10: product = product * k k = k + 2 print(product) print("Exercise 11c") product = 1 k = 0 while k <= 8: k = k + 2 product = product * k print (product) print("Exercise 12a") product = 1 n = 2 k = 0 while k <= 8: k = k + 2 product = product * n print (product) print("Exercise 12b") product = 1 n = 2 k = 0 while k <= 11: k = k + 2 product = product * n k = k + 2 print(product) product = 1 n = 2 for k in range(0, 9, 4): product = product * n print(product)
69cafd4bffccd6d13345df7d98de9f5479bf7459
franky-codes/Py4E
/Ex3.2.py
417
4.125
4
hours = input('How many hours did you work?: ') rate = input('What is your hourly rate?: ') try: fhours = float(hours) frate = float(rate) except: print('Please enter a numeric') quit() if fhours > 40.0: overtime_rate = frate * 1.5 pay = (fhours - 40) * overtime_rate + (frate * 40) print("Overtime") else: pay = fhours * frate print("Regular") print('You have earned: $',pay)
3c6881f88d5c24a4dfdde1f2a31a865d9e7b3c1a
LeilaHuang/python_projects
/data_related_program/data_file_4/data_run_4.py
2,149
3.53125
4
# 题目描述:统计1-3月气温在-10℃~10℃的天数统计直方图 import os import numpy as np import matplotlib.pyplot as plt data_path = './' data_filename = 'temp2.csv' month_temp_list = [] def get_data(): data_file = os.path.join(data_path, data_filename) temp_data = np.loadtxt(data_file, delimiter=',',dtype='int',skiprows=1) return temp_data def analyze_data(temp_data, month): # np.logical_and() one time can only use two values bool_arr = np.logical_and(temp_data[:, 0] == month, np.logical_and(temp_data[:, 1] <= 10, temp_data[:, 1] >= -10 )) filtered_month_temp_data = temp_data[bool_arr][:,1] return filtered_month_temp_data def output_histogram(filtered_month_temp_data_1, filtered_month_temp_data_2, filtered_month_temp_data_3): fig = plt.figure(figsize=(9, 8)) # count from 1 , the third number is the order ax1 = fig.add_subplot(1, 3, 1) ax2 = fig.add_subplot(1, 3, 2, sharey = ax1) ax3 = fig.add_subplot(1, 3, 3, sharey = ax1) hist_range = (-10, 10) # 多少份 n_bins = 10 #month 1 ax1.hist(filtered_month_temp_data_1, range = hist_range, bins = n_bins) ax1.set_xticks(range(-10, 11, 5)) ax1.set_title('month1') ax1.set_ylabel('Count') ax1.set_xlabel('temperature') #month2 ax2.hist(filtered_month_temp_data_2, range = hist_range, bins = n_bins) ax2.set_xticks(range(-10, 11, 5)) ax2.set_title('month2') ax2.set_ylabel('Count') ax2.set_xlabel('temperature') #month3 ax3.hist(filtered_month_temp_data_3, range = hist_range, bins = n_bins) ax3.set_xticks(range(-10, 11, 5)) ax3.set_title('month3') ax3.set_ylabel('Count') ax3.set_xlabel('temperature') # plt.tight_layout() plt.savefig('output.png') plt.show() def main(): temp_data = get_data() filtered_month_temp_data_1 = analyze_data(temp_data, 1) filtered_month_temp_data_2 = analyze_data(temp_data, 2) filtered_month_temp_data_3 = analyze_data(temp_data, 3) output_histogram(filtered_month_temp_data_1,filtered_month_temp_data_2,filtered_month_temp_data_3) if __name__ == '__main__' : main()
62815a3b55a40a6284c4e002ac849b3bf017d3b2
KIMBOSEO/problems
/4522_palind.py
439
3.578125
4
for t in range(1, int(input())+1): case = str(input()) if len(case) ==1: ans =0 for i in range(len(case)//2): if case[i] == case[-i-1]: ans =0 else: if '?' == case[i] or case[-i-1] == '?': ans =0 else: ans =1 break if ans == 0: print('#{} Exist'.format(t)) else: print('#{} Not exist'.format(t))
b5b8ebd1fab633ba09c6aaa555c6267c3dec5429
e-valente/ISTA-421-521-ML-UofA
/hw/hw2/ista421ML-Homework2-release/code/scripts/exer5.old.py
2,568
3.578125
4
## cv_demo.py # Port of cv_demo.m # From A First Course in Machine Learning, Chapter 1. # Simon Rogers, 31/10/11 [simon.rogers@glasgow.ac.uk] # Demonstration of cross-validation for model selection # Translated to python by Ernesto Brau, 7 Sept 2012 # NOTE: In its released form, this script will NOT run # You will get a syntax error on line 80 because w has not been defined import numpy as np import matplotlib.pyplot as plt def read_data(filepath, d = ','): """ returns an np.matrix of the data """ return np.asmatrix(np.genfromtxt(filepath, delimiter = d, dtype = None)) def fitpoly(x, t, model_order): #### YOUR CODE HERE #### w = None ### Calculate w column vector (as an np.matrix) myarray = np.ones((x.shape[0], 1)) #print(x.shape) #print(myarray.shape) #myarray = np.concatenate((myarray, x)) x = np.column_stack((myarray, x)) #clear our array myarray = np.zeros((x.shape[0], 1)) mypow = 2; for col in range(model_order -1): myarray = np.power(x.T[1], mypow) #print(myarray) #rint(x.T[1]) print("vai\n\n") mypow += 1 x = np.column_stack((x,myarray.T)) #np.insert(x,myarray, axis=0) #x[:,:-1] = myarray #print(x) #m1 = ((X^t)X) m1 = x.T.dot(x) #print m1 #m2 = m1^-1 = ((X^t)X)^1 m2 = np.linalg.inv(m1) #print m2 #m3 = m2.X^t = (((X^t)X)^1) X^t m3 = m2.dot(x.T) w = m3.dot(t) return w def makeTestMatrix_X(indexArray, X): testX = np.zeros(N-K) for i in range(N): if ((i in indexArray) == False): testX() # make plots interactive plt.ion() ## Generate some data # Generate x between -5 and 5 #N = 100 #x = 10*np.random.rand(N, 1) - 5 #t = 5*x**3 - x**2 + x + 150*np.random.randn(x.shape[0], x.shape[1]) N = 50 filepath1 = '../data/synthdata2014.csv' ## Problem 4 ## Run a cross-validation over model orders maxorder = 7 Data = read_data(filepath1, ',') X = Data[:, 0] # extract x (slice first column) t = Data[:, 1] # extract t (slice second column) #X = np.asmatrix(np.zeros(shape = (x.shape[0], maxorder + 1))) #testX = np.asmatrix(np.zeros(shape = (testx.shape[0], maxorder + 1))) K = 10 # K-fold CV N = Data.shape[0] indexArray = X[:] np.random.seed(1) np.random.shuffle(indexArray) print indexArray exit() for i in range(K): print "k= ", i for j in range(N/K): #print ((i*(N/K)) + j) print indexArray[(i*(N/K)) + j] test_X = makeTestMatrix_X(indexArray, X) print indexArray raw_input('Press <ENTER> to quit...')
a10d1535eb9bda35e4c3a31b7b97545e12047bfc
Apeoud/LeetCode
/25_ReverseKGroup.py
1,870
3.828125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): return self.val def __repr__(self): return str(self.val) class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head is None: return None last1 = ListNode("begin") last1.next = head tmo = last1 while head is not None: group = head # 首先判断是不是还有k个node 如果有 进行reverse 否则 直接返回 for i in range(k - 1): if head.next is not None: head = head.next else: return tmo.next line1 = group line2 = line1.next for i in range(k - 1): tmp = line2.next line2.next = line1 line1 = line2 line2 = tmp last1.next = line1 last1 = group # 如果刚好结束 接k的整数倍个节点 那么直接返回即可 如果没有结束 先把当前k-group的1接到下一个group的1 # 接续下一个轮回 group.next = line2 head = line2 return tmo.next def printListNode(head): if head is None: print("None") return while head.next is not None: print(head.val) head = head.next print(head.val) def create(NodeList): last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a if __name__ == "__main__": test = create([1]) printListNode(Solution().reverseKGroup(test, 3))
fd5e864bacfb4f25a6151e8f2e5a1b43fc667fd1
elpiniki/pythonista
/test3_1.py
358
4.09375
4
d1 = [1, 2, 3, 4, 5, 6] def invert(param): """This function inverts the contents of the array""" i = 1 l = len(param) while i<l-3: head = [param[0]] tail = param[1:l] param = tail + head i = i + 1 if i == l: break return param if __name__ == "__main__": invert(d1) print invert(d1) print invert.__doc__
030fa37760918ccee282bcae3336ae3f2644b8bb
TroutMaskReplica1/Grading
/grading.py
457
3.984375
4
num = int(input('enter grade ')) if num < 60: print('\nF') elif num < 65: print('\nD-') elif num < 68: print('\nD') elif num < 70: print('\nD+') elif num < 75: print('\nC-') elif num < 78: print('\nC') elif num < 80: print('\nC+') elif num < 85: print('\nB-') elif num < 88: print('\nB') elif num < 90: print('\nB+') elif num < 95: print('\nA-') elif num < 97: print('\nA') elif num <= 100: print('\nA+')
15b1f6ef7b0a25dd8299f5ae42fe949ebdb8c8dd
arturh85/projecteuler
/python/src/problem004.py
2,735
4.09375
4
''' Problem 4 16 November 2001 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. ---------------------------------------------------------- Created on 25.01.2012 @author: ahallmann ''' import unittest import timeit import itertools import operator from multiprocessing import Pool def is_palindrome(str): return str == str[::-1] ''' Find the largest palindrome made from the product of two 3-digit numbers. ''' def solve(digits): digits_range = range(10 ** (digits - 1), 10 ** digits) largest = 0 for x in digits_range: for y in digits_range: val = x * y if val > largest and is_palindrome(str(val)): largest = val return largest def multiply_tuple(t): return t[0] * t[1] def reduce_largest_palindrome(largest, product_tuple): product = product_tuple[0] * product_tuple[1] if not largest: largest = 0 if product > largest and is_palindrome(str(product)): return product return largest def reduce_largest_palindrome2(product_tuple): product = product_tuple[0] * product_tuple[1] if is_palindrome(str(product)): return (product, product) def solve_functional(digit_count): digits_range = range(10 ** (digit_count - 1), 10 ** digit_count) products = map(multiply_tuple, itertools.product(digits_range, digits_range)) palindromes = filter(is_palindrome, map(str, products)) return max(map(int, palindromes)) def solve_functional_mapreduce(digit_count): pool = Pool(processes=8) digits_range = range(10 ** (digit_count - 1), 10 ** digit_count) products = itertools.product(digits_range, digits_range) return pool.map(reduce_largest_palindrome2, products) #return reduce(reduce_largest_palindrome, products) class Test(unittest.TestCase): def test_simple(self): self.assertEqual(9, solve_functional_mapreduce(1)) self.assertEqual(9, solve_functional_mapreduce(1)) def test_sample(self): self.assertEqual(9009, solve_functional_mapreduce(2)) def test_answer(self): #self.assertEqual(906609, solve_functional_mapreduce(3)) pass # ----------------------------------------- def run(): return solve(3) if __name__ == '__main__': # unittest.main() pass if __name__ == '__main__': t = timeit.Timer("run()", "from __main__ import run") count = 100 print str(t.timeit(count)) + " seconds for " + str(count) + " runs"
3cef378239c8f79e881d4f265e61802610fb0dfd
yamunaAsokan/guvizen
/loop/factorial.py
207
3.984375
4
n=int(input('enter the input')) a=1 if(n<0): print('not valid value') elif(n==0): print('factorial of 0 is 1') if(n>0): for i in range(1,n+1): a=a*i print('factorial of',n,'is',a)
9a9606fea9e9dfc86321e537f54b81611e01f007
Michaelhuazhang/code_offer
/leetCode/longestPalindromeSubstring.py
861
3.65625
4
# -*- encoding:utf-8 -*- # 查找字符串最长回文 # 依次遍历每一个字符,找到最长的回文 # 回文有奇回文和偶回文,abcba是奇回文,abccba是偶回文 # 回文都是中心对称,找到对称点后,同时向前后寻找回文的最长串即可 # 奇回文和偶回文可以归为同一种情况,即abcba以c为对称点,abccba以cc为对称点, # 但为了代码可读性,可以分开讨论 class Solution: def __find_palindrome(self, s, j, k): while j >= 0 and k < len(s) and s[j] == s[k]: j -= 1 k += 1 if self.maxlen < k - j + 1: self.maxlen = k - j + 1 self.retstr = s[j+1:k] def longestPalindrome(self, s): self.maxlen = 0 self.retstr = "" if len(s) < 2: return s for i in range(len(s)): self.__find_palindrome(s, i, i) self.__find_palindrome(s, i, i+1) return self.retstr
c79e6f70a899e51f30fadb9e71d2a4d5fa8efbdb
wideglide/aoc
/2022/d04/solve.py
994
3.515625
4
#!/usr/bin/env python3 import re import sys RE_C = re.compile(r"(\d+)\-(\d+),(\d+)\-(\d+)") input_file = 'input' if len(sys.argv) == 1 else sys.argv[1] # part 1 data = list(open(input_file).read().strip().split('\n')) overlap = 0 for pair in data: p1, p2 = pair.split(',') a, b = list(map(int, p1.split('-'))) c, d = list(map(int, p2.split('-'))) if (a >= c and b <= d) or (c >= a and d <= b): overlap += 1 print(f" part1 = {overlap}") overlap = 0 for pair in data: a, b, c, d = list(map(int, RE_C.search(pair).groups())) if (a >= c and b <= d) or (c >= a and d <= b): overlap += 1 print(f" part1 = {overlap}") # part 2 overlap = 0 ranges = [] for pair in data: a, b, c, d = list(map(int, RE_C.search(pair).groups())) ranges.extend([b-a, d-c]) if (a >= c and a <= d) or (b >= c and b <= d) or \ (c >= a and c <= b) or (d >= a and d <= b): overlap += 1 print(f" part2 = {overlap}") print(f" MAX range {max(ranges)}")
5a558baadcd4946f246a874fc8fdf7868265e3f1
chyjuls/Computing-in-Python-IV-Objects-Algorithms-GTx-CS1301xIV-Exercises
/Extra_Course_Practice_Problems/practice_problem_25.py
1,440
4.40625
4
#Write a function called delete_from_list. delete_from_list #should have two parameters: a list of strings and a list of #integers. # #The list of integers represents the indices of the items to #delete from the list of strings. Delete the items from the #list of strings, and return the resulting list. # #For example: # # delete_from_list(["a", "b", "c", "d", "e", "f"], [0, 1, 4, 5]) # #...would return the list ["c", "d"]. "a" is at index 0, "b" at 1, #"e" at 4, and "f" at 5, so they would all be removed. # #Remember, though, as you delete items from the list, the #indices of the remaining items will change. For example, once #you delete "a" at index 0, the list will be ["b", "c", "d", #"e", "f"], and now "c" will be at index 1 instead of "b". The #list of indices to delete gives those values' _original_ #positions. # #You may assume that there are no duplicate items in the list #of strings. # #There is more than one way to do this, so if you find yourself #struggling with one way, try a different one! #Write your function here! #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #['c', 'd'] #['a', 'b', 'e', 'f'] # print(delete_from_list(["a", "b", "c", "d", "e", "f"], [0, 1, 4, 5])) # print(delete_from_list(["a", "b", "c", "d", "e", "f"], [2, 3]))
e2fc9ec61ced0ea7d7db3b012ec7cde5125977ec
sfeng77/myleetcode
/countAndSay.py
748
4.0625
4
""" The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string. """ class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ def say(s): if s == "": return "" c = s[0] n = 1 while(n<len(s) and s[n] == c): n += 1 return str(n)+c+say(s[n:]) s = '1' for i in range(1, n): s = say(s) return s
d1d560ba1d96b1d0b521a620d7a6acc57c0dd902
Avenger98/Python-Programms
/List.py
371
3.921875
4
a = [] for i in range(4): num = int(input("Enter the number: ")) a.append(num) print() print("This is list created: ",a) max = a[0] min = a[0] for numbers in a: if numbers > max: max = numbers if numbers < min: min = numbers print() print('This is the maximum number: ', max) print('This is the minimum number: ', min)
a05bae88c9748e5dc5acc75fad6a29a8bece0a59
marikell/eve-platform
/containers/eve-api/api/utils/validate_fields.py
455
3.546875
4
def check_empty_string(string: str, field: str): if not string: raise Exception('Not allowed empty strings for {}.'.format(field)) return True def check_if_key_exists(key: str, obj: dict): if key not in obj: raise Exception('Not allowed empty object for {}.'.format(key)) return True def check_empty_string_in_array(array: [], field:str): for a in array: if check_empty_string(a,field): continue
6bfb15d12b92f78d776e92284038d659e00df9e2
lsjroberts/codeclub
/python/lesson03/decode.py
614
4.125
4
# List of letters in alphabet alphabet = "abcdefghijklmnopqrstuvwxyz" # Secret letter to decode letter = "r" # Secret used to decode the letter secret = 17 # Find the position of the secret letter, this will # be a number between 0 and 25 secret_position = alphabet.find(letter) # Count backward from this position letter_position = secret_position - secret # If we count too far, loop back around if letter_position < 0: letter_position = letter_position + 26 # Now we look up the letter at this secret position letter = alphabet[letter_position] # Output the secret letter to the screen print(letter)
0197c2aed5d2f4cfe404824963a73edec5b050a4
Juma01/Juma_DZ_5
/juma_dz_3.py
856
3.734375
4
# 3. Создать текстовый файл (не программно), # построчно записать фамилии сотрудников и величину их окладов. # Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. # Выполнить подсчет средней величины дохода сотрудников. my_f = open("salary.txt", "r") content = my_f.read() print(f"Содержимое файла: \n {content}") sal = [] mini = [] my_list = content.split('\n') for i in my_list: i = i.split() if float(i[1]) < 20000: mini.append(i[0]) sal.append(i[1]) print(f"Оклад меньше 20.000 {mini}, Средний оклад {sum(map(float, sal)) / len(sal)}") my_f.close()
eb77549f297ff8a260f6092ca07492623b1187a2
timprod13/python_lesson3
/part2.py
569
3.84375
4
def my_info(name, surname, date, city, email, tel_num): print("Привет,", name, "с фамилией", surname, "рождённый", date, "из города", city, "с e-mail", email, "и номером телефона", tel_num) my_info(name=input("Введите имя "), surname=input("Введите фамилию "), date=input("Введите дату рождения "), city=input("Введите город "), email=input("Введите e-mail адрес "), tel_num=input("Введите номер телефона "))
dd5bb715de5f40386a3c56cd1d3450d543721803
ganeshiitr/CPP-Programs
/MyHashMap.py
969
3.859375
4
print "Hello World!\n" class MyHashMap: def __init__(self): self.size=10 self.map=[None]*self.size def insertInToMap(self,key,val): hash = 0 for char in str(key): hash += ord(char) keyHash = hash%self.size keyvalList = [key,val] if self.map[keyHash] is None: self.map[keyHash] = list(keyvalList) return True else: return False def getValue(self,key): hash = 0 for char in str(key): hash += ord(char) keyHash = hash%self.size if self.map[keyHash] is None: return False else: return self.map[keyHash] h = MyHashMap() print (h.insertInToMap('Ganesh',100)) print (h.insertInToMap('Andheri',200)) print (h.insertInToMap('Dolat',300)) print (h.getValue('Andheri'))
b7cb6814afbd2e8e968cc04c327f819467c1254e
faurehu/word_extractor
/reader.py
1,383
3.53125
4
import re TAG_RE = re.compile(r'<[^>]+>') def remove_tags(text): return TAG_RE.sub('', text) def is_time_stamp(l): if l[:2].isnumeric() and l[2] == ':': return True return False def has_letters(line): if re.search('[a-zA-Z]', line): return True return False def has_no_text(line): l = line.strip() if not len(l): return True if l.isnumeric(): return True if is_time_stamp(l): return True if l[0] == '(' and l[-1] == ')': return True if not has_letters(line): return True return False def is_lowercase_letter_or_comma(letter): if letter.isalpha() and letter.lower() == letter: return True if letter == ',': return True return False def clean_up(lines): """ Get rid of all non-text lines and try to combine text broken into multiple lines """ new_lines = [] for line in lines[1:]: if has_no_text(line): continue elif len(new_lines) and is_lowercase_letter_or_comma(line[0]): #combine with previous line new_lines[-1] = new_lines[-1].strip() + ' ' + line else: #append line new_lines.append(remove_tags(line)) return new_lines def read_file(file_name): with open(file_name, encoding='utf-8', errors='replace') as f: lines = f.readlines() if(file_name.split(".")[1] == "srt"): lines = clean_up(lines) return ''.join(x for x in lines)
622740825644a7204844889d3cb41b0a19dbf75b
CS-NF/Intro-Python-II
/src/room.py
1,480
3.75
4
# Implement a class to hold room information. This should have name and # description attributes. class Room: def __init__(self, room_name, description, items=[]): self.room_name = room_name self.description = description self.n_to = None self.s_to = None self.e_to = None self.w_to = None self.items = items def __str__(self): return f"{self.room_name} is {self.description}" def room_direction(self, direction): if direction == "n": return self.n_to elif direction == "s": return self.s_to elif direction == "e": return self.e_to elif direction == "w": return self.w_to else: return None # adds item to rooms # def inventory(self, inventory_items): # malay_weapons = ["Sword", "Axe", "Dagger"] # long_range_weapons = ["Crossbow", "Slingshot", "Throwing axe"] # weak_weapons = ["rock", "stick"] # if inventory_items == self.n_to: # return self.items.append(malay_weapons) # elif inventory_items == self.s_to: # return self.items.append(long_range_weapons) # elif inventory_items == self.e_to: # return self.items.append(malay_weapons) # elif inventory_items == self.w_to: # return self.items.append(weak_weapons) # else: # print("This room has no items to pick up")
94e281628de3cddc19bc84292b1b0974f093ece3
l0he1g/w2vExp
/common/util.py
533
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from nltk.util import ngrams def tokenize(text): """ :return list of tokens """ regex = r"[\u4e00-\ufaff]|[0-9_a-zA-Z\-]+\'*[a-z]*" matches = re.findall(regex, text, re.UNICODE) return matches def ngram_tokenize(text, N): """ :return list of tokens """ chars = tokenize(text) tokens = ngrams(chars, N, pad_left=True, left_pad_symbol="^", pad_right=True, right_pad_symbol="$") tokens = [",".join(t) for t in tokens] return tokens
cbafa61177772e117390087eaba4af6132d52800
aongenae/leetcode
/src/balanced_binary_tree.py
1,186
4
4
#!/usr/bin/env python3 ################################################################################ # # Filename: balanced_binary_tree.py # # Author: Arnaud Ongenae # # Leetcode.com: problem #110 # # Problem description: # https://leetcode.com/problems/balanced-binary-tree/ # ################################################################################ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isBalanced(self, root: TreeNode) -> bool: return self._isBalanced(root)[0] def _isBalanced(self, root: TreeNode) -> tuple[bool, int]: if not root: return True, 0 is_left_balanced, left_height = self._isBalanced(root.left) is_right_balanced, right_height = self._isBalanced(root.right) is_balanced = ( is_left_balanced and is_right_balanced and -1 <= (left_height - right_height) <= 1 ) height = max(left_height, right_height) + 1 return is_balanced, height
f2b9f094467e7e49232e168c61afc36f5166a125
enfiskutensykkel/euler
/1-25/15/pascal.py
324
3.75
4
#!/usr/bin/env python def pascal(n): triangle = [[1], [1,1]] for i in xrange(2,n): row = [] for j in xrange(1, len(triangle[i-1])): row.append(triangle[i-1][j-1] + triangle[i-1][j]) triangle.append([1] + row + [1]) return triangle def grid(dim): tri = pascal(2*dim+1) return tri[2*dim][dim] print grid(20)
8322b1d73f0e8919faafa2063a7ed34ff93666c5
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily2.py
683
4.28125
4
''' Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? ''' def index_product(array): output = [] for i in range(len(array)): product = 1 for k in range(len(array)): product *= array[k] product = product / array[i] output.append(product) return output print (index_product([1, 2, 3, 4, 5]))
032cfcf9799622185d60f992a411a7f4548b750f
gabriellaec/desoft-analise-exercicios
/backup/user_054/ch25_2020_09_30_11_42_04_791479.py
223
3.59375
4
import math v = int(input('qual a velocidade? ')) a = int(input('qual o angulo? ')) g = 9.8 d = v^2 * math.sin(2*a)/g if d < 100: print('Muito perto') elif d > 100: print ('Muito longe') else: print('Acertou!')
99ee51281e4a9fc0eea496fb7b1fd3d1f5458f09
CuongNgMan/alg
/sort/merge.py
527
3.765625
4
#!/usr/bin/env python3.6 import sys sys.path.append('../') def merge(L:list,R:list): result = [] i = j = 0 while i < len(L) and j < len(R): if L[i] < R[j]: result.append(L[i]) i+=1 else: result.append(R[j]) j+=1 result+=L[i:] result+=R[j:] return result def merge_sort(L:list): if len(L) <= 1: return L mid = int(len(L)/2) left = merge_sort(L[:mid]) right = merge_sort(L[mid:]) return merge(left,right)
44fe0b3875c00cfbdc7e3f61667d6e7f47dde7af
oOZeqOo/Projects
/PersonalAssistant/common/weather.py
1,175
3.640625
4
import python_weather import asyncio def say_weather(say): loop = asyncio.get_event_loop() result = loop.run_until_complete(get_weather()) say(result) async def get_weather(): try: # declare the client. format defaults to metric system (celcius, km/h, etc.) client = python_weather.Client(format=python_weather.IMPERIAL) # fetch a weather forecast from a city weather = await client.find("San Antonio") temp_celsius = weather.current.temperature temp_farenheit = int(conv_cel_to_fer(temp_celsius)) # returns the current day's forecast temperature (int) string = f"The current temperature today is {temp_farenheit} degrees fahrenheit in San Antonio" return string # get the weather forecast for a few days for forecast in weather.forecasts: print(str(forecast)) print(str(forecast.date), forecast.sky_text, forecast.temperature) # close the wrapper once done await client.close() return string except SystemExit: client.close() def conv_cel_to_fer(degrees_celsius): return (degrees_celsius * 1.8) + 32
7a01e7bd8664d8fd9c69dec6d30cadb796a5c6ae
goginenigvk/PythonSep_2019
/Datatypes/tupledatatype.py
509
3.765625
4
person=('john',28,200.56) print(person) print(type(person)) names='Sachin','Dravid','Ganguly' print(type(names)) print('-1 output',names[-1]) print(names[2]) print(names[1]) #Dravid names2=('Yuvaraj','Dhoni',20,24,names,(50,29,30)) print(names2) print(names2[4][1]) print(names2[0][2]) numbers=2,6,8,5,9,6,2,['a','b','c'] print(numbers[2:3]) print(numbers[:]) print(numbers.count(9)) print(numbers.index(9)) for i in numbers: print(i) del numbers #please try li =[1,2,8,78,90,32] del li print(li)
873080634c04430329a9e847fb82ab0ba37da79c
C-CEM-TC1028-414-2113/02-decisiones-A01753493-tec
/assignments/09CmaKmMtCm/tests/input_data.py
980
3.546875
4
# List of tuples # Each tuple contains a test: # - the first element are the inputs, # - the second are the output, # - and the third is the message in case the test fails # To test another case, add another tuple input_values = [ # Test case 1 ( ["100"], ["Introduce los cm:", "1 m"], "Revisa tu código", ), # Test case 2 ( ["240005"], ["Introduce los cm:", "2 km", "400 m", "5 cm"], "Revisa tu código", ), # Test case 3 ( ["67"], ["Introduce los cm:", "67 cm"], "Revisa tu código", ), # Test case 4 ( ["300004"], ["Introduce los cm:", "3 km", "4 cm"], "Revisa tu código", ), # Test case 5 ( ["1200500"], ["Introduce los cm:", "12 km", "5 m"], "Revisa tu código", ), ]
2676434f0ad308402d1c90bb6e45c0355ec3bc69
matthew-cheney/kattis-solutions
/solutions/weakvertices.py
748
3.609375
4
def getNeighbors(targ, matrix, excl=None): if excl is None: excl = set() return {my_x for my_x in range(len(matrix[targ])) if matrix[targ][my_x] == '1' and my_x not in excl} while True: N = int(input()) if N == -1: break matr = [] for n in range(N): matr.append(input().split(' ')) weak_verts = set() for i in range(N): neighbors = getNeighbors(i, matr) tri_found = False for neighbor in neighbors: n_neighbors = getNeighbors(neighbor, matr, {i}) if len(neighbors.intersection(n_neighbors)) > 0: tri_found = True if not tri_found: weak_verts.add(i) print(*sorted(list(weak_verts)))
91cbc6e5e0bcc5030d1c5a389d92f433489dd45d
mattnorris/tate
/src/find_scanned_docs.py
2,715
3.75
4
#! /usr/local/bin/python # Title: find_scanned_docs.py # # Description: Traverses a source directory. If PDFs are found, copy them # to the target directory. If no PDF is found, copy all files to # the target directory. # # (This was the convention I used when # uploading my scanned notes to Evernote: if a directory had a # PDF, it meant I combined all relevant JPEGs into a PDF, so just # upload that. If I didn't, I want to upload *all* of the JPEGs.) # # In this case, the target directory is a synced Evernote # directory for uploading files in bulk. # # Author: Matthew Norris # References: http://seagullcanfly.posterous.com/syncing-a-local-folder-to-evernote import os import shutil # TODO: These could be input from the command line. source_dir = 'D:\Documents\gallery_download' target_dir = 'D:\Documents\upload' def getFiles(currentDir): """ Returns a list of files to copy. """ files = [] # Walk directory tree starting at the given directory. for root, dirs, files in os.walk(currentDir): # Reset the flags for each directory. contains_pdf = False pdfs = [] jpgs = [] # Go through each file. for f in files: # If you find a PDF, you'll be grabbing PDF files. fext = os.path.splitext(f)[1].lower() if fext == '.pdf': contains_pdf = True pdfs.append((root, f)) # Otherwise get the JPEGs. elif fext == '.jpeg' or fext == '.jpg': jpgs.append((root, f)) # Prepare the files (if any) to copy. if contains_pdf and pdfs: print '"%s" contains PDF files. Copy only PDFs.' % root print 'Copying %d PDF files.' % len(pdfs) files += pdfs elif jpgs: print '"%s" contains only JPEG files. Copy all of them.' % root print 'Copying %d JPEG files.' % len(jpgs) files += jpgs else: print 'No files found in "%s"' % root return files # TODO: Implement a "dryrun" parameter. def main(): """ Copy PDFs and JPEGs from the source directory. """ print 'Scanning "%s"...\n' % target_dir files = getFiles(source_dir) print '\nPreparing to copy %d files to "%s"...' % (len(files), target_dir) for fileinfo in files: filepath = os.path.join(fileinfo[0], fileinfo[1]) print '.', shutil.copy(filepath, target_dir) print '\nDone.' if __name__ == "__main__": main()
2f7dd02cdf9351e3d69002c51f1ac9acff0666b9
sudhasr/Two-Pointers-2
/mergesortedarrays.py
727
3.8125
4
#Leetcode - wrong answer #Explanation - The idea is to have two pointers at end of each array to compare the values and put #them in appropriate positions class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ nums1len = len(nums1) i = n-1 while i>0 and nums1len >= 0 and m>=0: if nums2[i] > nums1[m]: nums1[nums1len-1] = nums2[i] nums1len -= 1 i -= 1 else: nums1[nums1len] = nums1[m] nums1[m] = 0 nums1len -= 1 m-=1=
4771950a56172f32c004940927f520f9d08fbee9
smoitra87/PythonChallenge
/challenge/p10.py
1,061
3.578125
4
#! /usr/bin/env python import string import urllib2 , bz2, re import pdb import Image, ImageDraw """ solution to problem 10 in pythonchallenge http://www.pythonchallenge.com/pc/return/bull.html The trick is to generate something known as Morris numbers """ def morris(last) : if not last : return None curr = last[0] count = 0 sol = '' for i in range(len(last)) : if last[i] == curr : count += 1 else : sol += str(count)+str(curr) # add string to solution curr = last[i] count = 1 sol += str(count)+str(curr) # to flush the last string return sol def genMorris(N) : for i in range(N) : if i == 0 : last = '1' yield '1' else : last = morris(last) yield last def main() : N = 31 # number of morris numbers needed seq = [last for last in genMorris(N)] # using generators :) print len(seq[30]) #print seq #pdb.set_trace() if __name__ == '__main__' : main()
b4e000b6e2fc02f4cbfcefe07ad8ebc3ae9c446c
sesliu/ULFTP
/ulftp/ulftp.py
2,266
3.515625
4
from ftplib import FTP from Prompt import Prompt import sys, getopt def main(argv): parametro = ' usage: ulftp.py -u <user> -p <password> -s <server> -r <port>[optional]' diretorioAtual = '' usuario = '' senha = '' servidor ='' porta = 21 ftpDados = FTP() try: opts, args = getopt.getopt(argv,"hu:p:s:c:r:") except getopt.GetoptError: print 'there are invalid parameters' print'' print parametro print '' sys.exit(2) for opt,arg in opts: if opt == '-h': print '' print '2015 - Software developed by Ulisses de Castro' print 'this is a basic ftp client' print '' print 'beta version 001' print '' print parametro print '' print 'This help' print '===============================' print '-u => user to connect' print '-p => password to connect' print '-s => FTP server' print '-r => port optional default 21' print '===============================' print '' sys.exit() elif opt in ("-u"): usuario = arg elif opt in ("-p"): senha = arg elif opt in ("-s"): servidor = arg elif opt in("-c"): diretorioAtual = arg elif opt in("-r"): if arg != '': porta = arg else: print 'there are invalid parameters' print'' print parametro print '' if usuario !='' and senha !='' and servidor !='': try: print '' prompt = Prompt() prompt.open(servidor,porta,usuario,senha) prompt.prompt ='>$ ' prompt.cmdloop('Starting prompt...') except Exception, e: print str(e) sys.exit(2) print parametro if __name__ =='__main__': main(sys.argv[1:])
a606e574eb7deba8ad0f9fcdd1f5b049dacee46a
shoroogAlghamdi/test
/Unit4/unit4-demo14.py
87
3.703125
4
# Slide 50 numl = 4 num2 = 3 if not(num2==3): print("True!") else: print("False!")
4ab712d12634fd657260d3c5083604ac0cade610
nykh2010/python_note
/02pythonBase/day08/res/exercise/dict_season.py
720
4.125
4
# 练习: # 1. 写程序,实现以下要求: # 1) 将如下数据形成字典 seasons # 键 值 # 1 '春季有1,2,3月' # 2 '夏季有4,5,6月' # 3 '秋季有7,8,9月' # 4 '冬季有10,11,12月' # 2) 让用户输入一个整数代表这个季度,打印这个季度的信息 # 如果用户输入的信息不存在,则提示用户您查找的信息不存在 seasons = {1: '春季有1,2,3月', 2: '夏季有4,5,6月', 3: '秋季有7,8,9月', 4: '冬季有10,11,12月' } n = int(input("请输入一个数: ")) if n in seasons: print(seasons[n]) else: print("您查找的信息不存在")
3cc5f1bbf8ccb5584b4196979f9ac24fd5138250
DanielF1976/SolarCar
/Gui.py
683
3.578125
4
import tkinter as tk from tkinter import * from tkinter import ttk ws = Tk() Label(ws, text="ISU Solar Car").grid(row=0, column=2) Label(ws, text="MPH").grid(row=1, column=0) Label(ws, text="00000").grid(row=2, column=0) Label(ws, text="RPM").grid(row=1, column=1) Label(ws, text="00000").grid(row=2, column=1) Label(ws, text="Odometer").grid(row=1, column=2) Label(ws, text="00000").grid(row=2, column=2) Label(ws, text="Battery Volt ").grid(row=3, column=0) Label(ws, text="78% ").grid(row=4, column=0) Label(ws, text="Battery Amp").grid(row=3, column=1) Label(ws, text="70%").grid(row=4, column=1) Button(ws, text="Are we there yet button").grid(row=6, column=4) ws.mainloop()
238c39995bd135c69fdea8caf9497898c8723c3f
hemangbehl/Data-Structures-Algorithms_practice
/session4/GroupMultipleOccurrenceInOrderArray.py
334
3.6875
4
def group(arr): if len(arr) <= 2: return arr dict1 = {} for ele in arr: dict1[ele] = dict1.get(ele, 0) + 1 ans = [] for key in dict1.keys(): for i in range(0, dict1[key] ): ans.append(key) return ans arr = [4, 6, 9, 2, 3, 4, 9, 6, 10, 4] print(arr) print(group([arr]) )
99eacfab2d534b8d2176a80585abbf629ccacc6b
Hower/NCSS-2013
/Week 1/Autobiographical_Numbers.py
395
3.890625
4
def addDigits(): total = 0 for char in num: total += int(char) return total def check(): for pos, char in enumerate(num): if num.count(str(pos)) != int(char): return True num = input("Number: ") no = "is not autobiographical" if len(num) != addDigits(): print(num, no) elif check(): print(num, no) else: print (num, "is autobiographical")
68b8dfe75df38b285f2dc53233246144a62c9cdf
FarzanaEva/Data-Structure-and-Algorithm-Practice
/InterviewBit Problems/Array/anti_diagonal.py
662
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 6 02:58:36 2021 @author: Farzana Eva """ """ PROBLEM STATEMENT: Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details. Example: Input: 1 2 3 4 5 6 7 8 9 Return the following : [ [1], [2, 4], [3, 5, 7], [6, 8], [9] ] Input : 1 2 3 4 Return the following : [ [1], [2, 3], [4] ] """ def diagonal(A): anti_diagonal = [[] for i in range(2*len(A) - 1)] for i in range(len(A)): for j in range(len(A)): anti_diagonal[i+j].append(A[i][j]) return anti_diagonal A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(diagonal(A))
855cfeefe041f2f0f6b74216cca0668d305e0865
ITT-21SS-UR/assignment6-modellinginteraction-sc2
/calculator/config_parser.py
1,646
3.59375
4
import json import os import sys from enum import Enum """ Responsible for parsing the json file for the config. If the given config is invalid the system exists and prints out error messages. """ # Author: Claudia # Reviewer: Sarah class ConfigKeys(Enum): PARTICIPANT_ID = "participant_id" TASK = "task" @staticmethod def get_all_values(): return list(map(lambda v: v.value, ConfigKeys)) class ConfigParser: @staticmethod def __exit_program(message="Please give a valid .json file as argument (-_-)\n"): sys.stderr.write(message) sys.exit(1) def __init__(self): self.__config = self.__read_test_config() self.__exit_if_not_valid_config() def __create_json_config(self): with open(self.file_name) as file: return json.load(file) def __read_test_config(self): if len(sys.argv) < 2: self.__exit_program() self.file_name = sys.argv[1] if not os.path.isfile(self.file_name): self.__exit_program("File does not exist (-_-)\n") file_extension = os.path.splitext(self.file_name) if file_extension[-1] == ".json": return self.__create_json_config() else: self.__exit_program() def __exit_if_not_valid_config(self): missing_key = False for key in ConfigKeys.get_all_values(): if key not in self.__config: missing_key = True print("config: no {0} found".format(key)) if missing_key: self.__exit_program() def get_config(self): return self.__config
29c96a0b21786f71005b2c79e10368f755d0f98f
YaserMarey/AI_for_Medicine_deeplearning.ai
/AI_for_Medical_Diagnosis/W_3/utf-8''AI4M_C1_W3_lecture_ex_03.py
14,435
3.953125
4
# coding: utf-8 # # AI4M Course 1 week 3 lecture notebook # ## U-Net model # In this week's assignment, you'll be using a network architecture called "U-Net". The name of this network architecture comes from it's U-like shape when shown in a diagram like this (image from [U-net entry on wikipedia](https://en.wikipedia.org/wiki/U-Net)): # # <img src="U-net_example_wikipedia.png" alt="U-net Image" width="600"/> # # U-nets are commonly used for image segmentation, which will be your task in the upcoming assignment. You won't actually need to implement U-Net in the assignment, but we wanted to give you an opportunity to gain some familiarity with this architecture here before you use it in the assignment. # # As you can see from the diagram, this architecture features a series of down-convolutions connected by max-pooling operations, followed by a series of up-convolutions connected by upsampling and concatenation operations. Each of the down-convolutions is also connected directly to the concatenation operations in the upsampling portion of the network. For more detail on the U-Net architecture, have a look at the original [U-Net paper by Ronneberger et al. 2015](https://arxiv.org/abs/1505.04597). # # In this lab, you'll create a basic U-Net using Keras. # In[1]: # Import the elements you'll need to build your U-Net import keras from keras import backend as K from keras.engine import Input, Model from keras.layers import Conv3D, MaxPooling3D, UpSampling3D, Activation, BatchNormalization, PReLU, Deconvolution3D from keras.optimizers import Adam from keras.layers.merge import concatenate # Set the image shape to have the channels in the first dimension K.set_image_data_format("channels_first") # ### The "depth" of your U-Net # The "depth" of your U-Net is equal to the number of down-convolutions you will use. In the image above, the depth is 4 because there are 4 down-convolutions running down the left side including the very bottom of the U. # # For this exercise, you'll use a U-Net depth of 2, meaning you'll have 2 down-convolutions in your network. # ### Input layer and its "depth" # # In this lab and in the assignment, you will be doing 3D image segmentation, which is to say that, in addition to "height" and "width", your input layer will also have a "length". We are deliberately using the word "length" instead of "depth" here to describe the third spatial dimension of the input so as not to confuse it with the depth of the network as defined above. # # The shape of the input layer is `(num_channels, height, width, length)`, where `num_channels` you can think of like color channels in an image, `height`, `width` and `length` are just the size of the input. # # For the assignment, the values will be: # - num_channels: 4 # - height: 160 # - width: 160 # - length: 16 # In[2]: # Define an input layer tensor of the shape you'll use in the assignment input_layer = Input(shape=(4, 160, 160, 16)) input_layer # Notice that the tensor shape has a '?' as the very first dimension. This will be the batch size. So the dimensions of the tensor are: (batch_size, num_channels, height, width, length) # ## Contracting (downward) path # Here you'll start by constructing the downward path in your network (the left side of the U-Net). The `(height, width, length)` of the input gets smaller as you move down this path, and the number of channels increases. # # ### Depth 0 # # By "depth 0" here, we're referring to the depth of the first down-convolution in the U-net. # # The number of filters is specified for each depth and for each layer within that depth. # # The formula to use for calculating the number of filters is: # $$filters_{i} = 32 \times (2^{i})$$ # # Where $i$ is the current depth. # # So at depth $i=0$: # $$filters_{0} = 32 \times (2^{0}) = 32$$ # # ### Layer 0 # There are two convolutional layers for each depth # Run the next cell to create the first 3D convolution # In[3]: # Define a Conv3D tensor with 32 filters down_depth_0_layer_0 = Conv3D(filters=32, kernel_size=(3,3,3), padding='same', strides=(1,1,1) )(input_layer) down_depth_0_layer_0 # Notice that with 32 filters, the result you get above is a tensor with 32 channels. # # Run the next cell to add a relu activation to the first convolutional layer # In[7]: # Add a relu activation to layer 0 of depth 0 down_depth_0_layer_0 = Activation('relu')(down_depth_0_layer_0) down_depth_0_layer_0 # ### Depth 0, Layer 1 # For layer 1 of depth 0, the formula for calculating the number of filters is: # $$filters_{i} = 32 \times (2^{i}) \times 2$$ # # Where $i$ is the current depth. # - Notice that the '$\times~2$' at the end of this expression isn't there for layer 0. # # # So at depth $i=0$ for layer 1: # $$filters_{0} = 32 \times (2^{0}) \times 2 = 64$$ # # In[8]: # Create a Conv3D layer with 64 filters and add relu activation down_depth_0_layer_1 = Conv3D(filters=64, kernel_size=(3,3,3), padding='same', strides=(1,1,1) )(down_depth_0_layer_0) down_depth_0_layer_1 = Activation('relu')(down_depth_0_layer_1) down_depth_0_layer_1 # ### Max pooling # Within the U-Net architecture, there is a max pooling operation after each of the down-convolutions (not including the last down-convolution at the bottom of the U). In general, this means you'll add max pooling after each down-convolution up to (but not including) the `depth - 1` down-convolution (since you started counting at 0). # # For this lab exercise: # - The overall depth of the U-Net you're constructing is 2 # - So the bottom of your U is at a depth index of: $2-1 = 1$. # - So far you've only defined the $depth=0$ down-convolutions, so the next thing to do is add max pooling # Run the next cell to add a max pooling operation to your U-Net # In[9]: # Define a max pooling layer down_depth_0_layer_pool = MaxPooling3D(pool_size=(2,2,2))(down_depth_0_layer_1) down_depth_0_layer_pool # ### Depth 1, Layer 0 # # At depth 1, layer 0, the formula for calculating the number of filters is: # $$filters_{i} = 32 \times (2^{i})$$ # # Where $i$ is the current depth. # # So at depth $i=1$: # $$filters_{1} = 32 \times (2^{1}) = 64$$ # # Run the next cell to add a Conv3D layer to your network with relu activation # In[10]: # Add a Conv3D layer to your network with relu activation down_depth_1_layer_0 = Conv3D(filters=64, kernel_size=(3,3,3), padding='same', strides=(1,1,1) )(down_depth_0_layer_pool) down_depth_1_layer_0 = Activation('relu')(down_depth_1_layer_0) down_depth_1_layer_0 # ### Depth 1, Layer 1 # # For layer 1 of depth 1 the formula you'll use for number of filters is: # $$filters_{i} = 32 \times (2^{i}) \times 2$$ # # Where $i$ is the current depth. # - Notice that the '$\times 2$' at the end of this expression isn't there for layer 0. # # So at depth $i=1$: # $$filters_{0} = 32 \times (2^{1}) \times 2 = 128$$ # # Run the next cell to add another Conv3D with 128 filters to your network. # In[11]: # Add another Conv3D with 128 filters to your network. down_depth_1_layer_1 = Conv3D(filters=128, kernel_size=(3,3,3), padding='same', strides=(1,1,1) )(down_depth_1_layer_0) down_depth_1_layer_1 = Activation('relu')(down_depth_1_layer_1) down_depth_1_layer_1 # ### No max pooling at depth 1 (the bottom of the U) # # When you get to the "bottom" of the U-net, you don't need to apply max pooling after the convolutions. # ## Expanding (upward) Path # # Now you'll work on the expanding path of the U-Net, (going up on the right side, when viewing the diagram). The image's (height, width, length) all get larger in the expanding path. # # ### Depth 0, Up sampling layer 0 # # You'll use a pool size of (2,2,2) for upsampling. # - This is the default value for [tf.keras.layers.UpSampling3D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/UpSampling3D) # - As input to the upsampling at depth 1, you'll use the last layer of the downsampling. In this case, it's the depth 1 layer 1. # # Run the next cell to add an upsampling operation to your network. # Note that you're not adding any activation to this upsampling layer. # In[12]: # Add an upsampling operation to your network up_depth_0_layer_0 = UpSampling3D(size=(2,2,2))(down_depth_1_layer_1) up_depth_0_layer_0 # ### Concatenate upsampled depth 0 with downsampled depth 0 # # Now you'll apply a concatenation operation using the layers that are both at the same depth of 0. # - up_depth_0_layer_0: shape is (?, 128, 160, 160, 16) # - depth_0_layer_1: shape is (?, 64, 160, 160, 16) # # - Double check that both of these layers have the same height, width and length. # - If they're the same, then they can be concatenated along axis 1 (the channel axis). # - The (height, width, length) is (160, 160, 16) for both. # # Run the next cell to check that the layers you wish to concatenate have the same height, width and length. # In[13]: # Print the shape of layers to concatenate print(up_depth_0_layer_0) print() print(down_depth_0_layer_1) # Run the next cell to add a concatenation operation to your network # In[14]: # Add a concatenation along axis 1 up_depth_1_concat = concatenate([up_depth_0_layer_0, down_depth_0_layer_1], axis=1) up_depth_1_concat # Notice that the upsampling layer had 128 channels, and the down-convolution layer had 64 channels so that when concatenated, the result has 128 + 64 = 192 channels. # ### Up-convolution layer 1 # # The number of filters for this layer will be set to the number of channels in the down-convolution's layer 1 at the same depth of 0 (down_depth_0_layer_1). # # Run the next cell to have a look at the shape of the down-convolution depth 0 layer 1 # In[15]: down_depth_0_layer_1 # Notice the number of channels for `depth_0_layer_1` is 64 # In[16]: print(f"number of filters: {down_depth_0_layer_1._keras_shape[1]}") # In[17]: # Add a Conv3D up-convolution with 64 filters to your network up_depth_1_layer_1 = Conv3D(filters=64, kernel_size=(3,3,3), padding='same', strides=(1,1,1) )(up_depth_1_concat) up_depth_1_layer_1 = Activation('relu')(up_depth_1_layer_1) up_depth_1_layer_1 # ### Up-convolution depth 0, layer 2 # # At layer 2 of depth 0 in the up-convolution the next step will be to add another up-convolution. The number of filters you'll want to use for this next up-convolution will need to be equal to the number of filters in the down-convolution depth 0 layer 1. # # Run the next cell to remind yourself of the number of filters in down-convolution depth 0 layer 1. # In[18]: print(down_depth_0_layer_1) print(f"number of filters: {down_depth_0_layer_1._keras_shape[1]}") # As you can see, the number of channels / filters in `down_depth_0_layer_1` is 64. # Run the next cell to add a Conv3D up-convolution with 64 filters to your network. # In[19]: # Add a Conv3D up-convolution with 64 filters to your network up_depth_1_layer_2 = Conv3D(filters=64, kernel_size=(3,3,3), padding='same', strides=(1,1,1) )(up_depth_1_layer_1) up_depth_1_layer_2 = Activation('relu')(up_depth_1_layer_2) up_depth_1_layer_2 # ### Final Convolution # # For the final convolution, you will set the number of filters to be equal to the number of classes in your input data. # # In the assignment, you will be using data with 3 classes, namely: # # - 1: edema # - 2: non-enhancing tumor # - 3: enhancing tumor # # Run the next cell to add a final Conv3D with 3 filters to your network. # In[20]: # Add a final Conv3D with 3 filters to your network. final_conv = Conv3D(filters=3, #3 categories kernel_size=(1,1,1), padding='valid', strides=(1,1,1) )(up_depth_1_layer_2) final_conv # ### Activation for final convolution # # Run the next cell to add a sigmoid activation to your final convolution. # In[21]: # Add a sigmoid activation to your final convolution. final_activation = Activation('sigmoid')(final_conv) final_activation # ### Create and compile the model # # In this example, you will be setting the loss and metrics to options that are pre-built in Keras. However, in the assignment, you will implement better loss functions and metrics for evaluating the model's performance. # # Run the next cell to define and compile your model based on the architecture you created above. # In[22]: # Define and compile your model model = Model(inputs=input_layer, outputs=final_activation) model.compile(optimizer=Adam(lr=0.00001), loss='categorical_crossentropy', metrics=['categorical_accuracy'] ) # In[23]: # Print out a summary of the model you created model.summary() # ### Congratulations! You've created your very own U-Net model architecture! # Next, you'll check that you did everything correctly by comparing your model summary to the example model defined below. # # ### Double check your model # # To double check that you created the correct model, use a function that we've provided to create the same model, and check that the layers and the layer dimensions match! # In[24]: # Import predefined utilities import util # In[25]: # Create a model using a predefined function model_2 = util.unet_model_3d(depth=2, loss_function='categorical_crossentropy', metrics=['categorical_accuracy']) # In[26]: # Print out a summary of the model created by the predefined function model_2.summary() # #### Look at the model summary for the U-Net you created and compare it to the summary for the example model created by the predefined function you imported above. # #### That's it for this exercise, we hope this have provided you with more insight into the network architecture you'll be working with in this week's assignment!
f964d8c26e7370c501a764e606bcebc6a6984dcf
SergioTA01229274/Python-Code
/Secondpartial/Game.py
751
3.96875
4
import random def game(n1, n2): lim1 = n1 lim2 = n2 answer = bool() while answer: number = random.randint(lim1, lim2) print("The number I'm thinking is: ", number) feedback = input("The number you're thinking is: ") feedback = feedback.lower() try: if feedback == "equal": print("Thanks for playing with me") answer = True else: if feedback == "higher": lim1 = number elif feedback == "lower": lim2 = number except ValueError: print("That is not a word, try it again") game(30, 230)
a25a53f60fb3fa10e5cf7c261a193fe358c85a87
dzampar/curso_python
/Exercicios/ex059.py
1,509
4.125
4
print("Insira dois valores abaixo") valor1 = float(input("Primeiro Valor:")) valor2 = float(input("Segundo Valor:")) opcao = 0 while opcao != 5: print(' [ 1 ]Somar\n' ' [ 2 ]Multiplicar\n' ' [ 3 ]Maior\n' ' [ 4 ]Novos numeros\n' ' [ 5 ]Sair') opcao = int(input(">>>>>Qual a sua opção?")) #if menu == 5: # sair = 5 if opcao == 1: soma = valor1 + valor2 print("A soma entre {} + {} é {}\n" "===========================".format(valor1,valor2,soma)) elif opcao == 2: multiplicar = valor1 * valor2 print("A multiplicação entre {} x {} é {}\n" "===========================".format(valor1,valor2,multiplicar)) elif opcao == 3: if valor1 > valor2: maior = valor1 print("O maior valor entre {} e {} é {}\n" "===========================".format(valor1,valor2,maior)) if valor1 < valor2: maior = valor2 print("O maior valor entre {} e {} é {}\n" "===========================".format(valor1,valor2,maior)) if valor1 == valor2: print("Os valores {} e {} são iguais\n" "=======================".format(valor1,valor2)) elif opcao == 4: print("Insira os valores novamente") valor1 = float(input("Primeiro Valor:")) valor2 = float(input("Segundo Valor:")) print("=-"*10) print('Fim do programa, obrigado!!!') print("=-"*10)
cde08ebd614b81d65993f51a8a1618e6d2e9b300
sonukrishna/Anandh_python
/chapter_2/q21_wrap.py
200
3.609375
4
''' wrap the file as per the given length ''' def wrap(filename,n): for i in open(filename): if len(i)>n : print i[0:n] print i[n:len(i)] else: print i wrap('she.txt',30)
e2a7694dfc492769306b9ce9227037edeb19e100
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_203/252.py
1,998
3.875
4
#!/usr/bin/python def fill(cake): r = len(cake) if r == 0: return cake c = len(cake[0]) if c == 0: return cake chars = [] for i in range(0,r): count = c for j in range(0,c): if cake[i][j] == '?': count -= 1 chars.append(count) for i in range(0, r): if not chars[i] == 0: # begin to fill the blank on that line l = [] for j in range(0,c): l.append(cake[i][j]) j = 0 while (l[j] == '?'): j += 1 letter = l[j] for k in range(0,j): l[k] = letter while (j < len(l)): if l[j] == '?': l[j] = letter j += 1 else: letter = l[j] j += 1 l = ''.join(l) cake.pop(i) cake.insert(i, l) chars[i] == c # then fill in the # print "inside function cake:" # print cake i = 0 while (i < len(cake) and chars[i] == 0): i += 1 if i == len(cake): return cake else: l = cake[i] #print "inside function cake:" #print cake for k in range(0,i): cake.pop(k) cake.insert(k, l) #print "inside function cake:" #print cake for k in range(i, len(cake)): if chars[k] == 0: cake.pop(k) cake.insert(k, l) else: l = cake[k] return cake if __name__ == "__main__": t = int(raw_input()) for i in range(0,t): s = raw_input() r, c = int(s.split()[0]), int(s.split()[1]) cake = [] for j in range(0,r): cake.append(raw_input()) # now I have the cake cake = fill(cake) print "Case #" + str(i + 1) + ":" for j in range(0,r): print cake[j]