blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2782bd75dee641c1a613daf749edf9657569cf17
way2arun/datastructures_algorithms
/src/arrays/minPartitions.py
1,839
4.03125
4
""" Partitioning Into Minimum Number Of Deci-Binary Numbers A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. Example 1: Input: n = "32" Output: 3 Explanation: 10 + 11 + 11 = 32 Example 2: Input: n = "82734" Output: 8 Example 3: Input: n = "27346209830709182346" Output: 9 Constraints: 1 <= n.length <= 105 n consists of only digits. n does not contain any leading zeros and represents a positive integer. Hide Hint #1 Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. Hide Hint #2 If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Hide Hint #3 Thus the answer is equal to the max digit. """ class Solution: def minPartitions(self, n: str) -> int: # Solution 1 - 188 ms """ res = 0 for x in n: if int(x) > res: res = int(x) return res """ # Solution 2 - 48 ms """ return max(n) """ # Solution 3 - 16 ms if '9' in n: return 9 if '8' in n: return 8 if '7' in n: return 7 if '6' in n: return 6 if '5' in n: return 5 if '4' in n: return 4 if '3' in n: return 3 if '2' in n: return 2 if '1' in n: return 1 # Main Call n = "32" solution = Solution() print(solution.minPartitions(n))
3295a12fbb2eb131d0595957dd9d76f1b9d1997f
krmaxwell/General
/fizzbuzz.py
159
3.5625
4
#!/bin/python i=1 while i <= 100: if i%15 == 0: print 'FizzBuzz' elif i%3 == 0: print 'Fizz' elif i%5 == 0: print 'Buzz' else: print i i = i + 1
40d09eeb5139de3c7a59d6586776f89c6f848b20
mnishiguchi/python_notebook
/MIT6001x/week2/bisectionSearch.py
808
4.21875
4
x = int(raw_input('Enter an integer: ')) # accuracy(+/-) epsilon = 0.00001 # record how many times the program guessed numGuesses = 0 # current range for search low = 0.0 high = x # initial value: user's input # hit the mid point ans = (high + low) / 2.0 # repeat same sequence until as accurate as epsilon while abs(ans**2 - x) >= epsilon: print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans)) numGuesses += 1 # if ans is too low, update low if ans**2 < x: low = ans ans = (high + low) / 2.0 # if ans is too high, update high else: high = ans ans = (high + low) / 2.0 print('numGuesses = ' + str(numGuesses)) print(str(ans) + ' is close to square root of ' + str(x))
d304c679b09cf09e8c9f0d29e9ed8193f41b60e2
ardinur03/belajar_python
/pembelajaran_dalam_yt/aplikasi/air_suhu.py
147
3.71875
4
suhu = float(input()) if int(suhu) <= 0: print("Beku!!!") elif int(suhu) > 0 and int(suhu) <= 100: print("Cair") else: print("Uap!!!")
6ec53dd3dcd0a1922cf139a3dd9ac403ce752fcf
OmarMourad14/Example1
/main.py
83
3.71875
4
def addItUP: sum = 0 for num in range(n+1): sum+=num return num
19c6393d19d3a50bb72966d0c88bcdf2e93e3a21
HenriqueNO/Python-cursoemvideo
/Desafios/Desafio_090.py
429
4.03125
4
info = {'nome': '', 'media': ''} info['nome'] = input('Nome: ') info['media'] = float(input(f'Média de {info["nome"]}: ')) print() print(f'Nome é igual a {info["nome"]}') print(f'Média é igual a {info["media"]}') if info['media'] >= 7: print('Situação do aluno igual a Aprovado!') elif info['media'] < 7: print('Situação do aluno igual a Recuperação!') else: print('Situação do alino igual a Reprovado!')
683bbf420be5d1e3bb1eae4609d7f62bb4d9cbf7
baluneboy/pims
/sandbox/multiple_inheritance.py
580
3.984375
4
#!/usr/bin/env python class First(object): def __init__(self): super(First, self).__init__() print "first" def method_one(self): print "method from %s" % self.__class__.__name__ class Second(object): def __init__(self): super(Second, self).__init__() print "second" def method_two(self): print "this is a method from %s" % self.__class__.__name__ class Third(Second, First): def __init__(self): super(Third, self).__init__() print "that's it" x = Third() x.method_one() x.method_two()
1ac0ae61df4bee8b17d7028e0f87353beec9b33d
danganea/iMTFA
/dutils/imageutils.py
2,498
4.03125
4
import cv2 from PIL import Image import numpy as np import matplotlib.pylab as plt def cv2array2pil(img): """ Take a numpy array from OpenCV BGR format and output it to PIL format to display (RGB). Though this is a simple one-liner one often forgets which underlying format the libraries use. Especially useful for displaying PIL images in Jupyter Notebooks, since OpenCV doesn't work there since it requires a window manager (e.g. libGTK). :param img: Numpy Array containing image in OpenCV BGR format :return: Image in RGB format """ pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) return pil_image _disable_img_display = False def disable_cv2_display(): """ Globally disables displaying images with functions internal to this module. Eg: cv2_display_img(...) """ global _disable_img_display _disable_img_display = True def enable_cv2_display(): """ Globally enables displaying images with functions internal to this module. Eg: cv2_display_img(...) """ global _disable_img_display _disable_img_display = False def cv2_display_img(img, window_title="Test Image", force_display=False): """ Displays a cv2 window with an image. Ensures you don't forget to "waitKey(0)" after displaying """ global _disable_img_display if not _disable_img_display: cv2.imshow(window_title, img) cv2.waitKey(0) def display_img_notebook(img_path : str): """ Args: img_path: Path to an image Returns: An image in PIL format which will automatically be displayed in an IPython notebook """ return display_img(img_path, separate_window=False) def display_img(img_path: str, separate_window=True): """ Loads an image via PIL and displays it. By default displays it in a new window. It can be displayed in a notebook by changing the separate_window attribute :param img_path: Path to image :param separate_window: Whether to display the image in a separate window or just return it :return: The Image """ img = Image.open(img_path, 'r') if separate_window: img.show() return img def display_np_img(np_img, h=8, **kwargs): """ Helper function to plot an image. """ y = np_img.shape[0] x = np_img.shape[1] w = (y / x) * h plt.figure(figsize=(w, h)) plt.imshow(np_img, interpolation="none", **kwargs) plt.axis('off') plt.show()
a29d68a232f4b76a8ba902ab1dd8f2b1f3ca1221
geofftm/python-challenge
/PyPoll/main.py
3,511
3.875
4
#import dependencies import os import csv from collections import Counter #file path csvpath = os.path.join('Resources', 'election_data.csv') # setting empty lists to be used later to variables candidates = [] voteCount = [] # set the total votes to 0 to count later in loop totalVotes = 0 # open and read the csv file with open(csvpath, 'r') as csvfile: # setting the delimiter on the comma as this is a csv file csvreader = csv.reader(csvfile, delimiter=',') # this will skip the header csv_header = next(csvreader) #loop through the file for row in csvreader: # append the candidates to the empty list 'candidates' each pass through the loop candidates.append(row[2]) # count the total votes by adding a vote each pass through the loop totalVotes += 1 # use the sort method to sort the list by candidate name sortedCandidates = sorted(candidates) # Use counter to give the total count of votes by each candidate countedCandidates = Counter (sortedCandidates) # use most_common() method to get the most - least counts and append the values to an empty list voteCount.append(countedCandidates.most_common()) # loop through voteCount list and assign the vote totals to variables, from highest to lowest, using the index values of in the list of couples for i in voteCount: platinum = i[0][1] gold = i[1][1] silver = i[2][1] bronze = i[3][1] # loop through the voteCount list again assign the names to variables using the index value in the list of couples name1 = i[0][0] name2 = i[1][0] name3 = i[2][0] name4 = i[3][0] # calculating the percentages of the vote and formatting to 3 decimal places using the float value platinumPct = format((platinum)*100/(sum(countedCandidates.values())), '.3f') goldPct = format((gold)*100/(sum(countedCandidates.values())), '.3f') silverPct = format((silver)*100/(sum(countedCandidates.values())), '.3f') bronzePct = format((bronze)*100/(sum(countedCandidates.values())), '.3f') print("Election Results") print("-------------------------") print(f"Total Votes : {totalVotes}") print("-------------------------") # using f strings to build the strings showing name, perentage of the vote and total votes print(f"{name1}: {platinumPct}% ({platinum})") print(f"{name2}: {goldPct}% ({gold})") print(f"{name3}: {silverPct}% ({silver})") print(f"{name4}: {bronzePct}% ({bronze})") print("-------------------------") print(f"Winner: {name1}") print("-------------------------") # write the results to a txt file election_analysis = os.path.join("Analysis", "election_analysis.txt") with open(election_analysis, "w") as output: output.write("Election Results\n") output.write("----------------------------\n") output.write("") output.write(f"Total Votes : {totalVotes}\n") output.write("-------------------------\n") output.write(f"{name1}: {platinumPct}% ({platinum})\n") output.write(f"{name2}: {goldPct}% ({gold})\n") output.write(f"{name3}: {silverPct}% ({silver})\n") output.write(f"{name4}: {bronzePct}% ({bronze})\n") output.write("-------------------------\n") output.write(f"Winner: {name1}\n") output.write("-------------------------\n")
915ff9dcb8fd33cf17a0fc657d9050e4b04f9dd1
kmkipta/AlgoProblems
/965UnivalTree.py
1,032
4.03125
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isUnivalTree(self, root): """ :type root: TreeNode :rtype: bool """ if root.left is None and root.right is None: return True currNode = root uniVal = root.val isUnival = True conQ = [] conQ.append(root.left) conQ.append(root.right) while conQ: currNode = conQ.pop() if currNode != None: if currNode.val != uniVal: isUnival = False if currNode.left != None: conQ.append(currNode.left) if currNode.right != None: conQ.append(currNode.right) return isUnival t1 = TreeNode(1) t2 = TreeNode(1) t3 = TreeNode(1) t3.left = t1 t3.right = t2 sol = Solution() print(sol.isUnivalTree(t1))
50d0998296e32307185a785d2daa1e03e2a204e0
chenctest/python_basic
/day3/shoppingcart.py
1,282
3.84375
4
# Author :zhouyun item_list = ({"RED_APPLE": 1000}, {"GREEN_ORANGE": 500}, {"WHITE_PEAR": 100}, {"BLACK_GRAPE": 10}) cart_list = [] at_first = input('please input your salary: ') flag = True while(flag): print('Welcome to my store:') '''打印商品列表''' for i in range(0, 4): for j in item_list[i]: print(i+1, j, item_list[i][j]) '''逻辑判断商品价格与工资大小''' cart_item = input('please input which you want to buy: ') for i in item_list[int(cart_item)-1]: item_price = item_list[int(cart_item)-1][i] if item_price > int(at_first): print('your salary is not enough,\nwant to try again?') else: cart_list.append(item_list[int(cart_item) - 1]) at_first = int(at_first) - item_price '''确认,退出打印商品列表''' choose_next = input('please choose y/q/s(确认;退出程序;查看账户余额):') if choose_next == 'y': continue elif choose_next == 'q': print('-----购物车里面:---\n %s \n your salary now is %s' % (cart_list, at_first)) break elif choose_next == 's': print('your salary now is', at_first) continue else: print('input error') continue
d5ee0efa3a82a11037d78c9e6eeed5d653e12ec6
ChandraSiva11/sony-presamplecode
/tasks/day02-string/day2task2.py
1,182
4.3125
4
tstr = "this is string example....wow!!!"; substr = "exam"; print("1. :%d" % tstr.find(substr)) print("2. :%d" % tstr.find(substr, 10)) print("3. :%d" % tstr.find(substr, 20)) print("4. :%d" % tstr.find("Exam")) print("5. :%d" % tstr.index(substr)) print("6. :%d" % tstr.index(substr, 10)) # print("7. :%d" % tstr.index(substr, 20)) print() print("1. :%r" % tstr.find(substr)) print("2. :%r" % tstr.find(substr, 10)) print("3. :%r" % tstr.find(substr, 20)) print("4. :%r" % tstr.find("Exam")) print("5. :%r" % tstr.index(substr)) print("6. :%r" % tstr.index(substr, 10)) # print("7. :%r" % tstr.index(substr, 20)) print() print("1. :%s" % tstr.find(substr)) print("2. :%s" % tstr.find(substr, 10)) print("3. :%s" % tstr.find(substr, 20)) print("4. :%s" % tstr.find("Exam")) print("5. :%s" % tstr.index(substr)) print("6. :%s" % tstr.index(substr, 10)) # print("7. :%s" % tstr.index(substr, 20)) print() print("1. :%c" % tstr.find(substr)) print("2. :%c" % tstr.find(substr, 10)) # print("3. :%c" % tstr.find(substr, 20)) # print("4. :%c" % tstr.find("Exam")) print("5. :%c" % tstr.index(substr)) print("6. :%c" % tstr.index(substr, 10)) # print("7. :%s" % tstr.index(substr, 20))
29d5bcf1bae562e87b82b33ee2f7b9acacf4ec71
maria-luiza-duda/prova1-estrdados
/questao5.py
1,396
4
4
#Faça um programa que preencha uma lista contendo um número indefinido de nome de #carros e seus consumos (quantos km cada carro faz com 1 litro de combustível). Calcule e #mostre: a. O modelo de carro mais econômico #b. O modelo de carro menos econômico #c. Quantos litros de combustível cada um dos carros cadastrados consome para #percorrer uma distância de 1000 km modelo_carro = [] consumo_km = [] print("Quando quiser sair do programa aperte enter.") while True: modelo_carro.append(str(input('Digite o modelo do carro: '))) consumo_km.append(float(input('Digite o consumo do carro (km por litro): '))) resposta = str(input('Quer continuar? Sim ou Não\n')) if resposta in 'Não': print("Você encerrou o programa, aguarde.") break resultado = '' valor_gasolina = 7.00 total_km = 1000 for j, c in enumerate(modelo_carro): print('Veiculo {}'.format(j+1)) print('Nome: {}'.format(c)) print('Km por litro: {}\n'.format(consumo_km[j])) consumo = round(total_km/consumo_km[j], 2) resultado += 'O carro {} consome {}L e custará $R{} quando fizer {}km\n'.format(c, consumo, round(consumo*valor_gasolina, 2), total_km) print('O carro mais econômico é o {}'.format(modelo_carro[consumo_km.index(max(consumo_km))])) print('O carro menos econômico é o {}'.format(modelo_carro[consumo_km.index(min(consumo_km))])) print(resultado)
39d8962d92c9c76c854617c929ee1b9f50c728b3
AscendentFive/Python
/FuncionFilter.py
253
3.625
4
#Filtrar solo numeros mayores a 0 def filtro(elem): return (elem > 0) l = [1,-3,2,-8,-9,10] lr = filter(filtro,l) print l print lr #Filtrar solamente las O def filtro(elem): return (elem == "o") s = "Hola Mundo" lr = filter(filtro,s) print s print lr
35e643a049a6a818ac95b86c82722035242be82a
yemreinci/python-education
/hafta3/odevler/001_mod_solution.py
197
3.5625
4
d = {} record = 0 while True: x = int(input()) if x == 0: break if x not in d: d[x] = 1 else: d[x] += 1 if record not in d or d[x] > d[record]: record = x print(record)
b08c2d3e62fd5f7b2519fdb12b2527deb352b6eb
soham-shah/coding_practice
/CTCI/chapter_1/1_1.py
163
3.625
4
def uniqueString(x): s = set() for i in x: if i in s: return False else: s.add(i) return True print(uniqueString("test")) print(uniqueString("true"))
20c7f859d2285a07f377c4b3db0fcd8c9d90dadc
joaoo-vittor/estudo-python
/revisao/aula34.py
258
3.5
4
""" Aula 34 Funções decoradoras e decoradores """ def camada1(func): def camada2(): print('Estou decorada') func() return camada2 # @<nome da função superior> @camada1 def fala_oi(): print('oi') # variavel = camada1(fala_oi) fala_oi()
d6f42afbcf8fde50c31577ba5bcc06733e15640e
Badwolf369/Project
/attempt-3.py
5,951
3.765625
4
"""Simple program to import and format a CSV file.""" # pylint: disable=C0103 # pylint: disable=R0201 # pylint: disable=R1723 import csv class CSVfile(): """Imported and formatted CSV file. Raises: ValueError: During format of RGB values Returns: list -- list of dicts gathered from passed in file """ def __init__(self, filename): """Load the file and format it when the object is created. Arguments: filename {str} -- Name of file to be opened. """ self.filename = filename self.load(filename) def format_xyz(self, i, d): """Format XYZ values in given waypoint. Arguments: i {str} -- index to be edited (x, y or z) d {dict} -- single waypoint Returns: int -- formatted index value """ try: d[i] = int(d[i]) except ValueError: print(f'Error loading {i} value in point {d["name"]}.') print(f'Value looks like {d[i]}.') while True: print('What\'s it supposed to be?') inp = input('-->:') try: d[i] = int(inp) print('Got it.') break except ValueError: print('Still can\'t load.') print('Whole integer is required.') return d[i] def format_vis(self, d): """Format visibility modifier in given waypoint. Arguments: d {dict} -- single waypoint Returns: bool -- visibility boolean """ if d["visible"].casefold() == 'true': d["visible"] = True elif d["visible"].casefold() == 'false': d["visible"] = False else: print(f'Error loading visibility boolean in point {d["name"]}.') print(f'Boolean looks like {d["visible"]}') while True: inp = input('-->:') inp = inp.casefold() if inp == 'true': d["visible"] = True break elif inp == 'false': d["visible"] = False break else: print('I still do not understand.') print('Value must be boolean.') return d["visible"] def format_rgb(self, i, d): """Format RGB values in given waypoint. Arguments: i {str} -- Index to be edited (red, green, or blue) d {dict} -- Single waypoint Raises: ValueError: To shortcut some code if incorrect valaue entered Returns: int -- formatted value at the specified index """ try: d[i] = int(d[i]) except ValueError: print(f'Error loading {i} value in point {d["name"]}') print(f'Value looks like {d[i]}.') while True: print('What\'s it supposed to be?') inp = input('-->:') try: d[i] = int(inp) if not 0 < d[i] < 255: raise ValueError() break except ValueError: print('Still can\'t understand.') print('Must be a whole integer between 0 and 255.') return d[i] def format_dim(self, d): """Format dimensions value in given waypoint. Arguments: d {dict} -- Single waypoint Returns: list -- Formatted list of dimensions """ d["dimensions"] = set(d["dimensions"].split('/')) for i in d["dimensions"]: if i not in ['end', 'overworld', 'nether']: print(f'I dont understand the dimensions of point {d["name"]}') print(f'The list looks like {d["dimensions"]}') while True: print('What are the dimensions supposed to be?') print('Type them separated by white space.') inp = input('-->:').split(r'\s') for x in inp: if x not in ['end', 'overworld', 'nether']: print('I still dont understand.') break else: print('Got it.') d["dimensions"] = inp break return d["dimensions"] def load(self, filename): """Load given file. Arguments: filename {str} -- name of file to be loaded """ with open(filename, 'r') as f: f = csv.DictReader(f) f = list(f) for i, d in enumerate(f): f[i] = dict(d) self.data = f for i, d in enumerate(self.data): d["x"] = self.format_xyz("x", d) d["y"] = self.format_xyz("y", d) d["z"] = self.format_xyz("z", d) d["visible"] = self.format_vis(d) d["red"] = self.format_rgb("red", d) d["green"] = self.format_rgb("green", d) d["blue"] = self.format_rgb("blue", d) d["uses"] = set(d["uses"].split('/')) d["dimensions"] = self.format_dim(d) self.data[i] = d self.write() def write(self): """Write current data to the file passed in during object creation.""" with open(self.filename, 'w') as f: keys = [ 'name', 'x', 'y', 'z', 'visible', 'red', 'green', 'blue', 'uses', 'dimensions'] w = csv.DictWriter(f, keys) w.writeheader() w.writerows(self.data) coords = CSVfile('moonbyte.csv')
fbf68159b9b067b0c2349c9bce3e4a45cefc75ce
wiltonjr4/Python_Language
/Estudos/Python_Exercicios_Curso_Em_Video/ex081.py
566
4.03125
4
lista = list() while True: lista.append(int(input('Digite um valor: '))) continuar = str(input('Quer continuar? [S/N] ')).upper().strip() while continuar not in 'SN': continuar = str(input('Tente novamente.. Quer continuar? [S/N] ')).upper().strip() if continuar == 'N': break print('-=' * 20) print(f'Você digitou {len(lista)} elementos.') print(f'Os valores em ordem decrescente são {sorted(lista, reverse=True)}') if 5 in lista: print('O valor 5 faz parte da lista!') else: print('O valor 5 Não faz parte da lista!')
8fc529aeb65e07a99da46d1c7ae1e885dbe05d2c
yallyyally/algo-moreugo
/Baekjoon/[1920] 수 찾기.py
882
3.5
4
#N개의 정수 A[1], A[2], ..., A[N]이 주어져 있을 때, #이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 #작성하시오. import sys def search(list,x,start,end): if start>end: print('0') #return 0 하면 main 함수가 아니고 본인함수로 돌아온다.유의할 것 return else: mid = (start+end)//2 if x==list[mid]: print('1') return elif x>list[mid]: search(list,x,mid+1,end) elif x<list[mid]: #x<mid search(list,x,start,mid-1) N = int(sys.stdin.readline()) numbers = sorted(list(map(int,sys.stdin.readline().split()))) M = int(sys.stdin.readline()) finding = list(map(int,sys.stdin.readline().split())) #finding 속의 숫자들이 numbers에 포함되면 1, 존재 하지 않으면 0 for x in finding: search(numbers,x,0,N-1)
e3ea03500c7c8875ce5f10aa5a771b2077998158
winstonfb/montyhall
/montyhall.py
4,485
4.3125
4
""" Simulate the Monty Hall 'paradox'.""" from scipy.stats import rv_discrete from fractions import Fraction import sys import argparse import logging import logging.config import json with open("logging_config.json", "r") as fd: logging.config.dictConfig(json.load(fd)) log = logging.getLogger(__name__) class Doors: """ Assign values to doors and select them as per simulated strategy. Attributes: values: Boolean indicating whether the door in that position contains a prize. probs: A list giving, for each door, the probability that this door will be the one with a prize. prize_door: A single randomly chosen discrete value from a probability distribution over discrete values; the door in this position has the prize. choice_first: A single randomly chosen discrete value from probability distribution over discrete values; this represents the player's first choice. goat_door: A single randomly chosen discrete value from probability distribution over discrete values; the door in this position is opened to reveal a goat. Which is not a prize. selection: A list of valid door selections for the host to open. choice_second: The player's final choice of doors, contingent on strategy (0 -> stay with first choice. 1 -> switch to unopened door.) Note: Some attributes (selection, choice_second, goat_door) assigned values in class methods for the sake of illustration. """ def __init__(self): self.values = [0, 0, 0] self.probs = [Fraction(1, 3)]*3 self.prize_door = rv_discrete(name = 'prize_door_selection', values = (range(len(self.values)), self.probs )).rvs(size=1) self.values[self.prize_door[0]] = 1 self.choice_first = rv_discrete(name = 'first_choice_selection', values = (range(len(self.values)), self.probs )).rvs(size=1) self.selection = None self.choice_second = None self.goat_door = None def reveal_goat(self): """ Open one door to reveal a goat (non-prize). Valid doors to open depend on choice_first. """ if self.prize_door[0] == self.choice_first[0]: self.probs = [.5]*3 else: self.probs = [1]*3 self.probs[self.prize_door[0]] = 0 self.probs[self.choice_first[0]] = 0 self.goat_door = rv_discrete(name = 'goat_door_selection', values= (range(len(self.values)), self.probs )).rvs(size=1) def choose_door(self, strategy): """ Choose a door based on player strategy (stay or switch). Args: strategy: 1 to switch to new, unopened door; 0 to stay with first choice. """ if strategy == 0: self.choice_second = self.choice_first else: self.selection = [0, 1, 2] self.selection.remove(self.choice_first[0]) self.selection.remove(self.goat_door[0]) self.choice_second = self.selection[0] def tally_score(self): """ Return a score for the trial. Returns: 1 if the chosen door has a prize; 0 otherwise. """ if self.choice_second == self.prize_door: return 1 else: return 0 if __name__ == '__main__': parser = argparse.ArgumentParser(description='Simulate the Monty Hall paradox, step-by-step.') parser.add_argument('trials', metavar='n', type=int, nargs='?', default=1000, help='number of trials for the simulation') args = parser.parse_args() TRIALS = args.trials log.info('Setting trials to {}'.format(TRIALS)) for y in range(0, 2): total_score = 0 log.debug('Iteratively testing strategy {}'.format(y)) for x in range(1, TRIALS): test = Doors() test.reveal_goat() test.choose_door(strategy=y) trial_score = test.tally_score() total_score += trial_score win_percentage = '{0:.2f}'.format((float(total_score) / float(TRIALS)) * 100) if y == 1: print("Strategy: switch doors | Trials: {0} | Wins: {1} ({2}%)".format(TRIALS, total_score, win_percentage)) else: print("Strategy: don\'t switch | Trials: {0} | Wins: {1} ({2}%)".format(TRIALS, total_score, win_percentage))
493e9faf8ebee8250ac691153116f2113df0f11d
cfudala82/DC-Class-Sept-17
/projects/week2/ex2FileIO.py
330
4.125
4
# This a program that prompts the user to enter a file name, then prompts the # user to enter the contents of the file, and then saves the content to the # file. fileName = input('Enter file name: ') file_handle = open(fileName,'w') content = str(input('Enter contents of file: ')) file_handle.write(content) file_handle.close()
59aebeb7f7aadc7d695cf67034a4ccda513dab0b
JBerkhout/technologiesForLearning
/variability.py
8,971
3.625
4
from typing import List, Dict import config import pandas as pd import numpy as np import matplotlib.pyplot as plt from pre_processing import get_short_rubrics_names_dict, get_topics_names_dict # Compute the variability statistics on all topics and return this in a list of dicts. def compute_variability_statistics() -> List[Dict[str, float]]: data_dict = pd.read_excel("data_v2.xlsx", None) output = [] for topic in range(1, 23): tab_name = 'topic' + str(topic) df = data_dict[tab_name] for rubric in range(1, 9): rubric_grades = df['Grade' + str(rubric)].tolist() new_dict = {"topic": topic, "rubric": rubric, "mean": np.mean(rubric_grades), "std": np.std(rubric_grades), "variance": np.var(rubric_grades), "q1": np.percentile(rubric_grades, 25), "q3": np.percentile(rubric_grades, 75) } output.append(new_dict) return output # Method to analyze the variability statistics. Returns list with dicts. def read_rubric_variability_statistics() -> List[Dict[str, float]]: # Let's infer some information from the statistics.xlsx variability_data = pd.read_excel("variability_statistics.xlsx", None) df = variability_data['Sheet1'] output = [] for rubric in range(1, 9): rubric_selection = df.loc[df['rubric'] == rubric] # First we compute the total mean value that is given for each rubric. means_list = rubric_selection['mean'].tolist() total_mean = np.mean(means_list) # Now let's see if students agree more with each other (less variability) on certain rubrics. std_list = rubric_selection['std'].tolist() mean_std = np.mean(std_list) # So this value above is the average standard deviation for each rubric. # Let's do the same for variance, in case we want to use that instead of std. variance_list = rubric_selection['variance'].tolist() mean_variance = np.mean(variance_list) # So this value above is the average variance for each rubric. # Now let's save all this information per rubric in a dictionary. rubric_variablility = { "rubric": rubric, "total_mean": total_mean, "mean_std": mean_std, "mean_variance": mean_variance} output.append(rubric_variablility) return output # Method to analyze the variability statistics. Returns list with dicts. def read_topic_variability_statistics(correct_format=True): # Let's infer some information from the statistics.xlsx variability_data = pd.read_excel("variability_statistics.xlsx", None) df = variability_data['Sheet1'] output = [] for topic in range(1, 23): topic_selection = df.loc[df['topic'] == topic] # First we compute the total mean value that is given for each topic. means_list = topic_selection['mean'].tolist() total_mean = np.mean(means_list) # Now let's see if students agree more with each other (less variability) on certain topics. std_list = topic_selection['std'].tolist() mean_std = np.mean(std_list) # So this value above is the average standard deviation for each topic. # Let's do the same for variance, in case we want to use that instead of std. variance_list = topic_selection['variance'].tolist() mean_variance = np.mean(variance_list) # So this value above is the average variance for each topic. # Now let's save all this information per rubric in a dictionary. topic_variability = { "topic": topic, "total_mean": total_mean, "mean_std": mean_std, "mean_variance": mean_variance} output.append(topic_variability) if correct_format: formatted_output = np.zeros(len(output)) for i_topic in range(len(output)): formatted_output[i_topic] = output[i_topic]["mean_variance"] return formatted_output return output # Save statistics to Excel file. def save_statistics_excel() -> None: out = compute_variability_statistics() df = pd.DataFrame.from_dict(out) df.to_excel('variability_statistics.xlsx') # Save variability per rubric to Excel file. def save_rubric_variability_excel() -> None: out = read_rubric_variability_statistics() df = pd.DataFrame.from_dict(out) df.to_excel('rubric_variability.xlsx') # Save variability per topic to Excel file. def save_topic_variability_excel() -> None: out = read_topic_variability_statistics(False) df = pd.DataFrame.from_dict(out) df.to_excel('topic_variability.xlsx') def plot_rubric_variability() -> None: out = read_rubric_variability_statistics() df = pd.DataFrame.from_dict(out) rubric_names = df.rubric.map(get_short_rubrics_names_dict()) plt.bar(rubric_names, df.mean_variance) plt.title('Bar plot of variability per rubric') plt.xlabel('Rubric') plt.ylabel('Variance') plt.show() def plot_topic_variability() -> None: out = read_topic_variability_statistics(False) df = pd.DataFrame.from_dict(out) topic_names = df.topic.map(get_topics_names_dict()) plt.bar(topic_names, df.mean_variance) plt.title('Bar plot of variability per topic') plt.xticks(rotation='vertical') plt.xlabel('Topic') plt.ylabel('Variance') plt.show() def plot_topic_variability_theme_grouped() -> None: out = read_topic_variability_statistics(False) df = pd.DataFrame.from_dict(out) topic_names = df.topic.map(get_topics_names_dict()) # topic_categories = [topic_name[0:3] for topic_name in topic_names] # topic_category_division = [[topic_cat[0], topic_cat[2]] for topic_cat in topic_categories] # (manually) specifying which topics belong to which theme y_t1 = df.mean_variance[0:6] y_t2 = df.mean_variance[6:9] y_t3 = df.mean_variance[9:13] y_t4 = df.mean_variance[13:16] y_t5 = df.mean_variance[16:22] # ensuring correct spacing between topics x_t1 = np.arange(len(y_t1)) x_t2 = 1 + np.arange(len(y_t2)) + len(y_t1) x_t3 = 2 + np.arange(len(y_t3)) + len(y_t1) + len(y_t2) x_t4 = 3 + np.arange(len(y_t4)) + len(y_t1) + len(y_t2) + len(y_t3) x_t5 = 4 + np.arange(len(y_t5)) + len(y_t1) + len(y_t2) + len(y_t3) + len(y_t4) fig, ax = plt.subplots() ax.bar(x_t1, y_t1, color='r', label="1 Student Modelling") ax.bar(x_t2, y_t2, color='b', label="2 Assessment") ax.bar(x_t3, y_t3, color='g', label="3 Adaptation") ax.bar(x_t4, y_t4, color='y', label="4 Intelligent Tutoring Systems") ax.bar(x_t5, y_t5, color='black', label="5 Big Educational Data") ax.set_title('Bar plot of variability per topic grouped per theme') ax.set_ylabel('Variance') ax.set_xlabel('Topic') ax.set_xticks(np.concatenate((x_t1, x_t2, x_t3, x_t4, x_t5))) ax.set_xticklabels(topic_names, rotation='vertical') ax.legend() plt.show() def plot_topic_variability_day_grouped() -> None: out = read_topic_variability_statistics(False) df = pd.DataFrame.from_dict(out) topic_names = df.topic.map(get_topics_names_dict()) # (manually) specifying which topics belong to which presentation day y_d1 = df.mean_variance[0:3] y_d2 = df.mean_variance[3:6] y_d3 = df.mean_variance[6:9] y_d4 = df.mean_variance[9:13] y_d5 = df.mean_variance[13:16] y_d6 = df.mean_variance[16:19] y_d7 = df.mean_variance[19:22] # ensuring correct spacing between topics x_t1 = np.arange(len(y_d1)) x_t2 = 1 + np.arange(len(y_d2)) + len(y_d1) x_t3 = 2 + np.arange(len(y_d3)) + len(y_d1) + len(y_d2) x_t4 = 3 + np.arange(len(y_d4)) + len(y_d1) + len(y_d2) + len(y_d3) x_t5 = 4 + np.arange(len(y_d5)) + len(y_d1) + len(y_d2) + len(y_d3) + len(y_d4) x_t6 = 5 + np.arange(len(y_d6)) + len(y_d1) + len(y_d2) + len(y_d3) + len(y_d4) + len(y_d5) x_t7 = 6 + np.arange(len(y_d7)) + len(y_d1) + len(y_d2) + len(y_d3) + len(y_d4) + len(y_d5) + len(y_d7) fig, ax = plt.subplots() ax.bar(x_t1, y_d1, color='r', label="Day 1") ax.bar(x_t2, y_d2, color='b', label="Day 2") ax.bar(x_t3, y_d3, color='g', label="Day 3") ax.bar(x_t4, y_d4, color='y', label="Day 4") ax.bar(x_t5, y_d5, color='black', label="Day 5") ax.bar(x_t6, y_d6, color='purple', label="Day 6") ax.bar(x_t7, y_d7, color='orange', label="Day 7") ax.set_title('Bar plot of variability per topic grouped per presentation day') ax.set_ylabel('Variance') ax.set_xlabel('Topic') ax.set_xticks(np.concatenate((x_t1, x_t2, x_t3, x_t4, x_t5, x_t6, x_t7))) ax.set_xticklabels(topic_names, rotation='vertical') ax.legend() plt.show() # MAIN #save_statistics_excel() #save_topic_variability_excel() #save_rubric_variability_excel()
b26c896e34c0c44c5efd2699a88209ffd958ffda
aiazm496/PythonPractice
/59A.py
267
3.9375
4
word = input() covToCap = False cntUpperCase = 0 cntLowerCase = 0 for i in range(len(word)): if(word[i].isupper()): cntUpperCase+=1 else: cntLowerCase+=1 if cntUpperCase> cntLowerCase: print(word.upper()) else: print(word.lower())
b2279719afa856475ab0eed4ad72ab6e26460c9c
KimTaeHyeong17/MyRepo
/Python/6_ _170526/EX89_201724447_김태형.py
291
4.03125
4
def is_even1(n): if n%2==0: return True else: return False print is_even1(4) print is_even1(3) #if Trueε Ű True ϴ def is_even2(n): return n%2==0 print is_even2(4) print is_even2(3)
c208208a621749fdaaf1d2ff9c16281f51ad91f3
cmoralesmani/sendEmailPython
/sendEmailTo/read_contacts.py
430
3.859375
4
def get_contacts( filename): """ Return two lists names, emails containing names and email addresses read from a file specified by filename """ names = [] emails = [] with open(filename, mode='r', encoding='utf-8') as contacts_file: for a_contact in contacts_file: names.append(a_contact.split()[0]) emails.append(a_contact.split()[1]) return names, emails
bbbd0b712cd64404380cc28e9da5fe8aa12a73dc
rachelreuters/cursoMachineLearningPython
/codigos/bibliotecas/Pandas/dataframes.py
853
3.703125
4
import pandas as pd df = pd.DataFrame([['dado1',1212],['dado2',4431],['dado3',5633]]) print(df) print(df.shape) #retorna as dimensoes do dataframe df = pd.DataFrame([['dado1',1212],['dado2',4431],['dado3',5633]], columns = ['repositorio','linhas']) #columns cria nomes para as colunas print(df) print(df['repositorio']) #retorna os elementos da coluna de nome repositorio print(df['linhas'].mean()) print(df.iloc[1]) #retorna os elementos da linha 1 print(df.iloc[1]['linhas']) #retorna o elemento linhas da linha correspondente df.index = pd.Index([2,5,9]) #associa cada indice a uma linha print(df) print(df.iloc[1]) print(df.ix[5]) df.index = df['repositorio'] #transforma a coluna em indice print(df.ix['dado1']) print(df) del df['repositorio'] #como ficou duplicado, pode deletar a coluna print(df) print(df.ix['dado1'])
88ac4a2bb6b8092d9e1ba99a4a31e07f9ee28196
lacklust/coding-winter-session
/test_applications/week_2/app_coin_check.py
856
4.28125
4
""" Write a program that asks the user for the value of a coin. Then determine what kind of coin they entered using that information. Sample runs: Enter a coin value: 1 That's a penny! Enter a coin value: 25 That's a quarter! Enter a coin value: 99 That's not a valid coin! """ def main(): print("sup") try: coin = int(input("what coin ya got? ")) except ValueError: print("thats not a valid number") # exit(10) return if coin == 1: print("homie got a penny") elif coin == 5: print("a nickel lulz") elif coin == 10: print("you a dime") elif coin == 25: print("a quarter it is") elif coin == 50: print("wow a whole half dollar") elif coin == 100: print("one dollar") else: print("that not very cash money of you") main()
6e3b83eb647d5c8e7d52c8ae38061aee2a583243
Buzzlet/Coursework
/cs131/monkey_problem.py
9,717
4.34375
4
# Program: monkey_problem.py # Class: cs131 # Date: 10/8/14 # Author: Joel Ristvedt # Description: The Monkey Problem program solves for the number of coconuts # in the problem in the instructions function over a range designated by the # user. The user specifies what range to search over, how many sailors they # want to watch suffer on the island, and whether or not they want to see # all of the results found. # Imports import time # Functions def Instructions(): """Prints the name of the program, story, and instructions. Requires none Returns none """ print() print('Monkey Problem') print('Five sailors are shipwrecked on an island. Fearing a long stay') print('before rescue, they gather together a large pile of coconuts as') print('a source of nourishment. Night falls before they are able to') print('divide the coconuts among themselves. So the sailors agree to go') print('to sleep and divide the pile of coconuts in the morning. During') print('the night, one of the sailors wakes up and decides to make sure') print('that he gets his fair share of coconuts. He divides the pile into') print('five equal piles, one for each sailor, with one coconut left') print('over. he hides his pile. pushes the other four piles together and') print('tosses the extra coconut to a monkey that is watching him. A') print('little while later, a second sailor wakes up and does the same') print('dividing and hiding. He ends up with two extra coconuts, which he') print('tosses to the monkey. As the night goes by, the other sailors') print('wake up in turn to divide the pile of coconuts left over, the') print('fourth sailor has four coconuts left over but the fifth sailor') print('has no coconuts left over. This works out well, since by the time') print('the fifth sailor awakens to divide the pile, it is fairly late') print('and the monkey has gone to bed. In the light of day, the pile of') print('coconuts is much smaller, but no one points this out since each') print('thinks he is responsible. The sailors do one last official') print('division in which each sailor receives the same number of') print('coconuts with one coconut left over. The sailors agree to give') print('the extra coconut to the monkey for breakfast. Each sailor then') print('takes his official pile and settles in to wait for rescue.') print() print('This program will ask for a range of coconuts to search for the') print('possible number of coconuts in the pile at the beginning. The') print('program will also ask for how many sailors there are on the') print('island, as it can solve for a variable number of sailors. Next') print('the program will ask if you want to see all of the possible') print('number of coconuts in the range entered for the number of sailors') print('entered (Enter range like 1337-9001).') print() def Get_Input(): """Gets the output from the user and returns it returns coconut_test, coconut_test_limit, sailors, print_results coconut_test = integer coconut_test_limit = integer sailors = integer print_results = boolean coconut_test - number to start checking for solutions with coconut_test_limit - the highest number to search for solutions sailors - number of sailors on the island print_results - boolean pertaining to whether the user wants to see the working solutions or not """ # coconut_test_string - string representing the starting number to check # answer - users string answer coconut_test_string, coconut_test_limit = input( 'What is the range of coconuts to test? ').split('-') coconut_test = int(coconut_test_string) coconut_test_limit = int(coconut_test_limit) sailors = int(input('How many sailors are on the island? ')) answer = input('Do you want to see the successful numbers (y/n)? ') print_results = (answer == 'y' or answer == 'Y') print() return coconut_test, coconut_test_limit, sailors, print_results def Calculations(coconut_test, coconut_test_limit, sailors, print_results): """Finds the difference between two working solutions requires: (int) coconut_test, (int) coconut_test_limit, (int) sailors, (boolean) print_results returns: (int)results coconut_test = the number of coconuts under scrutiny coconut_test_limit = the highest number of coconuts that will be results - the number of solutions found sailors - the number of sailors on the island put there by the malicious user print_results - boolean pertaining to whether the user wants to see all the results or just the number of how many results there are """ # first_result = the first working solution # scrutinized # sailor_count = the number of sailors that have taken their secret share # plausible - boolean pertaining to whether the coconut value is a # possible solution based on if the coconut value passed for # coconuts_in_pile - the running total of coconuts in the pile # leftover_coconuts - coconuts remaining after every secret division that # get thrown to the monkey # coconuts_taken - number taken during every secret division results = 0 while coconut_test < coconut_test_limit: sailor_count = 1 plausible = True coconuts_in_pile = coconut_test coconuts_taken, leftover_coconuts = divmod(coconuts_in_pile, sailors) while sailor_count < sailors and plausible == True: if leftover_coconuts == sailor_count: coconuts_in_pile -= (leftover_coconuts + coconuts_taken) coconuts_taken, leftover_coconuts = divmod(coconuts_in_pile, sailors) else: plausible = False sailor_count += 1 coconuts_in_pile -= (leftover_coconuts + coconuts_taken) if (plausible and leftover_coconuts == 0 and coconuts_in_pile % sailors == 1): if print_results: print(coconut_test) results += 1 coconut_test += 1 return results def Print_Output(results, coconut_test, coconut_test_limit, cpu_secs, wall_secs): """Prints the number of results over the specified range and the ammount of time the calculations took. requires: (int)results, (int)coconut_test, (int)coconut_test_limit, (float)cpu_secs, (float)wall_secs returns none results - the number of working solutions found coconut_test - the lowest number for checking for solutions coconut_test_limit - the highest number for checking for solutions cpu_secs - elapsed time it took for the cpu to do calculations wall_secs - elapsed time it took for the calculations to be finished """ if results == 0: results = 'no' s = 's' are = 'are' if results == 1: s = '' are = 'is' print() print('There ', are,' ', results, ' result', s,' within the range ', coconut_test, '-', coconut_test_limit, '.', sep='') print('CPU secs: ', '{0:.3f}'.format(cpu_secs)) print('Elapsed secs: ', '{0:.3f}'.format(wall_secs)) print() def Main(): """Prints the story with the instructions, gets the input from the user, starts timing, finds the difference between the first two working solutions and applies that to complete and print all working solutions, stops the timing returns output to the user. Requires none Returns none """ # coconut_test - the lowest number for checking for solutions # coconut_test_limit - the highest number for checking for solutions # sailors - the number of sailors put on the forsaken island # print_results - the boolean pertaining to whether the user wants to see # the results of just the number of how many results there # are # wall_start - the programs run time at the start of the calculations # cpu_start - the time spent computing at the beginning of the # calcluations # second_solution - the second working solution # results - the number of working solutions found # increment - the difference between any two working solutions # wall_stop - the programs run time at the end of the calculations # cpu_stop - the time spent computing at the end of the calculations # wall_secs - the elapsed time it took the program to complete the calcs # cpu_secs - the total time spent computing during the calculations Instructions() done = False while not done: coconut_test, coconut_test_limit, sailors, print_results = Get_Input() wall_start = time.time() cpu_start = time.clock() results = Calculations(coconut_test, coconut_test_limit, sailors, print_results) wall_stop = time.time() cpu_stop = time.clock() wall_secs = wall_stop - wall_start cpu_secs = cpu_stop - cpu_start Print_Output(results, coconut_test, coconut_test_limit, cpu_secs, wall_secs) answer = input('Would you like to enter numbers again (y/n)? ') done = (answer == 'n' or answer == 'N') print() # Main Function Main()
e0d6083e59ce66b9f749a94780b9010b562b8f2a
szabgab/slides
/python/examples/oop/mydate2/run.py
240
3.59375
4
from mydate import Date d = Date(2013, 11, 22) print(d) d.set_date(2014, 1, 27) print(d) print('') x = Date.from_str('2013-10-20') print(x) print('') # This works but it is not recommended z = d.from_str('2012-10-20') print(d) print(z)
1d9439850bc1ac93a667216731933d8cc4bc3373
sidv/Assignments
/Neethu/Aug13/erp_project.py
3,460
4.21875
4
Employee = {} #Empty dictionary while True: print("1. Add employee") print("2. Delete employee") print("3. Search employee by name") print("4. Display all employee") print("5. Change a employee name in the list") print("6. exit") ch = int(input("Enter your choice")) if ch == 1: #Add employee emp_id = input("\tEnter employe id ") if emp_id not in Employee.keys(): name = input("\tEnter name ") age = int(input("\tEnter age ")) gender = input("\tEnter the gender ") place = input("\tEnter the place ") date = input("\tEnter the date ") salary = int(input("\tEnter the salary ")) previous_company = input("\tEnter the previous company ") joining_date = input("\tEnter the joining date ") temp ={ "name":name, "age":age, "gender":gender, "place":place, "date":date, "salary":salary, "previous_company":previous_company, "joining_date":joining_date } Employee[emp_id] = temp else: print("\tEmployee id already Taken") elif ch == 2: #Delete student emp_id = input("\tEnter emp id") if emp_id not in Employee.keys(): print("\tWrong emp id") else: del Employee[emp_id] elif ch == 3: #Search employee name = input("\tEnter name") found = False for i in Employee.values(): if i["name"] == name: # find name print(f"\t{i['name']} | {i['age']} | {i['gender']} | {i['place']} | {i['salary']} | {i['previous_company']} | {i['joining_date']} | {i['date']} ") found = True break if found == False : print("\tNot found") elif ch == 4: #Display Employee for emp_id,employee in Employee.items(): print(f"\t{emp_id} | {Employee['name']} | {Employee['age']} | {Employee['gender']} | {Employee['date']} | {Employee['place']} | {Employee['salary']} | {Employee['previous_company']} | {Employee['joining_date']}") elif ch== 5: #Change a Employee print("\t1.change Name") print("\t2. change Age") print("\t3.change Gender") print("\t4.change Salary") ch = input("\tEnter your choice") if ch== 1: emp_id = input("\tEnter employ id ") if emp_id not in Employee.keys(): print("\tWrong employ id") else: Employee[emp_id]['name'] = input("\tEnter new name") if ch== 2: emp_id = input("\tEnter employ id ") if emp_id not in Employee.keys(): print("\tWrong employee") else: Employee[emp_id]['age'] = input("\tEnter new age") if ch== 2: emp_id = input("\tEnter employ id ") if emp_id not in Employee.keys(): print("\tWrong employ id") else: Employee[emp_id]['gender'] = input("\tEnter new gender") if ch== 3: emp_id = input("\tEnter employ id ") if emp_id not in Employee.keys(): print("\tWrong employ id") else: Employee[emp_id]['salary'] = input("\tEnter new salary") if ch== 4: emp_id = input("\tEnter employ id ") if emp_id not in Employee.keys(): print("\tWrong employ id") else: Employee[emp_id]['place'] = input("\tEnter new place") elif ch == 6: #Exit break; else: print("Invalid Choice")
57cc8bfb6abc0e16b04317efeaa31f7fba6fed7c
len-eberhard/PY4E
/ex9-4.py
472
3.796875
4
most_add = None most_count = None results = dict() filename = input('Enter a file name:') try: file = open(filename) except: print('Could not open file: ', filename) quit() for line in file: if line.startswith('From:'): words = line.split() print(words) results[words[1]] = results.get(words[1] , 0) + 1 for add,count in results(): if most_count == None or count > most_count: most_add = add most_count = count print(most_add, most_count)
1098ae91416a681aa739befed5e32d3f679435fc
qsang86/python_algorithm
/3. Sort/merge.py
822
3.703125
4
array_a = [1, 2, 3, 5] array_b = [4, 6, 7, 8] def merge_rest(array_a, index_a, output): if index_a < len(array_a): for i in range(index_a, len(array_a)): add_ele = array_a[i] output.append(add_ele) return output def merge(array1, array2): output = [] index1 = 0 index2 = 0 while index1 < len(array1) and index2 < len(array2): if array1[index1] < array2[index2]: output.append(array1[index1]) index1 += 1 else: output.append(array2[index2]) index2 += 1 rest_output1 = merge_rest(array1, index1, output) rest_output2 = merge_rest(array2, index2, output) if len(rest_output1) > len(rest_output2): return rest_output1 return rest_output2 print(merge(array_a, array_b))
6ff171c5902fbcdcfe008ca9910c15719d595255
taimoor391/100-Days-of-code
/Day_14Higher_or_Lower.py
1,101
3.625
4
import Day14Data as dat import random import Day14art as art data=dat.data #print(data) def choice(): return random.choice(data) def brandprint(A) : return ( ( ("{}, a {} from {}".format((A['name']), (A['description']),A['country'] )))) def results_compare(A,B): if A['follower_count']>B['follower_count']: return 'a' else: return 'b' branda=choice() brandb=choice() print(art.logo) print('compare A {}'.format(brandprint(branda))) print(art.vs) print('\nAgaints B {}'.format(brandprint(brandb))) player_choice=input("who has more follower A or B\n").lower() score=0 while player_choice==results_compare(branda,brandb): score += 1 print('you are right: current score: {}'.format(score)) branda = choice() brandb = choice() print('compare A {}'.format(brandprint(branda))) print(art.vs) print('\nAgaints B {}'.format(brandprint(brandb))) player_choice = input("who has more follower A or B\n").lower() print(" You are wrong Game ended , your final score: {} ".format(score))
b6930e66e2c3e80473b41160cf9055d723518438
KierenJackson/cp1404practicals
/prac_03/password_checker.py
606
4.21875
4
MIN_LENGTH = 6 def main(): print_password = "" password = get_password() print_password = asterisks_converter(password, print_password) print(print_password) def asterisks_converter(password, print_password): for char in range(len(password)): print_password += "*" return print_password def get_password(): password = input("Please enter your password: ") while len(password) < MIN_LENGTH: print("Password must at least be {} characters long".format(MIN_LENGTH)) password = input("Please enter your password: ") return password main()
2733f1474d384c5b9b75196cb3cd7f7bb751005f
GavinPHR/code
/phase1/169.py
310
3.53125
4
# Majority Element from typing import List import collections class Solution: def majorityElement(self, nums: List[int]) -> int: count = collections.Counter(nums) return count.most_common(1)[0][0] if __name__ == '__main__': s = Solution() print(s.majorityElement([2,2,1,1,1,2,2]))
1fb002002133e11a22655ace6196ba6cb02c645b
shekhar270779/Learn_Python
/prg_OOP_01.py
2,075
3.921875
4
# Python Object Oriented Programming ''' Object Oriented programming (OOP) is a programming paradigm that is based on the concept of classes and objects. Reusable pieces of code blueprints are called classes, which are used to create individual instances of objects. Building blocks of OOP - class : Classes allow to logically group data and functions - object : instances of a class are called as objects - method - attribute ''' class Employee: pass # e1 and e2 below are two instances of class Employee e1 = Employee() e2 = Employee() print(f"Id of object e1 is {id(e1)}") print(f"Id of object e2 is {id(e2)}") class Employee: def __init__(self, first_name, last_name, gender, sal): '''__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method is called when an object is created from the class and it allow the class to initialize the attributes of a class. ''' self.first_name = first_name self.last_name = last_name self.gender = gender self.sal = sal self.email = first_name + '.' + last_name + '@company.com' def fullname(self): return self.first_name + ' ' + self.last_name # Creating instances of the class Employee emp_list = [] emp_list.append(Employee('Annie', 'Kapoor', 'F', 30000)) emp_list.append(Employee('Shyam', 'Bose', 'M', 35000)) for e in emp_list: print(e.fullname(), e.gender, e.sal, e.email) for e in emp_list: print(Employee.fullname(e)) class Car: def __init__(self, company, model, color, speed_limit): self.company = company self.model = model self.color = color self.speed_limit = speed_limit def get_speed_limit(self): return self.speed_limit def get_model(self): return self.model my_first_Car = Car('Hyundai', 'i10', 'red', 150) print(f"My first car is {my_first_Car.get_model()}, having max speed limit as {my_first_Car.get_speed_limit()}")
6d2750ca3776983cc81021089df4dc1c5ec627d9
AbdelrahmanAhmed98/user-name-age
/Untitled9.py
188
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: name = input('Enter your name: ') name age = int( input('Enter your age:')) age print('Hello', name+',','\nyour age is',age,'years old')
b82e84b7d1de783fa60e319633b95bd69ab61d88
hamzah-hossenmamode/pyWorldAirport
/pyWorldAirport/pyWorldAirport.py
4,264
3.5625
4
import urllib.request import json import math class AirportLocation: def __init__(self,name,lon,lat): self.name = name self.lon = lon self.lat = lat def Distance(self,lon,lat): dLon = self.lon - lon dLat = self.lat - lat self.distance = math.sqrt(dLon * dLon + dLat * dLat) class WorldAircraftQuery: queryHead = 'https://mikerhodes.cloudant.com/airportdb/_design/view1/_search/geo?q=lon:[{}%20TO%20{}]%20AND%20lat:[{}%20TO%20{}]' querySort = '&sort="<distance,lon,lat,{},{},km>"' queryTail = '&bookmark={}' def __init__(self, localSort=True): self.queryValue = '' self.airports = [] self.localSort = localSort def ShowHead(self): print('World Of Airport Query Program') print('Please input the starting and ending longitudes and latitudes when prompted') def GetInput(self): try: lon1 = float(input('Enter starting longitude : ')) lon2 = float(input('Enter ending longitude : ')) lat1 = float(input('Enter starting latitude : ')) lat2 = float(input('Enter ending latitude : ')) lonMin = '{:.2f}'.format(min(lon1,lon2)) lonMax = '{:.2f}'.format(max(lon1,lon2)) latMin = '{:.2f}'.format(min(lat1,lat2)) latMax = '{:.2f}'.format(max(lat1,lat2)) self.lonCentre = (lon1 + lon2) / 2 self.latCentre = (lat1 + lat2) / 2 self.queryValue = WorldAircraftQuery.queryHead.format(lonMin,lonMax,latMin,latMax) except: return True return False def ShowError(self,error): print('Error: {}'.format(error)) def Process(self): try: bookmark = '' cumulativeRows = 0 while True: fullQuery = self.queryValue if not self.localSort: fullQuery+=WorldAircraftQuery.querySort.format(str(self.lonCentre),str(self.latCentre)) if bookmark != '': fullQuery+=WorldAircraftQuery.queryTail.format(bookmark) with urllib.request.urlopen(fullQuery) as response: responseValue = response.read() results = json.loads(responseValue) bookmark = results['bookmark'] allRows = results['total_rows'] availableRows = len(results['rows']) for rowIndex in range(availableRows): cumulativeRows+=1 row = results['rows'][rowIndex] fields = row['fields'] order = row['order'][0] airport = AirportLocation(fields['name'],fields['lon'],fields['lat']) if self.localSort: airport.Distance(self.lonCentre,self.latCentre) else: airport.distance = order self.airports.append((airport.distance,airport)) if allRows == cumulativeRows: break if self.localSort: self.airports.sort(key=lambda tup: tup[0]) except: return True return False def ShowResult(self): try: print('') tableView = '{:5} {:30} {:10} {:10} {:10}' print('From Centre Longitude: {:.2f}, Latitude: {:.2f}'.format(self.lonCentre,self.latCentre)) print(tableView.format('Order','Airport','Distance','Longitude','Latitude',)) for airportIndex in range(len(self.airports)): distance = self.airports[airportIndex][0] airport = self.airports[airportIndex][1] print(tableView.format(str(airportIndex + 1),airport.name,'{:.2f}'.format(distance),'{:.2f}'.format(airport.lon),'{:.2f}'.format(airport.lat),)) except: return True return False if __name__ == '__main__': query = WorldAircraftQuery(True) query.ShowHead() if query.GetInput(): query.ShowError('Illegal Input') elif query.Process(): query.ShowError('Processing Failed') else: query.ShowResult()
7d5f02e6ebcc99897b5e9a1e408338cc4b204f11
rbrito/scripts
/math/variance.py
1,082
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division def variance(x): """ Compute the sample variance of the elements in x[1..n] using Welford's recurrence formula: Initialize M_1 = x_1 and S_1 = 0. For subsequent x's, use the recurrence formulas M_k = M_{k-1} + (x_k - M_{k-1}) / k S_k = S_{k-1} + (x_k - M_{k-1}) * (x_k - M_k). For 2 ≤ k ≤ n, the k-th estimate of the variance is s^2 = S_k/(k - 1). Source: http://www.johndcook.com/standard_deviation.html >>> variance([1, 1]) (1.0, 0.0) >>> variance([1, 2]) (1.5, 0.5) >>> variance([1, 2, 3]) (2.0, 1.0) >>> variance([1e10, 1, -1e10]) (0.33333301544189453, 9.999999999999998e+19) """ assert(len(x) >= 2) mean = x[0] # the mean of x[1..1] var = 0 # the variance of x[1..1] n = len(x) for i in range(1, n): new_mean = mean + (x[i] - mean) / (i + 1) new_var = var + (x[i] - mean) * (x[i] - new_mean) mean = new_mean var = new_var return (mean, var/(n-1))
ad9ed223ceab8c144baaf34b83654f3daba44c42
rht/housing-model
/src/main/java/housing/Construction.py
3,039
3.734375
4
import random from typing import List class Construction(IHouseOwner): def __init__(self, prng): # Total number of houses in the whole model self.housingStock: int = 0 self.onMarket: List[House] = [] self.prng = prng # Number of houses built this month self.nNewBuild = 0 self.config = Model.config self.Model = Model #-------------------# #----- Methods -----# #-------------------# def init(self) -> None: self.housingStock = 0 self.onMarket.clear() def step(self) -> None: # Initialise to zero the number of houses built this month self.nNewBuild = 0 # First update prices of properties put on the market on previous time steps and still unsold for h in self.onMarket: self.Model.houseSaleMarket.updateOffer(h.getSaleRecord(), h.getSaleRecord().getPrice() * 0.95) # Then, compute target housing stock dependent on current and target population if len(self.Model.households) < self.config.TARGET_POPULATION: targetStock = int(len(self.Model.households) * self.config.CONSTRUCTION_HOUSES_PER_HOUSEHOLD) else: targetStock = int(self.config.TARGET_POPULATION * self.config.CONSTRUCTION_HOUSES_PER_HOUSEHOLD) # ...compute the shortfall of houses shortFall = targetStock - self.housingStock # ...if shortfall is positive... if shortFall > 0: # ...add this shortfall to the number of houses built this month self.nNewBuild += shortFall # ...and while there is any positive shortfall... while shortFall > 0: # ...create a new house with a random quality and with the construction sector as the owner newHouse = House(int(random.random() * self.config.N_QUALITY)) newHouse.owner = self # ...put the house for sale in the house sale market at the reference price for that quality self.Model.houseSaleMarket.offer( newHouse, self.Model.housingMarketStats.getReferencePriceForQuality(newHouse.getQuality()), False) # ...add the house to the portfolio of construction sector properties self.onMarket.append(newHouse) # ...and finally increase housing stocks, and decrease shortfall self.housingStock += 1 shortFall -= 1 def completeHouseSale(self, sale: HouseOfferRecord) -> None: self.onMarket.remove(sale.getHouse()) def endOfLettingAgreement(self, h: House, p: PaymentAgreement) -> None: print("Strange: a tenant is moving out of a house owned by the construction sector!") def completeHouseLet(self, sale: HouseOfferRecord) -> None: print("Strange: the construction sector is trying to let a house!") #----- Getter/setter methods -----# def getHousingStock(self) -> int: return self.housingStock def getnNewBuild(self) -> int: return self.nNewBuild }
0b59fcb902bffe4658d983f3bc6319aa7f9be85c
davidxbuck/adventofcode
/2018/src/Advent2018_02.py
1,034
3.609375
4
# Advent of Code 2018 Day 2 from collections import defaultdict, Counter file = open("../inputs/Advent2", 'r') inputs = [id[:-1] for id in file] twos = 0 threes = 0 for x in inputs: # For each ID code count = Counter() for y in x: count[y] += 1 # Create counter object for letters in ID inv_c = defaultdict(list) for k, v in count.items(): # Flip counter object inv_c[v].append(k) if len(inv_c[2]) > 0: twos += 1 # count ID containing twos or threes if len(inv_c[3]) > 0: threes += 1 print("Part1: Twos", twos, "Threes", threes, "Checksum", twos*threes) length = len(inputs[0]) candidates = [] for idx, x in enumerate(inputs): for y in inputs[idx+1:]: if sum(x[z] == y[z] for z in range(length)) == length - 1: candidates.append(x) candidates.append(y) answer = [] for x in range(length): if candidates[0][x] == candidates[1][x]: answer.append(candidates[0][x]) print("Part2: Common letters in target IDs", "".join(answer))
7b9a017cbf0b8aa5be124e27b8c867cf78f7a80f
karishay/HBExercise2
/testing.py
1,166
4.125
4
#import all functions from arithmetic file from arithmetic import * operators = ["+", "-", "/", "*", "pow", "square", "cube", "mod"] opDictionary = { "+" : add , "-" : subtract, "/" : divide, "*" : multiply, "pow": power, "square": square, "cube": cube, "mod": mod } while True: calcInput = raw_input("Parameters please.\n") calcList = calcInput.split(" ") if calcInput != "q": # this checks to see if the first in the list is an operator if calcList[0] not in operators: print "Operator first please." else: # returns and saves the operator calcOperator = calcList.pop(0) else: break # check other items in list to see if they are int or float for i in calcList: if i.isdigit() == False: print "Give me number only please" # if first item is operator elif calcOperator in operators: #then print the key paired function (in the dictionary) and pass it the parameters (the next items given by the user) print opDictionary.get(calcOperator)(int(calcList[0]), int(calcList[1]))
82775a59613fd8074ad44f64b7970f28ffe067a3
NicolaiNisbeth/StudentGrading
/inputNumber.py
422
3.96875
4
def inputNumber(prompt): # INPUTNUMBER Prompts user to input a number. Repeats until valid number. # # Usage: number = inputNumber(prompt) # # Author: From "Creating an interactive menu" made by Mikkel N. Schmidt. # Checks if user input is a number while True: try: number = float(input(prompt)) break except ValueError: pass return number
fdbfc07b1ad7424c926ad1f824a172cee78710b3
Aasthaengg/IBMdataset
/Python_codes/p03029/s847494228.py
119
3.515625
4
x = [int(i) for i in input().split()] if x[0] < 1 and x[1] < 2: print(0) else: print(((x[0] * 3) + x[1]) // 2)
4e41163bec478ac8781840319fbdaa461b3c6fdd
lenakchen/Hadoop
/project/mapper2.py
1,110
3.6875
4
#!/usr/bin/env python """ Final Project Task Two: Post and Answer Length Find if there is a correlation between the length of a post and the length of answers. Write a mapreduce program that would process the forum_node data and output the length of the post and the average answer (just answer, not comment) length for each post. Dataset: forum_node.tsv The fields in forum_node that are the most relevant to the task are: "id" "title" "tagnames" "author_id" "body" "node_type" "parent_id" "abs_parent_id" """ import sys import csv #import re reader = csv.reader(sys.stdin, delimiter='\t') for line in reader: # find the node id of a forum post node_id = line[0] if node_id == 'id': continue body = line[4] node_type = line[5] ##remove html tags #tags = re.compile('<.*?>') #body = re.sub(tags, '', body) post_len = len(body) if node_type == 'question': print '{0}\t{1}\t{2}'.format(node_id, 'A', post_len) if node_type == 'answer': abs_parent_id = line[7] print '{0}\t{1}\t{2}'.format(abs_parent_id, 'B', post_len)
a27ea7534fb87942eb192ca8e24cc9d974819c0b
CodeForContribute/Algos-DataStructures
/TreeCodes/Summation/maxSumLeafRootPath.py
1,275
3.515625
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def maxSumLeafRootPAth(root): if not root: return 0 target_leaf_ref = [None] import sys max_sum = [-sys.maxsize] getTargetLeaf(root, max_sum, 0, target_leaf_ref) printPath(root, target_leaf_ref) return max_sum[0] def getTargetLeaf(root, max_sum, current_sum, target_leaf_ref): if not root: return current_sum += root.data if not root.left and not root.right: if current_sum > max_sum[0]: max_sum[0] = current_sum target_leaf_ref[0] = root getTargetLeaf(root.left, max_sum, current_sum, target_leaf_ref) getTargetLeaf(root.right, max_sum, current_sum,target_leaf_ref) def printPath(root, target_leaf_ref): if not root: return False if root == target_leaf_ref[0] or printPath(root.left, target_leaf_ref) or printPath(root.right, target_leaf_ref): print(root.data,end=" ") return True return False if __name__ == '__main__': root = Node(10) root.left = Node(-2) root.right = Node(7) root.left.left = Node(8) root.left.right = Node(-4) sum = maxSumLeafRootPAth(root) print("\n") print(sum)
1337bf18b563a536cf89ddc061d11a6291da3f88
k4kaki/Python_Repo
/HigherOrderFns/closureExample.py
204
3.78125
4
def multiple_of(x): def multiple(y): return x*y return multiple c1 = multiple_of(5) # 'c1' is a closure c2 = multiple_of(6) # 'c2' is a closure print(c1(4)) print(c2(4))
51994bec20078171e5de9007b81ed0270783124e
thaReal/MasterChef
/codeforces/round_617/oddsum.py
560
3.796875
4
#!/usr/bin/python3 # Codeforces - Round 617 - Practice # Author: frostD # Problem A - Array with Odd Sum def read_int(): n = int(input()) return n def read_ints(): ints = [int(x) for x in input().split(" ")] return ints #--- def solve(n,a): odd = False even = False if sum(a) % 2 == 1: return "YES" for i in range(n): if a[i] % 2 == 1: odd = True else: even = True if odd and even: return "YES" return "NO" # Main t = read_int() for case in range(t): n = read_int() a = read_ints() sol = solve(n,a) print (sol)
4178b83aa72e2efd6a676a4bb5a928dbdee9b471
nickbent/covid-quebec-ontario
/src/plot/utils.py
664
3.75
4
from itertools import islice def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result def nday_avg(data, n): avg = [] for ndays in window(data, n): avg.append(sum(ndays)/n) return avg def per100k(data, population): return [ total/p*100000 for total, p in zip(data, population)] def string_to_float(string): return float(string.replace(",", "."))
d0822400df7daa5eb3c08faf3ca9682c28a5e548
mattclemons/Python
/ThinkPython/my_hypotenuse.py
359
4.03125
4
# Exercise 6.2. Use incremental development to write a function called hypotenuse # that returns the length of the hypotenuse of a right triangle given the # lengths of the two legs as arguments. Record each stage of the development # process as you go. import math def hypotenuse(x,y): return math.sqrt(x**2 + y**2) print hypotenuse(7, 10)
fd412501fab672c4e98278d5691aa877135d16db
gabo32/UniversidadPython
/Profundizando/representacion_objetos.py
959
3.984375
4
# REpresentacion de objetos (str, repr, format) # print(dir(object)) class Persona: def __init__(self, nombre, apellido): self.nombre = nombre self.apellido = apellido # repr mas enfocado a programadores def __repr__(self): return f'{self.__class__.__name__}(nombre:{self.nombre}, apellido: {self.apellido})' # return f'{self.__class__.__name__}{self.__dict__}' # str esta mas enfocado al usuario final u otros sistemas def __str__(self): return f'{self.__class__.__name__}: {self.nombre} {self.apellido}' #su implementacion por defecto es str #se llama cuando se imprimr un fstring def __format__(self, format_spec): return f'{self.__class__.__name__} con nombre {self.nombre} y apellido {self.apellido}' persona1 = Persona('Juan', 'Perez') print(persona1) # asegura el llamado a repr print(f'Mi objecto persona1: {persona1!r}') print(persona1) #format print(f'{persona1}')
62cfc31d3dec848f806b0c99cbaacf20ca4af4a1
BenjiQueens/Python-Practice
/VolleyballStats.py
1,745
3.65625
4
#Code by Benji Christie #Input the name of a volleyball player, then the specific stat associated to the #player and the amount of times they do that thing def validateName(prompt): while True: try: name = input(prompt) if(not (name.isalpha())): raise NameError break except NameError: prompt = "Invalid Name...Please enter a name with only letters:\n" return name def validateNum(prompt): while True: try: num = int(input(prompt)) if(num < 0): raise ValueError break except ValueError: prompt = "Please enter a positive number\n" return num def getName(): numPlayers = int(input("How many player's will you be entering stats for?\n")) namesBank = [] prompt = "Please enter the player's name: " for i in range(0,numPlayers): name = validateName(prompt) namesBank.append(name) return namesBank def getStats(stats,name): numStats=[] for i in range(0,len(stats)): prompt = "How many "+ stats[i] +" did "+name+" get?\n" num = validateNum(prompt) numStats.append(num) return numStats def setStats(stat,num): totalStat = {} for i in range(0,len(stat)): totalStat.update({stat[i]:num[i]}) return totalStat def createPlayerBase(names,stats): players = {} for i in range(0,len(names)): numStats = getStats(stats, names[i]) players[names[i]] = setStats(stats,numStats) return players #main names = getName() stats = ['kills','blocks','digs'] players = createPlayerBase(names,stats) print(players)
205f83b81d11399f38c95efc03d54758bf004699
shahstewart/katas
/programming/fibonacci/python/forwardRecursiveWithReduce.py
292
3.65625
4
from functools import reduce def fib(n=None): if n is None or not str(n).isnumeric() or n < 0: return 'Invalid Input!' if n < 2: return n ret = reduce(lambda acc, val: acc if val < 2 else [acc[1], acc[0] + acc[1]], range(n), [0, 1]) return ret[0] + ret[1]
a0a1946cce8484d2a216ba4cd4d221c2292b7beb
brichi15/Coding-Practice
/Longest common prefix.py
464
3.59375
4
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: letter_number = 0 if not strs: return "" for letter in strs[0]: for word in strs[1:]: if letter_number >= len(word) or letter != word[letter_number]: return strs[0][:letter_number] letter_number += 1 return strs[0][:letter_number]
5052f59c91f1d9a42ec94305333741ae34e7d4e7
black-star32/cookbook
/3/3.3.2.py
1,618
4.09375
4
# 需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节。 # 格式化输出单个数字的时候,可以使用内置的 format() 函数,比如: x = 1234.56789 # Two decimal places of accuracy print(format(x, '0.2f')) # Right justified in 10 chars, one-digit accuracy print(format(x, '>10.1f')) # Left justified print(format(x, '<10.1f')) # Centered print(format(x, '^10.1f')) # Inclusion of thousands separator print(format(x, ',')) print(format(x, '0,.1f')) # 如果你想使用指数记法,将f改成e或者E(取决于指数输出的大小写形式)。比如: print(format(x, 'e')) print(format(x, '0.2E')) # 同时指定宽度和精度的一般形式是 '[<>^]?width[,]?(.digits)?' , # 其中 width 和 digits 为整数,?代表可选部分。 # 同样的格式也被用在字符串的 format() 方法中。比如: print('The value is {:0,.2f}'.format(x)) # 数字格式化输出通常是比较简单的。上面演示的技术同时适用于 # 浮点数和 decimal 模块中的 Decimal 数字对象。 # 当指定数字的位数后,结果值会根据 round() 函数同样的规则进行四舍五入后返回。 # 比如 print(x) print(format(x, '0.1f')) print(format(-x, '0.1f')) # 包含千位符的格式化跟本地化没有关系。 如果你需要根据地区来显示千位符,你需要自己去调查下 locale 模块中的函数了。 # 你同样也可以使用字符串的 translate() 方法来交换千位符。比如: swap_separators = { ord('.'):',', ord(','):'.' } print(format(x, ',').translate(swap_separators))
769f66554ae25ec1e9f960bd7df412cf596f2a79
taehyungz/Algorithm
/programmers/level1/나누어 떨어지는 숫자 배열.py
168
3.53125
4
def solution(arr, divisor): answer = [] for n in arr: if n%divisor==0: answer.append(n) return sorted(answer) if len(answer)>0 else [-1]
f2f439184c81bdb417baab7f0d97a243d3776899
Ethan-Xie/python_study
/def binary_search.py
2,296
3.734375
4
# 二分查找法 def binary_search(data_source,find_n): mid=int(len(data_source)/2) if(mid==1): if data_source[mid] == find_n: print("存在") return print("不存在") return if data_source[mid] >find_n: #切片: data_source=data_source[:mid] print("数据在左边[%d]"%mid) binary_search(data_source,find_n) elif data_source[mid] <find_n: #切片: data_source=data_source[mid:] print("数据在右边[%d]"%mid) binary_search(data_source,find_n) #elif data_source[mid] ==find_n: # print("找到[%d]"%mid) else: print("存在") if __name__=='__main__': data = list(range(1,100,3)) #print(data) binary_search(data,63) # 二维数组 a=[[col for col in range(4)] for row in range(4)] print(a) print(range(0,4)) for i in a: print(i) print(a[0][1]) b = [[col for col in range(4)] for row in range(4)] for r_index,row in enumerate(a): #print(row,r_index) for c_index in range(len(row)): #tmp=data[]0 0 1 0 #print(c_index,r_index) #temp=a[c_index][r_index] #a[c_index][r_index]= row[c_index] #b[r_index][c_index]=temp b[r_index][c_index] = a[c_index][r_index] for i in b: print(i) import re m=re.match("abc","abcd") m = re.match("[0-9]{1,4}", "51561") m = re.match(".*", "51561") m = re.match(".+", "51561") m = re.search("6", "51561") #m = re.sub("\d","@", "5s56gf1",count=2) #@s@@gf@ print(m) # 匹配失败 if m==None: # if m: print(m) # 匹配失败 else: print(m.span()) print(m.group()) m = re.match("[0-9]{10}","515224" ) #None m = re.findall("[0-9]{10}", "54ge5wewf54") #[] m = re.findall("[0-9]{2}", "15255") #['15', '25'] m = re.findall(".*", "54ge5wewf54") #['54ge5wewf54', ''] m = re.findall("[a-zA-Z]+","54dfsef451es#%^") #['dfsef', 'es'] m = re.findall("%","54dfsef451es#%^") #['%'] m = re.search("\d+","45dfesf") #<_sre.SRE_Match object; span=(0, 2), match='45'> if m: print(m) #print(m.span()) #print(m.group()) else: print(m)
6d75561266d6e88e9f99d18e0402b370bfc3f52d
anyi400/ejercicios-1-10-
/ejercicio-3.py
194
3.9375
4
for numer in range(1, 60) numer == numer*numer print(es el numero) numer = 1 while numer <= 60 n = numer * numer print(f "el numero cuadrado es {numer} es {n}") numer += 1 print("este es :)")
bfa5d99e0b2e0d7ca04dae13040349d4be2a4a25
gurmeetkhehra/python-practice
/Tuple.py
350
3.515625
4
cars = ('Toyota', 'Nissan', 'Audi', 'Volvo') print (cars[0]) print (cars[1]) print (cars[2]) print (cars[3]) # cars[0]= 'Honda' cars = ('Tesla', 'BMW') print (cars) # farms = ('Froster', 'Milk Diary', 'Wheat', 'Almond') # # print (farms[0]) # print (farms[1]) # print (farms[2]) # print (farms[3]) # # farms = ('Tree', 'Grass') # print (farms) #
9717abd2287ea71b0ffdb6f8ca7202b031273e09
bar2104y/Abramyan_1000_tasks
/Results/Python/Series/4.py
131
3.609375
4
s = 0.0 a = 1.0 k = int(input()) for i in range(0,k): n = float(input()) s += n a *= n print("+ :",s) print("* :", a)
ff57c82a0a864d6d01ef93a7897056b8d38aedc0
AAAKgold/My-test
/python/py_pr/06匿名函数-文件/08-判断这一年的第几天-函数.py
768
3.515625
4
def judge_day(): '''用来输入年月日判断这一天是这一年的第几天''' a = [[31,28,31,30,31,30,31,31,30,31,30,31],[31,29,31,30,31,30,31,31,30,31,30,31]] #1.用户输入年月日 year = int(input("请输入需要判断的年:")) month = int(input("请输入需要判断的月:")) day = int(input("请输入需要判断的日:")) #2.判断是这一年的第几天 sum = 0 if year%4 == 0 and year%100 != 0 or year%400 == 0: for i in range(1,month): sum = sum + a[1][i] else: for i in range(1,month): sum = sum + a[0][i] sum += day #3.输出 print("%d年%d月%d日是这一年的第%d天"%(year,month,day,sum)) #print(a[1][2])#for test judge_day()
a7962bb5bacb50ca6a97b4ca8e1f545bd4ee9fd0
grigoriishveps/PosovSubject
/binary_answer.py
703
3.75
4
def check(array, l): m = 1 s = l for i in range(1, len(array)): if (s >= array[i] - array[i-1]): s -= array[i] - array[i-1] else: s = l m += 1 return m def binary_search(array, k): left = -1 right = array[-1] - array[0] while right > left + 1: middle = (left + right) // 2 if check(array, middle) <= k: right = middle else: left = middle return right def start_binary(): n = int(input()) a = [0]*n k = int(input()) for i in range(n): a[i] = int(input()) print(*a) print(binary_search(a, k)) if __name__ == '__main__': start_binary()
459584ecda8a9b95133153aa31af02650a2b8aef
nutllwhy/Leetcode_python
/Easy/6Dynamic_programing/1Climbing_stairs.py
619
3.546875
4
# 爬楼梯 # 假设你正在爬楼梯。需要 n 步你才能到达楼顶。 # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # 注意:给定 n 是一个正整数。 class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ # https://blog.csdn.net/guoziqing506/article/details/51646800 # 走到第i级台阶的走法:f[i] = f[i - 1] + f[i - 2] record = [1,1] if n >= 2: for i in range(2, n + 1): record.append(record[i - 1] + record[i - 2]) return record[n]
af381cffcfe870098bbe93c40501c6b5e43a4a6f
MeloMao/Python_program
/M_bundle2.0.py
1,360
3.625
4
#M2.0 def strback(a): b=[] for i in range(0,len(a)): b.append(a[len(a)-i-1]) return b def strmove(a): b=[] for i in range(0,len(a)): if(i==0): b.append(a[len(a)-1]) else: b.append(a[i-1]) return b def re_strmove(a): b=[] for i in range(0,len(a)): if(i==len(a)-1): b.append(a[0]) else: b.append(a[i+1]) return b def strchange(a): b=[] if(len(a)%2==0): for i in range(0,len(a)): if(i%2==0): b.append(a[i+1]) else: b.append(a[i-1]) else: for i in range(0,len(a)-1): if(i%2==0): b.append(a[i+1]) else: b.append(a[i-1]) b.append(a[len(a)-1]) return b #main print("请输入需要处理的字符串:") a=input("") print("输入1进行M加密,输入2进行M解密:") y=input() x=int(y) if(x==1): for i in range(0,9): a=strback(a) a=strmove(a) a=strchange(a) print("M加密结果为:") for i in range(0,len(a)): print(a[i],end='') print() else: for i in range(0,9): a=strchange(a) a=re_strmove(a) a=strback(a) print("M解密结果为:") for i in range(0,len(a)): print(a[i],end='') print()
df1f71991d809c7d2fb8cf9d6fec7915ebefd04a
KevDeem/TA_Session_Semester_1
/pokemon/pokemon.py
1,314
3.703125
4
import random def map(): li = [] x = 0 y = 0 file = open("map.txt", "r") raw = file.read().split("\n") for row in range(len(raw)): f = raw[row].split(",") li.append([]) for col in range(len(f)): if f[col] == "0": print("o", end = " ") li[row].append("o") if f[col] == "1": print("x",end = " ") li[row].append("o") x = col y = row if f[col] == "2": print("#", end = " ") li[row].append("#") print(" ") for i in range (0,8): if raw[i] == "0": li[y][x] = "o" elif raw[i] == "2": li[y][x] = "#" file.close() def random_prob(): prob = random.randint(0, 5) if prob == 0: print("A wild pokemon has appeard!") map() print("==============") print(" MENU ") print("==============") print("1. move up") print("2. move down") print("3. move left") print("4. move right") print("5. save and exit game") while 1: choice = int(input("choose action: ")) if choice == "1": print("move up") if ( y - 1 >= 0): y -= 1 if choice == "2": print("move down") if ( y + 1 <= 7): y += 1 if choice == "3": print("move left") if ( x - 1 >= 0): x -= 1 if choice == "4": print("move right") if ( x + 1 <= 7): x += 1 if choice == "5": print("game saved") break else: ("invalid input")
3343331de59fd08ff42c368e39e8c9535873d4ec
preetising/List
/reverse.py
148
3.90625
4
place=["delhi", "gujrat", "rajasthan", "punjab", "kerala"] print("place before reverse:",place) place.reverse() print("place after reverse :",place)
e55388f05a965b21430aebeab3f8191e0d4d4ece
qperotti/Cracking-The-Coding-Interview-Python
/Graph Algorithms/BellmanFord.py
1,111
4.1875
4
""" Bellman-Ford algorithm Time Complexity: O(EV) """ def shortestPath(graph, start): # Initialize distances. distance = {} for k in graph: distance[k] = float('inf') distance[start] = 0 # Rellax all edges V -1 Times. for _ in range(len(graph)): for node in graph: for neighbour in graph[node]: if distance[neighbour] > (distance[node] + graph[node][neighbour]): distance[neighbour] = (distance[node] + graph[node][neighbour]) return distance # Check for negative-weight cycles. for node in graph: for neighbour in graph[node]: if distance[neighbour] > (distance[node] + graph[node][neighbour]): raise NameError('Negative weight cycle!') if __name__ == "__main__": graph = { 'A': { 'B': -1, 'C': 4 }, 'B': { 'C': 3, 'D': 2, 'E': 2 }, 'C': { }, 'D': { 'C': 5, 'B': 1 }, 'E': { 'D': -3 } } distance = shortestPath(graph,'A') for k in graph: print("Distance from [ A ] to [",k,"] -> ",distance[k])
ee72d773ac848ef5cb10ba3bf64c425a18cfcbb3
yinxuan2001/SchoolProject
/__main__.py
2,885
3.90625
4
from ChooseCharacter import choose_character_1, choose_character_2, choose_character_3 from Enemy import Enemy, enemy_1, enemy_2, enemy_3 def play(chars): attack = False game_over = False turn = 0 print("Battle Start.The following character are present : \n") for c in chars: print(c) print("") if c.alive == True : while not game_over : n = list(chars) for i in len(n): sel = (input("Choose Character to attack: {0} {1}".format((i+1),(chars)))) attack = True while attack == True: sel(attack) attack == False while attack == False: Enemy(attack) # while not game_over: # print("It's the turn of Yours, Please select a character to attack: ".format(chars[turn].name)) # possible = [] # for i in list(len(chars)): # if not i == turn : # possible.append(i) # print(" - ({0}) : {1} ".format(i,chars[i].c)) # sel = -1 # while not sel in possible : # s = input("Selection : ") # try : # sel = int(s) # except : # print("That's not a valid choice") # chars[turn].attack(chars[sel]) # if chars[sel].hp <= 0 : # game_over = True # print("That was it! {0} has died and the game is over.".format(chars[sel].name)) # turn += 1 # if turn == len(chars): turn =0 def start_game(): start_game = False while start_game is False : print("Start the Games ?") answer = input("\n(Y)es\n(N)o\nAnswer: ").lower() if answer == "y" : start_game = True elif answer == "n" : print("Quited") exit() def main() : chars = [] enemy = [] menu = "" print("Testing 123") start_game() while start_game == True: menu = "" while not menu.lower() in ['c', 'l', 'b']: menu = input("\nMENU\n[C]reate Character \n[L]ist of Character\n[P]lay\n[Q]uit\n: ").lower() if menu == 'c': chars.append(choose_character_1(chars)) chars.append(choose_character_2(chars)) chars.append(choose_character_3(chars)) menu = "" elif menu == 'l' : print(chars) menu = "" elif menu == 'p' : play(chars) enemy.append(enemy_1(enemy)) enemy.append(enemy_2(enemy)) enemy.append(enemy_3(enemy)) elif menu == 'b' : print("\nPrepare Yourself !") if __name__ == "__main__": main()
87e25ca213b0f1d260fa0635f38cb90316c5c365
BerkayAkbulut/HangManGame
/main.py
2,055
3.59375
4
import random import hangman_art,getAWord from os import system, name def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') def startGame(): diaplay = list() chosenWord=str(getAWord.get_a_word()).replace('[\'','').replace('\\','').replace('\']','') chosenWord.replace('\'','') chosenWordLenght=len(chosenWord) for wordCount in range(chosenWordLenght): diaplay+='_' print(diaplay) return diaplay,chosenWordLenght,chosenWord lives = 6 endOfGame=False display,chosenWordLenght,chosenWord = startGame() usedletters=list() while not endOfGame: print('Used letters: '+ str(usedletters)) guess = input('Guess a letter: ').lower()#harfileri küçültüyoruz clear() if guess in display: print(f'You have already guessed {guess}') for position in range(chosenWordLenght): if chosenWord[position]==guess: display[position]=guess if guess not in chosenWord: print(f'You guessed {guess}, that is not in the word. You lose a life.') usedletters.append(guess) lives -=1 if lives==0: endOfGame=True print(f'you lose. Word is {chosenWord}') replay=input('Do you want to replay? (y/other letter):').lower() if(replay=='y'): lives=6 clear() endOfGame=False display.clear() usedletters.clear() display,chosenWordLenght,chosenWord = startGame() continue print(display) if '_' not in display: endOfGame=True print('You win!') replay = input('Do you want to replay? (y/other letter):').lower() if (replay == 'y'): lives = 6 clear() endOfGame = False display.clear() display, chosenWordLenght, chosenWord = startGame() continue print(hangman_art.stages[lives])
d5dda98e7a09e7fb0b8e1928614ca3ed4cdeaa0e
Escuhlade/Projects
/cipherText.py
337
3.90625
4
def caesar(givenstr, shift): encodedTxt = "" for i in givenstr: if i.isalpha(): InAlphaOrder = ord(i) + shift if InAlphaOrder > ord('z'): InAlphaOrder -= 26 lastLetter = chr(InAlphaOrder) encodedTxt += lastLetter print ("Your encoded ciphertext is: ", encodedTxt) return encodedTxt
bc6d4ea2301a2b71dc629fe97827d28beb4fe37e
willbrown600/CS241-OOP-Data_Structures
/Team Acitivities/ta10.py
1,967
4.28125
4
from random import randint MAX_NUM = 100 def merge_sort(items): """ Sorts the items in the list :param items: The list to sort """ """ Base case""" if len(items) == None: return """ Split into two halfs """ half = len(items) // 2 """first half """ first_half = items[:half] """ Second half """ second_half = items[half:] """Recursive part""" merge_sort(first_half) merge_sort(second_half) """Straight from instructors code""" # Merge the two sorted parts i = 0 # iterator for part 1 j = 0 # iterator for part 2 k = 0 # iterator for complete list while i < len(first_half) and j < len(second_half): # Get the smaller item from whichever part its in if first_half[i] < second_half[j]: items[k] = first_half[i] i += 1 k += 1 else: # part2 <= part1 items[k] = second_half[j] j += 1 k += 1 # At this point, one or the other size is done # Copy any remaining items from part1 while i < len(first_half): items[k] = first_half[i] i += 1 k += 1 # Copy any remaining items from part2 while j < len(second_half): items[k] = second_half[j] j += 1 k += 1 # The list is now sorted! def generate_list(size): """ Generates a list of random numbers. """ items = [randint(0, MAX_NUM) for i in range(size)] return items def display_list(items): """ Displays a list """ for item in items: print(item) def main(): """ Tests the merge sort """ size = int(input("Enter size: ")) items = generate_list(size) merge_sort(items) print("\nThe Sorted list is:") display_list(items) if __name__ == "__main__": main()
66ef02ee86866f31da8f80feb45347177914141e
tami888/PE
/Problem010.py
483
3.84375
4
# -*- coding: utf-8 -*- """ 10以下の素数の和は 2 + 3 + 5 + 7 = 17 である. 200万以下の全ての素数の和を求めよ. """ import math def isprime2(n, primes): for i in range(int(math.sqrt(n))): if n % primes[i] == 0: return False return True def primes(n): prms = [2] for i in range(3, n+1, 2): if isprime2(i, prms): prms.append(i) return prms if __name__ == '__main__': print sum(primes(2000000))
f5efe6028888bb8d344c6e7576e18ff1e4ac0ff7
chenxy3791/leetcode
/No0450-delete-node-in-a-bst-medium.py
1,804
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 2 14:32:25 2022 @author: chenxy """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if root==None: return None if root.val < key: root.right = self.deleteNode(root.right, key) elif root.val > key: root.left = self.deleteNode(root.left, key) else: if root.left==None and root.right==None: # 既没有左子树,也没有右子树 return None elif root.left==None and root.right!=None: # 只有右子树 return root.right elif root.left!=None and root.right=None: # 只有左子树 return root.left else: # 既有左子树,也有右子树 # 搜所根节点的successor,从右子节点出发一直沿着左子树往下寻找直到最后 # 一个没有左子节点的节点。然后递归地针对root.right调用deleteNode来删 # 除successor。因为successor 没有左子节点,因此这一步递归调用不会再 # 次步入这一种情况。然后将successor 更新为新的 root 并返回。 successor = root.right while successor.left: successor = successor.left successor.right = self.deleteNode(root.right, successor.val) successor.left = root.left return successor return root
17ba1718c25652793a611a88bda2f462083d35b6
AlphaBitz/Tarea_EED_Nicolas_Roman
/ABB.py
2,755
3.796875
4
class Nodo_ABB: def __init__(self, nombre,apellido,email,numero): self.left = None self.right = None self.nombre=nombre self.apellido = apellido self.email=email self.numero=numero self.parent = None def get_info(self): print (self.nombre,self.apellido,self.email,self.numero) return class ABB: def __init__(self): self.root = None def empty(self): return self.root == None def _insertar(self,nombre,apellido,email,numero , node): if apellido < node.apellido: if node.left == None: node.left = Nodo_ABB(nombre,apellido,email,numero) node.left.parent = node else: self._insertar(nombre,apellido,email,numero , node.left) elif apellido > node.apellido: if node.right == None: node.right = Nodo_ABB(nombre,apellido,email,numero) node.right.parent = node else: self._insertar(nombre,apellido,email,numero, node.right) else: print("El apellido ya a sido ingresado") def insertar_ABB(self, nombre,apellido,email,numero): if self.empty(): self.root = Nodo_ABB(nombre,apellido,email,numero) else: self._insertar(nombre,apellido,email,numero, self.root) def _buscar(self, apellido, node): if node.apellido == None: return node elif apellido == node.apellido: print ("Nodo Encontrado:") node.get_info() return node elif apellido < node.apellido and node.left != None: return self._buscar(apellido, node.left) elif apellido > node.apellido and node.right != None: return self._buscar(apellido, node.right) print("No encontrado") def buscar_ABB(self, apellido): if self.empty(): print ("Sin Raiz") return None else: return self._buscar(apellido, self.root) def imprimir_ABB(self, node): if node==None: pass else: self.imprimir_ABB(node.left) node.get_info() self.imprimir_ABB(node.right) def eliminar_ABB(root, apellido): if not root: return root if root.apellido > apellido: root.left = eliminar_ABB(root.left, apellido) elif root.apellido < apellido: root.right= eliminar_ABB(root.right, apellido) else: if not root.right: return root.left if not root.left: return root.right temp = root.right mini = temp.apellido while temp.left: temp = temp.left mini = temp.apellido root.apellido = mini root.right = eliminar_ABB(root.right,root.apellido) return root
eb7398bddac144beed06b4bf6203a7cac643fbb8
thanosa/coding-challenges
/advent_of_code/2019/02_program_alarm/aoc_2019_02.py
1,552
3.59375
4
''' Advent of code 2019 Day 2: 1202 Program Alarm''' import os INPUT_FILE=__file__.replace('.py', '.dat') # For part 1 def run_program(code: list) -> int: i = 0 while code[i] != 99: operation = code[i + 0] address1 = code[i + 1] address2 = code[i + 2] address3 = code[i + 3] if operation == 1: code[address3] = code[address1] + code[address2] elif operation == 2: code[address3] = code[address1] * code[address2] elif operation == 99: return code else: raise RuntimeError(f"error in operation: {i}") i += 4 return code # For part 1 and 2 def edit_memory(code: list, noun = 12, verb = 2) -> list: return [code[0], noun, verb, *code[3:]] # Part 1 asserts assert(run_program([1,0,0,0,99]) == [2,0,0,0,99]) assert(run_program([2,3,0,3,99]) == [2,3,0,6,99]) assert(run_program([2,4,4,5,99,0]) == [2,4,4,5,99,9801]) assert(run_program([1,1,1,4,99,5,6,0,99]) == [30,1,1,4,2,5,6,0,99]) # Part 1 solution with open(INPUT_FILE, 'r') as f: intcode = list(map(int, f.read().split(","))) result = run_program(edit_memory(intcode))[0] print(f"Part 1: {result}") # Part 2 solution target = 19690720 for noun in range(100): for verb in range(100): memory = intcode[:] check = run_program(edit_memory(memory, noun, verb))[0] if check == target: result = 100 * noun + verb print(f"Part 2: {result}")
64411378760a8f74627e80f3d58d25e346806eed
99062718/collections
/rekenen.py
1,170
3.859375
4
listOne = [1,2,3,4,5,6,7,8,9,10] listTwo = [2,4,6,8,10,12,14,16,18,20] def addAndDisplayLists(list1, list2): print("---------\nAdd lists") for number in range(len(listOne)): print(str(listOne[number]) + " + " + str(listTwo[number]) + " = " + str(listOne[number] + listTwo[number])) def subtractAndDisplayLists(list1, list2): print("---------\nSubtract lists") for number in range(len(listOne)): print(str(listOne[number]) + " - " + str(listTwo[number]) + " = " + str(listOne[number] - listTwo[number])) def multiplyAndDisplayLists(list1, list2): print("---------\nMultiply lists") for number in range(len(listOne)): print(str(listOne[number]) + " x " + str(listTwo[number]) + " = " + str(listOne[number] * listTwo[number])) def devideAndDisplayLists(list1, list2): print("---------\nDevide lists") for number in range(len(listOne)): print(str(listOne[number]) + " / " + str(listTwo[number]) + " = " + str(listOne[number] / listTwo[number])) addAndDisplayLists(listOne, listTwo) subtractAndDisplayLists(listOne, listTwo) multiplyAndDisplayLists(listOne, listTwo) devideAndDisplayLists(listOne, listTwo)
971695688cff2d47c082258b59ba5d111dc022fc
alvas-education-foundation/albinfrancis008
/coding_solutions/coding06.20.py
570
4.375
4
# Python program to rotate a matrix by 90 degrees M = 3 N = 3 matrix = [[12, 23, 34], [45, 56, 67], [78, 89, 91]] def rotateMatrix(k) : global M, N, matrix temp = [0] * M k = k % M for i in range(0, N) : for t in range(0, M -k) : temp[t] = matrix[i][t] for j in range(M -k, M) : matrix[i][j -M + k] = matrix[i][j] for j in range(k, M) : matrix[i][j] = temp[j -k] def displayMatrix() : global M, N, matrix for i in range(0, N) : for j in range(0, M) : print ("{} " . format(matrix[i][j]), end = "") print () k = 2 rotateMatrix(k) displayMatrix()
8c6f8185311f037268d0e2a5c932f1df4ebac493
Teminix/Intermediate-Codefest-Coding-Bootcamp
/2.2: Loops/For loop.py
379
4.59375
5
# For loops are definite loops, we know when the loop will end # The below code will print out the elements in a list myList = ['Hello world',23,1.0,3.141,69,False] # Declare list with items in them for i in myList: # The CURRENT item in the list is the variable named 'i' print(i) # We can use a range function to print a range of numbers for i in range(23, 50): print(i)
99d205e7cfeed3d45ce0f6f302ecc3acd8293fc4
sherryxiata/zcyNowcoder
/basic_class_03/RotateMatrix.py
867
3.828125
4
# -*- coding: utf-8 -*- # @Time : 2020/6/28 12:46 # @Author : wenlei ''' 顺时针旋转矩阵90度 ''' def rotateMatrix(matrix): tr = 0 tc = 0 dr = len(matrix) - 1 dc = len(matrix[0]) - 1 while tr < dr: rotateEdge(matrix, tr, tc, dr, dc) tr += 1 tc += 1 dr -= 1 dc -= 1 def rotateEdge(matrix, tr, tc, dr, dc): times = dc - tc for i in range(times): tmp = matrix[tr][tc + i] matrix[tr][tc + i] = matrix[dr - i][tc] matrix[dr - i][tc] = matrix[dr][dc - i] matrix[dr][dc - i] = matrix[tr + i][dc] matrix[tr + i][dc] = tmp def printMatrix(matrix): for i in range(len(matrix)): for j in range(len(matrix[0])): print(matrix[i][j]) if __name__ == '__main__': m = [[1,2,3],[4,5,6],[7,8,9]] rotateMatrix(m) printMatrix(m)
de038ea63fbaded0508784a2d5feeb110f975337
anjumrohra/Python_projects
/python_projects/digital_clock/clock.py
427
3.96875
4
from tkinter import * #strftime retrieves the computer's time to display on the application from time import strftime root = Tk() root.title("Digital Computer Clock") def time(): string = strftime("%H:%M:%S %p") lbl.config(text = string) lbl.after(1000, time) lbl = Label(root, font = "arial 100 bold",bg="yellow",fg = "black") lbl.pack(anchor ="center",fill="both",expand=1) time() mainloop()
73cf42f3f64274245c9709106c25449e2a831cd2
Diniz-G/Minicurso_Python
/minicurso_python/arquivos.py
696
3.828125
4
################################## # r -> somente leitura # w -> escrita (se o arquivo ja existir # será apagado e um novo # vazio será criado) # a -> leitura e escrita (adiciona o # novo conteúdo no fim # do arquivo) # r+ -> leitura e escrita # w+ -> escrita (tambem apaga o conteúdo) # a+ -> leitura e escrita (abre o arquivo # para atualização) arq = open("arquivo.txt") #linhas = arq.readlines() #print(linhas) texto_completo = arq.read() print(texto_completo) ########################################## arq2 = open("arquivo2.txt", "a") arq2.write("Escrevendo no arquivo 2\nEsse é meu arquivo\n") arq2.close()
74ab09a862a48b4fd7ff62ac1f5bcdc5b58c7551
xiuxim/store
/day02/99乘法表.py
397
3.546875
4
i=1 while i<=9: k=1 while k<=i: m=i*k print(i,"*",k,"=",m," ",end='') k=k+1 print() i=i+1 print() j=9 while j>0: p=1 while p<=j: l=j*p print(j,"*",p,"=",l," ",end='') p=p+1 print() j=j-1 ''' for i in range(1, 10): for j in range(1, i+1): print('{}x{}={}\t'.format(j, i, i*j), end='') print() '''
f74da8a6c8708f01c8c80f8ef333373d31d0d605
itroulli/HackerRank
/Tutorials/30_Days_of_Code/001-data_types.py
583
3.875
4
# Name: Day 1: Data Types # Problem: https://www.hackerrank.com/challenges/30-data-types/problem # Score: 30 i = 4 d = 4.0 s = 'HackerRank ' # Declare second integer, double, and String variables. i2, d2, s2 = int(input()), float(input()), input() # Read and save an integer, double, and String to your variables. # Print the sum of both integer variables on a new line. print(i+i2) # Print the sum of the double variables on a new line. print(f"{d+d2:.1f}") # Concatenate and print the String variables on a new line # The 's' variable above should be printed first. print(s+s2)
b0081e1b3e4dee7f98fa35da91c486b6485a1a14
ON1y01/web-code-editor
/files/11.py
324
3.703125
4
#11 print('Задание 11. Напишите программу для ввода шестнадцатеричного числа и вывода его в десятичной системе.') x = input ('Введите число в двоичном формате: ') x = int(x, 16) print('Ответ:', x) input ('')
92265b2f082a5c0878197c007c6983a91127562f
SupraKuning/Project-OKBOSS
/main.py
9,609
3.859375
4
class Pengguna: def __init__(self,level,idPengguna,namaPengguna,password): self.level = level self.idPengguna = idPengguna self.namaPengguna = namaPengguna self.__password = password def info(self): return '''Jabatan = {}\n ID = {}\n Nama = {}'''.format(self.level,self.idPengguna,self.namaPengguna) class Boss(Pengguna): gaji = 7000000 def __init__(self,level,idPengguna,namaPengguna,password): super().__init__('Boss',idPengguna,namaPengguna,password) def info(self): return '''Jabatan = {}\n ID = {}\n Nama = {}\n Gaji = {}'''.format(self.level,self.idPengguna,self.namaPengguna,Boss.gaji) def tambahPengguna(): x = None level = input('Masukkan level : ') idPengguna = int(input('Masukkan ID Pengguna : ')) namaPengguna = input('Masukkan Nama Pengguna : ') password = input('Masukkan Password : ') if level == 'Boss': Boss(level,idPengguna,namaPengguna,password) data.append(x) print('Data Boss {} berhasil ditambahkan'.format(namaPengguna)) elif level == 'Staff': Staff(level,idPengguna,namaPengguna,password) data.append(x) print('Data Staff {} berhasil ditambahkan'.format(namaPengguna)) elif level == 'Pelanggan': Pelanggan(level,idPengguna,namaPengguna,password) data.append(x) print('Data Pelanggan {} berhasil ditambahkan'.format(namaPengguna)) else: print('Unknown') class Staff(Pengguna): gaji = 0 def __init__(self,level,idPengguna,namaPengguna,password): super().__init__('Staff',idPengguna,namaPengguna,password) def info(self): return '''Jabatan = {}\n ID = {}\n Nama = {}\n Gaji = {}'''.format(self.level,self.idPengguna,self.namaPengguna,Staff.gaji) def gajiHarian(): masukShift = input('Masukkan Shift Anda (pagi/malam): ') masukDurasi = int(input('Masukkan Durasi Anda Bekerja : ')) if masukShift == 'Pagi': Staff.gaji = masukDurasi * 100000 print('Gaji anda adalah ',Staff.gaji) elif masukShift == 'Malam': Staff.gaji = masukDurasi * 120000 print('Gaji anda adalah ',Staff.gaji) else: print('unknown') def tambahPengguna(): x = None level = input('Masukkan level : ') idPengguna = int(input('Masukkan ID Pengguna : ')) namaPengguna = input('Masukkan Nama Pengguna : ') password = input('Masukkan Password : ') if level == 'Boss': Boss(level,idPengguna,namaPengguna,password) data.append(x) print('Data Boss {} berhasil ditambahkan'.format(namaPengguna)) elif level == 'Staff': Staff(level,idPengguna,namaPengguna,password) data.append(x) print('Data Staff {} berhasil ditambahkan'.format(namaPengguna)) elif level == 'Pelanggan': Pelanggan(level,idPengguna,namaPengguna,password) data.append(x) print('Data Pelanggan {} berhasil ditambahkan'.format(namaPengguna)) else: print('Unknown') class Pelanggan(Pengguna): def __init__(self,level,idPengguna,namaPengguna,password): super().__init__('Pelanggan',idPengguna,namaPengguna,password) def info(self): return '''ID = {}\n Nama = {}'''.format(self.idPengguna,self.namaPengguna) class Produk: stok = 0 total = 0 def __init__(self,idProduk,namaProduk,kategori,hargaBeli,harga): self.idProduk = idProduk self.namaProduk = namaProduk self.kategori = kategori self.hargaBeli = hargaBeli self.harga = harga def cari(): cari = input('Cari berdasarkan (id/nama) : ') if cari == b1.idProduk or cari == b1.namaProduk: return '''\nID : {}\n Nama : {}\n Kategori : {}\n Harga : {}'''.format(b1.idProduk,b1.namaProduk,b1.kategori,b1.harga) elif cari == b2.idProduk or cari == b2.namaProduk: return '''\nID : {}\n Nama : {}\n Kategori : {}\n Harga : {}'''.format(b2.idProduk,b2.namaProduk,b2.kategori,b2.harga) elif cari == b3.idProduk or cari == b3.namaProduk: return '''\nID : {}\n Nama : {}\n Kategori : {}\n Harga : {}'''.format(b3.idProduk,b3.namaProduk,b3.kategori,b3.harga) elif cari == a1.idProduk or cari == a1.namaProduk: return '''\nID : {}\n Nama : {}\n Kategori : {}\n Harga : {}'''.format(a1.idProduk,a1.namaProduk,a1.kategori,a1.harga) elif cari == a2.idProduk or cari == a2.namaProduk: return '''\nID : {}\n Nama : {}\n Kategori : {}\n Harga : {}'''.format(a2.idProduk,a2.namaProduk,a2.kategori,a2.harga) else: print('Maaf kami tidak menemukan apa yang anda cari') def beli(): barang = input('Mau beli apa? : ') banyak = int(input('Berapa banyak? : ')) if barang == b1.namaProduk: Produk.total = banyak * b1.harga print('''\n\tAnda telah membeli {} sebanyak {} Jumlah yang harus dibayar adalah {}'''.format(b1.namaProduk,banyak,Produk.total)) elif barang == b2.namaProduk: Produk.total = banyak * b2.harga print('''\n\tAnda telah membeli {} sebanyak {} Jumlah yang harus dibayar adalah {}'''.format(b2.namaProduk,banyak,Produk.total)) elif barang == b3.namaProduk: Produk.total = banyak * b3.harga print('''\n\tAnda telah membeli {} sebanyak {} Jumlah yang harus dibayar adalah {}'''.format(b3.namaProduk,banyak,Produk.total)) elif barang == a1.namaProduk: Produk.total = banyak * a1.harga print('''\n\tAnda telah membeli {} sebanyak {} Jumlah yang harus dibayar adalah {}'''.format(a1.namaProduk,banyak,Produk.total)) elif barang == a2.namaProduk: Produk.total = banyak * a2.harga print('''\n\tAnda telah membeli {} sebanyak {} Jumlah yang harus dibayar adalah {}'''.format(a2.namaProduk,banyak,Produk.total)) else: print('Maaf kami tidak menjual barang tersebut') def menu(): while True: print('''~~~~~Selamat Datang~~~~~''') user = input('Masuk sebagai (Boss/Staff/Pelanggan) : ') if user == 'Boss': key = input('Password : ') if key == 'luwakwhitecoffee': print('''Hello Boss !\nSilahkan Pilih Menu :\n 1. Tampilkan info detail Boss\n 2. Menambahkan pengguna\n 3. Logout''') pilih = input('Masukkan angka : ') if pilih == '1': print(boss.info()) elif pilih == '2': Boss.tambahPengguna() elif pilih == '3': print('Terimakasih') break else: print('Angka yang anda masukkan salah') else: print('Anda siapa?') elif user == 'Staff': key = input('Password : ') if key == 'nyamandilambung': print('''Hello Staff !\nSilahkan Pilih Menu :\n 1. Tampilkan info detail Staff\n 2. Menambahkan pengguna\n 3. Menghitung gaji harian\n 4. Logout''') pilih = input('Masukkan angka : ') if pilih == '1': id = int(input('Masukkan ID : ')) if id == 11: print(staff1.info()) elif id == 12: print(staff2.info()) elif pilih == '2': Staff.tambahPengguna() elif pilih == '3': Staff.gajiHarian() elif pilih == '4': print('Terimakasih') break else: print('Angka yang anda masukkan salah') else: print('Anda siapa?') elif user == 'Pelanggan': print('''Hello Stranger !\nSilahkan Pilih Menu :\n 1. Tampilkan info detail Pelanggan\n 2. Cari Produk\n 3. Belanja Produk\n 4. Logout''') pilih = input('Masukkan angka : ') if pilih == '1': print(pelanggan.info()) elif pilih == '2': Produk.cari() elif pilih == '3': Produk.beli() elif pilih == '4': print('Terimakasih\nSilahkan datang kembali') break else: print('Angka yang anda masukkan salah') else: print('Anda Siapa?') data = [] boss = Boss('Boss',0,'Kharisma','kharis88') data.append(boss) staff1 = Staff('Staff',11,'Jamal','jamal13') data.append(staff1) staff2 = Staff('Staff',12,'Panjul','panjul54') data.append(staff2) pelanggan = Pelanggan('Pelanggan',2,'Samsul','samsul20') data.append(pelanggan) b1 = Produk('0','Semen','Bahan',45000,50000) b2 = Produk('1','Paku','Bahan',16000,20000) b3 = Produk('2','Pipa','Bahan',25000,28000) a1 = Produk('3','Sekop','Alat',24000,30000) a2 = Produk('4','Gergaji','Alat',35000,40000) menu()
275a314ef8dc2ee992ae2ed4e5350eca9bdd09b9
PyTayfun/PyLabs
/whileloops/labs.py
206
4.03125
4
''' bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]] i = 0 j = 0 while i<len(bigList): while j<len(bigList[i]): print(“Element of list within a list -”,bigList[i][j]) j=j+1 i=i+1 '''
d4dc09bf385832e44b75ce08f80c65a7a5ccb1e3
jack-alexander-ie/data-structures-algos
/Projects/Project_2/problem_6.py
3,454
3.984375
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) def __eq__(self, other): # Overloaded so raw node values can be compared return self.value == other.value def __hash__(self): # Overloaded so nodes can be hashed for use in set return hash(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head: out_string += str(cur_head.value) + " -> " cur_head = cur_head.next return out_string def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def size(self): size = 0 node = self.head while node: size += 1 node = node.next return size def create_ll_from_set(values: set) -> LinkedList: linked_list = LinkedList() for element in values: linked_list.append(element) return linked_list def collect_ll_vals(head_node) -> set: values = set() node = head_node while node: values.add(node) node = node.next return values def collect_from_lists(list_1: LinkedList, list_2: LinkedList): if type(list_1) != LinkedList or type(list_2) != LinkedList: print('One or more input lists is not a linked list, exiting...') exit() if list_1.head is None or list_2.head is None: print('Warning: One or more lists contain no values') list_1_vals, list_2_vals = collect_ll_vals(list_1.head), collect_ll_vals(list_2.head) return list_1_vals, list_2_vals def union(list_1: LinkedList, list_2: LinkedList) -> LinkedList: vals = collect_from_lists(list_1, list_2) union_list = vals[0].union(vals[1]) return create_ll_from_set(union_list) def intersection(list_1: LinkedList, list_2: LinkedList) -> LinkedList: vals = collect_from_lists(list_1, list_2) intersection_list = vals[0].intersection(vals[1]) return create_ll_from_set(intersection_list) # Test Case 1 - Expected element_1, element_2 = {3, 2, 4, 35, 6, 65, 6, 4, 3, 21}, {6, 32, 4, 9, 6, 1, 11, 21, 1} linked_list_1, linked_list_2 = create_ll_from_set(element_1), create_ll_from_set(element_2) print(union(linked_list_1, linked_list_2)) print(intersection(linked_list_1, linked_list_2)) """ Expected Output: 32 -> 65 -> 2 -> 3 -> 35 -> 4 -> 6 -> 1 -> 9 -> 11 -> 21 -> 4 -> 21 -> 6 -> """ # Test Case 2 - Empty set(s) # element_1, element_2 = set(), set() # linked_list_1, linked_list_2 = create_ll_from_set(element_1), create_ll_from_set(element_2) # print(union(linked_list_1, linked_list_2)) # print(intersection(linked_list_1, linked_list_2)) """ Expected Output: Warning: One or more lists contain no values Warning: One or more lists contain no values """ # Test Case 3 - Incorrect data types # element_1, element_2 = {3, 2, 4, 35, 6, 65, 6, 4, 3, 21}, dict() # linked_list_1, linked_list_2 = create_ll_from_set(element_1), create_ll_from_set(element_2) # print(union(linked_list_1, linked_list_2)) # print(intersection(linked_list_1, linked_list_2)) """ Expected Output: One or more input lists is not a linked list, exiting... """
9c0b596429a76275cef46fe3b82312f7203e80a9
isabella232/vedo-datascience-toolkit
/linearclassification/lib/metrics.py
692
3.546875
4
from collections import defaultdict import logging def implode(x): return ','.join(map(str,x)) """ http://en.wikipedia.org/wiki/Confusion_matrix """ def confusion_matrix(list_of_pairs): freq=defaultdict(int) V=set() for l,r in list_of_pairs: V.add(l) V.add(r) freq[(l,r)]+=1 V=sorted(V) logging.info(implode(["l/r"]+V)) for l in V: logging.info(implode(["%s:" % str(l)]+[freq[(l,r)] for r in V])) agree=0 disagree=0 for l in V: for r in V: if l==r: agree+=freq[(l,r)] else: disagree+=freq[(l,r)] total=agree+disagree logging.info("agree=%i (%f pct); disagree=%i; total=%i",agree,float(agree)/total,disagree,total)
0ccc73c12116d20ba94fbcf4e0ac78390297f0cd
MihirShri/Machine-Learning
/1. Supervised Learning Algorithms/12. SVM/Iris_flower_classification_SVM.py
1,161
3.859375
4
""" Author @ Mihir_Srivastava Dated - 19-05-2020 File - Iris_flower_classification_SVM Aim - To predict the class of the iris flower by training the data set "load_iris" available in sklearn library using the Support Vector Machines (SVM) algorithm. """ # import necessary libraries import pandas as pd from sklearn.model_selection import train_test_split from sklearn import svm from sklearn.datasets import load_iris # Create load_iris object iris = load_iris() # Convert it into a DataFrame for better visualization df = pd.DataFrame(iris.data, columns=iris.feature_names) # Add some more details for better understandability df['target'] = iris.target df['target_names'] = df.target.apply(lambda x: iris.target_names[x]) # Create svm model model = svm.SVC() # Define features and labels X = df.drop(['target', 'target_names'], axis=1) y = iris.target # Split the data into training and testing set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Train the model model.fit(X_train, y_train) # Find accuracy accuracy = model.score(X_test, y_test) print("accuracy: " + str(accuracy))
389f74570b9caaa488475e4523f6e0d43bad8b61
hyang012/leetcode-algorithms-questions
/141. Linked List Cycle/Linked_List_Cycle.py
1,027
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Leetcode 141. Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def printLinkedList(l): res = '' if l is None: return 'Input is None' while l.next is not None: res = res + str(l.val) + '->' l = l.next res += str(l.val) return res def createLinkedList(nums): res = cur = ListNode(nums[0]) for num in nums[1:]: cur.next = ListNode(num) cur = cur.next return res def hasCycle(head): """ :type head: ListNode :rtype: bool """ if not head: return False slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False
dc4b94efb7f01f104d11fec0c275e26b9c71f4dc
RadkaValkova/SoftUni-Web-Developer
/Programming Fundamentals Python/11 Lists Basics Exercise/Hello France.py
1,350
3.609375
4
item = input().split('|') budget = float(input()) total_profit = 0 turnover = 0 new_prices = [] for i in range(len(item)): element = item[i].split('->') current_item = element[0] price = float(element[1]) new_price = 0 profit = 0 if current_item == 'Clothes': if price <= 50 and price <= budget: budget -= price new_price = float(price * 1.4) profit += new_price - price total_profit += profit new_prices.append(new_price) else: continue elif current_item == 'Shoes': if price <= 35 and price <= budget: budget -= price new_price = float(price * 1.4) profit += new_price - price total_profit += profit new_prices.append(new_price) else: continue else: if price <= 20.50 and price <= budget: budget -= price new_price = float(price * 1.4) profit += new_price - price total_profit += profit new_prices.append(new_price) else: continue for i in range(len(new_prices)): print(f'{new_prices[i]:.2f}', end=' ') print() print(f'Profit: {total_profit:.2f}') if sum(new_prices) + budget >= 150: print('Hello, France!') else: print('Time to go.')
f9ee0b2264a31fab7a75de41d52cdefb30d635f2
rhythm-sharma/leetcode-solutions-python
/9-Palindrome-Number.py
1,134
3.59375
4
import math import unittest class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ max_int = 2147483647 if x < 0 or x > max_int: return False if x < 10: return True base = 10 ** int(math.log(x, 10)) while base > 0: if x / base == x % 10: x = x % base / 10 base /= 100 else: return False return True class TestSolution(unittest.TestCase): def setUp(self): self.solution = Solution() def tearDown(self): pass def testIsPalindrome(self): self.assertEqual(self.solution.isPalindrome(121), True) self.assertEqual(self.solution.isPalindrome(-121), False) self.assertEqual(self.solution.isPalindrome(-77), False) self.assertEqual(self.solution.isPalindrome(76), False) self.assertEqual(self.solution.isPalindrome(0), True) self.assertEqual(self.solution.isPalindrome(-2147447412), False) if __name__ == "__main__": # unittest.main() pass
74bbed6c834d278d0f90f7cf56b99d8839fc3bf1
gleberof/PyBites
/53/text2cols.py
692
3.921875
4
COL_WIDTH = 20 def text_to_columns(text): """Split text (input arg) to columns, the amount of double newlines (\n\n) in text determines the amount of columns. Return a string with the column output like: line1\nline2\nline3\n ... etc ... See also the tests for more info.""" parts = text.split('\n\n') result = '' while any(len(part) > 0 for part in parts): idx = [(part+' ').rfind(' ', 0, COL_WIDTH+1) for part in parts] result += ' '.join([f'{part[:ind].strip():{COL_WIDTH}}' for ind, part in zip(idx, parts)]) + '\n' parts = [part[ind+1:] for ind, part in zip(idx, parts)] return result
c3db05aa136da1a124d665a887ba8f44f8e7e42f
SoyabulIslamLincoln/Home-Practice
/Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.py
591
4.125
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> #Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum >>> x=int(input("enter one number: ")) enter one number: 56 >>> y=int(input("Enter anothernumber : ")) Enter anothernumber : 45 >>> z=int(input("Enter third number : ")) Enter third number : 56 >>> if x==y and y==z and x==z: m=3*(x+y+z) print(m) else: n=x+y+z print(n) 157 >>>
236e133493f3e6227d30d5d22d3eb5f5b47e5465
akritskiy/coursera-dsa
/ds/is_bst.py
2,128
4
4
# python3 ''' Test whether a binary search tree (BST) data structure was implemented correctly. The requirement for a valid BST is: for any node of the tree with key x, any node key in its left subtree must be less than x, and any node key in its right subtree must be greater than x. Input: an integer n, the number of nodes, followed by n lines of three integers each: key (value of the node), and r and l, the 0-based indices of the left and right child. The 0th node is the root. Desired output: CORRECT if the tree is a valid BST, INCORRECT otherwise. For example: Input: 3 2 1 2 1 -1 -1 3 -1 -1 Output: CORRECT This describes the tree: ____2 __1___3 Input: 4 4 1 -1 2 2 3 1 -1 -1 5 -1 -1 Output: INCORRECT The input describes the tree: ________4 ____2 __1___5 5 is in the left subtree of 4, which is incorrect. If we searched for 5 in a valid BST with root 4, we would expect 5 to be in the right subtree. The strategy used here was to use the in-order traversal method from the tree traversals problem. An in-order traversal of a valid BST will output the keys in ascending order. If we find a key such that previous key > current key, we know the BST is incorrect. The feedback for this solution was: Good job! (Max time used: 0.57/10.00, max memory used: 21647360/536870912.) ''' import math class IsBST: def __init__(self): self.n = 0 def initArrays(self): self.keys = [0] * self.n self.l = [0] * self.n self.r = [0] * self.n def read(self): self.n = int(input()) if self.n not in (0, 1): self.initArrays() for i in range(self.n): self.keys[i], self.l[i], self.r[i] = [int(x) for x in input().split()] def checkBST(self): if self.n in (0, 1): return 'CORRECT' i = 0 # current node index stack = [] previous_key = -math.inf while True: if i != -1: stack.append(i) i = self.l[i] elif stack: i = stack.pop() if previous_key > self.keys[i]: return 'INCORRECT' previous_key = self.keys[i] i = self.r[i] else: break return 'CORRECT' if __name__ == '__main__': my_bst = IsBST() my_bst.read() print(my_bst.checkBST())
fcdb587700da43961de95186fdf1d4f81e35fbb5
justinminsk/Python_Files
/Intro_To_Python/HW11/make_list.py
541
3.59375
4
def make_list(readfile): hold_list = [] # set up our lists main_list = [] with open(readfile, 'r') as file: # read out file for line in file: # read each line line = line.strip() # strip each line hold_list = line.split() # create a list for each line main_list.insert(len(main_list), hold_list) # add the list to the main list print(main_list) # show the outcome return main_list if __name__ == '__main__': # Run the rewrite make_list('alkaline_metals.txt')
712314068fb6a7b01bf1e9a421c08e162b7ab3ff
stackwonderflow/LeetCode
/Problems/numIdenticalPairs.py
480
3.5
4
def numIdenticalPairs(nums): count = 0 pairs = {} for i in nums: if i not in pairs: pairs[i] = 0 else: pairs[i] += 1 for i, j in pairs.items(): count += (j + 1) * j / 2 return int(count) numIdenticalPairs([1,2,3,1,1,3]) # Runtime: 56 ms, faster than 6.27% of Python3 online submissions for Number of Good Pairs. # Memory Usage: 14.3 MB, less than 10.64% of Python3 online submissions for Number of Good Pairs.
a5bd20d6cad300e806ced849e9a7083b5bd74bfa
jshin07/Python
/Scores_and_Grades.py
616
4.0625
4
# Scores and Grades import random def scoreToGrade (repeat): print "Scores and Grades" for i in range(0, repeat): score = random.randint(60,101) if score >=60 and score <=69: print "Score: ", score,"; Your grade is D" elif score >= 70 and score <= 79: print "Score: ", score, "; Your grade is C" elif score >= 80 and score <= 89: print "Score: ", score, "; Your grade is B" elif score >= 90 and score <= 100: print "Score: ", score, "; Your grade is A" else: print "You failed" scoreToGrade(10)
2b85074709c0cc85212b5f1628c063f1abd3f76d
alonana/top
/python/2019/elly_three_primes.py
3,441
3.890625
4
from python.test_utils import test_solution, assert_equals, get_ints DIGITS = 5 primes_numbers = None primes_digits = None index = None sums = None def find_primes_numbers(): global primes_numbers if primes_numbers is not None: return limit = 10 ** DIGITS n = [True] * limit for i in range(2, limit // 2): if n[i]: multiplier = 2 * i while multiplier < limit: n[multiplier] = False multiplier += i primes_numbers = [] for i in range(limit // 10, limit): if n[i]: primes_numbers.append(i) print(primes_numbers) def find_primes_digits(): global primes_digits if primes_digits is not None: return primes_digits = [] for prime in primes_numbers: prime_str = str(prime) t = [] for d in range(0, DIGITS): digit = int(prime_str[d]) t.insert(0, digit) primes_digits.append(t) print(primes_digits) def index_primes(): global index if index is not None: return index = [] for d in range(DIGITS): digits = [] for i in range(10): digits.append([]) index.append(digits) for i, prime in enumerate(primes_digits): for d in range(DIGITS): index[d][prime[d]].append(i) print(index) return index def recursive_find(digit_index, possible_first, possible_second, possible_third): if len(possible_first) == 0 or len(possible_second) == 0 or len(possible_third) == 0: return None if digit_index == len(sums): return possible_first, possible_second, possible_third digit_sum = sums[digit_index] for first_digit in range(0, min(digit_sum + 1, 10)): for second_digit in range(0, min(digit_sum + 1 - first_digit, 10)): third_digit = digit_sum - first_digit - second_digit if third_digit > 9: continue first_options = index[digit_index][first_digit] possible_first_next = [v for v in possible_first if v in first_options] second_options = index[digit_index][second_digit] possible_second_next = [v for v in possible_second if v in second_options] third_options = index[digit_index][third_digit] possible_third_next = [v for v in possible_third if v in third_options] result = recursive_find(digit_index + 1, possible_first_next, possible_second_next, possible_third_next) if result is not None: return result return None def get_primes(sums_input): global sums sums = sums_input find_primes_numbers() find_primes_digits() index_primes() possible_first = [i for i in range(len(primes_digits))] possible_second = [i for i in range(len(primes_digits))] possible_third = [i for i in range(len(primes_digits))] result = recursive_find(0, possible_first, possible_second, possible_third) print(result) if result is None: return [] result = [primes_numbers[result[0][0]], primes_numbers[result[1][0]], primes_numbers[result[2][0]]] print(result) return result def run_line(match): sums = get_ints(match.group(1)) expected = get_ints(match.group(2)) actual = get_primes(sums) assert_equals(len(actual), len(expected)) test_solution(__file__, '{(.*)}\\s+{(.*)}', run_line)