blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
40d18a6d692ccd9d75134c793a5e3d1731a09222
navneethkour/LeetCode-Python-1
/Number/CountPrimes.py
487
3.671875
4
# https://leetcode.com/problems/count-primes/ # Count the number of prime numbers less than a non-negative number, n. # https://discuss.leetcode.com/topic/65044/python-beat-99-97-with-idea-discription def countPrimes(self, n): if n <= 2 : return 0 res = 1 trueTable = [True]*n trueTable[0:2] = [False]*2 for i in range(2,int(n ** 0.5) + 1) : if trueTable[i] == True : trueTable[i*2:n:i] = [False]*((n - 1 - i*2)/i + 1) return sum(trueTable)
7f44f3f0828f4328ea9eb7329af06983ddde8962
ACronje/rpc_microservice_challenge
/rpc_microservice_challenge/lib/square_odd_numbers.py
103
3.671875
4
def square_odd_numbers(*numbers): return [pow(number, 2) for number in numbers if number % 2 != 0]
382284dff526c17b857e5f3b7e081e0a0d4f92d6
tamasbrandstadter/python-learning
/week3/day1/carrier.py
1,927
3.515625
4
class Carrier(object): def __init__(self, ammo_store=500, hp=50): self.__aircrafts_f35 = [] self.__aircrafts_f16 = [] self.__ammo_store = ammo_store self.__hp = hp def add(self, aircraft): if aircraft.get_type() == 'F35': self.__aircrafts_f35.append(aircraft) else: self.__aircrafts_f16.append(aircraft) def fill(self): if self.__ammo_store == 0: raise ValueError('Ammo store is empty') required_ammo_for_f35s = 0 for f35 in self.__aircrafts_f35: required_ammo_for_f35s += f35.get_missing_ammo() required_ammo_for_f16s = 0 for f16 in self.__aircrafts_f16: required_ammo_for_f16s += f16.get_missing_ammo() required_total = required_ammo_for_f35s + required_ammo_for_f16s if required_total > self.__ammo_store: for f35 in self.__aircrafts_f35: missing = f35.get_missing_ammo() if missing > self.__ammo_store: print('Cannot refill, empty ammo store') break f35.refill(missing) self.__ammo_store -= missing else: for f35 in self.__aircrafts_f35: missing = f35.get_missing_ammo() f35.refill(missing) self.__ammo_store -= missing for f16 in self.__aircrafts_f16: missing = f16.get_missing_ammo() f16.refill(missing) self.__ammo_store -= missing def fight(self, other_carrier): total_dmg = 0 for f35 in self.__aircrafts_f35: total_dmg += f35.fight() for f16 in self.__aircrafts_f16: total_dmg += f16.fight() other_carrier.lower_hp(total_dmg) def get_hp(self): return self.__hp def lower_hp(self, dmg): self.__hp -= dmg
b6dd08888427a0ca2cef7d1ae9e662a7221a7db1
chesta123/PYTHON-codes
/tut11 dictationary.py
414
4.15625
4
mydict = {"drishti":"technical club of svnit","chrd":"fun club","acm":"coding club"} print("enter any name") word=input() print(mydict[word]) # my dictionary tells the hindi translation of words mydict={"crap" : "bakwas", "awesome" : "mast", "beautiful" : "sundar" } print("enter any english word,your options are",mydict.keys()) a = input() print("hindi translation is ",mydict[a] )
89bc7a5b6e474869e7e7d71d1e2397dbfaf4027e
saikrishna6415/python-problem-solving
/longestpalindrome.py
463
3.65625
4
def longestPalindrome(A): rev = A[::-1] l = len(A) while l > 0: for i in range(0, len(A) - l + 1): half = int(l / 2) print(half) left = A[i : i + half] print(left) right = rev[len(A) - (i + l) : len(A) - (i + l - half)] print(right) if left == right: return A[i:i+l] l -= 1 return None print(longestPalindrome("forgeeksskeegfor"))
95aa2c6add87cec2b9bc80820725ff2dd7a5aa7f
jsmack/learn
/old/language/python/udemy/kame-python/basic/11_format.py
106
3.890625
4
print('Assignment is {}'.format("hoge")) name = "John" print("Hey, {}!! How are you doing?".format(name))
e55c323d4858123e674d83470098caa03a19fbfb
Kunj-Rajput/Python_task_1
/# task 1 q 5.py
179
3.921875
4
# task 1 q 5 x= eval (input ('Enter the value for x')) y= eval (input ('Enter the value for y')) z= x+y+30 #a=z + '30' print ('Final Output: {}'.format(z)) # python version 3
308efd5517fe52b04d636f9b6b3e7da04e8f4025
royabouhamad/Algorithms
/Sorting/MergeSort.py
774
3.953125
4
def mergeSort(list): if len(list) > 1: mid = len(list)/2 leftHalf = list[:mid] rightHalf = list[mid:] mergeSort(leftHalf) mergeSort(rightHalf) i, j, k = 0, 0, 0 while i < len(leftHalf) and j < len(rightHalf): if leftHalf[i] < rightHalf[j]: list[k] = leftHalf[i] i += 1 else: list[k] = rightHalf[j] j += 1 k += 1 while i < len(leftHalf): list[k] = leftHalf[i] i += 1 k += 1 while j < len(rightHalf): list[k] = rightHalf[j] j += 1 k += 1 numbers = [11, 2, 32, 9, 29, 0, 15, 40, 8, 1, 37] mergeSort(numbers) print(numbers)
696fbf428e0bc1780c8e40a0a279497baa1b012e
leonardodamasio/learningPython.py
/Python_if_elif_else.py
708
3.84375
4
# coding: utf-8 # In[ ]: nome= str(input("Digite seu nome:\n")) idade = int(input("\nDigite sua idade:\n")) print("\n{0}, sua idade é {1} anos.".format(nome, idade)) if idade >= 18: def func(): cnh = input("\nVocê já tirou sua habilitação? (s/n)\n") if (cnh == "s") or (cnh == "n"): if cnh == "s": print("\nEntão, você já pode dirigir.") elif cnh == "n": print("\nVocê ainda não pode dirigir. Primeiro é necessário ser habilitado.") else: cnh == print("\nDigite um valor válido! (s/n)") func() func() else: print("\nVocê ainda não pode dirigir.")
ac25029d0cc88a44138c4616479570ad63a54968
singularitti/lazy-property
/lazy_property/__init__.py
4,026
3.625
4
__version__ = "0.0.1" from functools import update_wrapper class LazyProperty(property): def __init__(self, method, fget=None, fset=None, fdel=None, doc=None): """ Create an instance of a ``LazyProperty`` (or ``LazyWritableProperty``) inside a class ``C``'s declaration, this instance will be a class variable, just like a normal descriptor. You can access it by ``C.<method_name>``. :param method: The method which you want to cache. This is different from ``property`` which only takes *fget*, *fset*, *fdel* and *doc*. It is because that ``property`` already assumes that you have a hidden attribute ``_x`` and some ``getx`` and ``setx`` methods. But now you have to create it by yourself. :param fget: Usually ``None``. :param fset: For a ``LazyProperty`` instance, a ``__set__`` method inherits from ``property.__set__``. Thus it will directly call that ``__set__``. Since the default *fset* is ``None``, the ``property.__set__`` method will raise an ``AttributeError``. But for a ``LazyWritableProperty``, this will not happen since a ``__set__`` method is given and overrides the ``property.__set__`` method. :param fdel: Usually ``None``. :param doc: It will get the *method*'s documentation if it is given. """ self.method = method self.cache_name = "_{}".format(self.method.__name__) doc = doc or method.__doc__ super(LazyProperty, self).__init__(fget=fget, fset=fset, fdel=fdel, doc=doc) # Transfer attribute from *method*. update_wrapper(self, method) def __get__(self, instance, owner): """ Overrides ``__get__`` method inherits from ``property``. Once you get an attribute in the instance with ``self.method.__name__``, it will add ``self.cache_name`` into ``instance.__dict__``, then next time you try to get it, it will directly get ``instance.__dict__[self.cache_name]``. That is how it works. :param instance: The instance of the class ``c`` where this ``LazyProperty`` is declared. :param owner: The class ``C`` where this ``LazyProperty`` is declared. :return: The result calculated by ``self.method(instance)`` or by ``self.fget(instance)``. """ if instance is None: # If you call from class of the instance ``c``, e.g., ``C.<method_name>``, you will # get a ``LazyProperty`` instance. return self if hasattr(instance, self.cache_name): # Second time you call a property decorated, it will find ``_<method_name>`` in ``instance.__dict__``. result = getattr(instance, self.cache_name) else: if self.fget is not None: # Usually not used. result = self.fget(instance) else: result = self.method(instance) # First time you call a property decorated, this value is set in the *instance*. setattr(instance, self.cache_name, result) return result def getter(self, fget): return type(self)(self.method, fget, self.fset, self.fdel, self.__doc__) class LazyWritableProperty(LazyProperty): def __set__(self, instance, value): """ If you add this method directly into the definition of ``LazyProperty``, then you cannot make a read-only property by it. :param instance: The instance of the class where this ``LazyProperty`` is declared. :param value: The value you want to set for ``instance.__dict__[self.cache_name]``. :return: No return. """ if instance is None: raise AttributeError if self.fset is None: setattr(instance, self.cache_name, value) else: self.fset(instance, value) def setter(self, fset): return type(self)(self.method, self.fget, fset, self.fdel, self.__doc__)
9a940834e90a446c77d91ba4f5e5568358560f0a
santosdave/assignment
/assignment/a program to sum two numbers.py
106
3.546875
4
numa = 20 numb = 30 sum = numa + numb print("Sum of {0} and {1} is {2}" .format(numa, numb, sum))
1138aeeb7c8e087dfb2c847436630bfcbf57dd86
sharadbhat/Competitive-Coding
/LeetCode/Short_Encoding_Of_Words.py
419
3.5625
4
# LeetCode # https://leetcode.com/problems/short-encoding-of-words/ class Solution: def minimumLengthEncoding(self, words): """ :type words: List[str] :rtype: int """ words = set(words) words2 = words.copy() for word in words2: for i in range(1, len(word)): words.discard(word[i:]) return sum([len(i) + 1 for i in words])
8b69569af9b24f3bc5a091420b0216528d1e5bf8
mosesxie/CS1114
/HW #4/hw4q3.py
667
3.984375
4
userExpression = input("Enter a mathematical expression: ") spaceIndex1 = userExpression.find(" ") spaceIndex2 = userExpression.find(" ", spaceIndex1 + 1) firstNumber = int(userExpression[:spaceIndex1]) secondNumber = int(userExpression[spaceIndex2 + 1:]) if userExpression[spaceIndex1 + 1: spaceIndex2] == "+": answer = firstNumber + secondNumber if userExpression[spaceIndex1 + 1: spaceIndex2] == "-": answer = firstNumber - secondNumber if userExpression[spaceIndex1 + 1: spaceIndex2] == "*": answer = firstNumber * secondNumber if userExpression[spaceIndex1 + 1: spaceIndex2] == "/": answer = firstNumber / secondNumber print(answer)
776e35c626cb41c06bf225341f102351643cba2b
carlosgm128/python
/generadores2.py
277
3.890625
4
print("Generador 2") print("Un generador es una calse especian de funcion por la que nos permite generar valores los que podemos iterar") print("Ejemplo") def generador(n,m,s): while(n <= m): yield n n += s print("Si llamas la funcion Generador con 3 parapetros")
f45e8ef92652ec4eb2bb644608f0a4085c238714
daranzolin/codewars
/kata.py
2,963
4.3125
4
"""" A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10. """" def narcissistic( value ): d = [int(x) for x in list(str(value))] e = len(d) sum_out = sum([x**e for x in d]) return sum_out == value """" Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). """" import re def to_camel_case(text): inds = [m.start() for m in re.finditer('_|-', text)] if len(inds) == 0: return '' fc = text[0] == text[0].upper() tl = list(text) for i in inds: tl[i+1] = tl[i+1].upper() tl[i] = '' return ''.join(tl) """" Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2. """" def in_array(array1, array2): out = [] for x in array1: for x2 in array2: if x in x2: out.append(x) return sorted(list(set(out))) """" Your task is to write a function called valid_spacing() or validSpacing() which checks if a string has valid spacing. The function should return either True or False. For this kata, the definition of valid spacing is one space between words, and no leading or trailing spaces. """" import regex as re def valid_spacing(s): if s == "": return True w = re.findall(r"\w+", s) return s.count(" ") == len(w) - 1 """" Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. """" def duplicate_count(text): els = list(text.lower()) els_unique = set(els) n_distinct = 0 for el in els_unique: n = els.count(el) if n > 1: n_distinct += 1 return n_distinct """" Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b keeping their order. """" def array_diff(a, b): unique_b = set(b) new_a = [] for el in a: if el not in unique_b: new_a.append(el) return(new_a) """" Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. """" def create_phone_number(n): sn = "".join([str(int) for int in n]) return "(%s) %s-%s" % ("".join(sn[0:3]), sn[3:6], sn[6:])
3ef9183a5391bb813baa201a3adccd676c49f421
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Variables.py
809
4.21875
4
# clic derecho sobre el nombre del archivo (Pestaña superior) en # "Open Preview to the side" para ver como funcionara el programa # en tiempo real y con los valores de las variable. x = 3 y = 5 z = x + y print(z); w = z #Aca "w" y "z" ocupan la misma dirección de memoria #id(x) #Eso sirve para visualisar la dirección de memoria, #pero solo en el IDE de Python a = 1 # int b = 1.2 # float c = "Hola" # string d = False # bool print(c + str(x + y)) #Para concatenear strings con numeros se deben convertir primero print(c, x + y) #Al usar coma si se pueden concatenar pero siempre agrega un espacio num1 = 1 num2 = 2 resultado = num1 < num2 #Esto es un IF implicito print(resultado) if(num1 < num2): print("El valor num1 es menor que num2") else: print("El valor num1 no es menor que num2")
2621bf93b2bcf8a9d94a31e673ce79b5869fbb78
JerryHaaser/Sorting
/src/iterative_sorting/iterative_sorting.py
1,062
4.09375
4
# TO-DO: Complete the selection_sort() function below thing = [7, 15, 2, 58, 9] def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) print("cur_index- ", cur_index) print("smallest_index-", smallest_index) if smallest_index <= cur_index: print("made it") cur_index += 1 elif smallest_index > cur_index: smallest_index = cur_index cur_index += 1 # # TO-DO: swap return arr print(selection_sort(thing)) # TO-DO: implement the Bubble Sort function below def bubble_sort( arr ): #Get first two elements 0, 1 slot1 = 0 slot2 = 1 #compare 0 <= 1 #swap if false #move to elements 1,2 #repeat until there are zero swaps return arr # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): return arr
a0b17b335f0d27e18d1d24af6b89ad6bc67b0f17
fernandavincenzo/exercicios_python
/0-25/013_Aumento.py
138
3.515625
4
s = float(input('Qual é o seu salário? ')) ns = s+(15*s/100) print('O seu novo salário, com o aumento de 15% é de {:.2f}'.format(ns))
e4bee5eb52e44c487138d870a30efe9e9d0ad8a3
arpiagar/HackerEarth
/magic_dictionary/magic_dict.py
1,311
3.578125
4
class MagicDictionary { /** Initialize your data structure here. */ public MagicDictionary() { this.trie = new Trie(); } /** Build a dictionary through a list of words */ public void buildDict(String[] dict) { for (int i =0; i < dict.length; i++){ String word = doct[i]; addWordtoTrie(word); } return; } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ public boolean search(String word) { } } class Trie { Node root; public void Trie(){ this.root = new Node(); } public Node addWordToTrie(Node root, String word){ if word.length() == 1 if (root.NodeMap.get(word[i]) ){ addWordToTrie(root.NodeMap.get(word[i]), word.substring(1,word.length())) } else{ root.NodeMap.put(word[i], new Node()); } } } class Node { String nodeKey; Map<String,Object> nodeMap; public Node(String c){ this.nodeKey = c; this.nodeMap(); } } /** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * boolean param_2 = obj.search(word); */
29f6dab79c501d94fe299aef49fc56c66d8a73bf
Hixtink/Matplotlib_Tutorials
/01_绘制直线.py
379
3.71875
4
import matplotlib.pyplot as plt; import numpy as np; """ matplotlib官方教学教程网址:https://matplotlib.org/tutorials/index.html 构建一条y = 2x + 1 的直线 """ # 构建X方向的值, 1.初始值 2.结束值 3.分成多少份 X = np.linspace(-5,5,10); # 构建Y方向的值 Y = 2*X + 1; # 绘制直线, X ,Y 的坐标点 plt.plot(X,Y); # 显示 plt.show();
ceafed9040c05c4e1b147558d7b8c5e95017a45d
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/3f35b7dbbd81440fa5d12b0e7b229825.py
222
3.953125
4
def square_of_sum(num): return sum([x for x in range(num + 1)])**2 def sum_of_squares(num): return sum([x**2 for x in range(num + 1)]) def difference(num): return square_of_sum(num) - sum_of_squares(num)
e2df939dc8ca442ce7e5e7f20e56a9a57b11de80
apolanco18/CS334
/HW1/q1.py
2,787
3.796875
4
import numpy as np import numpy.testing as npt import time def gen_random_samples(): """ Generate 5 million random samples using the numpy random.randn module. Returns ---------- sample : 1d array of size 5 million An array of 5 million random samples """ ## TODO FILL IN ## Generates a 1-D array of random numbers with inputed length sample = np.random.randn(5000000) return sample def sum_squares_for(samples): """ Compute the sum of squares using a forloop Parameters ---------- samples : 1d-array with shape n An array of numbers. Returns ------- ss : float The sum of squares of the samples timeElapse: float The time it took to calculate the sum of squares (in seconds) """ timeElapse = 0 ss = 0 ## TODO FILL IN avg = 0 timeElapse = time.time() ## Finds the sum of all the values in array the divide by len of array for i in samples: avg += i avg /= len(samples) temp = 0 ## Finds the sum of square by subtracte mean by each value, then squaring those values, finally summing all the square values for i in samples: temp = i - avg ss += (temp * temp) ## Calculates the Time Elaose timeElapse = time.time() - timeElapse return ss, timeElapse def sum_squares_np(samples): """ Compute the sum of squares using Numpy's dot module Parameters ---------- samples : 1d-array with shape n An array of numbers. Returns ------- ss : float The sum of squares of the samples timeElapse: float The time it took to calculate the sum of squares (in seconds) """ timeElapse = 0 ss = 0 ## TODO FILL IN timeElapse = time.time() ## Calculates the avg by using numpy functions ## sum functions adds all the values in array then divide by number of arr avg = np.sum(samples) / len(samples) ## Created an arr of the avg and then subtract that arr by the samples arr avgArr = np.full((len(samples)),avg) temp = np.subtract(samples,avgArr) ## Dot product of vals to find the sum of squares ss = np.dot(temp,temp) timeElapse = time.time() - timeElapse return ss, timeElapse def main(): # generate the random samples samples = gen_random_samples() # call the sum of squares ssFor, timeFor = sum_squares_for(samples) # call the numpy version ssNp, timeNp = sum_squares_np(samples) # make sure they're the same value npt.assert_almost_equal(ssFor, ssNp, decimal=5) # print out the values print("Time [sec] (for loop):", timeFor) print("Time [sec] (np loop):", timeNp) if __name__ == "__main__": main()
fab0b63c044f03fbe961a5e7cb5b29ea7d705361
danghuuken/ZenReach
/functional_test.py
1,951
3.5625
4
import unittest import magic_sauce import os class HighestSuitibilityScoreTest(unittest.TestCase): # Read in test input file def setUp(self): test_input_file_dir = os.path.join(os.getcwd(), "TestInputFiles") self.simple_customer_input = os.path.join(test_input_file_dir, "simple_customer_input.txt") self.test_input_1 = os.path.join(test_input_file_dir, "test_input1.txt") def tearDown(self): pass def test_taking_input_file_and_return_highest_SS_score_per_case(self): #loop through the amount of test cases there are for test_case in magic_sauce.seperate_test_cases(self.test_input_1): evaluation = magic_sauce.eval_test(test_case) print("Overall Score is: {0:.2f}".format(evaluation[0])) print("Here is the list of top scores: ") print(evaluation[1]) self.fail('Finish functional test') # A Test to take in a simple input file of one customer and 3 products, and seeing what # product has the highest score for the customer. def test_one_customer_and_three_products(self): #read in the file. file_data = magic_sauce.read_file(self.simple_customer_input) # Get list of customers customers = magic_sauce.get_customers(file_data) # Get list of products products = magic_sauce.get_products(file_data) highest_score = 0 highest_product_name = "" #Pass in file string into single SS calculator for customer in customers: for product in products: score = magic_sauce.single_SS_eval(customer, product) if score > highest_score: highest_score = score highest_product_name = product # return the highest score print(str(highest_score) + " " + product) def test_best_customer_per_product(self): file_data = magic_sauce.read_file(self.simple_customer_input) customers = magic_sauce.get_customers(file_data) products = magic_sauce.get_products(file_data) for product in products: pass if __name__ == '__main__': unittest.main(warnings='ignore')
9810f97d3d2d0e0b83383a7825c857622bcf2643
godoydud/ClassCodes
/Lista Repetições/ex5.py
498
3.703125
4
numeros = list(map(int, input().split())) # Entrada de dados soma = 0 # Seta as variáveis em 0 qntd = 0 for num in numeros: soma = soma + num # Soma recebe soma + num digitado media = soma/len(numeros) # Calculo da média, soma dividido pela quantidade de números digitados for num in numeros: if num < media: # Se o numero digitado for menor que a média qntd += 1 # Soma-se +1 na variável quantidade print(media) print("Temos %d notas menores que a média." %(qntd))
fd09cebdb6500a98c3aefebcaf43909924235597
wanlq623/Studypython
/basic/less14.py
831
4.5
4
# 请补全以下代码: class Person: def __init__(self,name): self.name = name def show(self): print('大家注意了!') print('一个叫“%s”的人来了。' % self.name) # 子类的继承和定制 class Man(Person): def __init__(self): Person.__init__(self,name='范罗苏姆') def show(self): print('大家注意了!') print('一个叫“%s”的男人来了。' % self.name) def leave(self): print('大家注意了!') print('那个叫“%s”的男人留下了他的背影。' % self.name) author1 = Person('吉多') author1.show() # author1.leave() # 补全代码后,运行该行会报错:AttributeError:'Person' object has no attribute 'leave'. author2 = Man() author2.show() author3 = Man() author3.leave()
1a25c8c5aa1c152344fe9bdbeba0195042e43b9f
TheGreatSea/Traduc
/ex.py
3,839
3.765625
4
class data: def __init__(self, name, types, value): self.name = name self.types = types self.value = value def verifyVariable(variable): try: variable = int(variable) return variable except ValueError: print("error") pass pc = 0 while (pc < len(cuadruplos)): #print ("Program counter: ", pc) if (cuadruplos[pc][0] == 'PRINT'): print_var = verifyVariable(cuadruplos[pc][3].value) if(cuadruplos[pc][3].name == 'None'): print(print_var.value) elif(cuadruplos[pc][3].value == 0): print(cuadruplos[pc][3].name) else: print(cuadruplos[pc][3].name , print_var.value) pc += 1 continue if (cuadruplos[pc][0] == 'TAKE'): input_var = verifyVariable(cuadruplos[pc][3].value) input_var.value = input(cuadruplos[pc][3].name + " ") pc += 1 continue if (cuadruplos[pc][1] != '-'): a = verifyVariable(cuadruplos[pc][1]) #print("a= ", a.value) if (cuadruplos[pc][2] != '-'): b = verifyVariable(cuadruplos[pc][2]) #print("b= ", b.value) c = verifyVariable(cuadruplos[pc][3]) #print("c= ", c.value) if (cuadruplos[pc][0] == '+'): c.value = a.value + b.value pc += 1 elif (cuadruplos[pc][0] == '-'): c.value = a.value - b.value pc += 1 elif (cuadruplos[pc][0] == '*'): c.value = a.value * b.value pc += 1 elif (cuadruplos[pc][0] == '/'): c.value = a.value / b.value pc += 1 elif (cuadruplos[pc][0] == '='): if c.type == 'FLOAT': c.value = round(float(a.value),4) elif c.type == 'WORD': c.value = int(a.value) else: c.value = a.value pc += 1 elif (cuadruplos[pc][0] == '=='): checkBooleanOperation (a ,b) if (a.type == 'WORD'): c.type = 'WORD' elif (a.type == 'FLOAT'): c.type = 'FLOAT' c.value = a.value == b.value pc += 1 elif (cuadruplos[pc][0] == '>='): checkBooleanOperation (a ,b) if (a.type == 'WORD'): c.type = 'WORD' elif (a.type == 'FLOAT'): c.type = 'FLOAT' c.value = a.value >= b.value pc += 1 elif (cuadruplos[pc][0] == '<='): checkBooleanOperation (a,b) if (a.type == 'WORD'): c.type = 'WORD' elif (a.type == 'FLOAT'): c.type = 'FLOAT' c.value = a.value <= b.value pc += 1 elif (cuadruplos[pc][0] == '>'): checkBooleanOperation (a ,b) if (a.type == 'WORD'): c.type = 'WORD' elif (a.type == 'FLOAT'): c.type = 'FLOAT' c.value = a.value > b.value pc += 1 elif (cuadruplos[pc][0] == '<'): checkBooleanOperation (a ,b) if (a.type == 'WORD'): c.type = 'WORD' elif (a.type == 'FLOAT'): c.type = 'FLOAT' c.value = a.value < b.value pc += 1 elif (cuadruplos[pc][0] == '!='): checkBooleanOperation (a ,b) if (a.type == 'WORD'): c.type = 'WORD' elif (a.type == 'FLOAT'): c.type = 'FLOAT' c.value = a.value != b.value pc += 1 elif (cuadruplos[pc][0] == 'gotoF'): if(a.value == False): pc = c.value else: pc += 1 elif (cuadruplos[pc][0] == 'goto'): pc = c.value def t_NOT(t): r'NOT' t.type = 'NOT' return t def p_TXT(p): ''' TXT : ID TXT | ''' class var_obt: def __init__(self, name, types, dim1, dim2, dim3): self.name = name self.type = types self.dim1 = dim1 self.dim2 = dim2 self.dim3 = dim3
045f24c0c74bacf3d3f96f74ea9462ba4aa461c4
atrivedi8988/DSA-Must-Do-Questions
/45_Minimum Jumps To Reach The End/Ideal Solutions/minJumpsToEnd.py
834
4.125
4
# Min Jumps Steps to reach end def minJumpsToEnd(jumps): # Initialize Variable countSteps = 0 maxDistance = 0 currentDistance = 0 for index in range(len(jumps)): # Since we need to minimize the steps, therefore # 1. First move to the current Distance index value # 2. From there, we will try to reach end if index > currentDistance: # Max Distance should be keep track currentDistance = maxDistance # Keeping track of Steps Count countSteps += 1 # Keeping track what is the max distance we can reach from all the past current position maxDistance = max(maxDistance, index+jumps[index]) return countSteps if __name__ == "__main__": # input jumps = [2, 3, 1, 1, 4] print(minJumpsToEnd(jumps))
cd4650ea12a3905774d7f0f842d3d3c8eb2188a4
wuhanbronzer/PC
/learning/intr to algrithms.py
1,165
3.796875
4
#insertion-sort #升序 '''class sort_algri: def __init__(self,lis): self.lis = list(lis) def ascending(self): target = self.lis for i in range(len(target)-1, -1, -1): key = target[i] j = i + 1 while j < len(target) and target[j] < key: target[j-1] = target[j] j += 1 target[j-1] = key return target a = sort_algri([11111,11,1111,234,66,9,44,10]) print(a.ascending()) ''' #Poker牌堆合并问题 #MERGE '''def merge(li1, li2): source_lis1 = list(li1) source_lis2 = list(li2) source_lis1.append(9999) source_lis2.append(9999) target = [] i = 0 j = 0 for k in range(len(source_lis1)+len(source_lis2)-1): if i < len(source_lis1) and source_lis1[i] <= source_lis2[j]: target.append(source_lis1[i]) i = i + 1 if i+1 < len(source_lis1) else i elif j < len(source_lis2) and source_lis2[j] < source_lis1[i]: target.append(source_lis2[j]) j += 1 target.pop(-1) return target a = [1, 2, 3, 4, 5,19] b = [7,11, 14, 22, 27] print(merge(a,b))'''
918e4363c4aa9dc999dfe56c99cf7ed522852a60
4cylinder/codility
/binarygap.py
1,847
3.765625
4
''' A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. Write a function: that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. E.g., given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Assume that N is an integer within the range [1..2,147,483,647]. Expected worst-case time complexity is O(log(N)); Expected worst-case space complexity is O(1). ''' def solution(N): if N<5: return 0 bin = "{0:b}".format(N) left = 0 right = len(bin)-1 while left<right and not(bin[left]=='1' and bin[left+1]=='0'): left += 1 while right > left and not(bin[right]=='1' and bin[right-1]=='0'): right -= 1 gap = 0 while left <= right: mid = (left+right)/2 potential = 0 hasOne = 0 for i in range(left+1,right): if bin[i]=='1': hasOne = i break if hasOne: potential = hasOne-left-1 gap = max(potential,gap) if hasOne <=mid: left = hasOne else: right = hasOne else: potential = right-left-1 gap = max(potential,gap) return gap return gap
5ca31e3ba9c7afd2e25ba194707b3737f88b5f6b
Boberkraft/Data-Structures-and-Algorithms-in-Python
/chapter6/C-6.21.py
970
3.9375
4
""" Show how to use a stack S and a queue Q to generate all possible subsets of an n-element set T nonrecursively. Use the stack to store the elements yet to be used to generate subsets and use the queue to store the subsets generated so far. Hmmm the truth is that i only used queue """ from collections import deque def gen(T): # its basicly more complex and worse gen2 s = [set()] q = deque() for el in T: s.append({el}) q.appendleft({el}) for _ in range(len(q) - 1): new = {el} old = q.pop() new = new.union(old) s.append(new) q.appendleft(new) q.appendleft(old) return s def gen2(T): # not using any stack and queue ;/ s = [set()] for el in T: for x in range(len(s)): s.append(s[x].union({el})) return s s = gen2({1, 2, 3, 4}) s1 = gen({1, 2, 3, 4}) print('Stack:') print(s, len(s)) print(s1, len(s1))
6d27551bbd3a4ae27408f6a21e88d1bec4aba7bb
bullethammer07/python_code_tutorial_repository
/python_concepts_and_basics/python_inbuilt_set_methods.py
21,609
3.53125
4
# -------------------------------------------------------------- # Python set inbuilt methods # -------------------------------------------------------------- # add() : Method adds a given element to a set. If the element is already present, it doesn't add any element. # clear() : Method removes all elements from the set. # copy() : Method returns a shallow copy of the set. # difference() : Method returns the set difference of two sets. # difference_update() : Updates the set calling difference_update() method with the difference of sets. # discard() : Method removes a specified element from the set (if present). # intersection() : Method returns a new set with elements that are common to all sets. # intersection_update() : Updates the set calling intersection_update() method with the intersection of sets. # isdisjoint() : Method returns True if two sets are disjoint sets. If not, it returns False. # issubset() : Method returns True if all elements of a set are present in another set (passed as an argument). If not, it returns False. # issuperset() : Method returns True if a set has every elements of another set (passed as an argument). If not, it returns False. # pop() : Method removes an arbitrary element from the set and returns the element removed. # remove() : Method removes the specified element from the set. # symmetric_difference() : Method returns the symmetric difference of two sets. # union() : Method returns a new set with distinct elements from all the sets. # update() : Method updates the set, adding items from other iterables. #---------------------------------------------------------------------------------------------------------------------- # add() # Description : Method adds a given element to a set. If the element is already present, it doesn't add any element. # Syntax : set.add(elem) # elem - the element that is added to the set print("\n") # Return Value from Set add() # add() method doesn't return any value and returns None. # Example 1: Add an element to a set # set of vowels vowels = {'a', 'e', 'i', 'u'} # adding 'o' vowels.add('o') print("add : ", 'Vowels are:', vowels) # adding 'a' again vowels.add('a') print("add : ", 'Vowels are:', vowels) # Example 2: Add tuple to a set # set of vowels vowels2 = {'a', 'e', 'u'} # a tuple ('i', 'o') tup = ('i', 'o') # adding tuple print("add : ","printing initial set of vowel : ", 'Vowels are:', vowels2) vowels2.add(tup) print("add : ","after adding tuple to vowel : ", 'Vowels are:', vowels2) # adding same tuple again vowels.add(tup) print("add : ","after adding the same tuple again to vowel : ",'Vowels are:', vowels2) #---------------------------------------------------------------------------------------------------------------------- # clear() # Description : Method removes all elements from the set. # Syntax : set.clear() # clear() method doesn't take any parameters. print("\n") # Return value from Set clear() # clear() method doesn't return any value and returns a None. # Example 1: Remove all elements from a Python set using clear() # set of vowels vowels3 = {'a', 'e', 'i', 'o', 'u'} print("clear : ", 'Vowels (before clear):', vowels3) # clearing vowels vowels3.clear() print("clear : ", 'Vowels (after clear):', vowels3) #---------------------------------------------------------------------------------------------------------------------- # copy() # Description : Method returns a shallow copy of the set. # Syntax : set.copy() # It doesn't take any parameters. print("\n") # Return Value from copy() # The copy() method returns a shallow copy of the set. # A set can be copied using = operator in Python. For example: numbers = {1, 2, 3, 4} new_numbers = numbers # The problem with copying the set in this way is that if you modify the numbers set, the new_numbers set is also modified. for eg. new_numbers.add(5) print("copy : ", "Original Set", 'numbers: ', numbers) print("copy : ", "Copied Set", 'new_numbers: ', new_numbers) # However, if you need the original set to be unchanged when the new set is modified, you can use the copy() method. # Example 1: How the copy() method works for sets? numbers2 = {1, 2, 3, 4} new_numbers2 = numbers2.copy() new_numbers2.add(5) print("copy : ", "Original Set", 'numbers: ', numbers2) print("copy : ", "Copied Set", 'new_numbers: ', new_numbers2) #---------------------------------------------------------------------------------------------------------------------- # difference() # Description : Method returns the set difference of two sets. # Syntax : A.difference(B) # Here, A and B are two sets. The following syntax is equivalent to A-B. print("\n") # Return Value from difference() # difference() method returns the difference between two sets which is also a set. It doesn't modify original sets. # Example 1: How difference() works in Python? A = {'a', 'b', 'c', 'd'} B = {'c', 'f', 'g'} # Equivalent to A-B print("difference : ", A.difference(B)) # Equivalent to B-A print("difference : ", B.difference(A)) # Example 2: Set Difference Using - Operator. print("difference : ", A-B) print("difference : ", B-A) #---------------------------------------------------------------------------------------------------------------------- # difference_update() # Description : Updates the set calling difference_update() method with the difference of sets. # Syntax : A.difference_update(B) # Here, A and B are two sets. difference_update() updates set A with the set difference of A-B. print("\n") # Return Value from difference_update() # difference_update() returns None indicating the object (set) is mutated. # Suppose, # result = A.difference_update(B) # When you run the code, # result will be None # A will be equal to A-B # B will be unchanged # Example: How difference_update() works? setA = {'a', 'c', 'g', 'd'} setB = {'c', 'f', 'g'} result = setA.difference_update(setB) print("difference_update : ", 'A = ', setA) print("difference_update : ", 'B = ', setB) print("difference_update : ", 'result = ', result) #---------------------------------------------------------------------------------------------------------------------- # discard() # Description : Method removes a specified element from the set (if present). # Syntax : s.discard(x) # discard() method takes a single element x and removes it from the set (if present). print("\n") # Return Value from discard() # discard() removes element x from the set if the element is present. # This method returns None (meaning, absence of a return value). # Example 1: How discard() works? numbers3 = {2, 3, 4, 5} numbers3.discard(3) print("discard : ", 'numbers = ', numbers3) numbers3.discard(5) print("discard : ", 'numbers = ', numbers3) numbers3.discard(10) print("discard : ", 'numbers = ', numbers3) #---------------------------------------------------------------------------------------------------------------------- # intersection() # Description : method returns a new set with elements that are common to all sets. # Syntax : A.intersection(*other_sets) # intersection() allows arbitrary number of arguments (sets). print("\n") # Return Value from Intersection() # intersection() method returns the intersection of set A with all the sets (passed as argument). # If the argument is not passed to intersection(), it returns a shallow copy of the set (A). # Example 1: How intersection() works? set_A = {2, 3, 5, 4} set_B = {2, 5, 100} set_C = {2, 3, 8, 9, 10} print("intersection : ", set_B.intersection(set_A)) print("intersection : ", set_B.intersection(set_C)) print("intersection : ", set_A.intersection(set_C)) print("intersection : ", set_C.intersection(set_A, set_B)) # Example 2 : More Examples set__A = {100, 7, 8} set__B = {200, 4, 5} set__C = {300, 2, 3} set__D = {100, 200, 300} print("intersection : ", set__A.intersection(set__D)) print("intersection : ", set__B.intersection(set__D)) print("intersection : ", set__C.intersection(set__D)) print("intersection : ", set__A.intersection(set__B, set__C, set__D)) #---------------------------------------------------------------------------------------------------------------------- # intersection_update() # Description : Updates the set calling intersection_update() method with the intersection of sets. # Syntax : A.intersection_update(*other_sets) # The intersection_update() method allows an arbitrary number of arguments (sets). print("\n") # Return Value from Intersection_update() # This method returns None (meaning it does not have a return value). It only updates the set calling the intersection_update() method. # For example: # result = A.intersection_update(B, C) # When you run the code, # result will be None # A will be equal to the intersection of A, B, and C # B remains unchanged # C remains unchanged # Example 1: How intersection_update() Works? set___A = {1, 2, 3, 4} set___B = {2, 3, 4, 5} result = set___A.intersection_update(set___B) print("intersection_update : ", 'result =', result) print("intersection_update : ", 'A =', set___A) print("intersection_update : ", 'B =', set___B) # Example 2: intersection_update() with Two Parameters SET_A = {1, 2, 3, 4} SET_B = {2, 3, 4, 5, 6} SET_C = {4, 5, 6, 9, 10} result = SET_C.intersection_update(SET_B, SET_A) print("intersection_update : ", 'result =', result) print("intersection_update : ", 'C =', SET_C) print("intersection_update : ", 'B =', SET_B) print("intersection_update : ", 'A =', SET_A) #---------------------------------------------------------------------------------------------------------------------- # isdisjoint() # Description : Method returns True if two sets are disjoint sets. If not, it returns False. # Syntax : set_a.isdisjoint(set_b) # isdisjoint() method takes a single argument (a set). # NOTE : You can also pass an iterable (list, tuple, dictionary, and string) to disjoint(). # isdisjoint() method will automatically convert iterables to set and checks whether the sets are disjoint or not. print("\n") # Return Value from isdisjoint() # isdisjoint() method returns # 1. True if two sets are disjoint sets (if set_a and set_b are disjoint sets in above syntax) # 2. False if two sets are not disjoint sets # Example 1: How isdisjoint() works? set_a = {1, 2, 3, 4} set_b = {5, 6, 7} set_c = {4, 5, 6} print("isdisjoint : ", 'Are A and B disjoint?', set_a.isdisjoint(set_b)) print("isdisjoint : ", 'Are A and C disjoint?', set_a.isdisjoint(set_c)) # Example 2: isdisjoint() with Other Iterables as arguments set_aa = {'a', 'b', 'c', 'd'} set_bb = ['b', 'e', 'f'] set_cc = '5de4' set_dd = {1 : 'a', 2 : 'b'} set_ee = {'a' : 1, 'b' : 2} print("isdisjoint : ", 'Are A and B disjoint?', set_aa.isdisjoint(set_bb)) print("isdisjoint : ", 'Are A and C disjoint?', set_aa.isdisjoint(set_cc)) print("isdisjoint : ", 'Are A and D disjoint?', set_aa.isdisjoint(set_dd)) print("isdisjoint : ", 'Are A and E disjoint?', set_aa.isdisjoint(set_ee)) #---------------------------------------------------------------------------------------------------------------------- # issubset() # Description : method returns True if all elements of a set are present in another set (passed as an argument). If not, it returns False. # Syntax : A.issubset(B) # The above code checks if A is a subset of B. print("\n") # Return Value from issubset() # issubset() returns # True if A is a subset of B # False if A is not a subset of B # Example: How issubset() works? s_A = {1, 2, 3} s_B = {1, 2, 3, 4, 5} s_C = {1, 2, 4, 5} # Returns True print("issubset : ", s_A.issubset(s_B)) # Returns False # B is not subset of A print("issubset : ", s_B.issubset(s_A)) # Returns False print("issubset : ", s_A.issubset(s_C)) # Returns True print("issubset : ", s_C.issubset(s_B)) #---------------------------------------------------------------------------------------------------------------------- # issuperset() # Description : method returns True if a set has every elements of another set (passed as an argument). If not, it returns False. # Syntax : A.issuperset(B) # The following code checks if A is a superset of B. print("\n") # Return Value from issuperset() # issuperset() returns # True if A is a superset of B # False if A is not a superset of B # Example: How issuperset() works? st_A = {1, 2, 3, 4, 5} st_B = {1, 2, 3} st_C = {1, 2, 3} # Returns True print("issuperset : ", st_A.issuperset(st_B)) # Returns False print("issuperset : ", st_B.issuperset(st_A)) # Returns True print("issuperset : ", st_C.issuperset(st_B)) #---------------------------------------------------------------------------------------------------------------------- # pop() # Description : Method removes an arbitrary element from the set and returns the element removed. # Syntax : set.pop() # The pop() method doesn't take any arguments. print("\n") # Return Value from pop() # The pop() method returns an arbitrary (random) element from the set. Also, the set is updated and will not contain the element (which is returned). # If the set is empty, TypeError exception is raised. # Example: How pop() works for Python Sets? stA ={'a', 'b', 'c', 'd'} print("pop : ", 'Return Value is', stA.pop()) print("pop : ", 'A = ', stA) #---------------------------------------------------------------------------------------------------------------------- # remove() # Description : Method removes the specified element from the set. # Syntax : set.remove(element) # The remove() method takes a single element as an argument and removes it from the set. print("\n") # Return Value from remove() # The remove() removes the specified element from the set and updates the set. It doesn't return any value. # If the element passed to remove() doesn't exist, KeyError exception is thrown. # Example 1: Remove an Element From The Set # language set language = {'English', 'French', 'German'} # removing 'German' from language print("remove : ", 'Original language set :', language) language.remove('German') # Updated language set print("remove : ", 'Updated language set after remove :', language) # Example 2: Deleting Element That Doesn't Exist # animal set animal = {'cat', 'dog', 'rabbit', 'guinea pig'} # Deleting 'fish' element # animal.remove('fish') # UNCOMMENT TO RUN : This will return an exception : KeyError: 'fish' # Updated animal # print("remove : ", 'Updated animal set:', animal) # UNCOMMENT TO RUN : This will return an exception : KeyError: 'fish' #---------------------------------------------------------------------------------------------------------------------- # symmetric_difference() # Description : Method returns the symmetric difference of two sets. # The symmetric difference of two sets A and B is the set of elements that are in either A or B, but not in their intersection. # Syntax : A.symmetric_difference(B) print("\n") # Example 1: Working of symmetric_difference() p = {'a', 'b', 'c', 'd'} q = {'c', 'd', 'e' } r = {} print("symmetric_difference : ", p.symmetric_difference(q)) print("symmetric_difference : ", q.symmetric_difference(p)) print("symmetric_difference : ", p.symmetric_difference(r)) print("symmetric_difference : ", q.symmetric_difference(r)) # Example : Symmetric difference using ^ operator # In Python, we can also find the symmetric difference using the ^ operator. print("symmetric_difference : ", "using ^ operator : ", p ^ q) print("symmetric_difference : ", "using ^ operator : ", q ^ p) print("symmetric_difference : ", "using ^ operator : ", p ^ p) print("symmetric_difference : ", "using ^ operator : ", q ^ q) #---------------------------------------------------------------------------------------------------------------------- # union() # Description : Method returns a new set with distinct elements from all the sets. # Syntax : A.union(*other_sets) # NOTE : * is not part of the syntax. It is used to indicate that the method can take 0 or more arguments. print("\n") # Return Value from union() # The union() method returns a new set with elements from the set and all other sets (passed as an argument). # NOTE : If the argument is not passed to union(), it returns a shallow copy of the set. # Example 1: Working of union() us_A = {'a', 'c', 'd'} us_B = {'c', 'd', 2 } us_C = {1, 2, 3} print("union : ", 'A U B =', us_A.union(us_B)) print("union : ", 'B U C =', us_B.union(us_C)) print("union : ", 'A U B U C =', us_A.union(us_B, us_C)) print("union : ", 'A.union() =', us_A.union()) # You can also find the union of sets using the | operator. # Example 2: Set Union Using the | Operator print("union : ", "using | operator : ", 'A U B =', us_A | us_B) print("union : ", "using | operator : ", 'B U C =', us_B | us_C) print("union : ", "using | operator : ", 'A U B U C =', us_A | us_B | us_C) #---------------------------------------------------------------------------------------------------------------------- # update() # Description : Method updates the set, adding items from other iterables. # Syntax : A.update(iterable) # Here, A is a set, and iterable can be any iterable such as list, set, dictionary, string, etc. The elements of the iterable are added to the set A. # A.update(iter1, iter2, iter3) # Here, the elements of iterables iter1, iter2, and iter3 are added to set A. print("\n") # Return Value from update() # This set update() method returns None (returns nothing). # Example 1: Python set update() up_A = {'a', 'b'} up_B = {1, 2, 3} rslt = up_A.update(up_B) print("update : ", 'A =', up_A) print("update : ", 'result =', rslt) # Example 2: Add elements of string and dictionary to Set string_alphabet = 'abc' numbers_set = {1, 2} # add elements of the string to the set numbers_set.update(string_alphabet) print("update : ", 'numbers_set =', numbers_set) info_dictionary = {'key': 1, 'lock' : 2} numbers_set = {'a', 'b'} # add keys of dictionary to the set numbers_set.update(info_dictionary) print("update : ", 'numbers_set =', numbers_set) # ================================================================================================ # OUTPUT # ================================================================================================ # add : Vowels are: {'a', 'e', 'o', 'i', 'u'} # add : Vowels are: {'a', 'e', 'o', 'i', 'u'} # add : printing initial set of vowel : Vowels are: {'a', 'e', 'u'} # add : after adding tuple to vowel : Vowels are: {'a', ('i', 'o'), 'e', 'u'} # add : after adding the same tuple again to vowel : Vowels are: {'a', ('i', 'o'), 'e', 'u'} # # # clear : Vowels (before clear): {'o', 'a', 'i', 'e', 'u'} # clear : Vowels (after clear): set() # # # copy : Original Set numbers: {1, 2, 3, 4, 5} # copy : Copied Set new_numbers: {1, 2, 3, 4, 5} # copy : Original Set numbers: {1, 2, 3, 4} # copy : Copied Set new_numbers: {1, 2, 3, 4, 5} # # # difference : {'a', 'b', 'd'} # difference : {'f', 'g'} # difference : {'a', 'b', 'd'} # difference : {'f', 'g'} # # # difference_update : A = {'a', 'd'} # difference_update : B = {'f', 'g', 'c'} # difference_update : result = None # # # discard : numbers = {2, 4, 5} # discard : numbers = {2, 4} # discard : numbers = {2, 4} # # # intersection : {2, 5} # intersection : {2} # intersection : {2, 3} # intersection : {2} # intersection : {100} # intersection : {200} # intersection : {300} # intersection : set() # # # intersection_update : result = None # intersection_update : A = {2, 3, 4} # intersection_update : B = {2, 3, 4, 5} # intersection_update : result = None # intersection_update : C = {4} # intersection_update : B = {2, 3, 4, 5, 6} # intersection_update : A = {1, 2, 3, 4} # # # isdisjoint : Are A and B disjoint? True # isdisjoint : Are A and C disjoint? False # isdisjoint : Are A and B disjoint? False # isdisjoint : Are A and C disjoint? False # isdisjoint : Are A and D disjoint? True # isdisjoint : Are A and E disjoint? False # # # issubset : True # issubset : False # issubset : False # issubset : True # # # issuperset : True # issuperset : False # issuperset : True # # # pop : Return Value is a # pop : A = {'b', 'c', 'd'} # # # remove : Original language set : {'English', 'French', 'German'} # remove : Updated language set after remove : {'English', 'French'} # # # symmetric_difference : {'a', 'b', 'e'} # symmetric_difference : {'a', 'b', 'e'} # symmetric_difference : {'a', 'b', 'c', 'd'} # symmetric_difference : {'e', 'c', 'd'} # symmetric_difference : using ^ operator : {'a', 'b', 'e'} # symmetric_difference : using ^ operator : {'a', 'b', 'e'} # symmetric_difference : using ^ operator : set() # symmetric_difference : using ^ operator : set() # # # union : A U B = {2, 'd', 'a', 'c'} # union : B U C = {1, 2, 3, 'd', 'c'} # union : A U B U C = {1, 2, 3, 'd', 'a', 'c'} # union : A.union() = {'a', 'c', 'd'} # union : using | operator : A U B = {2, 'd', 'a', 'c'} # union : using | operator : B U C = {1, 2, 3, 'd', 'c'} # union : using | operator : A U B U C = {1, 2, 3, 'd', 'a', 'c'} # # # update : A = {1, 2, 3, 'a', 'b'} # update : result = None # update : numbers_set = {1, 2, 'a', 'b', 'c'} # update : numbers_set = {'a', 'b', 'lock', 'key'}
09f694cd9b2aec187e7ab89aaa6de444eebf1fc4
mathews19/projetoPython
/ex15.py
660
4.0625
4
from sys import argv script = argv # file_name = argv Nessa linha recebemos/descompactamos os parametros recebidos file_name = input("Digitev aqui o nome do arquivo") txt = open(file_name) # Nessa linha abrimos o arquivo que recebemos como parametro no command line print(f"Here\'s your file {file_name}: ") print(txt.read()) # Nessa linha abrimos e lemos o arquivo txt.close() print("Type the file name again: ") # Aqui colocamos o nome novamente do arquivo que queremos ler file_again = input("> ") txt_again = open(file_again) # Aqui o arquivo será aberto novamente print(txt_again.read()) # E aqui executamos a leitura do arquivo txt_again.close()
adb0fcff2f41faf8fd56b07460bc2c5262c3b801
garethbowles/tictactoe
/tictactoeboard.py
1,978
3.953125
4
#!/usr/bin/env python import logging __version__ = '0.0.1' logging.basicConfig(level=logging.INFO) class TicTacToe(object): """ Calculate the results of a TicTacToe game given a player ID and a 2-dimensional array containing the cells that the player occupies. Currently supports a 3x3 board and needs error checking to be added. """ def __init__(self, player, board): self.player = player self.board = board def result(self): won = False cells = 0 board = self.board player = self.player # Brute force algorithm - check rows, then columns, then diagonals # Check rows for row in range(0, 3): logging.debug('Checking row %d' % row) for col in range(0, 3): if board[row][col] == player: cells += 1 logging.debug('Player filled out %d,%d, cells=%d' % (row, col, cells)) if cells == 3: won = True break cells = 0 # Check columns for col in range(0, 3): logging.debug('Checking column %d' % col) for row in range(0, 3): if board[row][col] == player: cells += 1 logging.debug('Player filled out %d,%d, cells=%d' % (row, col, cells)) if cells == 3: won = True break cells = 0 # Check diagonals if board[0][0] == player and board[1][1] == player and board[2][2] == player or board[0][2] == player and board[1][1] == player and board[2][0] == player: won = True for row in range(0, 3): for col in range(0, 3): print '%s ' % board[row][col], print '' if won == True: print 'Player %s won !!!' % player else: print 'Player %s lost :-(' % player return won
834c310cb8046ef6178c343b549092b6dea86bd2
AMyachev/bachelor_degree
/amyachev_degree/exact_algorithm.py
1,539
3.8125
4
from amyachev_degree.core import JobSchedulingFrame def johnson_algorithm(frame: JobSchedulingFrame) -> list: """ Compute solution for case of 2 machines of flow job problem by Johnson's algorithm. Parameters ---------- frame: JobSchedulingFrame frame with exactly 2 machines Returns ------- exact_solution: list list of job index """ if frame.count_machines != 2: raise ValueError('count machines must be 2') # init job indexes exact_solution = [i for i in range(frame.count_jobs)] # sorting by increasing the minimum processing time exact_solution.sort( key=lambda idx_job: min( frame.get_processing_time(idx_job, idx_machine=0), frame.get_processing_time(idx_job, idx_machine=1) ) ) jobs_on_first_machine = [] jobs_on_second_machine = [] # distribution of jobs on machines for idx_job in exact_solution: frst = frame.get_processing_time(idx_job, idx_machine=0) scnd = frame.get_processing_time(idx_job, idx_machine=1) if frst < scnd: jobs_on_first_machine.append(idx_job) else: jobs_on_second_machine.append(idx_job) exact_solution = jobs_on_first_machine # simulating the installation of jobs that are processed faster on the # second machine to the end of the processing queue on the first machine jobs_on_second_machine.reverse() exact_solution.extend(jobs_on_second_machine) return exact_solution
f03f056950e83329574a92b0668bc572a84e8898
kelpasa/Code_Wars_Python
/6 кю/Balance the arrays.py
350
3.5
4
''' https://www.codewars.com/kata/58429d526312ce1d940000ee/train/python ''' def balance(arr1, arr2): set1 = set(arr1) set2 = set(arr2) arr1_c = [] arr2_c = [] for i in set1: arr1_c.append(arr1.count(i)) for i in set2: arr2_c.append(arr2.count(i)) if sorted(arr1_c) == sorted(arr2_c): return True
f1aac6e3350fcf17d894548dc31da74cbef1bf98
ktamilara/player-set-1
/3a.py
97
3.515625
4
n1=int(input()) rem1=0 while n1!=0: temp1=n1%10 rem1=(rem1*10)+temp1 n1=n1//10 print(rem1)
c1f68dd6e82d98bd9e0cbf2de91a712d0cf0216e
shankarapailoor/Project-Euler
/Project Euler/utils/sieveofatkin.py
915
3.8125
4
from math import sqrt, floor from copy import deepcopy def sieve(x): limit = x isPrime = [False for i in range(5, limit)] for x in range(1, int(floor(sqrt(limit))) +1): for y in range(1, int(floor(sqrt(limit)))+1): n = 4*x**2 + y**2 if n <= limit and (n%12 == 1 or n %12 == 5): isPrime[n-5] = not isPrime[n-5] n = 3*x**2 + y**2 if n <= limit and (n%12 == 7): isPrime[n-5] = not isPrime[n-5] n = 3*x**2 - y**2 if x > y and n <= limit and n % 12 == 11: isPrime[n-5] = not isPrime[n-5] for n in range(5, int(floor(sqrt(limit)))+1): if isPrime[n-5]: k = 1 temp = deepcopy(n) while temp < limit-1: isPrime[temp-5] == False temp = k*n**2 k += 1 arr = [] for j in range(0, len(isPrime)): if isPrime[j]: arr.append(j+5) primes = {} for j in range(0, len(arr)): primes[j] = 1 return arr if __name__=='__main__': x = sieve(100000) print x
0657eec1116efbd99b71b7db78c4d0ed34438ee3
Nahid5/Project-Euler-Problems
/Problem9.py
708
4.28125
4
''' Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import random """ a+b+c = 1000 a < sidesTotal/3 a < b < sidesTotal/2 c = 1000-a-b """ sidesTotal = 1000 a = 0 b = 0 c = 0 while(a**2+b**2 != c**2 or a+b+c != 1000): #random if the theory is not met or the sum is not 100 a = random.randint(1,334) #the first number has to be lower than 100/3 b = random.randint(335, 650) #b is greater than a but smaller than c c = 1000 - a - b #using the equation print(a) print(b) print(c)
4dc55e0f8b1a68a6f2fdce0a271534a12841667e
lebronbolt/beginnerprojects
/XandO.py
2,992
3.96875
4
print("this really is my first python file") #Develop code for XandO terminal game #construct input for XandO box xando = {'7':" ", '8': " ", '9':" ", '4': " ", '5': " ", '6': " ", '1': " ", '2': " ", '3': " "} board_keys = [] for key in xando: board_keys.append(key) #print XandO box to begin game def printboard(board): print(board['7'] + '|' + board['8'] + '|' + board['9']) print('-+-+-') print(board['4'] + '|' + board['5'] + '|' + board['6']) print('-+-+-') print(board['1'] + '|' + board['2'] + '|' + board['3']) #game function to take player input & update XandO box def game(): turn = 'X' count = 0 for i in range(10): printboard(xando) print('Player ' + turn + ' , please select your move..') move = input() if xando[move] == " ": xando[move] = turn count += 1 else: print("Position already filled.\nMove to which place?") continue #loop to check for winner if count >= 5: #horizontal if xando['7'] == xando['8'] == xando['9'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break elif xando['4'] == xando['5'] == xando['6'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break elif xando['1'] == xando['2'] == xando['3'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break #vertical if xando['7'] == xando['4'] == xando['1'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break elif xando['8'] == xando['5'] == xando['2'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break elif xando['9'] == xando['6'] == xando['3'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break #diagonal if xando['7'] == xando['5'] == xando['3'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break elif xando['1'] == xando['5'] == xando['9'] != " ": printboard(xando) print("Game over. " + turn + " is the champion") break if count == 9: print("It's a draw game") if turn == "X": turn = "0" else: turn = "X" #ask players to play again? replay = input("Would you like to play again?(y/n)") if replay == "y" or replay == "Y": for key in board_keys: xando[key] = " " game() if __name__ == "__main__": game()
4e15006b97a80770c2987e4c9620ad3ffe1d0c3e
vporta/DataStructures
/fundamentals/average.py
430
3.71875
4
""" average.py $ python fundamentals/average.py 10.0 5.0 6.0 """ import sys class Average: @staticmethod def main(*args): count, _sum = 0, 0.0 a = list(*args) while count < len(a): value = float(a[count]) _sum += value count += 1 average = _sum / count print(f'average is {average}') if __name__ == '__main__': Average.main(sys.argv[1:])
cc43c03d67f39cc9a9cad8480613be08c90bdc88
rahuladream/Python-Exercise
/Edugrade/prime_till_no.py
411
3.859375
4
"""You will get a number in input you have to get all the prime no.s till that no Example - Input - 10 Output -[2,3,5,7] Explanation - First element of input list is 4 so multiply the whole list by 4 and return the output list.""" def main(i): arry = [] for i in range(2,i): if i > 1: for j in range(2, i): if (i % j) == 0: break else: arry.append(i) return arry print(main(10))
7c96a310acf3a1c3a754e87be8e631d1c0691fce
franklin18ru/bilaleigaTinna
/data_access/carsDataAccess.py
8,685
3.5
4
import csv import os from datetime import date, timedelta # Data access that has anything to do with cars # class CarsDataAccess: def __init__(self): self.cars = self.getAllCars() # get all cars in the system in store them in a dictionary # def getAllCars(self): car_list = [] with open("../data/cars.csv","r") as openfile: csv_reader = csv.reader(openfile) next(csv_reader) for line in csv_reader: licenseplate = line[0] typef = line[1] brand = line[2] model = int(line[3]) seats = int(line[4]) car_list.append([licenseplate,typef,brand,model,seats]) return car_list # add a new car to the system # def addCar(self,LicensePlate,Type,Brand,Model,Seats): with open('../data/cars.csv', 'a',newline="") as openfile: openfile.write("\n"+LicensePlate+","+Type+","+Brand+","+Model+","+Seats) # delete the car with the given input # def deleteCar(self,licenseplate): # moving the data to a temp file but if any line matches the given input it # does not go to the temp file self.deleteCarLeases(licenseplate) with open("../data/cars.csv","r+") as openfile: csv_reader = csv.reader(openfile) with open("../data/tempfile.csv","w",newline="") as tempfile: csv_writer = csv.writer(tempfile) for line in csv_reader: if licenseplate == line[0]: continue csv_writer.writerow(line) openfile.truncate(0) # the data back to the original file self.moveFromTempFile("cars") # delete all leases under that license plate # self.deleteCarLeases(licenseplate) # delete all leases under a specific car # def deleteCarLeases(self,licenseplate): with open("../data/leases.csv","r+") as openfile: csv_reader = csv.reader(openfile) with open("../data/tempfile.csv","w",newline="") as tempfile: csv_writer = csv.writer(tempfile) for line in csv_reader: if licenseplate == line[4]: continue csv_writer.writerow(line) openfile.truncate(0) # the data back to the original file self.moveFromTempFile("leases") # edits the car in cars file from the given inputs# def editCar(self,olddatalist,newdatalist): old_licensePlate = olddatalist[0] new_licensePlate = newdatalist[0] Type = olddatalist[1] new_brand = newdatalist[1] new_model = newdatalist[2] new_seats = newdatalist[3] with open("../data/cars.csv","r+",newline="") as openfile: csv_reader = csv.reader(openfile) with open("../data/tempfile.csv","w",newline="") as tempfile: csv_writer = csv.writer(tempfile) for line in csv_reader: if old_licensePlate == line[0]: new_line = [new_licensePlate,Type,new_brand,new_model,new_seats] csv_writer.writerow(new_line) continue csv_writer.writerow(line) openfile.truncate(0) # the data back to the original file self.moveFromTempFile("cars") # if the license plate is not changed then system does nothing # # if the license plate is changed the we need to update the leases # # under that license plate # if old_licensePlate == new_licensePlate: pass else: self.editCarLeases(old_licensePlate,new_licensePlate) # Goes through the lease file and checks if the old license plate is there and # # updates the leases under that license plate # def editCarLeases(self,old_licensePlate,new_licensePlate): with open("../data/leases.csv","r+",newline="") as openfile: csv_reader = csv.reader(openfile) with open("../data/tempfile.csv","w",newline="") as tempfile: csv_writer = csv.writer(tempfile) for line in csv_reader: if old_licensePlate == line[4]: new_line = [line[0],line[1],line[2],line[3],new_licensePlate,line[5]] csv_writer.writerow(new_line) continue csv_writer.writerow(line) openfile.truncate(0) # the data back to the original file self.moveFromTempFile("leases") # Function to move the contents of a tempfile to another file and # # then destroy the temp file # def moveFromTempFile(self,fileName): # the data back to the original file filetowrite = "../data/"+fileName+".csv" with open("../data/tempfile.csv","r") as openfile: csv_reader = csv.reader(openfile) with open(filetowrite,"w",newline="") as writingfile: csv_writer = csv.writer(writingfile) for line in csv_reader: csv_writer.writerow(line) # removing the temp file os.remove("../data/tempfile.csv") # takes in a lease period and checks if any other lease period with the same license plate is active # # returns false if the car is not available and returns true if the car is available# def checkIfCarIsAvailable(self,leaseStart,leaseEnd,licensePlate): with open("data/leases.csv","r")as checkfile: csv_checker = csv.reader(checkfile) frame = self.getTimeFrame(leaseStart,leaseEnd) for line in csv_checker: if line[4] == licensePlate: for day in frame: if line[2] == day or line[3] == day: return False return True def getCarsType(self,Type,leaseStart,leaseEnd): # Get all available type cars # # Put all types in dict, license plate is the key, then check if the car is Available cars_dictionary = dict() with open("data/cars.csv","r") as openfile: csv_reader = csv.reader(openfile) next(csv_reader) for line in csv_reader: if line[1] == Type: if self.checkIfCarIsAvailable(leaseStart,leaseEnd,line[0]): cars_dictionary[line[0]] = (line[2],line[3],line[4]) return cars_dictionary def getAvailableCars(self,leaseStart,leaseEnd): # Get all available type cars in the system # # Put all type cars that was chosen in dict, license plate is the key, then check if the car is Available # cars_dictionary = dict() with open("data/cars.csv","r") as openfile: csv_reader = csv.reader(openfile) next(csv_reader) for line in csv_reader: if self.checkIfCarIsAvailable(leaseStart,leaseEnd,line[0]): cars_dictionary[line[0]] = (line[1],line[2],line[3],line[4]) return cars_dictionary # find the car that the customer is returning and return him in the system by # # making the lease activity completed # def returnCar(self,licensePlate,leaseStart,leaseEnd): with open("data/leases.csv","r+") as openfile: csv_reader = csv.reader(openfile) with open("data/tempfile.csv","w",newline="") as tempfile: csv_writer = csv.writer(tempfile) for line in csv_reader: if licensePlate == line[4] and leaseStart == line[2] and leaseEnd == line[3]: new_line = [line[0],line[1],line[2],line[3],line[4],"completed"] csv_writer.writerow(new_line) continue csv_writer.writerow(line) openfile.truncate(0) # the data back to the original file self.moveFromTempFile("leases") # gets all dates between to dates including start and end, you can also skip end # def getTimeFrame(self,time1,time2): t1 = time1.split(".") t2 = time2.split(".") start = date(int(t1[0]),int(t1[1]),int(t1[2])) end = date(int(t2[0]),int(t2[1]),int(t2[2])) delta = end-start frame = [] for x in range(delta.days+1): day = str(start+timedelta(x)) editday = day.replace("-",".") frame.append(editday) return frame
1af78c50379c74529bbe8cf66f7e785c57596a90
clipklop/PYT8-frii
/hw10/basic_flask_tasks.py
1,137
4.125
4
""" 1) Повторить basic.py 2) добавить route который принимает 2 числа и возвращает их сумму 3) добавить route который принимает три строки и возвращает самую длиннную """ from flask import Flask app = Flask(__name__) @app.route('/') def home(): return '<br><br><br><br><br><br><b>hello dude!</b>' @app.route('/post/<int:number>') def another_home1(number): return 'test view {}'.format(number) @app.route('/sum/<path:string>') def sum(string): x, y = int(string[0]), int(string[1:]) mysum = x + y return 'enter two numbers, {0}, {1}! Ok the SUM is {2}'.format( string[0], string[1], str(mysum)) @app.route('/strings/<path:s1>/<path:s2>/<path:s3>') def three_strings(s1, s2, s3): myargs = [s1, s2, s3] win = max([len(x) for x in myargs]) return '{0}<br>{1}<br>{2}<br>Winner: {3}'.format(s1, s2, s3, win) if __name__ == '__main__': app.run() # @app.route('/<user>') # @app.route('/<path:user_name>') # def username(user): # return 'hello, user: ' + user
209f3aacadf0336cc4834a0376ec77f77ae3038a
clairefischer/npfl104
/hw/python/xyz_there.py
587
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 16:27:13 2019 @author: clairefischer """ #10 def xyz_there(str): bool=False if len(str)<=2: return False elif len(str)==3: if str=='xyz': return True else: return False elif len(str)>3: if 'xyz' in str: for i in range(len(str)): if str[i]=='x' and str[i+1]=='y' and str[i+2]=='z' and str[i-1]!='.': bool+=True return bool==1 #Test if xyz_there('abdxyz')==True and xyz_there('ab.xyz')==False: print(True)#There is no error else: print(False)
f691ed16d80ec3cc0870a51e4a4e0f9f0067fb41
D-sourav-M044/NSL_RA_TRAINNING
/Python_Basic/week_01/list.py
890
3.828125
4
data = [1,2,3] print(data + [4,5,6]) print(3 in data) print([2] in data) #append data.append(10); print(data) #insert data.insert(1,'b') print(data) #index print(data.index('b')) try: print(data.index(5)) except : print("the searching element is not in list") #count print(data.count(2)) #build_in_function data = [1,2,4] char =['a','b','c'] print(max(data)) print(min(data)) print(max(char)) #range data =list(range(5,50,5)) print(data) data = [1,2,3,4,5] print(data[2:4]) print(data[2:-1]) print(data[::-1]) new_data = data[::-1] print(new_data) matrix_1d =[] matrix_2d = [[2,3,4], [1,2,3]] for row in matrix_2d: for num in row: matrix_1d.append(num) print(matrix_1d) #list_comprehensio: #vowel = ['a','e','i','o','u'] vowel = 'aeiou' sentence = "i am a kuetian" new_sentence = ''.join(i for i in sentence if i not in vowel ) print(new_sentence)
d26b1ec53eba9f9d862642d413b1274287a482c4
Donavan-Tay/2021-Complete-Python-Bootcamp-From-Zero-to-Hero-in-Python
/BlackJack.py
7,885
4.15625
4
import random # Global variables to create cards suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} playing = True class Card: """ Creates a default class for all cards """ def __init__(self, suit, rank): self.suit = suit self.rank = rank self.value = values[rank] def __str__(self): return self.rank + " of " + self.suit class Deck: """ Creates a default class for deck """ def __init__(self): self.deck = [] # start with an empty list for suit in suits: for rank in ranks: add_cards = Card(suit, rank) self.deck.append(add_cards) def shuffle(self): random.shuffle(self.deck) def deal(self): return self.deck.pop() def __str__(self): print("This shows the list of cards in the deck") list_cards = '' i = 0 for card in self.deck: i += 1 if i > 10: list_cards += f"{i}: {card}\n" return list_cards class Hand: def __init__(self): self.cards = [] # start with an empty list as we did in the Deck class self.value = 0 # start with zero value self.aces = 0 # add an attribute to keep track of aces def add_card(self, card): self.cards.append(card) self.value += values[card.rank] if card.rank == 'Ace': self.aces += 1 def adjust_for_ace(self): # If total values is more than 21 and there is an ace in hand # change value of ace to be 1 instead of 11 while self.value > 21 and self.aces > 0: self.value -= 10 self.aces -= 1 class Chips: def __init__(self, total=100): self.total = total # This can be set to a default value or supplied by a user input self.bet = 0 def win_bet(self): self.total += self.bet def lose_bet(self): self.total -= self.bet def take_bet(chips): while True: try: chips.bet = int(input("How many chips would you like to bet? ")) except ValueError: print("Please enter a correct value!") else: if chips.total < chips.bet: print("Sorry your current balance is ${} unable to bet ${}".format(chips.total, chips.bet)) else: break def hit(deck, hand): hand.add_card(deck.deal()) hand.adjust_for_ace() def hit_or_stand(deck, hand): global playing # to control an upcoming while loop while True: answer = input("Press H for Hit or S for stand ").upper() if answer == "H": hit(deck, hand) elif answer == "S": print("Player stands. Dealer is playing. ") playing = False else: print("Sorry wrong input please try again") continue break def show_some(player, dealer): # shows the dealer's second card print("\n Dealer's Hand: ") print("First card hidden! ") print(dealer.cards[1]) # Shows all the cards in player's hand print("\n Player's hand: ") for card in player.cards: print(card) def show_all(player, dealer): # shows all the dealer's card print("\n Dealer's hand: ") for card in dealer.cards: print(card) # Calculate and display value for dealer print(f"Value of Dealer's hand is:{dealer.value} ") # Shows all player's card print("\n Player's hand: ") for card in player.cards: print(card) # Calculate and display value for player print(f"Value of Player's hand is:{player.value} ") def player_busts(chips): print("Player Busts!") chips.lose_bet() def player_wins(chips): print("Player Wins!") chips.win_bet() def dealer_busts(chips): print("Dealer Busts!") chips.win_bet() def dealer_wins(chips): print("Dealer Wins!") chips.lose_bet() def player_low(chips): print("Player score below 17! Player loses!") chips.lose_bet() def push(): print("Dealer and Player tie! It's a push. ") def main(): global playing # Set up the Player's chips player_chips = Chips() while True: # Print an opening statement print("Welcome to the game of BlackJack! Score as close to 21 to win! \n") print("Each play has to have 17 or more to win!\nAce counts as 11 or 1. ") # Create & shuffle the deck, deal two cards to each player deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) # Shows the starting chips and prompt the Player for their bet print(f"\nPlayer has {player_chips.total} chips") take_bet(player_chips) # Show cards (but keep one dealer card hidden) show_some(player_hand, dealer_hand) print(f"Player Value:{player_hand.value}") while playing: # recall this variable from our hit_or_stand function # Prompt for Player to Hit or Stand hit_or_stand(deck, player_hand) # Show cards (but keep one dealer card hidden) show_some(player_hand, dealer_hand) print(f"Player Value:{player_hand.value}") # If player's hand exceeds 21, run player_busts() and break out of loop if player_hand.value > 21: player_busts(player_chips) break # If Player hasn't busted, play Dealer's hand until Dealer reaches 17 if player_hand.value <= 21: while dealer_hand.value < 17: hit(deck, dealer_hand) # Show all cards show_all(player_hand, dealer_hand) # Run different winning scenarios if player_hand.value < 17: player_low(player_chips) elif dealer_hand.value > 21: dealer_busts(player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_chips) elif dealer_hand.value < player_hand.value: player_wins(player_chips) else: push() # Inform Player of their remaining chips print(f"\nPlayer has {player_chips.total} chips remaining") # Checks to see if the player has chips left if player_chips.total <= 0: print("Player has run out of chips! \nPlayer lost!") no_chips = input("Do you want to play again? Key in Y to play, any other key to stop").upper() # If there are no chips, ask the player if they want to play again, else exit the game if no_chips == "Y": player_chips = Chips() playing = True continue else: print("Thank you for playing!") break # Ask to play again new_hand = input("Enter Y to play another hand. Any other key to stop playing ").upper() if new_hand == "Y": playing = True continue else: print("Thank you for playing!") break if __name__ == "__main__": main()
cd717674f5ce71adb362d5cdb1964751cbeac2d5
JorinW/DebtCalculator
/debt_calculator.py
3,052
4.375
4
#!/usr/bin/env python3 """Simple command line python script that outputs a spreadsheet of data about your debt payments. Jorin Weatherston August, 2017""" import csv import sys, getopt from math import floor def main(argv): ## initialization ## # initialize argument variables initial_debt = 0 interest_rate = 0 payment = 0 # initialize getopt (credit: https://www.tutorialspoint.com/python/python_command_line_arguments.htm) try: options, arguments = getopt.getopt(argv, "hd:i:p", ["debt=", "interest=", "payment="]) except getopt.GetoptError: print('Error: Accepted format is: ./debt_calculator.py -d <initial debt> -i <interest rate> -p <payment amount>') sys.exit(2) for option, argument in options: if option == '-h': print('./debt_calculator.py -d <initial debt> -i <interest rate> -p <payment amount>') sys.exit(2) elif option in ('-d', "--debt"): initial_debt = float(argument) elif option in ('-i', "--interest"): interest_rate = float(argument) elif option in ('-p', "--payment"): payment = float(argument) # constants days_between_payments = 15 days_per_year = 365 # initialized variables interest_to_pay = 0 principle_reduced = 0 payment_number = 1 debt_remaining_after_payment = initial_debt debt_remaining_before_payment = initial_debt interest_rate_per_15_day_cycle = (interest_rate / days_per_year) * days_between_payments ## debt calculation ## # open file writer = csv.writer(open('paymentRecord.csv', 'w', newline='')) # add column headers writer.writerow(['Payment Number', 'Debt Remaining Before Payment', 'Interest to be Paid', 'Payment', 'Principle Reduced', 'Debt Remaining After Payment']) # iterate until debt is repayed while debt_remaining_after_payment > 0: debt_remaining_before_payment = debt_remaining_after_payment interest_to_pay = debt_remaining_before_payment * interest_rate_per_15_day_cycle principle_reduced = payment - interest_to_pay debt_remaining_after_payment = debt_remaining_before_payment - principle_reduced writer.writerow([payment_number, debt_remaining_before_payment, interest_to_pay, payment, principle_reduced, debt_remaining_after_payment]) writer.writerow(['']) payment_number = payment_number + 1 # calculate metrics about repayment and add to final row total_days = payment_number * days_between_payments total_months = floor(total_days/30.4) total_years = total_months/12 writer.writerow(['Total payments:', payment_number, 'Days in repayment:', total_days, 'Months in repayment:', total_months, 'Years in repayment:', total_years]) print('Success.') print('Total payments:', payment_number, ', Days in repayment:', total_days, ', Months in repayment:', total_months, ', Years in repayment:', total_years) print('Goodluck with your payments!') if __name__ == "__main__": main(sys.argv[1:])
589d7da90df38fb46cbb303dc689027fcbf8c104
hanguangchao/python_learn
/basic/9.py
455
3.671875
4
# -*- coding=utf-8 -*- def repeater(value): while True: new = (yield value) if new is not None: value = new r = repeater(42) print r.next() print r.send("Hello World!") def triangles(): ls = [] while True: ls.insert(0, 1) for k, v in enumerate(ls[1:-1], 1): ls[k] = v + ls[k + 1] yield ls n = 0 for t in triangles(): print(t) n += 1 if n == 10: break
24d8a3712a6bb4fddcfa05564e8c411bab920db0
Yeshwanth115/Python
/positive or negative.py
92
3.828125
4
n=int(input()) if(n>0): print('%d is positive' %n) else: print('%d is negative' %n)
bbcc7334dc05555730ec90a034a7a9d88b14818c
shkwhr/study-python
/dictoionary.py
412
3.71875
4
# coding: utf-8 item_dic = {'醤油': 100, '砂糖': 80, '胡椒': 70} item_dic2 = sorted(item_dic, reverse=True) for (name, price) in item_dic.items(): print(name + 'は' + str(price) + '円です') print('Price Only') for name in item_dic: print(str(item_dic[name]) + '円') else: # forloopが終わったら出力 # breakした場合はelseは通らない print('金額出力終了!')
59a1146910cbe2fe79f662959648b56f8adcb676
bedros-bzdigian/intro-to-python
/week5/Homework/problem6/customer.py
316
3.75
4
from productchek import check def main (product,num,price): def buy(product,num,price): a = check(product,num) if a == True : print ("You bought",product,"and spent",num*price) else: print ("Sorry! We are out of the product") main("candy",11,3)
c414a70c8ec5f01ab75377a780aabf7d6875cf97
Piyawan00/calculeter
/menu.py
1,401
4.09375
4
import one #prototype import two import three import four Add=1 Substeact=2 Multiply=3 Divide=4 Quit=5 def main(): chioce = 0 while chioce !=Quit: display_manu() chioce =int(input("Selec your operation")) if chioce ==Add: num1=float(input("Enter you first number: ")) num2=float(input("Enter you second number: ")) print("The result is",one.add(num1,num2)) elif chioce== Substeact: num1=float(input("Enter you first number: ")) num2=float(input("Enter you second number: ")) print("The result is",two.substract(num1,num2)) elif chioce == Multiply: num1=float(input("Enter you first number: ")) num2=float(input("Enter you second number: ")) print("The result is",three.multiply(num1,num2)) elif chioce==Divide: num1=float(input("Enter you first number: ")) num2=float(input("Enter you second number: ")) print("The result is",four.devide(num1,num2)) elif chioce==Quit: print("Exite program.") else: print("Eror") def display_manu(): print('Select operation from number') print('') print('-'*10) print('1)Add') print('2)Substract ') print('3)Multiply') print('4)Devide') print('5)Quit') print('-'*10) main()
cf07d3eb81547bc5e66bad2f4b1333becdf592ff
LeeHeejae0908/python
/Day02/str_swap.py
534
3.9375
4
''' * 문자열 알파벳 형태 변경 메서드 1. lower(): 영문 알파벳을 모두 소문자로 변경 2. upper(): 영문 알파벳을 모두 대문자로 변경 3. swapcase(): 영문 대소문자를 각각 반대로 변환 4. capitalize(): 문장의 맨 첫글자만 대문자, 나머지는 소문자 5. title(): 각 단어의 맨 첫글자만 대문자, 나머지는 소문자 ''' s = 'GOOD morNing !! mY nAme IS LeE' print(s) print(s.lower()) print(s.upper()) print(s.swapcase()) print(s.capitalize()) print(s.title())
8eb943f0ad70308aecd62c854f0bab9804d1f651
OhOHOh/LeetCodePractice
/python/No206.py
815
3.84375
4
# -*- coding: UTF-8 -*- # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head): ''' 递归方式 ''' def reverse(pre, cur): if cur is None: return pre tmp = cur.next cur.next = pre return reverse(cur, tmp) return reverse(None, head) def reverseList_1(self, head): ''' 双指针法 ''' if head is None or head.next is None: return head pre, cur = None, head while cur is not None: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre
89f39a069591a613d990f06efa182fa834429ffa
JPChaus/362HW-4
/listAvg.py
895
3.96875
4
def main(): list_length = uInput("How big do you want the list? Positive integer value only: ", 1) my_list = [] for i in range(0, list_length): my_list.insert(i, uInput("Enter a number to add to the list. Integer value only: ", 0)) answer = calculateAvg(my_list) print("Average of the list: ", answer) def uInput(x, y): if(y == 0): while True: try: z = int(input(x)) break except ValueError: print("Invalid input!") elif(y == 1): while True: try: z = int(input(x)) if(z < 1): raise ValueError break except ValueError: print("Invalid input!") return z def calculateAvg(x): listAvg = sum(x)/len(x) return listAvg if __name__ == '__main__': main()
b0066c4e983a4159abefce606eb3e00f4e701893
phumin1994/AiTasks
/Task4/task4.py
1,930
3.5
4
import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') print("***** Train_Set *****") print(train.head()) print("\n") print("***** Test_Set *****") print(test.head()) print(train.columns.values) # print the columns in the dataset # Fill missing values with mean column values in the train set train.fillna(train.mean(), inplace=True) # Fill missing values with mean column values in the test set test.fillna(test.mean(), inplace=True) # remove unwanted columns from the dataset train = train.drop(['Name', 'Ticket', 'Cabin', 'Embarked'], axis=1) test = test.drop(['Name', 'Ticket', 'Cabin', 'Embarked'], axis=1) # converting the sex column into integer values of 0 and 1 labelEncoder = LabelEncoder() labelEncoder.fit(train['Sex']) labelEncoder.fit(test['Sex']) train['Sex'] = labelEncoder.transform(train['Sex']) test['Sex'] = labelEncoder.transform(test['Sex']) X = np.array(train.drop(['Survived'], 1).astype(float)) # declaring X with only features and without the outcome y = np.array(train['Survived']) # declaring Y with column to be predicted. scaler = MinMaxScaler() X_scaled = scaler.fit_transform(X) kmeans = KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,\ n_clusters=2, n_init=10,\ random_state=None, tol=0.0001, verbose=0) # You want cluster the passenger records into 2: Survived or Not survived kmeans.fit(X) # feeding the values into the model # calculating the accuracy of the model with the test dataset. correct = 0 for i in range(len(X)): predict_me = np.array(X[i].astype(float)) predict_me = predict_me.reshape(-1, len(predict_me)) prediction = kmeans.predict(predict_me) if prediction[0] == y[i]: correct += 1 print("accuracy ", correct/len(X))
ace972b63fb4b7bf760930360eedd9a8c4de1f49
MatthewDaws/CodeJam
/2015_1b/c_slow.py
1,790
3.65625
4
import sys from collections import namedtuple Group = namedtuple("Group", ["degree", "hikers", "minutes"]) def cost_zeros(time, zero_hikers): count = 0 for g in zero_hikers: for k in range(g.hikers): min = (g.minutes + k) * 360 count += max(1, time // min) return count def cost_nonzeros(time, nons): """Assume non_zero_hikers sorted by "offset". Returns (crude lower bound, count).""" lower, cost = 0, 0 for (min, offset) in nons: if time < offset: cost += 1 else: cost += (time - offset) // min # If `time` increases then so will this. lower += (time - offset) // min return lower, cost num_cases = int(input()) for case in range(1, num_cases+1): N = int(input()) hikers = [ (int(x) for x in input().split()) for _ in range(N) ] hikers = [Group(D,H,M) for (D,H,M) in hikers] # Find those with 0 degrees and those with non-zero degree # Actually, if we read the problem correctly, then zeros will always # be empty! zeros = [ g for g in hikers if g.degree == 0 ] nonzeros = [ g for g in hikers if g.degree != 0 ] # (min, offset) pairs nons = [ ((g.minutes + k) * 360, (360 - g.degree) * (g.minutes + k)) for g in nonzeros for k in range(g.hikers) ] nons.sort(key = lambda pair : pair[1]) best = cost_zeros(0, zeros) _, cost = cost_nonzeros(0, nons) best += cost print(best) for _, time in nons: count = cost_zeros(time, zeros) lower, cost = cost_nonzeros(time, nons) print(count + lower, count + cost) if count + lower >= best: break best = min(best, count + cost) print("Case #{}: {}".format(case, best))
8b8b35661ac269c345d2c95df876e59a6753a379
lglucin/VendingMachine
/vendingMachine.py
5,519
3.625
4
from stock import Stock from product import Product import locale locale.setlocale( locale.LC_ALL, '' ) class VendingMachine(): def __init__(self, stock = Stock(100)): self.credit = 0 self.stock = stock self.change = {"20":20, "10":10, "5":5, "1":1, "Q":0.25, "D":0.10, "N":0.05, "P":0.01} def serveCustomer(self): print("Menu:") self.stock.displayMenu() self.promptForCredit() while True: next = input("More [C]redit, make [P]urchase, or [M]enu? (ENTER TO EXIT): ") next = next.upper() if next == 'C': self.promptForCredit() elif next == 'P': self.purchase(); elif next == 'M': self.stock.displayMenu() elif next == "": break else: print("Invalid input. Please Try Again.") if self.getCredit() != 0: self.giveChange() def displayMenu(self): if self.stock != None: self.stock.displayMenu() else: print("No Stock.") def promptForCredit(self): print("Please add credit. (Cash Only)") self.receiveCredit(input("Input Money [20, 10, 5, 1, Q, D, N, P]: ")) print("Credit: " + currencyFmt(self.getCredit())) if self.canBuy(self.getCredit()): affordableProducts = self.affordableProducts(self.getCredit()) print("Products Under " + currencyFmt(self.getCredit()) + ":") for i in range(len(affordableProducts)): product = affordableProducts[i] print("\t[" + str(i + 1) + "]: " + product + ": " + currencyFmt(self.stock.getPrice(product))) def purchase(self): if self.canBuy(self.getCredit()): print("Products Under " + currencyFmt(self.getCredit()) + ":") if self.canBuy(self.getCredit()): affordableProducts = self.affordableProducts(self.getCredit()) while True: for i in range(len(affordableProducts)): product = affordableProducts[i] print("\t[" + str(i + 1) + "]: " + product + ": " + currencyFmt(self.stock.getPrice(product))) while True: productNum = input("Enter # to purchase: ") if productNum.isdigit(): productNum = int(productNum) - 1 break else: print("Invalid input. Try again.") if productNum >= 0 and productNum < len(affordableProducts): self.vend(affordableProducts[productNum]) break else: print("Invalid input. Please Try Again.") else: print("No item affordable with " + currencyFmt(self.getCredit())) def receiveCredit(self, input): """ Assumption: Machine can take an infinite amount of credit? """ if input.isalpha(): input = input.upper() if input in self.change: self.credit += self.change[input] else: print(input + " is not acceptable.") def canBuy(self, credit): return len(self.affordableProducts(credit)) != 0 def getCredit(self): return self.credit def affordableProducts(self, credit): if self.stock != None: priceTable = self.stock.getPriceTable() affordableProducts = [] for k,v in priceTable.items(): if v <= credit and k in self.stock.getMenu(): affordableProducts.append(k) return affordableProducts else: print("No Stock.") def vend(self, pName): if self.stock != None: self.stock.vend(pName) else: print("No Stock.") self.credit -= self.stock.prices[pName] self.giveChange() def giveChange(self): credit = int(self.credit * 100) clist = [1, 5, 10, 25, 100, 500, 1000, 2000] coinsUsed = [0]*(int(credit) + 1) coinCount = [0]*(int(credit) + 1) print("Making change for", currencyFmt(credit/100),"requires:") print(self.dpMakeChange(clist,credit,coinCount,coinsUsed),"items") self.printChange(coinsUsed,credit) def dpMakeChange(self,coinValueList,change,minCoins,coinsUsed): """ Adatped from http://interactivepython.org/runestone/static/pythonds/Recursion/DynamicProgramming.html """ change = int(change) for cents in range(change+1): coinCount = cents newCoin = 1 for j in [c for c in coinValueList if c <= cents]: if minCoins[cents-j] + 1 < coinCount: coinCount = minCoins[cents-j]+1 newCoin = j minCoins[cents] = coinCount coinsUsed[cents] = newCoin self.credit = 0 return minCoins[change] def printChange(self,coinsUsed,change): coin = change changeList = [] valToCoin = dict([[v,k] for k,v in self.change.items()]) while coin > 0: thisCoin = coinsUsed[coin] print(valToCoin[thisCoin / 100], end=" ") coin = coin - thisCoin print("") def currencyFmt(val): return str(locale.currency(val, grouping=True))
a04b1756b7d01e7dacca43e5c880116547e39976
franslay/smell_me
/BigramModel.py
3,042
3.515625
4
from LanguageModel import LanguageModel import random class BigramModel(LanguageModel): def __init__(self): super().__init__() self.unigramcounts = dict() self.unigramcounts[self.STOP] = 0 self.bigramcounts = dict() self.N = 0 # REQUIRED FUNCTIONS from abstract parent LanguageModel def train(self, sentences): # count num bigrams and num unigrams # counting unigrams for line in sentences: line = line.copy() # don't want to alter the original given sentences line.append(self.STOP) for word in line: if not word in self.unigramcounts: # word is new self.unigramcounts[word] = 1 else: # word was not found self.unigramcounts[word] += 1 self.N += len(line) # counting bigrams for line in sentences: line = line.copy() # don't want to alter the original given sentences line.insert(0, self.START) # add start token line.append(self.STOP) for i in range(len(line)): if line[i] == self.STOP: # ex: </s> --> stop loop continue ### elif not (line[i], line[i+1]) in self.bigramcounts: # word is new self.bigramcounts[(line[i], line[i+1])] = 1 else: # word was found self.bigramcounts[(line[i], line[i+1])] += 1 return def get_word_probability(self, sentence, index): # usage: word prev if index == len(sentence): # end of sentence return self.get_bigram_probability(self.STOP, sentence[index-1]) elif index == 0: # start of sentence return self.get_bigram_probability(sentence[0], self.START) else: return self.get_bigram_probability(sentence[index], sentence[index-1]) def get_vocabulary(self): words = list(self.unigramcounts.keys()) return words def generate_sentence(self): words = [] word = self.generate_word(self.START) # give prev word ( | GIVEN ) # start sentence token as first --> prev # make old word prev --> loop while word != self.STOP: words.append(word) prev = word word = self.generate_word(prev) return words # HELPER FUNCTIONS def get_bigram_probability(self, word, prev): if not (prev, word) in self.bigramcounts: return 0.0 elif prev == self.START: return float(self.bigramcounts[(prev, word)] / self.unigramcounts[self.STOP]) else: return float(self.bigramcounts[(prev, word)] / self.unigramcounts[prev]) def generate_word(self, prev): threshold = random.uniform(0, 1) sum = 0.0 for word in self.unigramcounts.keys(): sum += self.get_bigram_probability(word, prev) if sum > threshold: return word
786a7037884a872201e8191442cca1a377683737
RiderLai/pytest
/study/dictionary.py
1,161
3.765625
4
a = 1 '''test1''' alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points']) alien_0['a'] = 'a' print(alien_0['a']) print(alien_0) # alien_0['color'] = 'red' # print(alien_0) # del alien_0['color'] # print(alien_0) alien_0[1] = 1 for key, value in alien_0.items(): print("key:" + str(key)) print("value:" + str(value) + "\n") print("----------------------------------------------") '''test2''' favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } friends = ['phil', 'sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print("Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!") print() for name in sorted(favorite_languages.keys()): print(name.title() + ", thank you for taking the poll.") print("----------------------------------------------") '''test3''' alien_1 = {'color': 'red', 'points': 15} alien_2 = {'color': 'yellow', 'points': 10} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien)
13e44f6a62e15e0a8b36fc55f3ffe163a5927b5f
m04kA/my_work_sckool
/pycharm/GeekBrains/python_lvl_1/lesson_7/task_2.py
1,074
3.890625
4
from abc import ABC, abstractmethod class Сlothes(ABC): def __init__(self, name): self.name = name self.material = None @abstractmethod def calc_expenditure(self): return self.material @property def show_material(self): return f'Вот нужный материал {self.material}' def __add__(self, other): self.material += other.material return self.material class Сoat(Сlothes): def __init__(self, name, value): self.value = value super().__init__(name) self.calc_expenditure(self.value) def calc_expenditure(self, value=0): self.material = (value / 6.5) + 0.5 class Suit(Сlothes): def __init__(self, name, value): self.value = value super().__init__(name) self.calc_expenditure(self.value) def calc_expenditure(self, value=0): self.material = (2 * value) + 0.3 my_coat = Сoat('Сoat', 20) my_suit = Suit('Suit', 30) print(my_suit.show_material) print(my_coat.show_material) print(my_coat + my_suit)
0c1036ef4d65d2b9c3dde229f3c2b56cb2aaaa9a
paulrigor/Combining-existing-sequence-analysis-methods-with-graph-displays-for-visualization
/preprocessing/computedistances.py
2,639
3.578125
4
"""Computes a pairwise distance matrix from a BLAST alignment.""" import argparse from typing import Callable, TextIO, Tuple def short_hamming(ident: int, len1: int, len2: int) -> float: """Compute the normalized Hamming distance between two sequences.""" return 1 - ident / min(len1, len2) def parse_line(line: str, distance_metric: Callable) -> Tuple[str, str, float]: """Parse a line of BLAST+6 output. Parameters ---------- line : str A blast line in format `-outfmt "6 qacc sacc length qlen slen ident"` distance_metric : Callable A function that computes a distance metric from the info in `line`. Returns ------- query_accession : str The query sequence accession. subject_accession : str The subject sequence accession. distance : float The distance between the sequences. """ qacc, sacc, length, qlen, slen, ident = line.split() return qacc, sacc, distance_metric(int(ident), int(qlen), int(slen)) def parse_file( inputfile: TextIO, outputfile: TextIO, distance_metric: Callable ) -> None: r"""Parse blast+6 output and compute distances. Parameters ---------- inputfile : TextIO The input stream. A blast file in format `-outfmt "6 qacc sacc length qlen slen ident"` outputfile : TextIO The output stream. Will output in format "qacc\tsacc\tdistance\n" distance_metric : Callable A function that computes a distance metric from the info in `line`. Returns ------- None """ for line in inputfile: id1, id2, distance = parse_line(line, distance_metric) outputfile.write(f"{id1}\t{id2}\t{distance}\n") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Parse blast output and compute distances." ) parser.add_argument( "-i", "--inputfile", type=str, required=True, help=r"Blast output generated with `-outfmt '6 qacc sacc length qlen slen ident'`", ) parser.add_argument( "-o", "--outputfile", type=str, required=True, help=r"Output in TSV format with fields qacc, tsacc, and distance", ) parser.add_argument( "--distance_metric", choices=["short_hamming"], default="short_hamming", help="The distance metric to use. DEFAULT: short_hamming", ) args = parser.parse_args() with open(args.inputfile, "r") as inputfile: with open(args.outputfile, "w") as outputfile: parse_file(inputfile, outputfile, short_hamming)
9b2ef854c0bd1bbfba36f3953ffd0b898294024a
breezescut/zbin
/Python/Design of Computer Programs/Leeson1.py
356
3.765625
4
#! /usr/bin/env python # coding=utf-8 def ss(num): total = 0 for i in range(num+1): total += i #print("%d:%d" % (i, total)) return total def poker(hands): return max(hands) def hand_rank(hand): if __name__ == "__main__": num = int(input("Input num:")) print("sum(%d) = %d" % (num,ss(num)))
bbdef231a1257b47700c621c0e9e8295f1311cfb
HackerWithDrip/Python-PasswordManager
/PasswordManager.py
3,116
3.859375
4
import re class BasePasswordManager: def old_passwords(self): old_pass = ['247abc', 'abc247', '247365bac', '247365bac$'] self.old_pass = old_pass[-1] return self.old_pass def get_password(self): current_pass = self.old_pass self.current_pass = current_pass return "Current password is " + self.current_pass def is_correct(self, pwd=input('enter your password: ')): self.pwd = pwd print("New password is the same as the current password:", self.pwd == self.current_pass) return self.pwd class PasswordManager(BasePasswordManager): def get_level(self): self.security_lvl = 0 check_al = False check_num = False if self.pwd.isdigit(): self.security_lvl = 0 print('Security level', self.security_lvl, ':WEAK') print('Password consists of digits only') elif self.pwd.isalpha(): self.security_lvl = 0 print('Security level', self.security_lvl, ':WEAK') print('Password consists of alphabets only') elif check_al == False and check_num == False and (bool(re.match('^[a-zA-Z0-9]*$', self.pwd)) == True): for i in self.pwd: if i.isalpha(): check_al = True for j in self.pwd: if j.isnumeric(): check_num = True if check_al == True and check_num == True: self.security_lvl = 1 print('Security level', self.security_lvl, ': MODERATE') print('Password is alphanumeric with NO special characters') elif check_al == False and check_num == False: for i in self.pwd: if i.isalpha(): check_al = True for j in self.pwd: if j.isnumeric(): check_num = True if check_al == True and check_num == True and (bool(re.match('^[a-zA-Z0-9]*$', self.pwd)) == False): self.security_lvl = 2 print('Security level', self.security_lvl, ':STRONG') print('Password is alphanumeric with special characters') else: self.security_lvl = 1 print('Security level', self.security_lvl, ': MODERATE') print('Password contains special characters with either numbers or alphabets only') def set_password(self): if len(self.pwd) < 6: print("New password must have 6 characters or more") print("Password change:UNSUCCESSFUL") elif self.security_lvl < 2: print("New password must contain at least 1 special character with numbers and alphabets") print("Password change:UNSUCCESSFUL") elif self.pwd == self.current_pass: print("Password change: No changes detected") else: print("Password change:SUCCESSFUL") current = PasswordManager() current.old_passwords() current.get_password() current.is_correct() current.get_level() current.set_password()
91982e583cd2bc10b0fc58c31982782ce4945214
fotavio16/PycharmProjects
/PythonExercicio/ex012.py
207
4.03125
4
nome = str(input('Qual é o seu nome? ')) if nome == 'Fernando': print('Que nome bonito!') elif nome == 'Felizberto': print('Você deve ser muito feliz!') print('Tenha um bom dia, {}!'.format(nome))
71be98bc23e62aed4a6a9052a15aa5fee3611ec6
sbobbala76/Python.HackerRank
/0 - Tutorials/10 Days of Statistics/Day 0 - Mean Median and Mode.py
801
3.90625
4
def mean(values: list) -> int: length = len(values) result = 0 for value in values: result += value result /= length return result def median(values: list) -> float: length = len(values) values = sorted(values) if length % 2 != 0: return values[length // 2] else: return (values[length // 2] + values[length // 2 - 1]) / 2 def mode(values: list) -> int: counters = dict() result = None for value in values: if value in counters: counters[value] += 1 else: counters[value] = 1 if (result is None) or (counters[value] > counters[result]): result = value elif (counters[value] == counters[result]) and (value < result): result = value return result n = int(input()) x = [int(token) for token in input().split()] print(mean(x)) print(median(x)) print(mode(x))
96d60712dbd534c6e1cb1db473c5066c158bfd23
GovorunV/file
/file.py
698
3.640625
4
'''str=input("vedite text:") #записть в файл str += "\n" file = open('date/text.txt','a') file.write(str) file.close() try: file = open('date/text.txt', 'rt') # чтение з файла for line in file: print(line) file.close() except FileNotFoundError: print("Fail ne daiden") ''' # Исключения!!! userinp2=False while userinp2==False: try: a=int(input("Vedite chislo")) userinp2=True except ValueError: print("vedite chislo 1") userinp=False while userinp==False: try: b=int(input("Vedite chislo")) userinp=True except ValueError: print("vedite chislo 2") print("rezult sumu=",a+b)
be59ce0e978c8423d278b586c5379c26aeb94545
syn7hgg/ejercicios-python
/8_6/2.py
1,076
3.59375
4
class Persona: def __init__(self): self.rut = "" self.nombre = "" def setRut(self, rut): self.rut = rut def setNombre(self, nombre): self.nombre = nombre def getRut(self): return self.rut def getNombre(self): return self.nombre def __str__(self): return self.rut + " " + self.nombre # pl=Persona() # pl.setRut("12334768-8") # pl.setNombre("Juan López") # print(pl) def guardarPersonas(personas): personas_f = open("personas2.txt", "w") for persona in personas: personas_f.write(str(persona) + "\n") personas_f.close() def cargarPersonas(): personas = [] personas_f = open("personas.txt", "r") for persona_l in personas_f: datos = persona_l.split(",") persona = Persona() persona.setRut(datos[0]) persona.setNombre(datos[1].strip()) personas.append(persona) personas_f.close() return personas personas = cargarPersonas() for persona in personas: print(persona) guardarPersonas(personas)
601c5c6d68645a68c2edfdae1e8bf02b04f57162
petersdana/PythonLab
/know_the_anagram.py
961
4.25
4
#Enter a word whose anagram you would like to know #The computer gives a set of valid and meaningful anagrams word = input ("\n Enter a word: ") word = word.upper() # To match dictionary format l_word = len(word) ana_words = list() dictionary = open ("dictionary.txt") for d_word in dictionary: d_word = d_word.strip() t_word = word match = 0 if len(d_word) == l_word: for d_letter in d_word: counted = 0 for letter in t_word: if letter == d_letter: t_word = t_word[:counted] + t_word[counted+1:] #To eliminate matching repeat letters match = match + 1 break counted = counted + 1 if match == l_word: if d_word != word: ana_words.append(d_word) print("\n Anagrams of the given word are: ", ana_words) print ("\n Total no. of meaningful anagrams are: ", len(ana_words),"\n")
26e81356afa13ebf41f74c59643b4e54f27a2d0f
SWUFE-labs/python_with_corey
/oop_classes/run_oop_05.py
845
3.9375
4
"""This is the user interface script to the 'oop.py' employee class file""" from oop_05 import Employee emp_1 = Employee('george', 'kaimakis', 50000) emp_2 = Employee('TEST', 'EMPLOYEE', 60000) # # this is equivalent to __str__ and str(): # print(emp_1) # These pairs are equivalent - this is for the official object representation: # print(repr(emp_1)) # print(emp_1.__repr__()) # These pairs are equivalent - this is for the informal object representation: print(str(emp_1)) print(emp_1.__str__()) # this uses the special method __add__ on the pay instance variable: # print(emp_1 + emp_2) # this uses the special method __len__ to count the characters of full_name: # print(len(emp_1)) # These pairs are equivalent - behind the scenes stuff: # print(1+2) # print(int.__add__(1, 2)) # print('a'+'b') # print(str.__add__('a', 'b'))
83b82b62b171f439ec340c59044712dff45ae6fb
howard31622/fibonacci-algorithm
/fib3.py
272
3.75
4
count = 0 def fibonacci(n): global count if not isinstance(n, int): print ('Invalid Input') return None if n < 0: print ('Invalid Input') return None count = (( (1 + (5 ** 0.5))/2) ** n)/(5 ** 0.5) fibonacci(5) print(count)
e70fee8f17850e9d1607713b657420c0f213aa0b
fugbk/pystu-N27
/day5-1 面向对象核心概念/t.py
392
3.65625
4
# encoding = utf-8 __author__ = "Ang Li" class Person: age = 100 def __init__(self, name): self.name = name tom = Person('Tom') print(tom.age) # tom 中没有定义age,访问的是类的,如果类中没有会接着访问上层的父类的 print(*tom.__dict__.items()) # 但是这种访问,是直接访问,tom实例并不会 并不会新增一个age属性。
8f076f012de7d9e71daff7736fc562eff99078aa
kartikay89/Python-Coding_challenges
/countLetter.py
1,042
4.5
4
""" Write a function called count_letters(text, letter), which receives as arguments a text (string) and a letter (string), and returns the number of occurrences of the given letter (count both capital and small letters!) in the given string. For example, count_letters('trAvelingprogrammer', 'a') should return 2 and count_letters('trAvelingprogrammer', 'A') should return also 2. If you are quite advanced, use Regular Expressions or Lambda function here :) """ def count_letters(text, letter): newText = text.lower() result = 0 for letts in newText: if letter in letts: result +=1 return result print(count_letters("Kartikay", "k")) """ import testyourcode # one possibility def count_letters(text, letter): return text.lower().count(letter.lower()) # another possibility import re def count_letters2(text, letter): return len(re.findall(letter.lower(), text.lower())) # another possibility def count_letters3(text, letter): return sum(map(lambda x : 1 if letter.lower() in x else 0, text.lower())) """
72402629bb93281bbec810bc4d52bb909b20adcd
cannonja/tensorflow
/tensorflow/examples/tutorials/mnist/my_files/MNIST_exp/single_layer.py
1,626
3.734375
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ## Read and unpack images mnist = input_data.read_data_sets('MNIST_data', one_hot=True) ## Launch interactive session ## Interavtive session allows us to interleave operations that build graph ## with those that run/execute graph ## Regular session makes you build first, then execute sess = tf.InteractiveSession() ########## Build softmax regression single layer #################### ## Start building computation graph by defining placeholders (inputs and target labels) x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) ## Then define variables, generally model parameters (weights, biases) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) ## Initialize variables so they can be used within the session sess.run(tf.initialize_all_variables()) ## Add activation node y = tf.nn.softmax(tf.matmul(x,W) + b) ## Define Loss cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) ########### Train the model ########################################### train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) for i in range(1000): batch = mnist.train.next_batch(50) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) ########### Evaluate ################################################## correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
c9a44ae6392b9f829606cb0ea52a8c3e2ca5ae8f
tomdottom/programming-excersises
/hacker_rank/PALG-2-simple-array-sum/python/main.py
314
3.5625
4
#!/bin/python3 import sys def parse_input(text): lines = text.split('\n') n = int(lines[0]) numbers = [int(i) for i in lines[1].split()] return n, numbers def main(n, numbers): return sum(numbers) if __name__ == '__main__': args = parse_input(sys.stdin.read()) print(main(*args))
e1f29bcd3953484dbae8e45e55fee4d85346488d
ailic96/mandelbrot
/functions.py
2,714
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import numpy def mandelbrot(x, y, maxit): """ Computes real and imaginary numbers, number of iterations returns value of current iteration. Takes input of complex numbers: x - real value y - imaginary value maxit - maximum iteration. z is a part of Mandelbrot set only if the absolute value for z is greater than 2 and if the function doesn't go to infinity (does not diverge when iterated) """ c = x + y * 1j z = 0 + 0j it = 0 while abs(z) < 2 and it < maxit: z = z*z + c it += 1 return it help_text = """HELP MENU:\n\n This code implements compution of Mandelbrot set\n\n ||||||Data types: \t w = int\t Image width,\n \t h = int\t Image height,\n \t x1 = float\t minimum X-Axis value,\n \t x2 = float\t maximum X-Axis value,\n \t y1 = float\t minimum Y-Axis value,\n \t y2 = float\t maximum Y-Axis value,\n \t maxit = int\t maximum interation,\n\n \t color_mode=int (0-3) color modes, 0 - default\n ||||||Running Instructions:\n\t Serial: python3 mandelbrot_s.py width height x1 x2 y1 y2 maxIt color_mode Parallel: mpirun -np numProcc mandelbrot_p.py width height x1 x2 y1 y2 maxIt color_mode \nExample:\n\t python3 mandelbrot_s 512 512 -2.0 1.0 -1.0 1.0 250 0 mpirun -np 3 python3 mandelbrot_s 512 512 -2.0 1.0 -1.0 1.0 250 0 """ def help_menu(): """ Help function with instructions for running the code. Enables using -h as a help argument""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help=help_text) parser.parse_args() def change_colors(c, C): """ Argument c calls a mathematical operation used on argument C and returns a value. Used for graphing""" if c == 0: return C #defualt elif c == 1: return numpy.sin(numpy.abs(C)) elif c == 2: return numpy.cos(numpy.abs(C)) elif c == 3: return numpy.log(numpy.abs(C)) else: print("Invalid color input! Assigning default color mode...") return C import sys def progressbar(it, prefix="", size=60, file=sys.stdout): """ Code progress bar, not implemented (yet) """ count = len(it) def show(j): x = int(size*j/count) file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count)) file.flush() show(0) for i, item in enumerate(it): yield item show(i+1) file.write("\n") file.flush()
68b04d2aff18d8bdaaaa684140e10729f5a8390c
sethuramvinoth/DataStructures
/Array/ClassAndObjects.py
1,571
4.40625
4
class MyClass: "Description of the Class Comes here!!!" a = 10; def func(self): print('Hi') print(MyClass.func); print(MyClass.a); print(MyClass.__doc__); # whenever an object calls its method, the object itself is passed as the first argument. So, ob.func() translates into MyClass.func(ob). # In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument # list that is created by inserting the method's object before the first argument. # Creating Objects class ClassTwo: "Class with object" a = 5; def func(self): print('Called by Object') ob = ClassTwo() print(ob.a) print(ob.func()) #Using the Constructors class Employee: "Class using Constructors" def __init__(self,id,name): #__init__()gets called whenever a new object of that class is instantiated. self.name = name; #Class functions that begins with double underscore (__) are called special functions as they have special meaning. self.id = id; def display(self): print('This is ',self.name,'with ID',self.id); emp1 = Employee(100,'Employee_1'); emp1.display(); emp2 = Employee(200,'Employee_2'); emp2.salary=2000 print(emp2.salary) #Deleting Attributes and Objects del emp2.salary del emp2 #On the command del emp2 this binding is removed and the name emp2 is deleted from the corresponding namespace # emp2.display(); The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed.
9aa96e9c47f0109ff061d0ce0b3718e69e53b95c
kenandres/Python_Program_Flow
/ifChallenge.py
311
4.15625
4
name = input("Please enter your name: ") age = int(input("Please enter your age: ")) if 18 <= age < 31: print("Welcome to the club, {0}!".format(name)) elif age < 18: print("Please come back in {0} years.".format(18 - age)) else: print("Sorry, {0}, you're not welcome here.".format(name))
03c211b6f2e345d7bc99e0a96e26d810085046d6
gniadoo/Simple_banking_system
/main.py
7,773
3.90625
4
import sys import sqlite3 from random import randint # Creating database try: con = sqlite3.connect("card.s3db") except sqlite3.Error as error: print('Failed to connect SQLite: ', error) sys.exit() cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS card(" "id INTEGER PRIMARY KEY AUTOINCREMENT," "number TEXT," "pin TEXT," "balance INTEGER DEFAULT 0)") con.commit() print('DB has been created') def card_luhn_generator(): # Creating card number with luhn algorithm can = "" for i in range(9): can += str(randint(0, 9)) check_sum = 0 luhn_index = int(1) for digit in str(400000) + can: if luhn_index % 2 != 0: digit = int(digit) * 2 if int(digit) > 9: digit = int(digit) - 9 check_sum += int(digit) luhn_index += 1 last_digit = 10 - (check_sum % 10) if last_digit == 10: last_digit = 0 return str(400000) + can + str(last_digit) def is_number_valid_with_luhn(number): # Checking if card is valid with luhn algorithm check_sum = 0 luhn_index = int(1) for digit in number: if luhn_index % 2 != 0: digit = int(digit) * 2 if int(digit) > 9: digit = int(digit) - 9 check_sum += int(digit) luhn_index += 1 return check_sum % 10 def log_into_account(card): # Defining whole log in process print(" ") print("Enter your card number:") try: card_number = int(input(">")) print("Enter your PIN:") card_pin = int(input(">")) try: cur.execute("SELECT COUNT (*) FROM card WHERE number = ? AND pin = ?", (int(card_number), int(card_pin),)) is_data_valid = cur.fetchone()[0] if is_data_valid: print(" ") print("You have successfully logged in!") print(" ") card.user_panel(card_number) else: print(" ") print("Wrong card number or PIN!") print(" ") except ValueError: print(" ") print("Wrong card number or PIN!") print(" ") except ValueError: print(" ") print("Wrong card number/PIN type!\n") class Card: # Defining card class def __init__(self): self.number = None self.pin = "" self.balance = 0 def create_card(self): print("Your card has been created") print("Your card number:") while True: self.number = card_luhn_generator() # Checking if card with this number already exists in database cur.execute("SELECT COUNT (*) FROM card WHERE number = ?", (self.number,)) is_number_taken = cur.fetchone()[0] if is_number_taken == 1: continue else: break print(self.number) for i in range(4): self.pin += str(randint(0, 9)) print("Your card PIN:") print(self.pin) # Inserting card data to database cur.execute("INSERT INTO card (number, pin, balance) VALUES (?, ?, ?)", (self.number, self.pin, self.balance)) con.commit() # Defining whole functionality after log in def user_panel(self, number): while True: self.number = number print("1. Balance\n" "2. Add income\n" "3. Do transfer\n" "4. Close account\n" "5. Log out\n" "0. Exit\n") while True: user_action = input(">") if user_action == str(0) or user_action == str(1) or user_action == str(2) or\ user_action == str(3) or user_action == str(4) or user_action == str(5): break else: print("Wrong action index") if user_action == str(1): print(" ") cur.execute("SELECT balance FROM card WHERE number = ?", (number,)) print("Balance: {}".format(cur.fetchone()[0])) print(" ") elif user_action == str(2): print(" ") print("Enter income: ") try: income = int(input("> ")) cur.execute("UPDATE card SET balance = balance + ? WHERE number = ?", (income, number,)) con.commit() print(" ") print("Income was added!\n") except ValueError: print(" ") print("Wrong amount!\n") elif user_action == str(3): print(" ") self.transfer_money(number) print(" ") elif user_action == str(4): print(" ") cur.execute("DELETE FROM card WHERE number = ?", (number,)) con.commit() print("The account has been closed!") print(" ") break elif user_action == str(5): print(" ") print("You have successfully logged out!") print(" ") break elif user_action == str(0): print(" ") print("Bye!") sys.exit() # Defining whole money transfer process def transfer_money(self, number): print("Enter card number:") receiving_card = input(">") try: if int(receiving_card) == int(self.number): print("You can't transfer money to the same account!") return None if is_number_valid_with_luhn(receiving_card): print("Probably you made a mistake in the card number. Please try again!") return None cur.execute("SELECT COUNT (*) FROM card WHERE number = ?", (receiving_card,)) is_number_taken = cur.fetchone()[0] if int(is_number_taken) == 0: print("Such a card does not exist.") return None except ValueError: print("Incorrect account type number!") return None print("Enter how much money you want to transfer:") try: transfer_money = int(input(">")) cur.execute("SELECT balance FROM card WHERE number = ?", (number,)) if transfer_money > int(cur.fetchone()[0]): print("Not enough money!") return None cur.execute("UPDATE card SET balance = balance + ? WHERE number = ?", (transfer_money, receiving_card,)) con.commit() cur.execute("UPDATE card SET balance = balance - ? WHERE number = ?", (transfer_money, self.number,)) con.commit() print("Success!") except ValueError: print("Incorrect money type!") # Main panel while True: print("1. Create an account\n2. Log into account\n0. Exit") while True: action = input(">") if action == str(0) or action == str(1) or action == str(2): break else: print("Wrong action index") new_card = Card() if action == str(1): print(" ") new_card.create_card() print(" ") elif action == str(2): cur.execute("SELECT COUNT (*) FROM card") card_numbers_in_database = cur.fetchone()[0] if not card_numbers_in_database: print(" ") print("No account to log in") print(" ") else: log_into_account(new_card) elif action == str(0): break print(" ") print("Bye") print(" ") cur.close()
aeaaf247c9f355528f2313e5a60046bd0ddf1701
PrayasMishra/basic-calculator
/calc.py
1,985
3.5625
4
from tkinter import * w=Tk() w.title("my Calculator") w.geometry("260x240") exp="" def clear(): global exp exp="" v.set(exp) def btnclk(n): global exp exp+=str(n); v.set(exp) def calculate(): global exp res=eval(exp) v.set(res) v=StringVar() E=Entry(w,text="",bg="aqua",font=("arial",18,"bold"),textvariable=v) b0=Button(w,text="0",font=("arial",18,"bold"),command=lambda:btnclk(0)) b1=Button(w,text="1",font=("arial",18,"bold"),command=lambda:btnclk(1)) b2=Button(w,text="2",font=("arial",18,"bold"),command=lambda:btnclk(2)) b3=Button(w,text="3",font=("Arial",18,"bold"),command=lambda:btnclk(3)) b4=Button(w,text="4",font=("arial",18,"bold"),command=lambda:btnclk(4)) b5=Button(w,text="5",font=("arial",18,"bold"),command=lambda:btnclk(5)) b6=Button(w,text="6",font=("arial",18,"bold"),command=lambda:btnclk(6)) b7=Button(w,text="7",font=("arial",18,"bold"),command=lambda:btnclk(7)) b8=Button(w,text="8",font=("arial",18,"bold"),command=lambda:btnclk(8)) b9=Button(w,text="9",font=("arial",18,"bold"),command=lambda:btnclk(9)) bAns=Button(w,text="=",font=("arial",18,"bold"),command=calculate) bReset=Button(w,text="C",font=("arial",18,"bold"),command=clear) bPlus=Button(w,text="+",font=("arial",18,"bold"),command=lambda:btnclk('+')) bMinus=Button(w,text="-",font=("arial",18,"bold"),command=lambda:btnclk('-')) bTimes=Button(w,text="*",font=("arial",18,"bold"),command=lambda:btnclk('*')) bDivide=Button(w,text="/",font=("arial",18,"bold"),command=lambda:btnclk('/')) E.grid(row=1,column=1,columnspan=4) b1.grid(row=2,column=1) b2.grid(row=2,column=2) b3.grid(row=2,column=3) b4.grid(row=2,column=4) b5.grid(row=3,column=1) b6.grid(row=3,column=2) b7.grid(row=3,column=3) b8.grid(row=3,column=4) b9.grid(row=4,column=1) b0.grid(row=4,column=2) bAns.grid(row=4,column=3) bReset.grid(row=4,column=4) bPlus.grid(row=5,column=1) bMinus.grid(row=5,column=2) bTimes.grid(row=5,column=3) bDivide.grid(row=5,column=4) w.mainloop()
57e1a1887edc29dc97a69f4c860fe6f9cb833fe9
ncy906302/okonomiface
/cs.py
158
3.515625
4
import numpy as np def CalculateSimilarity(a,b): a = np.array(a[:]) b = np.array(b[:]) return sum(a*b)/ (sum(a*a) **0.5 ) * (sum(b*b) **0.5)
9fa42681e84ebaae9d4323370259342b2820b0ed
Mike-Whitley/Programming
/cosc367 AI - Machine learning/lb9q5.py
1,378
3.578125
4
import csv def learn_likelihood(file_name, pseudo_count=0): with open(file_name) as in_file: training_examples = [tuple(row) for row in csv.reader(in_file)] #open the csv file as read in all the values true_values = 0 row_count = 0 likelihoods = [] for row in training_examples: is_spam = 1 if row[-1] == '1' else 0 if row_count == 0: #if its the first row we want the liklihoods to be the psuedo count value pairs for length of all items likelihoods = [[pseudo_count, pseudo_count] for i in range(len(row) - 1)] else: for i in range(len(row) - 1): likelihoods[i][is_spam] += int(row[i]) row_count += 1 true_values += is_spam #determine if probability likligood is true of false divide and add together for probability in likelihoods: probability[True] /= (true_values + 2 * pseudo_count) probability[False] /= (row_count - 1 - true_values + 2 * pseudo_count) return likelihoods likelihood = learn_likelihood("spam-labelled.csv") print("P(X1=True | Spam=False) = {:.5f}".format(likelihood[0][False])) print("P(X1=False| Spam=False) = {:.5f}".format(1 - likelihood[0][False])) print("P(X1=True | Spam=True ) = {:.5f}".format(likelihood[0][True])) print("P(X1=False| Spam=True ) = {:.5f}".format(1 - likelihood[0][True]))
4bc01cc5d6ea25762c811c747d78c76e13bdc1f2
Keftcha/codingame
/training/medium/conway-sequence/python.py
520
3.53125
4
r = int(raw_input()) l = int(raw_input()) liste = [r] for _ in range(l -1): liste_suivante = [] pointeur_rouge, pointeur_bleu = 0, 0 while pointeur_bleu < len(liste): while (pointeur_rouge < len(liste)) and (liste[pointeur_rouge] == liste[pointeur_bleu]): pointeur_rouge += 1 liste_suivante.extend([pointeur_rouge - pointeur_bleu, liste[pointeur_bleu]]) pointeur_bleu = pointeur_rouge liste = liste_suivante liste = [str(nb) for nb in liste] print(" ".join(liste))
d8e0455d47fc664f8ec900b5cb6ca0730a0de514
anasahmed700/python
/5thClass/Dictionary.py
3,517
3.890625
4
# DICTIONARY 1 # e.g; dict = {'key': 'value'} profile = {'name': 'Anas', 'age': 24, 'email': '[email protected]'} print(profile) print(profile['name']) print(profile['age']) # DICTIONARY 2 profile = {'name': 'Anas', 'age': 24, 'email': '[email protected]', True: 'working', 5: True} print(profile[True]) print(profile[5]) # DICTIONARY 3 print('\nCHANGING VALUE OF A KEY:') profile['name'] = 'Anas Ahmed' print(profile) # DICTIONARY 4 print('\nPRINTING KEYS & VALUES IN SEPARATED LISTS') print(profile.items()) print('USING for loop') for key, value in profile.items(): print('\nkey: ', key) print('value: ', value) # DICTIONARY 5 print('\nPRINTING JUST VALUES FROM DICT') print(profile.values()) print('USING for loop') for value in profile.values(): # print('\nkey: ', key) print('value: ', value) # DICTIONARY 6 favoriteLanguage = {'anas': 'python', 'babar': 'C#', 'sameer': 'html', 'ali': 'python'} print('\nSORT THE DICT FOR TEMPORARILY') for name in sorted(favoriteLanguage.keys()): print(name.title()+', thank you for taking the poll.') # DICTIONARY 7 print('\nUSING set KEYWORD TO PICK ALL UNIQUE VALUES') for language in set(favoriteLanguage.values()): print(language.title()) # DICTIONARY 8 print('\nDICTIONARY DOES NOT DUPLICATE THE VALUES') a = {'anas', 'ahmed', 'ahmed'} print(a) # DICTIONARY 9 user1 = {'name': 'anas', 'email': '[email protected]'} user2 = {'name': 'ali', 'email': '[email protected]'} user3 = {'name': 'asad', 'email': '[email protected]'} users = [] users.append(user1) users.append(user2) users.append(user3) print('\nAPPENDING DICTIONARY IN A LIST') print(users) # DICTIONARY 10 stud1 = {'name': 'anas', 'email': '[email protected]', 'languages': ['python', 'C#', 'sql']} stud2 = {'name': 'babar', 'email': '[email protected]', 'languages': ['C#', 'java', 'php']} stud3 = {'name': 'ali', 'email': '[email protected]', 'languages': ['C', 'python', 'sql']} students = [stud1,stud2,stud3] print(students) # DICTIONARY 11 print('\nNESTED for loop') for stud in students: print(stud) for key, val in stud.items(): print('key: ', key,' -- value: ',val) if key == 'languages': for lang in val: print (lang) print ('') # Dictionary 12 print('\nSTORING LISTS IN A DICTIONARY:') studentDict = {} studentDict['stud1'] = stud1 studentDict['stud2'] = stud2 studentDict['stud3'] = stud3 print(studentDict) # Dictionary 13 responses = {} pollingActive = True while pollingActive: name = input('\nwhat is your name? ') response = input('\nWhich mountain would you like to climb someday? ') responses[name] = response repeat = input('\nWould you like to let another person respond? (yes/no) ') if repeat == 'no': pollingActive = False print('\n--polling results--') for name, response in responses.items(): print(name + ' would you like to climb '+ response + '.') # Dictionary 14 ''' Global dictionary 1) cmp(dic1, dict2) 2) len(dic) 3) str(dic) 4) type(variable) Class function 1) dic.clear() 2) dic.copy() 3) dict.fromkeys() 4) dic.get(key, default=None) 5) dic.has_key(key) 6) dic.items() 7) dic.keys() 8) dic.values() 9) dic.setdefault(key, default=None) 10) dic.update(dic2) ''' print('\nUSE OF DICT CLASS FUNCTIONS') student = {'Name': 'Anas','age': 23} print(student) # student.clear() # print(student) # print(student.fromkeys()) print(student)
0e1d66d35116674a8bafb1fabd2de1847d6fcc15
aquatiger/assignments
/fibo.py
243
3.609375
4
global steps steps = 0 def fibo(n): global steps steps += 1 if n <= 2: return 1 return fibo(n-1) + fibo(n-2) for i in range(20): steps = 0 print(str(i) + ' ' + str(fibo(i)) + ' ' + str(steps)) print(fibo(10))
8b252a0a235157a98e7b18ac690527cd74824cc9
ceharrin/legendary-octo-giggle
/src/main.py
2,790
4
4
import random import src.BinManager as BinManager # Some constants and default values min_int = 20001 max_int = 380000 bin_size = 36000 range_size = 1000 num_bins = 10 # Main entry point. Prompt for user input and then create the bins based on the provided input. # Generate the random numbers and bin them. # Output the results into a csv file that can be loaded into Excel. # # This is a naive implementation. Inputs are not constrained beyond int type checking and # string length. Bin sizes are calculated based upon homework specification and not dynamically # determined. # # File output is not verified. Basic unit tests are available in ../test/ # # Author: Chris Harrington # July 2019 # CSC 540 Homework assignment #3 # Histograms # # You can clone the project from: https://github.com/ceharrin/legendary-octo-giggle.git # (I let GitHub name the repo....) def main(): show_banner() n_bins = read_int_input("Please enter the number of bins to create: ") rand_num_cnt = read_int_input("Please enter the count of random numbers to generate: ") file_name = input( "Please enter the file name to store the output: (an existing file with the same name will be overwritten)") # Default to constant if needed if n_bins < 1: n_bins = num_bins # Create an instance of the BinManager using the inputs. bin_manager = BinManager.BinManager(n_bins, min_int, max_int, bin_size) # Default to constant if needed if rand_num_cnt < 1: rand_num_cnt = range_size # Generate a random int N times and bin it for x in range(rand_num_cnt): res = random.randint(min_int, max_int) bin_manager.bin(res) # Output summary data to console and then write the data out in a csv file bin_manager.print_me() bin_manager.output_me(file_name) # Read an int from input. Little validation performed other than # throwing an error if the user enters a non-int. Use can re-enter value def read_int_input(message): while True: try: userInput = int(input(message)) except ValueError: print("The input must be an integer. Please enter a new value.") continue else: return userInput # Read a string from input. Little validation performed other than # checking the string length. User can re-enter data def read_string_input(message): while True: userInput = input(message) if userInput.__len__() == 0: print("Please enter a file name: ") continue else: return userInput # A fun banner is displayed when the program runs def show_banner(): with open("../resources/banner.txt") as f: line = f.read() print(line) if __name__ == "__main__": main()
ac5f72205adb4c5c3efd2339a62414bb0d30e658
abhidurg/CSE_480_Database_Systems
/proj04/CRUD_principles.py
325
3.5625
4
import sqlite3 def crud(conn): conn.execute("INSERT INTO students VALUES ('Cam', 98, ''); ") conn.execute("UPDATE students SET grade=100 WHERE name='Josh';") conn.execute("UPDATE students SET grade=grade-10, notes='SUCKER' WHERE name LIKE '%z%'") conn.execute("DELETE FROM students WHERE grade <= 60")
0b662dc40c78bd7488e0a5a06dad2930f8d58ace
sfeng77/myleetcode
/perfectSquares.py
734
3.890625
4
""" Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. """ #ACCEPTED class Solution(object): def __init__(self): self.d = {0:0} def numSquares(self, n): """ :type n: int :rtype: int """ from math import sqrt if n not in self.d: m = n for i in range(int(sqrt(n)), 0, -1): if i * i * m < n: break k = self.numSquares(n - i * i) m = min(m, k + 1) self.d[n] = m return self.d[n]
9ab5421fa8b620e360afe5081e14b64cfeeeafe6
allen880117/Othello-IntroAI-GroupProject
/Othello-Src-Python/othello.py
1,897
3.734375
4
#!/usr/bin/env python3 import display import othello import board import player import game_util import coord class Othello(): """ Class: Othello """ def __init__(self): self.board = board.Board() self.player_black = player.Player() self.player_white = player.Player() def do_pre_process(self) -> None: self.board.clear() self.player_black.set_color(True) self.player_white.set_color(False) self.do_welcome_event def do_main_process(self) -> None: is_black = True # Print Board display.clear() display.display(self.board) while not game_util.is_end(self.board): # There exists valid step for this color valid_steps = game_util.get_valid_steps(self.board, is_black) if len(valid_steps) != 0: # Ask Player step = coord.NO_ACTION if is_black: step = self.player_black.get_step(self.board) else: step = self.player_white.get_step(self.board) game_util.do_set_and_flip(self.board, is_black, step) # Reverse Color is_black = not is_black # Print Board display.clear() display.display(self.board) def do_post_process(self) -> None: result = game_util.get_result(self.board) if result == 0: # Draw print("Draw") elif result > 0: # Black Win print("Black Win, %d" % (result)) else: # White Win print("White Win, %d" % (-result)) def do_welcome_event(self) -> None: display.clear() display.display(self.board) def start_game(self) -> None: self.do_pre_process() self.do_main_process() self.do_post_process()
685b938734e206efa305d03636fc5b26fa6cbbf6
dfeusse/2018_practice
/dailyPython/07_july/23_smallestInArray.py
686
4.34375
4
''' Find the smallest integer in the array Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this kata, that the supplied array will not be empty. ''' def find_smallest_int(arr): minNum = arr[0] for i in arr: if i < minNum: minNum = i return minNum print find_smallest_int([78, 56, 232, 12, 11, 43])#, 11) print find_smallest_int([78, 56, -2, 12, 8, -33])#, -33) print find_smallest_int([0, 1-2**64, 2**64])#, 1-2**64) def findSmallestInt(arr): #sort array arr.sort() return arr[0]
d45ed169b854ad1602277079a3ff18df306daf7c
BYU-ACM/warm-up-day-2-tehrmc08
/sol.py
2,808
4.28125
4
def Binary_Search(arr, to_find): """A direct implementation of Newton's Method (For sanity assume that func and func_prime define there own division correctly, that is, don't cast anything to a float) params: arr (a list ordered from least to greatest) to_find (the item to find in arr) returns: index (int), x, s.t. arr[x] == to_find None(none-type) if for all x, arr[x] != to_find """ cont = True low = 0 high = len(arr)-1 #c = 0 while(cont): mid = (low + high)/2 if(arr[mid] < to_find): #print mid low = mid elif(arr[mid] > to_find): #print mid high = mid else: return mid if(arr[mid] == to_find): return mid if(arr[low] == to_find): return low if(arr[high] == to_find): return high if(high==low or high == (low +1)): #print mid return None #c=c+1 #pass def Bisection(func, left_side, right_side, tol=1e-5): """A direct implementation of Newton's Method (For sanity assume that func and func_prime define there own division correctly, that is, don't cast anything to a float) params: func (a function) left_side (a value for the function to take on, it should have opposite sign from `right_side`) right_side (a value for the function to take on, it should have opposite sign from `left_side`) tol (a value for which the function should return once a value at least that distance from zero is found) returns: root (float), x, s.t. abs(func(x))<tol None(none-type) if func(left_side), func(right_side) < 0 or func(left_side), func(right_side) > 0 """ if(func(left_side) < 0 and func(right_side) < 0): return None if(func(left_side) > 0 and func(right_side) > 0): return None cont = True times = 0 if(func(left_side) < 0): #print "HERE" low = left_side high = right_side while(cont): times += 1 mid = (low + high)/2 if(func(mid) < -tol): low = mid elif(func(mid) > tol): high = mid else: return mid if(times > 100): return mid else: #print "THERE" low = right_side high = left_side while(cont): times += 1 mid = (low + high)/2 if(func(mid) < -tol): low = mid elif(func(mid) > tol): high = mid else: return mid if(times > 100): print mid return mid pass
3c3c8ac1cb37a49fc3bcd310186c3d756630a289
thewinterKnight/Python
/dsa/miscellaneous/quicksort.py
1,067
4.03125
4
# Quick Sort import random def create_array(m, M): arr = list(range(m, M+1)) random.shuffle(arr) return arr def create_array_wt_duplicates(m, M, num_duplicates): arr = list(range(m, M+1)) # print(arr) arr.extend(generate_random_list(m, M, num_duplicates)) random.shuffle(arr) return arr def generate_random_list(m, M, num_elements): arr = [] arr_len = len(arr) while arr_len < num_elements: arr.append(random.randint(m, M)) arr_len = len(arr) return arr def quicksort(arr, start, end): if start < end: pivot = partition(arr, start, end) quicksort(arr, start, pivot-1) quicksort(arr, pivot+1, end) def partition(arr, start, end): pivot_element = arr[end] i = start-1 for j in range(start, end): if arr[j] < pivot_element: i+=1 swap(arr, i, j) swap(arr, i+1, end) return i+1 def swap(arr, index1, index2): temp = arr[index1] arr[index1] = arr[index2] arr[index2] = temp if __name__=="__main__": arr = create_array_wt_duplicates(0,7,3) print(arr) quicksort(arr, 0, len(arr)-1) print('sorting...\n', arr)
feac0b03affbecf09ea2e611d6f05a699ad82e6d
narangmohit3121/Python
/DictionaryPractice.py
288
3.71875
4
directions = {'North': 'N', 'South': 'S', 'West': 'W', 'East': 'E' } for direction in directions.keys(): print(direction) def make_dictionary(**kwargs): return kwargs print(make_dictionary(one='one', two='2', three=3))
859580e90ce38cfc9514fb75b75f381aa4aaf2ae
colafson/Virtual_Sommolier_CPSC322
/mysklearn/.ipynb_checkpoints/myutils-checkpoint.py
13,937
3.5
4
import math import numpy as np import random #import mysklearn.mypytable as mypytable #this is used to get the total number of occuances of #each diffrent value for a certain column in a table def get_table_frequency (table, header_id): col = table.get_column(header_id) ids = [] values = [] for val in col: if val in ids: ind = ids.index(val) values[ind] += 1 else: ids.append(val) values.append(1) return [ids, values] #this fucntion is given a list of cut offs for a #column of numerical data and returns how many elements #were in each group def range_rating(table, cut_offs, col_name): col = table.get_column(col_name) values = [] for row in col: for ran in range(len(cut_offs)): low = cut_offs[ran][1] high = cut_offs[ran][2] score = cut_offs[ran][0] if ran == 0 and row <= high: values.append(score) elif ran + 1 == len(cut_offs) and row >= low: values.append(score) else: if row >= low and row <= high: values.append(score) return values #this function seprates the elements of a numeric #column into five predetemined boxes and returns #the number of occuences. def five_boxes(table, col_name): col = table.get_column(col_name) max_val = max(col) min_val = min(col) difference = max_val - min_val division = int(difference/5) ranges = [] start = min_val for x in range(5): value = [x+1] value.append(start) value.append(start+division) start = start+division+1 ranges.append(value) return range_rating(table,ranges,col_name) #this fucntion gets the frequency for a set of scores #and return how many times each score occurs def get_range_frequencey(data, scores): values = [] for _ in range(len(scores)): values.append(0) for row in data: if row in scores: index = scores.index(row) values[index] += 1 return values #this computes the slope, intercept, #correlation coefficent, and covariance for #the input data sets def compute_slope_intercept(x,y): meanX = sum(x)/len(x) meanY = sum(y)/len(y) m = 0 top = 0 bottomX = 0 bottomY = 0 for i in range(len(x)): top += ((x[i]-meanX)*(y[i]-meanY)) bottomX += (x[i]-meanX)**2 bottomY += (y[i]-meanY)**2 m = top/bottomX b = meanY-m*meanX r = top / (bottomX*bottomY)**(1/2) cov = top/len(x) return m,b,r,cov #this fucntion gets multiple columns from # a data table and returns them to the user def get_row_totals(table, cols): indexes = [] values = [] for x in cols: indexes.append(table.column_names.index(x)) values.append(0) for row in table.data: for ind in range(len(indexes)): values[ind] += row[indexes[ind]] return values # this fucntion is used to convert ratings into a #decimal form in the range of 1 to 10 def convert_to_decimal_rating(ratings): fixed = [] for row in ratings: if not row == "": temp = str(row).replace("%","") temp = float(temp) temp = temp%10 fixed.append(temp) else: fixed.append("") return fixed #this removes any blank entries from a list def remove_blanks(data): clean =[] for x in data: if not x == "": clean.append(x) return clean #this fucntion returns the average rating for a specified #column. it returns what the average value for each distinct #element of the column is. def get_genre_frequency(table, header_id, rate): col = table.get_column(header_id) ids = [] values = [] for val in range(len(col)): genre = "" rating = rate[val] for x in range(len(col[val])): if not col[val][x] == ',' and not x == len(col[val]): genre += col[val][x] else: if genre in ids: if not rating == "": ind = ids.index(genre) values[ind] = (values[ind]+float(rating))/2 else: if not rating == "": ids.append(genre) values.append(float(rating)) genre = "" return [ids, values] def compute_euclidean_distance(v1, v2): dist = np.sqrt(sum([(v1[i] - v2[i]) ** 2 for i in range(len(v1))])) return dist def compute_mpg_rating(num): if num <= 13: return 1 elif num >= 13 and num < 15: return 2 elif num >= 15 and num < 17: return 3 elif num >= 17 and num < 20: return 4 elif num >= 20 and num < 24: return 5 elif num >= 24 and num < 27: return 6 elif num >= 27 and num < 31: return 7 elif num >= 31 and num < 37: return 8 elif num >= 37 and num < 45: return 9 else: return 10 def normalize_data(data): maximun = max(data) mininum = min(data) normal = [] for x in data: val = (x - mininum)/(maximun-mininum) * 10.0 normal.append(val) return normal def get_accuracy_error(matrix): accuracy = 0 error = 0 total = 0 for row in range(len(matrix)): total += sum(matrix[row]) for col in range(len(matrix[row])): if row == col: accuracy += matrix[row][col] else: error += matrix[row][col] accuracy = accuracy/total error = error/total return accuracy, error def catagorical_to_numeric(data, catagories): for row in range(len(data)): for col in range(len(data[row])): if data[row][col] in catagories: index = catagories.index(data[row][col]) data[row][col] = index return data def catagorical_weight(data): result = [] for x in data: if x <= 1999: result.append(1) elif x>2000 and x<= 2499: result.append(2) elif x>2500 and x<= 2999: result.append(3) elif x>3000 and x<= 3499: result.append(4) else: result.append(5) return result def print_matrix(label, matrix): header = "" for i in range(len(label)): header += "\t"+str(label[i]) header += "\tTotal" print(header) print("---------------------------------------------------------------------------------") for x in range(len(matrix)): row = str(label[x])+"|" for elm in matrix[x]: row += "\t"+str(elm) row += "\t"+str(sum(matrix[x])) print(row) def make_header(instances): header = [] for col in range(len(instances[0])): header.append("att"+str(col)) return header def make_att_domain(instances, header): dic = {} for x in range(len(header)): vals = [] for row in instances: if not row[x] in vals: vals.append(row[x]) dic[header[x]] = vals return dic def select_attribute(instances, available_attributes, header, attribute_domain): #need to do entropy based selection entropy_scores = [] for att in available_attributes: dic = attribute_domain[att] row = [] for _ in range(len(dic)): row.append(0) values = [] classes = [] att_index = header.index(att) for element in instances: if not element[-1] in classes: classes.append(element[-1]) values.append(row.copy()) class_ind = classes.index(element[-1]) val_ind = dic.index(element[att_index]) values[class_ind][val_ind] += 1 att_entropy = [] counts = [] for col in range(len(values[0])): total = 0 vals = [] entropy = 0 for row in range(len(values)): value = values[row][col] total += value vals.append(value) for x in vals: if x > 0: entropy += -(x/total)*(math.log2(x/total)) att_entropy.append(entropy) counts.append(total) new_entropy = 0 for ind in range(len(att_entropy)): new_entropy += (counts[ind]/len(instances))*att_entropy[ind] entropy_scores.append(new_entropy) index = entropy_scores.index(min(entropy_scores)) return available_attributes[index] def all_same_class(instances): first_label = instances[0][-1] for instance in instances: if instance[-1] != first_label: return False return True def partition_instances(instances, split_attribute, header, attribute_domains): # comments refer to split_attribute "level" attribute_domain = attribute_domains[split_attribute] attribute_index = header.index(split_attribute) partitions = {} # key (attribute value): value (partition) # task: try to finish this for attribute_value in attribute_domain: partitions[attribute_value] = [] for instance in instances: if instance[attribute_index] == attribute_value: partitions[attribute_value].append(instance) return partitions def majority_leaf(partition): classes = [] num_classes = [] for element in partition: if not element[-1] in classes: classes.append(element[-1]) num_classes.append(1) else: index = classes.index(element[-1]) num_classes[index] += 1 instances = max(num_classes) index = num_classes.index(instances) return classes[index], instances def tdidt(current_instances, available_attributes, header, attribute_domain): # basic approach (uses recursion!!): # select an attribute to split on split_attribute = select_attribute(current_instances, available_attributes,header,attribute_domain) #print("splitting on:", split_attribute) # remove split attribute from available attributes # because, we can't split on the same attribute twice in a branch available_attributes.remove(split_attribute) # Python is pass by object reference!! tree = ["Attribute", split_attribute] # group data by attribute domains (creates pairwise disjoint partitions) partitions = partition_instances(current_instances, split_attribute, header, attribute_domain) #print("partitions:", partitions) # for each partition, repeat unless one of the following occurs (base case) for attribute_value, partition in partitions.items(): values_subtree = ["Value", attribute_value] # TODO: append your leaf nodes to this list appropriately # CASE 1: all class labels of the partition are the same => make a leaf node if len(partition) > 0 and all_same_class(partition): #print("CASE 1") leaf = ["Leaf", partition[0][-1], len(partition), len(current_instances)] values_subtree.append(leaf) tree.append(values_subtree) # CASE 2: no more attributes to select (clash) => handle clash w/majority vote leaf node elif len(partition) > 0 and len(available_attributes) == 0: #print("CASE 2") val, instances = majority_leaf(partition) #get number of values in the partition. use insted of len(partition) leaf = ["Leaf", val, instances, len(current_instances)] values_subtree.append(leaf) tree.append(values_subtree) # CASE 3: no more instances to partition (empty partition) => backtrack and replace attribute node with majority vote leaf node elif len(partition) == 0: #print("CASE 3") tree = [] #get all the instances of the higher up attribute and use as partition #for the majority leaf and return tree val, instances = majority_leaf(current_instances) leaf = ["Leaf", val, instances, len(current_instances)] return leaf else: # all base cases are false, recurse!! #print("Recurse") #print(available_attributes) subtree = tdidt(partition, available_attributes.copy(),header, attribute_domain) values_subtree.append(subtree) tree.append(values_subtree) return tree #this funtion is used by the predict fuction in MyDecisionTree #it determines which class a single test instance classifies to def classify_tdidt(tree, instance): prediction = "" if tree[0] == "Attribute": attribute = tree[1] index = int(attribute[-1]) value = instance[index] for x in range(2,len(tree)): if tree[x][0] == "Value": if tree[x][1] == value: return classify_tdidt(tree[x][2], instance) if tree[0] == "Leaf": prediction = tree[1] return prediction #this fucnction is used by print_decision_tree_rules in the MyDecisionTree Class #This determines ther rules of a given tree and prints them to the console def print_rules(tree, attribute_names, class_name, rules): if tree[0] == "Attribute": attribute = tree[1] index = int(attribute[-1]) att_name = attribute_names[index] if rules == "": rules+="IF " else: rules+=" AND " rules += str(att_name) + " == " for x in range(2,len(tree)): if tree[x][0] == "Value": temp = str(tree[x][1]) print_rules(tree[x][2], attribute_names, class_name, rules+temp) if tree[0] == "Leaf": rules += " THEN "+ str(class_name) +" = "+str(tree[1]) print(rules)
5c6043e2a822c8db84f00666f4f27d96fd89398b
ChickenBC/Python-homework
/Chapter10/10-6.py
266
4.0625
4
try: x = input("Enter a number:") x = int(x) y = input("Enter a number:") y = int(y) except ValueError: print("Sorry, I really need a number.") else: sum = x + y print("The sum of " + str(x) + " and " + str(y) + " is " + str(sum) + ".")
cdc53f48838f5cfcad170c98ea9fd468d675ba92
nibsdey/Udemy_SelfDrivingCar
/finding-lanes/lanes_v1.py
1,068
3.796875
4
import cv2 import numpy as np image = cv2.imread('test_image.jpg') lane_image = np.copy(image) # Change to gray scale to convert it from multi-channel (RGB) to single channel image which is easier to process gray = cv2.cvtColor(lane_image, cv2.COLOR_RGB2GRAY) #cv2.imshow('result', gray) # Gaissian filter # Kernel of normally distributed values. It takes the weighted average of each pixel with the neighbouring pixels, thus smoothing the lane_image # 5 by 5 is a typical kernal size # GaussianBlur is used to reduce noise in the gray scale image blur = cv2.GaussianBlur(gray, (5, 5), 0) # cv2.imshow('result', blur) # Apply "Canny" method to identify edges in our image. Done through identifying change in COLOR # Change in brightness is called Gradient # Canny function calculates the derivative of the image function f(x,y) calculating the gradient which tells us the change in brightness # Canny outlines the strongest gradients of our image canny = cv2.Canny(blur, 50, 150) #50 = low threshold, 150=high threshold cv2.imshow('result', canny) cv2.waitKey(0)
82883d73c3cd0c71ac0002ef74cf90c3d4a7e35d
lepangdan/tensorflow_learning
/try.py
19,132
4.1875
4
# empty = 'empty' # # # def is_link(s): # """s is a linked list if it is empty or a (first, rest) pair""" # return s == empty or (len(s) == 2 and is_link(rest(s))) # # # def link(first_s, rest_s): # """construct a linked list from its first element and rest""" # assert is_link(rest_s), "rest must be a linked list." # return [first_s, rest_s] # # # def first(s): # """Return the first element of a linked list s.""" # assert is_link(s), "first only applies to linked lists." # assert s != empty, "empty linked list has no first element." # return s[0] # # # def rest(s): # """Return the rest of the elements of a linked list s.""" # # assert is_link(s), "rest only applies to linked lists." # # assert s != empty, "empty linked list has no rest." # return s[1] # # # def extend_link(s, t): # """Return a list with the elements of s followed by those of t.""" # assert is_link(s) and is_link(t) # if s == empty: # return t # else: # return link(first(s), extend_link(rest(s), t)) # # # def apply_to_all_link(f, s): # """Apply f to each element of s.""" # assert is_link(s) # if s == empty: # return s # else: # return link(f(first(s)), apply_to_all_link(f, rest(s))) # # # def partitions(n, m): # """Return a linked list of partitions of n using parts of up to m. # Each partition is represented as a linked list""" # if n == 0: # return link(empty, empty) # elif n < 0 or m == 0: # return empty # else: # using_m = partitions(n-m, m) # # print('m',m) # with_m = apply_to_all_link(lambda s: link(m, s), using_m) # # print('with_empty',with_m) # without_m = partitions(n, m - 1) # # print('without_m',without_m) # return extend_link(with_m, without_m) # # print(partitions(2,2)) # def is_sort(n): # if n < 10: # return True # else: # return is_sort(n // 10) and (((n // 10) % 10) >= (n % 10)) # # print(is_sort(2)) # print(is_sort(22222)) # print(is_sort(9876543210)) # print(is_sort(9087654321)) # # def mario_number(level): # if level == 1: # return 1 # elif level % 10 == 0: # return 0 # else: # return mario_number(level // 10) + mario_number(level // 100) # # print(mario_number(10101)) # print(mario_number(11101)) # print(mario_number(100101)) # def make_change(n): # # if n == 1 or n == 3 or n == 4: # return 1 # elif n == 2: # return 2 # else: # use1=1+make_change(n-1) # use3=1+make_change(n-3) # use4=1+make_change(n-4) # return min(use1, use3, use4) # # print(make_change(10)) # def elephant(name, age, can_fly): # return [name, age, can_fly] # # def elephant_name(elephant): # return elephant[0] # # def elephant_age(elephant): # return elephant[1] # # def elephant_can_fly(elephant): # return elephant[2] # # dumbo=elephant("Dumbo", 10, True) # print(elephant_name(dumbo)) # print(elephant_age(dumbo)) # print(elephant_can_fly(dumbo)) # def elephant (name, age, can_fly): # def select(command): # if command == "name": # return name # elif command == "age": # return age # elif command == "can_fly": # return can_fly # # return select # def elephant_name(e): # return e("name") # def elephant_age(e): # return e("age") # def elephant_can_fly(e): # return e("can_fly") # # chris=elephant("Christs Martin", 38, False) # print(elephant_name(chris)) # print(elephant_age(chris)) # print(elephant_can_fly(chris)) # class Car(object): # num_wheels = 4 # gas = 30 # headlights = 2 # size = 'Tiny' # # def __init__(self, make, model): # self.make = make # self.model = model # self.color = 'No color yet. You need to paint me.' # self.wheels = Car.num_wheels # self.gas = Car.gas # # def paint(self, color): # self.color = color # return self.make + ' ' + self.model + ' is now ' + color # # def drive(self): # if self.wheels < Car.num_wheels or self.gas <= 0: # return self.make + ' ' + self.model + ' cannot drive!' # self.gas -= 10 # return self.make + ' ' + self.model + ' goes vroom!' # # def pop_tire(self): # if self.wheels > 0: # self.wheels -= 1 # # def fill_gas(self): # self.gas += 20 # return self.make + ' ' + self.model + ' gas level: ' + str(self.gas) # # # class MonsterTruck(Car): # size = 'Monster' # # def rev(self): # print('Vroom! This Monster Truck is huge!') # # def drive(self): # self.rev() # return Car.drive(self) # # # class FoodTruck(MonsterTruck): # delicious = 'meh' # def serve(self): # if FoodTruck.size == 'delicious': # print('Yum!') # if self.food != 'Tacos': # return 'But no tacos...' # else: # return 'Mmm!' # # taco_truck = FoodTruck('Tacos', 'Truck') # taco_truck.food = 'Guacamole' # taco_truck.serve() # taco_truck.food = taco_truck.make # FoodTruck.size = taco_truck.delicious # taco_truck.serve() # taco_truck.size = 'delicious' # taco_truck.serve() # #FoodTruck.pop_tire() # FoodTruck.pop_tire(taco_truck) # print(taco_truck.drive()) # class VendingMachine: # def __init__(self, product, price, num=0, paid=0): # self.product = product # self.price = price # self.paid = paid # self.num = num # # def vend(self): # if self.num == 0: # return 'Machine is out of stock.' # elif self.paid < self.price: # return 'You must deposit $%s more.' % (self.price - self.paid) # elif self.paid == self.price: # self.num -= 1 # return 'Here is your %s' % self.product # else: # self.num -= 1 # temp_paid = self.paid # self.paid = 0 # return 'Here is your %s and $%s change' % (self.product, temp_paid - self.price) # # def deposit(self, paid): # if self.num == 0: # return 'Machine is out of stock. Here is your $%s.' % paid # else: # self.paid += paid # return 'Current balance: $%s' % self.paid # # def restock(self, num): # self.num += num # return 'Current %s stock: %s' % (self.product, self.num) # # v=VendingMachine('candy', 10) # print(v.vend()) # print(v.deposit(15)) # print(v.restock(2)) # print(v.vend()) # print(v.deposit(7)) # print(v.vend()) # print(v.deposit(5)) # print(v.vend()) # print(v.deposit(10)) # print(v.vend()) # print(v.deposit(15)) # # w = VendingMachine ('soda', 2) # print(w.restock(3)) # print(w.restock(3)) # print(w.deposit(2)) # print(w.vend()) # # ten, twenty,thirty = 10, 'twenty', [30] # print('{0} plus {1} is {2}'.format(ten, twenty, thirty)) # class Link: # """A linked list. # # >>> s = Link(1) # >>> s.first # 1 # >>> s.rest is Link.empty # True # >>> s = Link(2, Link(3, Link(4))) # >>> s.second # 3 # >>> s.first = 5 # >>> s.second = 6 # >>> s.rest.rest = Link.empty # >>> s # Displays the contents of repr(s) # Link(5, Link(6)) # >>> s.rest = Link(7, Link(Link(8, Link(9)))) # >>> s # Link(5, Link(7, Link(Link(8, Link(9))))) # >>> print(s) # Prints str(s) # <5 7 <8 9>> # """ # empty = () # # def __init__(self, first, rest=empty): # assert rest is Link.empty or isinstance(rest, Link) # self.first = first # self.rest = rest # # @property # def second(self): # return self.rest.first # # @second.setter # def second(self, value): # self.rest.first = value # # def __repr__(self): # if self.rest is not Link.empty: # rest_repr = ', ' + repr(self.rest) # else: # rest_repr = '' # return 'Link(' + repr(self.first) + rest_repr + ')' # # def __str__(self): # string = '<' # while self.rest is not Link.empty: # string += str(self.first) + ' ' # self = self.rest # return string + str(self.first) + '>' # # link = Link(1) # print(link) # link.rest = link # # print(link.rest.rest.rest.rest.first) # print([2, 3, 4][::-1]) # a = [1, 2, 3] # print(a[len(a):]) from doctest import testmod from doctest import run_docstring_examples # # def sum_naturals(n): # """Return the sum of the first n natural numbers. # # >>> sum_naturals(10) # 55 # >>> sum_naturals(100) # 5050 # """ # total, k = 0, 1 # while k <= n: # total, k = total + k, k + 1 # return total # # print(testmod()) # run_docstring_examples(sum_naturals, globals(),True) # def is_sorted(n): # """ # >>> is_sorted(2) # True # >>> is_sorted(22222) # True # >>> is_sorted(9876543210) # True # >>> is_sorted(9087654321) # False # """ # if n < 10: # return True # return is_sorted(n // 10) and (n // 10 % 10 >= n % 10) # # print(testmod()) # def mario_number(level): # """ # Return the number of ways that Mario can traverse the # level, where Mario can either hop by one digit or two # digits each turn. A level is defined as being an integer # with digits where a 1 is something Mario can step on and 0 # is something Mario cannot step on. >>> mario_number(10101) # >>> mario_number(10101) # 1 # >>> mario_number(11101) # 2 # >>> mario_number(100101) # 0 # """ # if level == 1: # return 1 # elif level % 10 == 0: # return 0 # elif level % 10 == 1: # return mario_number(level // 10) + mario_number(level // 100) # # print(testmod()) # def make_change(n): # """ # Write a function, make_change that takes in an integer amount, n, and returns the minimum number # of coins we can use to make change for that n, # using 1-cent, 3-cent, and 4-cent coins. # Look at the doctests for more examples. # >>> make_change(5) # 2 # >>> make_change(6) # tricky! Not 4 + 1 + 1 but 3 + 3 # 2 # """ # if n <= 4: # return 1 # return min(make_change(n-4), make_change(n-3), make_change(n-1))+1 # print(testmod()) # def elephant(name, age, can_fly): # """ # Takes in a string name, an int age, and a boolean can_fly. Constructs an elephant with these attributes. # >>> dumbo = elephant("Dumbo", 10, True) # >>> elephant_name(dumbo) # 'Dumbo' # >>> elephant_age(dumbo) # 10 # >>> elephant_can_fly(dumbo) # True # """ # # return [name, age, can_fly] # def elephant_name(e): # return e[0] # def elephant_age(e): # return e[1] # def elephant_can_fly(e): # return e[2] # # print(testmod()) # a = [1,5, 4, [2, 3], 3] # print(a[0], a[-1]) # print(len(a)) # print(2 in a) # print(4 in a) # print(a[3][0]) # a = [3, 1, 4, 2, 5, 3] # print(a[1::2]) # print(a[:]) # print(a[4:2]) # print(a[1:-2]) # print(a[::-1]) # # print([i + 1 for i in [1, 2, 3, 4, 5] if i % 2 == 0]) # print( [i * i - i for i in [5, -1, 3, -1, 3] if i > 2]) # print([[y * 2 for y in [x, x + 1]] for x in [1, 2, 3, 4]]) # def is_leaf(tree): # return not branches(tree) # # # def tree(label, branches=[]): # return [label] + list(branches) # # # def label(tree): # return tree[0] # # # def branches(tree): # return tree[1:] # # # def tree_max(t): # if is_leaf(t): # return label(t) # return max(label(t), max([tree_max(branch) for branch in branches(t)])) # # # def height(t): # """Return the height of a tree""" # if is_leaf(t): # return 0 # return 1+ max(height(branch) for branch in branches(t)) # # # def square_tree(t): # if is_leaf(t): # return label(t) ** 2 # return tree(label(t) ** 2, [square_tree(branch) for branch in branches(t)]) # # # def find_path(tree, x): # if label(tree) == x : # 在这个问题里面,最简单的子问题应该是这个!! 与是不是Leaf没有关系 # return [label(tree)] # for b in branches(tree): # if i in []: pass! # path = find_path(b, x) # if path: # return [label(tree)] + path # #after running function body, it will return None automatically if there is no return command # #!!!!什么都不返回 就会返回None!! # # # def prune(t,k): # if k == 0: # # return label(t) #终止条件也要返回的是一棵树才行啊!! # return tree(label(t)) # return tree(label(t), [prune(branch, k-1) for branch in branches(t)]) # # # t = tree(1, # [tree(3, # [tree(4), # tree(5), # tree(6)]), # tree(2)]) # # t1= (2,[tree(7, [tree(3), tree(6, [tree(5), tree(11)])]), tree(15)]) # print(is_leaf(t1)) # print(tree_max(t)) # print(height(t)) # print(square_tree(t)) # print(find_path(t, 5)) from doctest import testmod from doctest import run_docstring_examples # # def list_of_lists(lst): # """ # >>> list_of_lists([1, 2, 3]) # [[0], [0, 1], [0, 1, 2]] # >>> list_of_lists([1]) # [[0]] # >>> list_of_lists([]) # [] # """ # result = [] # for i in lst: # result.append([x for x in range(i)]) # return result # # run_docstring_examples(list_of_lists, globals(),True) # def tree(label, branches=[]): # return [label] + branches # # def label(tree): # return tree[0] # # def branches(tree): # return tree[1:] #returns a list of branches # # def sum_of_node(tree): # """ # >>> t = tree(9,[tree(2),tree(4,[tree(1)]),tree(4, [tree(7), tree(3)])])# Tree from question 2. # >>> sum_of_node(t) # 9 + 2 + 4 + 4 + 1 + 7 + 3 = 30 # 30 # """ # if not branches(tree): # return label(tree) # return label(tree) + sum([sum_of_node(branch) for branch in branches(tree)]) # # # t = tree(4, # # [tree(5, []), # # tree(2, # # [tree(2, []), # # tree(1, [])]), # # tree(1, []), # # tree(8, # # [tree(4, [])])]) # # # # print(t) # t1 = tree(9,[tree(2),tree(4,[tree(1)]),tree(4, [tree(7), tree(3)])]) # run_docstring_examples(sum_of_node,globals(),True) # # def memory(n): # """ # >>> f = memory(10) # >>> f = f(lambda x: x * 2) # 20 # >>> f = f(lambda x: x - 7) # 13 # >>> f = f(lambda x: x > 5) # True # """ # def cal(func): # nonlocal n # n = func(n) # print(n) # return cal # return cal # print(testmod()) #run_docstring_examples(memory, globals(), True) # # def add_this_many(x, el, lst): # """ Adds el to the end of lst the number of times x occurs in lst. # >>> lst = [1, 2, 4, 2, 1] # >>> add_this_many(1, 5, lst) # >>> lst # [1, 2, 4, 2, 1, 5, 5] # >>> add_this_many(2, 2, lst) # >>> lst # [1, 2, 4, 2, 1, 5, 5, 2, 2] # """ # count =0 # for i in lst: # if x == i: # count += 1 # for i in range(count): # lst.append(el) # # print(testmod()) # def reverse(lst): # """ Reverses lst in place. # >>> x = [3, 2, 4, 5, 1] # >>> reverse(x) # >>> x # [1, 5, 4, 2, 3] # """ # for i in range(len(lst) // 2): # lst[i], lst[-1-i] = lst[-1-i], lst[i] # print(testmod()) # def group_by(s, fn): # """ # >>> group_by([12, 23, 14, 45], lambda p: p // 10) # {1: [12, 14], 2: [23], 4: [45]} # >>> group_by(range(-3, 4), lambda x: x * x) # {0: [0], 1: [-1, 1], 4: [-2, 2], 9: [-3, 3]} # """ # groups = {} # for i in s: # key = fn(i) # if key in groups: # groups[key].append(i) # else: # groups[key] = [i] # return groups # # print(testmod()) # def replace_all_deep(d, x, y): # """ # >>> d = {1: {2: 'x', 'x': 4}, 2: {4: 4, 5: 'x'}} # >>> replace_all_deep(d, 'x', 'y') # >>> d # {1: {2: 'y', 'x': 4}, 2: {4: 4, 5: 'y'}} # """ # for key in d: # if type(d[key]) != dict: # if d[key] == 'x': # d[key] = 'y' # else: # replace_all_deep(d[key],x, y) # # print(testmod()) # Constructor def is_tree(tree): if type(tree) != list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True def Tree(label, branches=[]): for branch in branches: assert is_tree(branch) return [label] + branches # Selectors def label(tree): return tree[0] def branches(tree): return tree[1:] # For convenience def is_leaf(tree): return not branches(tree) # def sum_range(t): # """ # Returns the range of the sums of t, that is, the\ # difference between the largest and the smallest # sums of t. # """ # def helper(t): # # return largest sum and smallest sum # if is_leaf(t): # return [label(t), label(t)] # else: # a = min([helper(branch)[1] for branch in branches(t)]) # b = max([helper(branch)[0] for branch in branches(t)]) # x = label(t) # return [b+x, a+x] # x, y = helper(t) # return x - y # # # t = tree(5, [tree(1,[tree(7, [tree(4, [tree(3)])]),tree(2)]),tree(2, [tree(0), tree(9)])]) # print(sum_range(t)) # def no_eleven(n): # """ # Return a list of lists of 1's and 6's that do not contain 1 after 1. # >>> no_eleven(2) # [[6, 6], [6, 1], [1, 6]] # >>> no_eleven(3) # [[6, 6, 6], [6, 6, 1], [6, 1, 6], [1, 6, 6], [1, 6, 1]] # >>> no_eleven(4)[:4] # first half # [[6, 6, 6, 6], [6, 6, 6, 1], [6, 6, 1, 6], [6, 1, 6, 6]] # >>> no_eleven(4)[4:] # second half # [[6, 1, 6, 1], [1, 6, 6, 6], [1, 6, 6, 1], [1, 6, 1, 6]] # """ # result = [] # if n == 0: # return [] # elif n == 1: # return [[6], [1]] # else: # for i in no_eleven(n-1): # if i[-1] == 6: # # result.append(i+[1]) # result.append(i+[6]) # # else: # result.append(i+[6]) # return result # print(testmod()) # def eval_with_add(t): # """ # Evaluate an expression tree of * and + using only # addition. # >>> plus = Tree('+', [Tree(2), Tree(3)]) # >>> eval_with_add(plus) # 5 # >>> times = Tree('*', [Tree(2), Tree(3)]) # >>> eval_with_add(times) # 6 # >>> deep = Tree('*', [Tree(2), plus, times]) # >>> eval_with_add(deep) # 60 # >>> eval_with_add(Tree('*')) # 1 # """ # # if label(t) == '+': # return sum([eval_with_add(branch) for branch in branches(t)]) # elif label(t) == '*': # total =1 # # for b in branches(t): # total, term = 0, total # for _ in range(eval_with_add(b)): # total = total + term # # return total # # else: # return label(t) # print(testmod())
dfe42ed7244c19677a4b7e908e65fd2ca8b57429
armsiwadol69/Python_ss2
/WORK I/ex2.3 dic.py
607
3.859375
4
#2.3 Dictionary #Ex1 dic1 = { "Name" : "Plume", "Class" : "Vanguard", "Rarity" : 3 } print(dic1,type(dic1)) #ex2 dic1 = { "Name" : "Plume", "Class" : "Vanguard", "Rarity" : 3 } print(dic1["Name"],"Is",dic1["Class"]) #ex3 dic1 = { "Name" : "Plume", "Class" : "Vanguard", "Rarity" : 3 } dic1["Name"] = "Elysium" dic1["Rarity"] = 5 print(dic1) #ex dic2 = { "Name" : "Manticore", "Class" : "Specialist", "Rarity" : 5 } dic2["Faction"] = "R.I." print(dic2) #ex5 dic3 ={ "Name" : "Haze", "Class" : "Caster", "Rarity" : 4 } dic3.pop("Class") print(dic3)
c4862502ee055bf006035e0157c37ac58ee0d87e
eclipse-ib/Software-University-Fundamentals_Module
/08-Mid_Exam/More exams/2/2-Shopping_List.py
893
4.0625
4
groceries = input().split("!") while True: command_no_splt = input() if command_no_splt == "Go Shopping!": break command = command_no_splt.split() main_command = command[0] item = command[1] if main_command == "Urgent": if item not in groceries: groceries.insert(0, item) else: continue elif main_command == "Unnecessary": if item in groceries: groceries.remove(item) else: continue elif main_command == "Correct": if item in groceries: old_name = groceries.index(item) new_item = command[2] groceries[old_name] = new_item else: continue elif main_command == "Rearrange": if item in groceries: groceries.remove(item) groceries.append(item) print(", ".join(groceries))
7d3f907c51f789461210fddb8c0c84482f89856a
aspittel/open-file-python
/script.py
98
3.5
4
with open("input.txt") as text: for line in text: print("-------") print(line)