blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
aef193e69c925483ca035a17485800439a593157
jiangjinshi/1807
/13day/学生系统.py
448
3.796875
4
a = [] while True: print("欢迎来到学生系统") print("1:添加学生信息") print("2:查找学生信息") print("3:修改学生信息") print("4:删除学生信息") print("5:退出学生系统") i = int(input("请输入序号:")) if i == 1: name = input("请输入姓名") age = input("请输入年龄") sex = input("请输入性别") d = {} d["name"] = name d["age"] = age d["sex"] = sex a.append(d) print(a)
5510b33e93e7bd0c27694933ebab2e80819cbf72
shibing624/python-tutorial
/06_tool/re_demo.py
437
3.515625
4
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: 正则表达式示例 """ import re a = "物流太糟糕了,申通{服务恶劣啊,自己去取的" for i in re.finditer(',', a): print(i.group(), i.span()[1]) s = '{通配符}你好,今天开学了{通配符},你好' print("s", s) a1 = re.compile(r'\{.*?\}') d = a1.sub('', s) print("d", d) a1 = re.compile(r'\{[^}]*\}') d = a1.sub('', s) print("d", d)
2f28196f0a6b12348cc3e9af4d6b1916d035e05a
sanketdofe/pythonlabwork
/fibonacci.py
182
3.875
4
n=int(input("Enter the length of sequence:")) list1 = [] a = 0 list1.append(a) b=1 list1.append(b) for i in range(2,n): j=list1[i-1]+list1[i-2] list1.append(j) print(list1)
721c1b5e13917b43a6d2110425d768b7cc113e25
pr4nshul/CFC-Python-DSA
/Siddhant/q4.py
480
3.609375
4
def Anargams(lists): result = [] for string in lists: freq = {} for item in string: freq[item] = freq.get(item, 0) + 1 result.append(freq) ans = [] for i in range(len(result) // 2): for j in range(i + 1, len(result)): if result[i] == result[j]: ans.append([i + 1,j + 1]) return ans # lists = ["cat", "dog", "god", "tca"] lists = [item for item in input().split()] print(Anargams(lists))
d0149daa8a12ab0a9de316166a4539f7b28f874b
jeangiraldo/Python-Curso
/excepciones python.py
433
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 29 12:49:17 2020 @author: CEC """ try: print("1") x=1/0 print("2") except: print("Oh dear, something went wrong...") print("3") try: x=int(input("Enter a number")) y=1/x print(y) except ZeroDivisionError: print("You must enter an integer value.") except: print("oh dear, something went wrong...") print("THE END.")
8a9acc007b1d766c50a48464617cc0c8f033f307
MACHEIKH/Datacamp_Machine_Learning_For_Everyone
/21_Introduction_to_Deep_Learning_with_Keras/1_Introducing_Keras/helloNets.py
1,198
4.3125
4
# Hello nets! # You're going to build a simple neural network to get a feeling of how quickly it is to accomplish this in Keras. # You will build a network that takes two numbers as an input, passes them through a hidden layer of 10 neurons, and finally outputs a single non-constrained number. # A non-constrained output can be obtained by avoiding setting an activation function in the output layer. This is useful for problems like regression, when we want our output to be able to take any non-constrained value. # Instructions # 100 XP # Import the Sequential model from keras.models and the Denselayer from keras.layers. # Create an instance of the Sequential model. # Add a 10-neuron hidden Dense layer with an input_shape of two neurons. # Add a final 1-neuron output layer and summarize your model with summary(). # Import the Sequential model and Dense layer from keras.models import Sequential from keras.layers import Dense # Create a Sequential model model = Sequential() # Add an input layer and a hidden layer with 10 neurons model.add(Dense(10, input_shape=(2,), activation="relu")) # Add a 1-neuron output layer model.add(Dense(1)) # Summarise your model model.summary()
34a07326e375ed006620ed4b1aca6ee683885546
pamnesham/magic8Ball
/magicBall8.py
293
3.859375
4
import random answers = ['Yes', 'Very probably', 'Should not get your hopes up.', 'No', 'Eh, unlikely', 'Would not bet on it.'] print('Think of a question and then press enter.') input() print(answers[random.randint(0, len(answers)-1)])
bdd8fb2f247bc1c9fa0754f5b6393fc97a33fd28
Adlaneb10/Python
/Lab6/q6.py
314
4.21875
4
# Ask the user to enter a number and print it back on the screen. # Keep asking for a new number until they enter a negative number num = 0 while(num > -1): num = int(input("Enter a negative number ")) print("You entered ",num) if num < 0: print("Thank you") break
8477c5ab45f0f1cf9dfcfb09f18892575083361a
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 86 - ReverseLLII.py
1,370
4.0625
4
# Reverse Linked List II # Question: Reverse a linked list from position m to n. Do it in-place and in one-pass. # For example: # Given 1->2->3->4->5->NULL, m = 2 and n = 4, # Return 1->4->3->2->5->NULL. # Note: Given m, n satisfy the following condition: # 1 ≤ m ≤ n ≤ length of list. # Solutions: class ListNode(object): def __init__(self, x): self.val = x self.next = None def to_list(self): return [self.val] + self.next.to_list() if self.next else [self.val] class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head node = dummy for __ in range(m - 1): node = node.next prev = node.next curr = prev.next for __ in range(n - m): next = curr.next curr.next = prev prev = curr curr = next node.next.next = curr node.next = prev return dummy.next if __name__ == "__main__": n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 r = Solution().reverseBetween(n1, 2, 4) print ( r.to_list() )
12e1cb5334565b3e15ad395c88e34a44d9a70cda
saywordsahn/DataScience1
/CA Housing Model/2.stratify.py
1,255
3.546875
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np pd.set_option('display.max_row', 1000) pd.set_option('display.max_columns', 50) data = pd.read_csv('housing.csv') # split into training and test data sets from sklearn.model_selection import train_test_split train_set, test_set = train_test_split(data, test_size=0.2, random_state=42) ########################### # let's stratify by income ########################### # create bucket with the pandas cut function data['income_cat'] = pd.cut(data['median_income'], bins=[0., 1.5, 3.0, 4.5, 6., np.inf], labels=[1, 2, 3, 4, 5]) # show the hist of the bucketed field data['income_cat'].hist() plt.show() from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) for train_index, test_index in split.split(data, data['income_cat']): strat_train_set = data.loc[train_index] strat_test_set = data.loc[test_index] # test stratified sample (can similarly check full data bucket and unstratified) strat_test_set['income_cat'].value_counts() / len(strat_test_set) # drop income_cat from training sets for set_ in (strat_train_set, strat_test_set): set_.drop('income_cat', axis=1, inplace=True)
eae84ef179c725c044fc79ba78b08820d6e14597
jeffreytzeng/HackerRank
/Python/02. Basic Data Types/03. Nested Lists/grades.py
441
3.65625
4
from operator import itemgetter n = int(input()) students = sorted([[input(), float(input())] for i in range(n)], key=itemgetter(1)) lowest = min(students, key = lambda grade: grade[1]) second_low = min(filter(lambda grade: grade[1] != lowest[1], students), key = lambda grade: grade[1]) names = list(filter(lambda grade: grade[1] == second_low[1], students)) names.sort(key = lambda grade: grade[0]) for name in names: print(name[0])
1020fa3bba3aa0397b62c93f2caa171bacb1ee71
Ignotus111/labyrinth
/classes/position.py
1,129
4.1875
4
class Position: """Class that handles position on the grid""" def __init__(self, x, y): self.position = (x, y) def __repr__(self): """Return a position object in string""" return str(self.position) def __hash__(self): """Give a hash for each created object""" return hash(self.position) def __eq__(self, pos): """What happens when we try to compare 2 position object""" return self.position == pos.position @property def up(self): """When this method is called, return postion -1 on x""" x, y = self.position return Position(x-1, y) @property def down(self): """When this method is called, return postion +1 on x""" x, y = self.position return Position(x+1, y) @property def left(self): """When this method is called, return postion -1 on y""" x, y = self.position return Position(x, y-1) @property def right(self): """When this method is called, return postion +1 on y""" x, y = self.position return Position(x, y+1)
81c40d90180f84416242f3e01154fe02e94c06ac
aitorlb/Udacity-Free-Courses
/Intro to Computer Science/Lesson_5_How_Programs_Run/19-Better_Hash_Functions/supplied/studentMain.py
620
4.15625
4
# Define a function, hash_string, # that takes as inputs a keyword # (string) and a number of buckets, # and returns a number representing # the bucket for that keyword. # https://discussions.udacity.com/t/challenging-the-professor-testing-times-need-your-help-to-analyze-this-fun-discovery/121419 def hash_string(keyword, buckets): hash = 0 for char in keyword: hash += ord(char) return hash % buckets print(hash_string('a', 12)) # >>> 1 print(hash_string('b', 12)) # >>> 2 print(hash_string('a', 13)) # >>> 6 print(hash_string('au', 12)) # >>> 10 print(hash_string('udacity', 12)) # >>> 11
e01a1e8bc03b3dedaeb37a36ea645a39593b3662
victormasayesva/Project-One
/hangman/python/Functions/debugFunctionDrillsV1.py
2,718
4.09375
4
''' The following functions have problems that keep them from completing the task that they have to do. All the problems are either Logical or Syntactical errors with FUNCTIONS. Focus on the functions and find the problems with the FUNCTIONS. For this debug, there could be problems with executing the functions. For example, calling the function may have been done wrong, or put in the wrong spot. So don't just look at the function itself but also the line calling the function. Additionally, if converting becomes difficult, ask the instructor about how to use a conversion table or other tricks to help make sure the conversion is right. The number of errors are as follows: ouncesToGallons: 4 gallonsToOunces: 6 gramsToPounds: 4 poundsToGrams: 4 ''' #The problems are between the two --- lines #------------------------------------------------- ouncesToGallons(24) ''' This function converts ounces to gallons using three steps. ''' def ouncesToGallons(ounces): #There are eight ounces in a cup cups = ounces / 8 #There are four cups in a quart quarts = cups / 4 #There are four quarts in a gallon gallons = quarts / 4 return gallons ouncesToGallons(24) #------------------------------------------------ #The problems are between the two --- lines #------------------------------------------------- ''' This function converts gallons to ounces using three steps. ''' def gallonsToOunces(gallons): #There are four quarts in a gallon quarts = gallons + 4 #There are four cups in a quart cups = quarts - 4 #There are 8 ounces in a cup ounces = cups + 8 return ounces gallonToOunces(24) gallonToOunces(4) #------------------------------------------------ #The problems are between the two --- lines #------------------------------------------------- ''' This function converts grams to pounds using two steps. ''' def gramsToPounds (grams): #There are 16 ounces in one pound pounds = ounces / 16 #There are .035 ounces in a gram ounces = grams * .035 return pounds gramsToPounds() gramsToPounds(360) #------------------------------------------------ #The problems are between the two --- lines #------------------------------------------------- ''' This function converts pounds to grams using two steps. ''' def poundsToGrams(pounds): #There are 16 ounces in one pound ounces = pounds * 16 #There are .035 ounces in a gram grams = ounces / .035 return grams poundsToGrams() poundsToGrams 360) #------------------------------------------------
99c9891b0a4e0dd886a353329e7dfd6ca852289f
rvsp/cbse
/9_python.py
456
3.875
4
# 9) Write a recursive code to display and calculate the sum of Geometric # progression . a, ar, ar2 , ar3 , ar4 Up to n terms # function to calculate sum of geometric series def sumOfGP(a, r, n) : sum = 0 i = 0 while i < n : sum = sum + a a = a * r i = i + 1 return sum a = 1 # first term r = (float)(1/2.0) # common ratio n = 10 # number of terms print("value is : %.5f" %sumOfGP(a, r, n)),
465d816600d73bf9c1b478fe6f1cce75446ca5a0
SujeethJinesh/Computational-Physics-Python
/In Class/in_class.py
374
3.890625
4
def in_class(): t = float(input("Please input the time: ")) height = float(input("Please input the height: ")) g = 9.8 #m/s^2 distance = (1/2.0)*g*t**2.0 #m height_above_ground = height - distance #m if height_above_ground <= 0: print ("The ball hit the ground") else: print("The height of the ball is ", height_above_ground, "meters")
559461103eb714962dfb97c97d38132b17ec0976
caliuf/hacker_rank
/code_flows_r1/getMaximumOutfits.py
2,114
3.90625
4
#!/bin/python3 # -*- coding: utf-8 -*- """ Points: 50 Result: 3/8 Time: 13m+30m Note: I can't manage to understand how to make the last 5 tests pass. Maybe I don't well understand the specs, I tried: - Go ahead until it find an outfit it can't buy, then exit - [My final choice] Go ahead until money is over or the list is over, skipping outfits too expensive for the current budget - Sort all outfits by price ascending, than go ahead buying until money is over (a true getMaximumOutfits function) """ import math import os import random import re import sys DEBUG = False SORT = True # # Complete the 'getMaximumOutfits' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY outfits # 2. INTEGER money # # def getMaximumOutfits(outfits, money): # for i,o in enumerate(outfits): # print("%(money)s - %(o)s"%vars()) # if o > money: # return i # money -= o # # return len(outfits) def getMaximumOutfits(outfits, money): if SORT: outfits.sort() bought = 0 for i, o in enumerate(outfits): if money <= 0: return bought if money >= o: if DEBUG: print("%(money)s - %(o)s (BOUGHT!)" % vars()) bought += 1 money -= o else: if DEBUG: print("%(money)s - %(o)s" % vars()) return bought def test(): global DEBUG DEBUG = True print(">>>> %s <<<<" % getMaximumOutfits( [1,5,5,2,2,2,1,1,1], 10 )) print(">>>> %s <<<<" % getMaximumOutfits( [1, 5, 5, 2, 2, 2, 1, 1, 1], 1 )) # print(">>>> %s <<<<" % getMaximumOutfits( # [10,10,10], # 5 # )) print(">>>> %s <<<<" % getMaximumOutfits( [], 10 )) def main(): fptr = None if ('OUTPUT_PATH' in os.environ): fptr = open(os.environ['OUTPUT_PATH'], 'w') else: fptr = sys.stdout outfits_count = int(input().strip()) outfits = [] for _ in range(outfits_count): outfits_item = int(input().strip()) outfits.append(outfits_item) money = int(input().strip()) result = getMaximumOutfits(outfits, money) fptr.write(str(result) + '\n') fptr.close() if __name__ == '__main__': #test() main()
1ccf6856f9756f22743094806b0b1a32478989a5
felipesergios/Python
/039.py
495
4.0625
4
from datetime import date atual = date.today().year nascimento = int(input('Ano de Nascimento:')) idade = atual-nascimento print('Quem nasceu no ano de {} tem {} anos de Idade '.format(atual,idade)) if idade==18: print('Voce Precisa se Alistar!!') elif idade>18: saldo=idade-18 print('Voce Precisa Ir A Junta Urgentemente\n Voce Passou {} anos do seu alistamento'.format(saldo)) elif idade<18: saldo = 18-idade print('Ainda Faltam {} anos para Seu Alistamento'.format(saldo))
ada0dcc3257266e28f37253861992bab4b3ea1c8
yingCMU/tensor_flow
/kalman_filters/trigonometry.py
1,601
4.6875
5
# Python's math module has functions called sin, cos, and tan # as well as the constant "pi" (which we will find useful shortly) from math import sin, cos, tan, pi # Run this cell. What do you expect the output to be? print(sin(60)) from math import pi def deg2rad(theta): """Converts degrees to radians""" # TODO - implement this function (solution # code at end of notebook) return theta * pi / 180 assert(deg2rad(45.0) == pi / 4) assert(deg2rad(90.0) == pi / 2) print("Nice work! Your degrees to radians function works!") for theta in [0, 30, 45, 60, 90]: theta_rad = deg2rad(theta) sin_theta = sin(theta_rad) print("sin(", theta, "degrees) =", sin_theta) import numpy as np from matplotlib import pyplot as plt def plot_sine(min_theta, max_theta): """ Generates a plot of sin(theta) between min_theta and max_theta (both of which are specified in degrees). """ angles_degrees = np.linspace(min_theta, max_theta) angles_radians = deg2rad(angles_degrees) values = np.sin(angles_radians) X = angles_degrees Y = values plt.plot(X,Y) plt.show() # EXERCISE 2.1 Implement this! Try not to look at the # implementation of plot_sine TOO much... def plot_cosine(min_theta, max_theta): """ Generates a plot of sin(theta) between min_theta and max_theta (both of which are specified in degrees). """ angles_degrees = np.linspace(min_theta, max_theta) angles_radians = deg2rad(angles_degrees) values = np.cos(angles_radians) X = angles_degrees Y = values plt.plot(X,Y) plt.show()
8e748c411118a132508c57ccaf68d304f0798d92
BenThomas33/practice
/interviews/csvparser.py
1,486
3.5
4
import unittest class Solution: def add_cell_to_row(self, cell, row): row.append(''.join(cell).strip()) del cell[:] def add_row_to_result(self, cell, row, result): self.add_cell_to_row(cell, row) result.append(list(row)) del row[:] def parse(self, s): row, result, cell = [], [], [] in_quote, after_slash = False, False for i in s: if i == ',' and not in_quote and not after_slash: self.add_cell_to_row(cell, row) elif i == '"' and not after_slash: in_quote = (not in_quote) elif i == '\\' and not after_slash and in_quote: after_slash = True # slash for escape elif i == '\n': self.add_row_to_result(cell, row, result) else: after_slash = False cell.append(i) self.add_row_to_result(cell, row, result) return result class Test(unittest.TestCase): def test(self): s = Solution() self.assertEqual(s.parse('123, jason, "hello world"'), [['123', 'jason', 'hello world']]) self.assertEqual(s.parse(r'''123, jason, "hello world" 124, mike, "nihao shijie" 125, mike\, "\"nihao shijie\\"'''), [['123', 'jason', 'hello world'], ['124', 'mike', 'nihao shijie'], ['125', 'mike\\', '"nihao shijie\\']]) if __name__ == '__main__': unittest.main()
c08f83a83e7ce83cb69275d3c02c30782ae5f94d
ironsubhajit/india_map_pattern
/app.py
780
3.546875
4
# Python3 program to print india map pattern # code by ironsubhajit a = 0 b = 0 c = 10 s = ("TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs" " UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPe" "HBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFA" "gcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm S" "On TNn ULo0ULo#ULo-WHq!WFs XDt!") # Read each character of encoded string a = ord(s[b]) while a != 0: if b < 170: a = ord(s[b]) b += 1 while a > 64: a -= 1 c += 1 if c == 90: c = 10 print(end=chr(c)) # 10 = \n else: if b % 2 == 0: print(chr(33), end='') # 33 = ! and 32 = ' ' else: print(chr(32), end='') else: break
26908a07581f0ad329293d6cf3a841ccb52a887e
dougmcnally/school-projects
/ProteinFolding/smart_protein_folding.py
15,027
3.640625
4
# Computational Physics Final Project # Protein Folding # - Optimized for faster runtime # author Doug McNally ### IMPORTANT ### # Running this program in IDLE may cause catastrophic failure when testing the plot_dynamic_temp() # function. Run this program manually from a directory, i.e. double click on the file icon when # testing this function. This is because of multiprocessing implemented to speed up results! import numpy import random import math import pylab class AminoAcid: """ A class to modle AminoAcid objects which stores thier type (represented by a number 1-20), there position in the chain, and any neighboring amino acids in the chain. """ def __init__(self, kind, loc, left=None, right=None): self.kind, self.loc, self.left, self.right = kind, loc, left, right def __repr__(self): return str(self.kind) + ' at ' + str(self.loc) def __str__(self): return self.__repr__() def display_protein(protein): """ Shows a quasi-graphical representation of the protein. Note that it is displayed such that the location of the protein is printed, not the type and therefore the covalent bonding can be discerned by the sequential numbering scheme - that is amino acids with number n are bonded to those with number n-1 and n+1 and this can be followed throughout the protein. """ data, space, e = protein['data'], protein['space'], protein['e'] for i, aa in enumerate(data): print str(i) + ': ' + str(aa) for r, rows in enumerate(space): for c, aa in enumerate(rows): if aa: index = data.index(aa) pad = (index < 10 and ' ') or '' print '[' + pad + str(index) + ']', else: print '[ ]', def init(num): """ Setup the initial structure of the protein. This is done linearly along the horizontal axis of the grid. """ data = [] space = [[None for i in range(num)] for i in range(num)] for i in range(num): aa = AminoAcid(random.randint(1, 20), (0, i)) data.append(aa) space[0][i] = aa # fill in the amino acids randomly (1-20, where # the number represents which type of amino acid) for i in range(num): if i: data[i].left = data[i-1] if num-1-i: data[i].right = data[i+1] return {'data':data, 'e':0, 'space':space} def init_SAW(num, energies): """ Create the initial structure of the protein by way of a Self Avoiding Random Walk (SAW). This is suggested on page 395 of Computational Physics. Please note that for an input value of num greater than ~ 20 will almost certainly not work at short times (or at all) because of the nature of this algorithm! """ count = 1 bounds = num while count: loc = 0, 0 num = bounds - 1 space = [[None for i in range(bounds)] for i in range(bounds)] space[0][0] = aa = AminoAcid(random.randint(1, 20), loc) data = [aa] while num: num -= 1 neighbors = nearest_neighbors(bounds, loc, adjacent = True) nr, nc = loc = neighbors[random.randint(0, len(neighbors) - 1)] if space[nr][nc]: break space[nr][nc] = bb = AminoAcid(random.randint(1, 20), loc) aa.right, bb.left = bb, aa aa, bb = bb, aa data.append(aa) if not num: return {'data':data, 'e':calc_energy(data, energies), 'space':space} def attraction_energy(): """ Generate some hypothetical attraction energies between any two amino acids. Therefore this must be a 20x20 matrix whose entries correspond to the attraction energy between the i-th and j-th amino acids. Make this 21x21 to avoid 0 indexing. """ energies = list() for i in range(21): energies.append(list()) for j in range(21): energies[i].append(-2 * (random.random() + 1)) # now make the matrix symmetric, because the i,j entry should # equal the j,i entry for i in range(len(energies)): for j in range(len(energies[i])): energies[i][j] = energies[j][i] return energies detached = lambda a,b: a not in (b.left, b.right) def calc_spot(protein, aa, energies): """ In order to avoid the repeated calculation of the energy of the entire protein only the change in energy for a small selected region is considered because the rest should remain constant under such a so called "micro-step" structural transition. This is one of several streamlined improvements to decrease run time on the method suggested in Computational Physics (pg. 394 - 404). """ new_e = 0 r, c = aa.loc data, space = protein['data'], protein['space'] for nr, nc in nearest_neighbors(len(data), aa.loc, adjacent=True): bb = space[nr][nc] if bb and still_bonded(aa.loc, bb.loc) and detached(aa, bb): new_e += energies[aa.kind][bb.kind] return new_e def calc_energy(aas, energies): """ Calculates the current energy of the protein given the current spatial configuration (aas) and the attraction energies between amino acids of differen types (energies) """ energy = 0 for i in range(len(aas)): for j in range(i + 1, len(aas)): a, b = aas[i].loc, aas[j].loc if (still_bonded(a, b) and detached(aas[i], aas[j])): energy += energies[aas[i].kind][aas[j].kind] return energy def fold_protein(protein, energies, T): """ Choose a random protein and move it to a nearest neighbor site if available and the energy change is negative. If energy change is positive, only allow if the Boltzmann factor is greater than a random number in [0,1). """ data, space = protein['data'], protein['space'] index = random.randint(0, len(data) -1) rndAA = data[index] # consider where the amino acid can move pot = nearest_neighbors(len(data), rndAA.loc) # now there is a list of places this amino acid # could theoretically move. Must now choose 1 of these # check if it breaks a covalent bond, and then see if it # will occur new_r, new_c = new_spot = pot[random.randint(0, len(pot)-1)] # tuple of the new location if space[new_r][new_c]: return False if rndAA.left and not still_bonded(new_spot, rndAA.left.loc): return False elif rndAA.right and not still_bonded(new_spot, rndAA.right.loc): return False old_e = calc_spot(protein, rndAA, energies) old_r, old_c = rndAA.loc space[old_r][old_c], space[new_r][new_c] = None, rndAA rndAA.loc = new_spot # left and right neightbors and type remain the same new_e = calc_spot(protein, rndAA, energies) dE = new_e - old_e if (dE < 0) or (math.exp(-dE/T) > random.random()): protein['e'] += dE return True else: rndAA.loc = old_r, old_c space[old_r][old_c], space[new_r][new_c] = rndAA, None return False def nearest_neighbors(bounds, loc, adjacent=False): """ Determine all possible "nearest neighbor" locations on a square grid given a location (tuple) by adding unit movements in each of 8 possible directions and then see if they are allowed. Only consider locations 1 unit away if "adjacent" is True. """ unit_mov = (-1,-1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1) if adjacent: unit_mov = (-1, 0), (0, 1), (1, 0), (0, -1) result = list() for r, c in unit_mov: nr, nc = loc[0] + r, loc[1] + c if nr >= 0 and nc >= 0 and nr < bounds and nc < bounds: result.append((nr, nc)) return result def still_bonded(loc1, loc2): """ Check if two amino acids (loc1 and loc2 are tuples) are still bonded. If not, this will return a number larger than 1 (F). Iff the bond still exists, T will be returned. """ return abs(loc1[0] - loc2[0]) + abs(loc1[1] - loc2[1]) == 1 def progress_report(progress_step): """ Give the current progress of the program as a percentage. """ progress_report.progress = 0 def _(new): if new - progress_report.progress >= progress_step: progress_report.progress = new print "Progress", str(progress_report.progress) + "%..." return new return _ def copy(protein): """ Create a deep copy of an amino acid list (i.e. protein). """ num = len(protein['data']) data, space = [], [[None for i in range(num)] for i in range(num)] for i, aa in enumerate(protein['data']): r, c = aa.loc bb = AminoAcid(aa.kind, aa.loc) space[r][c] = bb data.append(bb) if i: bb.left, data[i-1].right = data[i-1], bb return {'e':protein['e'], 'data':data, 'space':space} def calc_length(loc1, loc2): """ Returns the current end to end length of a protein given its first and last amino acid locations. """ return ((loc1[0]-loc2[0])**2 + (loc1[1] - loc2[1])**2)**0.5 def plot_folding(num, T, steps, energy=True, SAW=False, anneal=False): """ Plots either the length or energy of the protein against time given the number of amino acids in the chain, the temperature (in units of Boltzmann's constant, the number of Monte Carlo time steps whether to plot energy or length, how to initilize the protein, and whether or not annealling will occur. """ energies = attraction_energy() # The attractions between different amino acids if (not SAW): protein = init(num) # The amino acid positions else: protein = init_SAW(num, energies) # The amino acid can walk now display_protein(protein) # show the configuration at the start monte_carlo_steps = steps progress_step = 10 x, y = [], [] progress = progress_report(progress_step) for i in range(int(monte_carlo_steps)): if (anneal): if (i == int(steps/T)): T = 0.75 * T elif (i == 2*int(steps/T)): T = 0.5 * T elif (i == 3*int(steps/T)): T = 0.25 * T fold_protein(protein, energies, T) if energy: y.append(protein['e']) else: y.append(calc_length(protein['data'][0].loc, protein['data'][-1].loc)) x.append(i) progress(round((i + 1)/monte_carlo_steps * 100)) display_protein(protein) # show the configuration at the end pylab.plot(x, y) if energy: pylab.title("Protein Folding: Energy v. Time") pylab.ylabel("Energy (arb. units)") else: pylab.title("Protein Folding: End to End Length v. Time") pylab.ylabel("Length") pylab.xlabel("Time (Monte Carlo Steps)") pylab.show() def create_process(T, protein, steps, energies): """ Creates a subprocess to handle the averaging in plot_dynamic_temp() for one temperature. """ z = [] for i in range(int(steps)): fold_protein(protein, energies, T) #z.append(calc_length(protein['data'][0].loc, protein['data'][-1].loc)) # the above line is to plot length instead of energy z.append(protein['e']) return T, sum(z)/len(z) def plot_dynamic_temp(num, T, steps): """ Calculates an average energy for the protein comprised of num AminoAcids over monte_carlo_steps data points for temperatures in the range 1 to T by 0.5 steps and plots this. Ideally there is a distinct trend of higher energy -> higher (nearer to 0) energy. """ from multiprocessing import Process, Pool monte_carlo_steps = steps base_protein = init(num) # The amino acid positions energies = attraction_energy() pool = Pool(None) # number of processes, cpu_count() by default x, y = [], [] def get_result(result): T, average = result t = int(T*2-1) x.insert(t, T) y.insert(t, average) print T, average for t in range(20, 0, -1): if t == 1: continue pool.apply_async(create_process, args=(float(t)/2, copy(base_protein), monte_carlo_steps, energies), callback = get_result) pool.close() pool.join() pylab.scatter(x, y) pylab.title("Protein Folding: Average Energy v. Temperature") pylab.ylabel("Energy (arb. units)") pylab.xlabel("Temperature (Boltzmann units)") pylab.show() def plot_dynamic_temp_old(num, steps): """ Calculates an average energy for the protein comprised of num AminoAcids over monte_carlo_steps data points for temperatures in the range 1 to 10 by 0.5 steps and plots this. Ideally there is a distinct trend of higher energy -> higher (nearer to 0) energy. This should only be used if plot_dynamic_temp() will not work on your machine! """ progress_step = 10 monte_carlo_steps = steps base_protein = init(num) # The amino acid positions energies = attraction_energy() # The attractions between different amino acids x, y = [], [] for t in range(20, 0, -1): protein = copy(base_protein) T = float(t)/2 print 'T =', T z = [] progress = progress_report(progress_step) for i in range(int(monte_carlo_steps)): fold_protein(protein, energies, T) z.append(protein['e']) progress(round((i + 1)/monte_carlo_steps * 100)) total = sum(z) average = total / len(z) print 'average =', str(total) + "/" + str(len(z)) + "=" + str(average) y.append(average) x.append(T) pylab.scatter(x, y) pylab.title("Protein Folding: Energy v. Temperature") pylab.ylabel("Average Energy (arb. units)") pylab.xlabel("Temperature (Boltzmann units)") pylab.show() if __name__ == '__main__': plot_folding(15, 1.0, 5e5, energy=True, SAW=False, anneal=False) #plot_dynamic_temp(15, 10, 10e5) #plot_dynamic_temp_old(15,5e5) # only use this if the test_with_processes() function does not work! # In the above methods, each will produce a different plot modeling the behavior of a protein. Select # the apropriate on based on docstring descpritions (i.e. uncomment a method call above in the __main__ block, # and in any method, a call to init() may be replaced with init_SAW() to intilize the protein with a # Self Avoiding Walk (SAW) instead of a default straight line configuration.
b3b3e6b370aa81c2c271fc3f11d86cfe18f924bf
inki-hong/python-oop
/f111_instance.py
543
3.609375
4
class Sedan(): no_of_doors = 4 def set_owner(self, owner): self.owner = owner # alice_sedan.owner = 'Alice' def set_plate_no(self, plate_no): self.plate_no = plate_no def set_mileage(self, mileage): self.mileage = mileage alice_sedan = Sedan() # print(alice_sedan.owner) # attribute error Sedan.set_owner(alice_sedan, 'Alice') alice_sedan.set_owner('Alice') Sedan.set_plate_no(alice_sedan, 'ABCDE') alice_sedan.set_mileage(10000) print(alice_sedan.owner) print(alice_sedan.plate_no) print(alice_sedan.mileage) #
ff2cf5445211321ab385bafa073b5c5f0cf95096
brunoreyes/python_fundamentals
/sorting.py
1,291
4
4
pangram = "The quick brown fox jumps over the lazy dog" #pangram is a phrase that contains all letters of the alphabet, to check lets sort letters = sorted(pangram) print(letters) # [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T', 'a', 'b', 'c', 'd', 'e', 'e', 'e', 'f', 'g', 'h', # 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'o', 'o', 'o', 'p', 'q', 'r', 'r', 's', 't', 'u', 'u', 'v', 'w', 'x', 'y', 'z'] numbers = [2.3, 4.5, 8.7, 3.1, 9.2, 1.6] #sort can sort numbers, letters, and literals sorted_numbers = sorted(numbers) print(sorted_numbers) #don't do this, sorted = sorted(numbers) missing_letter = sorted("The quick brown fox jumped over the lazy dog") print(missing_letter) #here we see s is missing, making this not a pangram missing_letter = sorted("The quick brown fox jumped over the lazy dog", key=str.casefold) #to sort without having to worry about capitilization use key=str.casefold names = [ 'eric','John', 'terry', 'micheal', 'Terry' ] names.sort(key=str.casefold) print(names) #['eric', 'John', 'micheal', 'terry', 'Terry'] empyty_list = [] more_numbers = numbers[:] #here we slice digits = sorted("439228394") print(digits) # ['1','2','3','4','5','6','7','8','9'] print(numbers is more_numbers) #False not fully true print(numbers == more_numbers) #True truthy
b8aa1b2038d7260f60df01496283180bb97494b4
quanwen20006/PythonLearn
/day1/基础语法.py
2,171
3.625
4
# _*_ coding:utf-8 _*_ ''' 主要是记录学习基础过程中的demo 该文档记录的主要是基础知识 ''' # 2022.5.24 int = 1 #查看数据的类型,使用type可查看到 print(type(int),int,'\n数据相加\t',type(1+1.1),'\n数据相乘\t',type(1*1.1),'\n数据相除\t',type(1/1)) #整形数相除,但是想得到整形 print('整形相除、但是想得到整形:',type(1//1)) print('转换为16进制',hex(13)) print('转换为8进制',oct(13)) print('转换为2进制',bin(13)) print('let\'s go') print('hello \\n world') print('hello \\n world'[-3]) #列表 tempList = ['ShangHai','BeiJing','TianJing','ShenZen'] print(tempList[2]) tempList.append('ChongQing') print(tempList) tempTuple = ('ShangHai','BeiJing','TianJing','ShenZen') print(tempTuple[3]) print(tempTuple[1:3]) tempTuple1=(1,) print(type(tempTuple1)) #获得字符串的十进制值 print(ord('a')) #set集合 tempSet1=set() tempSet={'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print('空集合: ',type(tempSet1),'有内容集合: ',tempSet) #print('获得set的值:',tempSet[1]) #字典 tempDict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} tempDict1 = {} print('有内容字典: ',tempDict,'空字典: ',type(tempDict1)) print('获取字典的值:',tempDict['Alice']) print(35<=45<75) #等价于 45 》=35 and 45 《75 print(35<=25<75) #按位与-把值转换为2进制,然后每一位进行与值,如果都为1,就把结果设置为1,否则为0, print(3 & 10) print(3 | 10) account = 'qiyue' pwd = '123456' user_account = input('please input account: ') user_pwd = input('please input pwd: ') if user_account == account and user_pwd == pwd : print('succuess') else: print('fail') # for 循环--else 执行完列表后,再执行 fruitList = ['apple', 'pear', 'bananan'] for fruit in fruitList: print('fruit is :',fruit, end='\t') else: print('打印完毕') #while 循环--else 条件为False,再执行 count = 0 while count <= 10: count += 1 print(count) else: print('count is: ',count) # for -- range -range不包含右边界 for i in range(1,10): print('i is: ',i)
098887ea4aa1bca0ccc297af45c5b365d29c7184
quadrant26/python_in_crossin
/Lesson/lesson14_task.py
352
3.75
4
from random import randint print('Guess what i think!') num = randint(1, 100) bingo = False while bingo == False: answer = int(input()) if answer < num: print('%d is too small!' % answer) if answer > num: print('%d is to big!' % answer) if answer == num: print('%d is equal!' % answer) bingo = True
5a29058b09ae15c2e5a2bb1b096cd1f29cc00728
Dimildizio/learn_tkinter
/alt_pygame_canvas/BFS.py
7,088
3.515625
4
import queue from random import choice ''' 27. Terrain class: 27.1 attributes 27.1.1 terrain difficulty 27.1.2 terrain danger 27.2 terrain_effect() ''' class Terrain: def __init__(self, name, speed_penalty = 1, penalty = 1, effects = []): self.name = name self.speed_penalty = speed_penalty self.penalty = penalty self.effects = effects def terrain_effect(self): return self.effects class Node: def __init__(self, pos, t_type = Terrain('stone')): self.pos = pos self.inside = [] self.occupied = False self.neighbours = [] self.t_type = t_type self.sprite = 'g.png' def __repr__(self): if self.inside: return str(self.inside[0]) elif self.occupied: return str(self.occupied) return '.' class Field: def __init__(self, maxsize): self.maxsize = maxsize self.cells = {} self.create_nodes() self.creatures = [] def __repr__(self): return str(type(self.cells[0, 0])) def bounds(self, cell): x,y = cell mx,my = self.maxsize return 0 <= x < mx and 0 <= y < my def create_nodes(self): mx, my = self.maxsize for x in range(mx): for y in range(my): self.cells[x, y] = Node((x,y)) #creating neighbours directions = [(x+1,y), (x, y+1), (x-1,y), (x,y-1), (x-1,y-1), (x-1,y+1), (x+1,y+1), (x+1, y-1)] for n in directions: if self.bounds(n): self.cells[x, y].neighbours.append(n) def add_in(self, pos, obj): if self.bounds(pos): cell = self.cells[pos] if obj.passable: cell.inside.append(obj) else: cell.occupied = obj return True def remove(self, obj): cell = self.cells[obj.pos] if obj.passable: cell.inside.remove(obj) else: cell.occupied = False def reposition(self, obj, pos): if self.bounds(pos): self.remove(obj) self.add_in(pos, obj) return True def port_object(self, pos, obj): if obj.passable: self.add_in(pos, obj) elif not self.cells[pos].occupied: self.add_in(pos,obj) else: pos = self.port_object(choice(self.cells[pos].neighbours), obj) return pos def create_obj(self, position, obj): self.creatures.append(obj) return self.port_object(position, obj) def destroy_obj(self, obj): self.remove(obj) self.creatures.remove(obj) def draw_y0(self): for x in range(self.maxsize[1]): if x == 0: print('.', end = ' ') myend = ' ' if len(str(x)) > 1 else ' ' print(x, end = myend) print() def show(self): self.draw_y0() mx,my = self.maxsize for x in range(mx): for y in range(my): if y == 0: myend = ' ' if len(str(x)) > 1 else ' ' print (x, end = myend) myend = ' ' if len(str(self.cells[x,y])) > 1 else ' ' print(self.cells[x,y], end = myend) print() def bfs(self, start, goal): my_q = queue.Queue() my_q.put(start) came = {start:None} while not my_q.empty(): current = my_q.get() if self.cells[current] == self.cells[goal]: return came for n in self.cells[current].neighbours: if not (n in came or self.cells[n].occupied): my_q.put(n) came[n] = current def find_path(self, start, goal): if self.cells[goal].occupied: occs = [x for x in self.cells[goal].neighbours if not self.cells[ x].occupied] goal = min(occs) if goal > start else max(occs) current = goal path = [] came = self.bfs(start, goal) while current != start: path.append(current) current = came[current] path.append(start) path.reverse() if self.cells[path[-1]].occupied: del path[-1] return path def build_rect(self, x, xm, y, ym, no = []): for i in range(x, xm+1): self.cells[i, y].occupied = '#' self.cells[i, ym].occupied = '#' for j in range(y, ym+1): self.cells[x,j].occupied = '#' self.cells[xm,j].occupied = '#' if no: for x in no: self.cells[x].occupied = False class Object: def __init__(self, pic, x, y, passable = False): self.passable = passable self.pic = pic self.reach = 1 self.pos = self.appear((x,y)) def __repr__(self): return str(self.pic) def appear(self, position): return current_location.port_object(position, self) def step(self, position): if current_location.reposition(self, position): self.pos = position return True def goto(self, position): if current_location.bounds(position): mygoal = current_location.find_path(self.pos, position) for x in mygoal: if not self.step(x): #current_location.show() return False #current_location.show() return True current_location = Field((16, 12)) if __name__ == '__main__': class Object: def __init__(self, pic, x, y, passable = False): self.passable = passable self.pic = pic self.reach = 1 self.pos = self.appear((x,y)) def appear(self, position): return current_location.port_object(position, self) def step(self, position): if current_location.reposition(self, position): self.pos = position return True def goto(self, position): mygoal = current_location.find_path(self.pos, position) for x in mygoal: if not self.step(x): #current_location.show() return False #current_location.show() return True def generate_location(x = 20, y = 20): return Field((x,y)) current_location = generate_location(15, 15) current_location.build_rect(5,9, 8,14, [(9, 12)]) a = Object('Y', 0,0) b = Object('W', 6,9) current_location.show()
455a43db949c61853979efd29ceb5673a19d716a
GeekChao/Coding
/Educative/coding/fast_slow_pointers/ex3.py
1,371
3.953125
4
""" Problem: Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number ‘1’. All other (not-happy) numbers will never reach ‘1’. Instead, they will be stuck in a cycle of numbers which does not include ‘1’. Difficulty: Medium """ # Solution one: a hashmap def calcNum(num): digits = [int(x) for x in str(num)] sum = 0 for x in digits: sum += x * x return sum def isHappyNum(num): map = {} while True: if num == 1: return True if num in map: return False map[num] = num num = calcNum(num) assert(isHappyNum(23) == True) assert(isHappyNum(12) == False) # Solution two: fast / slow pointer # The process to find out if a number is a happy number or not, always ends in a cycle. def find_happy_number(num): slow, fast = num, num while True: slow = find_square_sum(slow) # move one step fast = find_square_sum(find_square_sum(fast)) # move two steps if slow == fast: # found the cycle break return slow == 1 # see if the cycle is stuck on the number '1' def find_square_sum(num): _sum = 0 while (num > 0): digit = num % 10 _sum += digit * digit num //= 10 return _sum
8ab7e1919f49b823a53545560559877092d0f0c4
5ran6/Algorithm-challenges
/random_algorithms/sum_of _smallest_number.py
172
3.796875
4
# sum of two smallest numbers def sum_two_smallest_numbers(numbers): numbers.sort() return numbers[0] + numbers[1] print(sum_two_smallest_numbers([19,5,42,3,77]))
d849291eb2e78233ab477d22c14acf3e9422c3dc
Coalin/Daily-LeetCode-Exercise
/111_Minimum-Depth-of-Binary-Tree.py
1,960
3.859375
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 minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 if root.left and not root.right: return self.minDepth(root.left)+1 elif root.right and not root.left: return self.minDepth(root.right)+1 elif root.left and root.right: return min(self.minDepth(root.left), self.minDepth(root.right))+1 else: return 1 # Exercise II # Aug 23, 2020 # 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 minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 if root.left is None and root.right is None: return 1 if root.left is None: return self.minDepth(root.right)+1 if root.right is None: return self.minDepth(root.left)+1 return min(self.minDepth(root.left), self.minDepth(root.right))+1 # Exercise III: # Mar 2, 2023 # 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 minDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 if not root.left and root.right: return self.minDepth(root.right)+1 if not root.right and root.left: return self.minDepth(root.left)+1 return min(self.minDepth(root.left), self.minDepth(root.right))+1
623ad63a942ad344e1e339c7e9b5f5cfb41aeefd
AhmedShehab/leetCodeFun
/RomanToInteger.py
553
3.734375
4
def romanToInt(s: str) -> int: # Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. # These are there valuse romanNumerals = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} number = 0 track = 0 for i in range(len(s)-1,-1,-1): digit = romanNumerals[s[i]] if track != 0: if digit < romanNumerals[s[i+1]]: number -= digit else: number += digit else: number +=digit track += 1 return number
2eb18ebfa2f9edf979740b1473e3684d954b583d
RoryBaxter/Route-Planner
/gui.py
13,784
3.96875
4
'''Setup and running of the GUI, as well as calling to other sub systems ''' import tkinter as tk from time import time from PIL import ImageTk from goompy import GooMPy import location import search class RoutePlanGUI: '''The GUI for the Route Planning System All the GUI features are created and run though this class. All expected user input will come though this GUI, along with all output to the user Attributes: root The Root from which the application is running #max_height Maximium height for the window #max_width transport_mode Transport mode setting locations List of all the current locations location_view Index of what can currently be viewed VIEW_SIZE A limit of how many items can be viewed at one time to ensure they fit on screen latitude The current latitude of the device running the system longitude The cyrrent longitude of the device running the system zoom The zoom level of the tiles map_width The width of the displayed map map_height The height of the displayed map goompy A goompy object to act as the API to download the map tiles Methods: _draw_UI Creates the UI features and places them in the correct location _redraw_map Redraws the map _add_location Adds a location to the list of locations _remove_location Removes a location from the list of locations _move_boxes Moves the displayed list of locations _search Runs the search algorithm after fetching and passing it data ''' def __init__(self, root): self.root = root self.max_height = self.root.winfo_screenheight() self.max_width = self.root.winfo_screenwidth() self.root.geometry((str(int(self.max_width/2))+"x"+str(int(self.max_height/2)))) ## self.radiogroup = Frame() ## self.root.bind("<Key>", self.user_input) ## self.root.bind("<Button>", self.user_input) self.root.bind("<Escape>", lambda e: self.root.destroy()) # The user is able to select differnt modes of transportation # They are diffined here, as well as the mechanism for storing them self.transport_mode = tk.StringVar() self.transport_mode.set("Walking") self.transport_modes = ["Walking", "Bicycling", "Driving", "Transit"] # All the locations the user is using, stored in a list self.locations = [] # The index used to calualate which locations are currently visable self.location_view = 0 # Used to limit the system from attempting to display more locations # than possible self.VIEW_SIZE = 10 # The coordinates of the current location of the user self.latitude = float( location.CURRENT_LOCATION[:location.CURRENT_LOCATION.find(",")] ) self.longitude = float( location.CURRENT_LOCATION[location.CURRENT_LOCATION.find(",")+1:] ) # The zoom level on the map self.zoom = 15 # The dimentions of the map self.map_width = 500 self.map_height = 500 # GooMPy object to act as an API self.goompy = GooMPy(self.map_width, self.map_height, self.latitude, self.longitude, self.zoom, "roadmap") self.live = False # Starts the system self._draw_UI() self.root.mainloop() def _draw_UI(self): '''Draw the UI ''' # Backbone of the GUI layout self.frame = tk.Frame(self.root) # Placement of Radiobuttons with correct control assignment for index, mode in enumerate(self.transport_modes): tk.Radiobutton( self.frame, text=mode, variable=self.transport_mode, value=mode ).grid(row=0, column=index) # Movement buttons self.up_button = tk.Button( self.frame, text=" Up ", bg="yellow", command=lambda: self._move_boxes(1) ) self.down_button = tk.Button( self.frame, text="Down", bg="yellow", command=lambda: self._move_boxes(-1) ) self.showing_movement_buttons = False # Start button self.go_button = tk.Button( self.frame, text="Start Search", bg="yellow", command=lambda: self._search() ) # Entry box for user input, along with an associated button self.entry_box = tk.Entry(self.frame) self.entry_box.insert("end", "Add Location") self.entry_box.bind("<Return>", self._add_location) self.entry_button = tk.Button( self.frame, text="+", bg="green", command=self._add_location ) # Configureation of the widgets just defined self.entry_box.grid(row=2, column=0, columnspan=4, sticky="ew") self.entry_button.grid(row=2, column=4) self.go_button.grid(row=1, column=3, columnspan=2, sticky="e") # Canvas to hold the map self.canvas = tk.Canvas( self.root, width=self.map_width, height=self.map_height, bg="black" ) # Underlay to configure the tile image self.label = tk.Label(self.canvas) self.zoom_in_button = tk.Button(self.canvas, text="+", width=1, command=lambda:self._map_zoom(+1)) self.zoom_out_button = tk.Button(self.canvas, text="-", width=1, command=lambda:self._map_zoom(-1)) # Packing of the two layout features self.frame.pack(side="left", fill="y") self.canvas.pack(side="right", expand=True, fill="both") ## x = int(self.canvas['width']) - 50 ## y = int(self.canvas['height']) - 80 ## ## self.zoom_in_button.place(x=x, y=y) ## self.zoom_out_button.place(x=x, y=y+30) # Load a tile self._reload() def _redraw_map(self): '''Fetch a new tile and place that on the map ''' ## print("redrawing") # Get the tile that goompy has been told to fetch self.goompy._fetch_and_update() self.image = self.goompy.getImage() # Load the image tile onto the map self.image_tk = ImageTk.PhotoImage(self.image) self.label['image'] = self.image_tk self.label.place( x=0, y=0, width=self.map_width, height=self.map_height ) def _reload(self): self.coords = None if self.live: self._redraw_map() def _add_location(self, event=None): '''Make the user's input a Location and add to the list of locations ''' # The details of the new location user_input = self.entry_box.get() new_location = location.Location(user_input) self.locations.append(new_location) precise = new_location.location # goompy loading a new tile as per the location self.goompy.lat = float(precise[:precise.find(",")]) self.goompy.lon = float(precise[precise.find(",")+1:]) self._reload() # Differnt actions depending on how many locations currently exist if len(self.locations) > self.VIEW_SIZE: # Configure the movement buttons is not configured if not self.showing_movement_buttons: self.up_button.grid(row=1, column=0, columnspan=2, sticky="w") self.down_button.grid( row=self.VIEW_SIZE+10, column=0, columnspan=2, sticky="w" ) # Ensures the latest location is displayed at the bottom while len(self.locations)-self.location_view > self.VIEW_SIZE: self._move_boxes(1) else: # Move the entry box, and its button, down on space self.entry_box.grid_configure( row=self.entry_box.grid_info()["row"]+1 ) self.entry_button.grid_configure( row=self.entry_box.grid_info()["row"] ) # The row the the entry box moved from row = self.entry_box.grid_info()["row"]-1 # Create a Label and a Button for the new location tk.Label( self.frame, text=user_input, bg="white", anchor="w" ).grid(row=row, column=0, sticky="ew", columnspan=4) tk.Button( self.frame, text="X", bg="red", command=lambda: self._remove_location(len(self.locations)) ).grid(row=row, column=4, sticky="ew") # Reset the text in the entry box self.entry_box.delete(0, "end") self.entry_box.insert("end", "Add Location") def _remove_location(self, row): '''Remove the location selected by the user by visualy and from list ''' # Remove the location from the location list self.locations.pop(row+self.location_view-1) # Marker to indicate if the locations below should move up move = False # List of all the locations, as per what is on the Labels remaining_locations = [x.user_input for x in self.locations] # Index to keep track of where is being investigated index = 0 # Looping though all the slaves and adjusting them as needed for slave in self.frame.grid_slaves()[::-1]: # Reversed for simplicity # Anaylse and configure the Labels if type(slave) == tk.Label: if self.location_view+index == len(self.locations): slave.grid_forget() else: if slave.cget("text") not in remaining_locations: move = True if move: slave.config( text=self.locations[ self.location_view+index ].user_input ) index += 1 # Ensure that the final button is removed if needed if (type(slave) == tk.Button and self.location_view+index-1 == len(self.locations)): slave.grid_forget() self.location_view -= 1 def _move_boxes(self, direction): '''Move the visual list of locations in required direction ''' for i in self.locations: print(i) # Ensure that the given command is valid in the current configuration if ((self.location_view == 0 and direction == -1) or (self.location_view+self.VIEW_SIZE == len(self.locations) and direction == 1)): return None else: self.location_view += direction # Iterate though the Labels and change their values for index, slave in enumerate(self.frame.grid_slaves()[::-1]): if type(slave) == tk.Label: slave.config( text=self.locations[ self.location_view+index ].user_input ) ## def user_input(self, event): ## if event.char == "a": ## print(self.transport_mode.get()) def _search(self): '''Calculate and return the most efficent route ''' # Using the Latitude and Longitude, calculate the distance matrix precise_locations = [l.location for l in self.locations] distance_matrix_info = location.GM.distance_matrix( precise_locations, precise_locations, mode=self.transport_mode.get().lower() ) self.distance_matrix = [] for origin in distance_matrix_info["rows"]: self.distance_matrix.append( [dest["duration"]["value"] for dest in origin["elements"]] ) ######################################################################################################################## t = time() _time, _route = search.nearest_neighbour(self.distance_matrix) print("nn time") print(time()-t) t2 = time() _time2, _route2 = search.brute_force(self.distance_matrix) print("bf time") print(time()-t2) print(_time) print(_route) ######################################################################################################################## # Write message to the user about the best route msg = "The best route to visit every location in the minimun amount of time is " for loc in _route[:-1]: msg += self.locations[loc].user_input msg += ", then " msg += "and then finally " msg += self.locations[_route[-1]].user_input # Set up the message to tell the user which route is best self.route_box = tk.Toplevel(master=self.root) self.route_box.title("Best Route") # Configure widgets in message box tk.Message(self.route_box, text=msg).pack() tk.Button( self.route_box, text="OK", command=lambda:self.route_box.destroy() ).pack() if __name__ == "__main__": root = tk.Tk() RoutePlanGUI(root)
22bf75f98127604df26dac5c4a3bf674b48bf3a1
DavidHan6/Week2
/Week2/ImageProcessing.py
4,275
3.515625
4
from PIL import Image from PIL import ImageFilter print(" What is your request? ") print(" a is invert") print(" b is darken") print(" c is brigten") print(" d is greyscale") print(" e is posterize") print(" f is solarize") print(" g is denoise1") print(" h is denoise2") print(" i is denoise3") print(" j is blur") print(" k is sharpen") print(" l is crop") mudder = input(" ") def apply_filter(image, filter): pixels = [ filter(p) for p in image.getdata() ] nim = Image.new("RGB",image.size) nim.putdata(pixels) return nim def open_image(filename): image = Image.open(filename) if image == None: print("Specified input file " + filename + " cannot be opened.") return Image.new("RGB", (400, 400)) else: print(str(image.size) + " = " + str(len(image.getdata())) + " total pixels.") return image.convert("RGB") def identity(pixel): r,g,b = pixel return (r,g,b) def invert(pixel): r,g,b = pixel return (255-r, 255-g, 255-b) def darken(pixel): r,g,b = pixel return (int((9/10) * r), int((9/10) * g), int((9/10)* b)) def brighten(pixel): r,g,b = pixel return (int((1000000/10) * r), int((1000000/10) * g), int((100000/10)* b)) def gray_scale(pixel): r,g,b = pixel gry = (r + g + b) / 3 return (int(gry), int(gry), int(gry)) def posterize(pixel): r,g,b = pixel if r >= 0 and r <= 63: r = 50 if r >= 64 and r <= 127: r = 100 if r >= 128 and r <= 191: r = 150 if r >= 192 and r <= 255: r = 200 if g >= 0 and g <= 63: g = 50 if g >= 64 and g <= 127: g = 100 if g >= 128 and g <= 191: g = 150 if g >= 192 and g <= 255: g = 200 if b >= 0 and b <= 63: b = 50 if b >= 64 and b <= 127: b = 100 if b >= 128 and b <= 191: b = 150 if b >= 192 and b <= 255: b = 200 return (r,g,b) def solarize(pixel): r,g,b = pixel if r < 128: r = 255 - r if g < 128: g = 255 - g if b < 128: b = 255 - b return (r,g,b) def denoise(pixel): (r,g,b) = pixel return(r*10, g*0, b*0) '''def denoise2(pixel): def denoise3(pixel):''' def blur(pixel): num = int(input("What is your blur power: ")) original_image = Image.open(input_file) blurred_image = original_image.filter(ImageFilter.GaussianBlur(num)) blurred_image.show() exit() def sharpen(pixel): original_image = Image.open(input_file) sharpened_image = original_image.filter(ImageFilter.SHARPEN) sharpened_image.show() exit() def crop(pixel): coord1 = input("what is your first x") coord2 = input("what is your first y") coord3 = input("what is your second x") coord4 = input("what is your second y") allcords = (coord1, coord2, coord3, coord4) original_image = Image.open(input_file) blurred_image = original_image.crop(allcords) blurred_image.show() exit() def load_and_go(fname,filterfunc): print("Loading ...") image = open_image(fname) nimage = apply_filter(image,filterfunc) #image.show() #nimage.show() ''' processedImage.jpg is the name of the file the image is saved in. The first time you do this you may have to refresh to see it. ''' nimage.save("processedImage.jpg") if __name__ == "__main__": ''' Change the name of the file and the function to apply to the file in the line below ''' input_file = input("What file would you like?") if mudder == "a": mudder = invert if mudder == "b": mudder = darken if mudder == "c": mudder = brighten if mudder == "d": mudder = gray_scale if mudder == "e": mudder = posterize if mudder == "f": mudder == solarize if mudder == "g": mudder = denoise if mudder == "h": mudder = denoise2 if mudder == "i": mudder == denoise3 if mudder == "j": mudder = blur if mudder == "k": mudder = sharpen if mudder == "l": mudder = crop load_and_go(input_file, mudder)
5dadbbe6ec2cf90c77f482417ac263e4ab9dd88d
sai10/Python-Sample-Programs
/Practice/CONDITIONAL/IfElif.py
197
3.6875
4
a = 5; b = 9; if a>b: print('greater'); elif a<b: print('other way round') else: # optional or when required print('check your code');
94ff7641dd48da4411b59e4f9f209eb4207a4b45
chixujohnny/Leetcode
/Leetcode2020/剑指offer/链表/剑指 Offer 24. 反转链表.py
978
3.734375
4
# coding: utf-8 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return None node = head.next i = 0 while node != None: if i == 0: # 如果是第一轮 head.next = None nodeNext = node.next node.next = head head = node node = nodeNext i += 1 else: nodeNext = node.next node.next = head head = node node = nodeNext return head l = [1] head = ListNode(l[0]) node = head for i in xrange(1, len(l)): tag = ListNode(l[i]) node.next = tag node = node.next s = Solution() s.reverseList(head)
9746e66d27ee13bc57868c25b1daaacee030a4c6
shouliang/Development
/Python/SwordOffer/re_order_array_01.py
1,221
3.828125
4
''' 题目描述 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分, 所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 思路: 两指针,一个从左向右扫描,遇到偶数停止,一个从右往左扫描,遇到奇数停止,然后交换两数 但是此方便不能保证奇数和奇数,偶数和偶数之间的相对位置不变 ''' # coding=utf-8 class Solution: def reOrderArray(self, array): if not array: return [] begin, end = 0, len(array) - 1 while begin < end: # 向右一直移动,直到找到偶数 while begin < end and array[begin] & 0x1 != 0: begin += 1 # 向左一直移动,直到找到奇数 while begin < end and array[end] & 0x1 == 0: end -= 1 # 交换 if begin < end: temp = array[begin] array[begin] = array[end] array[end] = temp return array s = Solution() array = [1, 2, 3, 4, 5, 6, 7] s.reOrderArray(array) print(array)
54030f834bc1b2c021574a78940131efd22afa81
NARESHSWAMI199/5-Star-On-Hacker-Rank-Python
/modified_kaprekar_number.py
397
3.6875
4
start_point = int(input()) end_point = int(input()) string = '' if start_point == 0 or start_point == 1: print(1 ,end=' ') for x in range(start_point,end_point+1): square = str(x*x) length = len(square) // 2 if len(square) == 1: continue else: if int(square[0:length]) + int(square[length : ]) == x: print(x ,end=' ') string+=str(x) if len(string)==0: print('INVALID RANGE')
1d3a6beef7fcb71e048d788bef2a7290a97490e4
wellington-ishimaru/IFSP--Estruturas-de-repeticao
/questao4.py
2,087
3.75
4
# -*- coding: UTF-8 -*- print("******************************") print(" Venda de passagens de ônibus ") print("******************************\n") poltrona_janela_esq = [0 for x in range(0, 12)] poltrona_corredor_esq = [0 for x in range(0, 12)] poltrona_janela_dir = [0 for x in range(0, 12)] poltrona_corredor_dir = [0 for x in range(0, 12)] vagas = 48 escolha = 1 while vagas != 0 and escolha != 0: print("1 - Venda de passagem.") print("2 - Mapa de ocupação.") print("0 - Sair.") escolha = int(input("Escolha a opção desejada: ")) if escolha == 1: print("\n>>>>>>>>>> Venda de passagens <<<<<<<<<<\n") escolha_jan_corr = int(input("Escolha 1 para janela e 2 para corredor: ")) escolha_num_poltrona = int(input("Escolha o número da poltrona de 1 a 12: ")) if escolha_jan_corr == 1: if poltrona_janela_dir[escolha_num_poltrona - 1] == 0: poltrona_janela_dir[escolha_num_poltrona - 1] = 1 print("Venda efetivada.") vagas -= 1 elif poltrona_janela_esq[escolha_num_poltrona - 1] == 0: poltrona_janela_esq[escolha_num_poltrona - 1] = 1 print("Venda efetivada.") vagas -= 1 else: print("\nPoltrona ocupada.") if escolha_jan_corr == 2: if poltrona_corredor_dir[escolha_num_poltrona - 1] == 0: poltrona_corredor_dir[escolha_num_poltrona - 1] = 1 print("Venda efetivada.") vagas -= 1 elif poltrona_corredor_esq[escolha_num_poltrona - 1] == 0: poltrona_corredor_esq[escolha_num_poltrona - 1] = 1 print("Venda efetivada.") vagas -= 1 else: print("\nPoltrona ocupada.") print(f"Restam {vagas} \n") if escolha == 2: print("\n") print(poltrona_janela_esq) print(poltrona_corredor_esq, "\n") print(poltrona_corredor_dir) print(poltrona_janela_dir, "\n") print("Ônibus lotado.")
70fc0a35c3c41f4d490021f46444b720a21c03bb
hudingjing244/interview
/py_interview/distribute_candies.py
884
3.90625
4
""" 给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。 示例 1: 输入: candies = [1,1,2,2,3,3] 输出: 3 解析: 一共有三种种类的糖果,每一种都有两个。 最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。 示例 2 : 输入: candies = [1,1,2,3] 输出: 2 解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。 注意: 数组的长度为[2, 10,000],并且确定为偶数。 数组中数字的大小在范围[-100,000, 100,000]内。 """ def distribute_candies(candies): pass
95c39250eb139a54473d04b02f080bf68884b1c0
gsaurabh98/machine_learning_basics
/mlPackage/pandas/missing_data.py
561
3.640625
4
import numpy as np import pandas as pd d = {'A':[1,2,np.nan],'B':[1,np.nan,np.nan],'C':[1,2,3],'D':[np.nan,np.nan,np.nan]} df = pd.DataFrame(d) print df # for removing NaN value print df.dropna() #by removing column which has Nan print df.dropna(axis=1) #Keep only the rows with at least 2 non-na values: print df.dropna(thresh=2) #Drop the columns where all elements are nan: print df.dropna(axis=1,how='all') #filling the NaN Value print df.fillna(value = 'Missing Value') # filling value in particular column print df['A'].fillna(value=df['A'].mean())
b4ebfcf72dbeecf7881cd779c60f58a4aa136471
gridl/Lonang
/lnn/statements/variable.py
1,609
3.671875
4
from .statement import Statement from variables import Variable from operands import Operand def variable(c, m): """Variable or constant definition. For instance: byte little = 42 short big = 1234 byte[5] vector1 byte[] vector2 = 1, 2, 3, 4, 5 const VALUE = 7 """ # TODO Perform more checks to ensure the value is correct vartype = m.group(1) vector_size = m.group(2) name = m.group(3) value = m.group(4) if not value: value = '?' if vector_size is None: # Single item variable c.add_variable(Variable( name=name, vartype=vartype, value=value )) else: # We have a vector, get the comma-separated values values = Operand.get_csv(value) # Determine its size (remove '[]' by slicing) if given vector_size = vector_size[1:-1].strip() if vector_size: vector_size = int(vector_size) else: if value == '?': raise ValueError('A list of values must be supplied when ' 'no vector size is specified') vector_size = len(values) c.add_variable(Variable( name=name, vartype=vartype, value=values, vector_size=vector_size )) variable_statement = Statement( # Type for the variable vector or' ' optional value r'(byte|short|string|const)(?: (\[ \d* \]) | )(VAR)(?: = (.+))?', # name variable )
1470c0335c3ff17a6aa7c48a09ce1a1e27510c93
Miguelsantos101/algoritmos1-2021-1
/palindromo.py
736
3.71875
4
# Retorna o número de digitos de num def contaDigitos(num): dig = 0 while num != 0: num = num // 10 dig = dig + 1 return dig #---------------------------------------- # Função que recebe n e retorna True se n é palíndromo, False caso contrário. def EhPalindromo(n): numero = n digitos = contaDigitos(n) n = numero inv = 0 while n != 0: mod = n % 10 inv = inv + mod * 10 ** (digitos-1) digitos = digitos - 1 n = n // 10 return True if numero == inv else False #if numero == inv: # return True #else: # return False #-------------------------------------- def main(): n = int(input()) if EhPalindromo(n): print("SIM") else: print("NAO") #-------------------------------------- main()
4ccd439d367504072cc73d63d9d5dc53b5058858
tomim19/frro-soporte-2019-09
/practico_04/ejercicio04.py
3,850
3.890625
4
## 4. Ejercicio al Formulario del Ejercicio 3 , agrege los siguientes botones 1- un botón Alta ## que inicia otra venta donde puedo ingresar una ciudad y su código postal . ## 2 – un botón Baja que borra del listad de ciudades la ciudad que esta selecionada en Treeview . ## 3 – un botón Modificar . Todos los cambios se deben ver reflejados en la lista que se muestra . from tkinter import * from tkinter import ttk class Aplicacion(): def __init__(self): self.raiz = Tk() self.raiz.title("Ciudades y codigos postales") self.tree = ttk.Treeview(self.raiz) #Variable self.ciu=StringVar() self.cp=IntVar() self.i = 0 #Columnas self.tree["columns"]=("one","two") self.tree.column("#0", width=100) self.tree.column("one", width=100 ) self.tree.column("two", width=100) self.tree.heading("#0", text="Id") self.tree.heading("one", text="Ciudad") self.tree.heading("two", text="Codigo Postal") #Insert self.boton0 = ttk.Button(self.raiz, text="Agregar", command=self.grilla) self.boton1 = ttk.Button(self.raiz, text="Eliminar", command=self.Baja) self.boton2 = ttk.Button(self.raiz, text="Modificar", command=self.grilla2) self.boton0.grid(row=1, column=5) self.boton1.grid(row=2, column=5) self.boton2.grid(row=3, column=5) #Loop self.tree.grid() self.raiz.mainloop() #Alta def Agrega(self): self.tree.insert('', 'end', text=str(self.i), values=(self.ciu.get(), self.cp.get()),iid=self.i) self.i = self.i + 1 def grilla(self): self.ventana = Toplevel() self.ventana.title("Nueva ciudad") self.label0 = ttk.Label(self.ventana, text="Ciudad: ") self.label1 = ttk.Label(self.ventana, text="Codigo postal:") self.entry0 = ttk.Entry(self.ventana, textvariable=self.ciu, width=30) self.entry1 = ttk.Entry(self.ventana, textvariable=self.cp, width=30) self.boton0 = ttk.Button(self.ventana, text="Agregar", command=self.Agrega) self.label0.grid(row=0, column=0) self.label1.grid(row=1, column=0) self.entry0.grid(row=0, column=1) self.entry1.grid(row=1, column=1) self.boton0.grid(row=2, column=2) #Baja def Baja(self): selected_item = self.tree.selection()[0] self.tree.delete(selected_item) #Modificacion def Modificar(self): x = self.tree.selection()[0] for item in x: self.tree.item(item, values=(self.ciu.get(), self.cp.get())) def grilla2(self): self.ventana = Toplevel() self.ventana.title("Modificar ciudad") self.label0 = ttk.Label(self.ventana, text="Ciudad: ") self.label1 = ttk.Label(self.ventana, text="Codigo postal:") self.entry0 = ttk.Entry(self.ventana, textvariable=self.ciu, width=30) self.entry1 = ttk.Entry(self.ventana, textvariable=self.cp, width=30) self.boton0 = ttk.Button(self.ventana, text="Modificar", command=self.Modificar) self.label0.grid(row=0, column=0) self.label1.grid(row=1, column=0) self.entry0.grid(row=0, column=1) self.entry1.grid(row=1, column=1) self.boton0.grid(row=2, column=2) def main(): mi_app = Aplicacion() return mi_app if __name__ == '__main__': main()
1365e2539b4f9e7eb4fd961a5e85f79fbe04dcc2
siddharth952/Interview-Prep
/CodeForces/54/A.py
639
3.703125
4
''' Question: Letters can be deleted from s => it results to "hello" Solution: Have to keep track of stream of hello ''' from collections import Counter from sys import stdin def read_int(): return int(stdin.readline()) def read_ints(): return map(int, stdin.readline().split()) def main(): t = 1 for case in range(t): s = list(stdin.readline().strip()) i = 0 tmp = "hello" for c in s: if c == tmp[i]: i += 1 if i >= 5: print("YES") return print("NO") main()
7c4796031a510f6c7718d012c4cff221e3196ad6
CorinnaBuerger/yinyang
/yinyang.py
926
3.609375
4
from turtle import circle, begin_fill, end_fill, dot, left, right, fillcolor, pencolor, pensize, shape, shapesize, speed, fd, penup, pendown, hideturtle, home def jump(distance, angle): penup() left(angle) fd(distance) left(-angle) pendown() def yin(diameter, color_1, color_2): radius = diameter / 2 radius_2 = radius / 2 dot_dia = radius_2 / 2 fillcolor(color_1) pencolor("black") pensize(5) shape("turtle") shapesize(2) speed(10) left(90) begin_fill() circle(radius_2, 180) circle(radius, 180) left(180) circle(-radius_2, 180) end_fill() jump(radius_2, 90) dot(dot_dia, color_2) jump(radius_2, 270) def yinyang(diameter, color_1 = "black", color_2 = "white"): yin(diameter, color_1, color_2) home() left(180) yin(diameter, color_2, color_1) hideturtle() if __name__ == "__main__": yinyang(400)
e45a47d64dc34024f14eac262daa74627712b5a2
nikkokun/nlp
/nlp-02.py
697
4.34375
4
# STOP WORDS # !/anaconda/bin/python python 3 from nltk.corpus import stopwords from nltk.tokenize import word_tokenize example_sentence = "This is an example showing off stop word filtration." def main(): # main code here stop_words = set(stopwords.words("english")) print(stop_words) words = word_tokenize(example_sentence) print(words) # long method below # filtered_sentence = [] # for word in words: # if word not in stop_words: # filtered_sentence.append(word) filtered_sentence = [word for word in words if not word in stop_words] print('\t') print(filtered_sentence) if __name__ == "__main__": # main execution main()
2d473e283ea5b1adace7f70d5a433f452da96d73
CarlosG4rc/CursoPy
/Curso Python/3. Listas/list.py
554
4.15625
4
numeros = [1,2,3,4] datos = [4, "una cadena",-15,3.14,"Otra cadena"] print(datos[0]) print(datos[1]) print(datos[-2:]) print(numeros + [5,6,7,8]) pares = [0,2,4,5,8,10] print("pares incorrectos" ) print(pares) pares[3]=6 #modificar valores print("pares correctos") print(pares) pares.append(12) #agregar valores print(pares) letras=['a','b','c','d','e','f'] print(letras[:3]) letras[:3]=['x','y','z']#modificamos datos con slicing print(letras) a=[1,2,3] b=[4,5,6] c=[7,8,9] r=[a,b,c] print(r) print(r[0]) print(r[2][0])
d9cf91d569f339edcbc905ca3beb9d8aca8c24b7
someshwar123/python
/arrind.py
500
3.984375
4
#------------------------------------------------------------------------------- # Name: module4 # Purpose: # # Author: Somesh # # Created: 01/08/2018 # Copyright: (c) Somesh 2018 # Licence: <your licence> #------------------------------------------------------------------------------- array = [] n = int(raw_input('Enter how many elements you want: ')) for i in range(0, n): x = raw_input('Enter the numbers into the array: ') array.append(x) print(array[i],i)
b101b01f621e02578cd918ee672c7524e484d57b
AngelRem1/TXT_test
/main.py
2,565
4.3125
4
# Name : Angel Remigio # SSID : 1848012 # Assignment #: 3 # Submission Date : 10/26/2020 # # Description of program : # Single Player Tic Tac Toe against a computer from random import randint # void function to print the board state the_board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]] # Printing the function def print_board(board): # prints the current board for row in range(len(board)): for col in range(len(board[row])): print(board[row][col], end="") print() print("the board as rows and columns ") # Checking to see if there are 3 in a row within the rows def check_rows(board): for row in range(len(board)): if board[row][0] == board[row][1] == board[row][2] != "-": return True return False # Checking to see if there are 3 in a row within the columns def check_cols(board): for cols in range(len(board)): if board[0][cols] == board[1][cols] == board[2][cols] != "-": return True return False # Checking to see if there are 3 in a row when it comes to diag 1 def check_diag1(board): if board[0][0] == board[1][1] == board[2][2] != "-": return True return False # Checking to see if there are 3 in a row when it comes to diag 2 def check_diag2(board): if board[0][2] == board[1][1] == board[2][0] != "-": return True return False # Function to detect computer's move def move(board): while True: ai_x = randint(0, 2) ai_y = randint(0, 2) if board[ai_x][ai_y] == "-": board[ai_x][ai_y] = "0" break # Function to check if there is a winning state on the board def check_ifwin(board): if check_rows(board): return True if check_cols(board): return True if check_diag1(board): return True if check_diag2(board): return True return False # Reruns reiterations of the code in which the player and the computer make moves while True: print_board(the_board) move(the_board) print("use coordinates such as 00,01,02 and etc in order to move") user_move = input() x = int(user_move[0]) y = int(user_move[1]) the_board[x][y] = "X" if check_ifwin(the_board): print_board(the_board) print("We have a winner") print("Do you wanna try again? Type yes or no") response = input() if response == "yes" or response == "Yes" or response == "Y": the_board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]] else: break
f0280f9a182c0ecf15cc710cf6ac125e6af5f81d
GOUTHAMRAEES/python
/python/palindrome.py
170
4
4
a=input("Enter the string") b="" for i in range(len(a)-1,-1,-1): b=b+a[i] if(b==a): print("it is palindrome") else: print("Not a palindrome")
cbb6f70c92d9cad7a7b505f1ead50ca138a13386
IlkoAng/-Python-Fundamentals-Softuni
/05. Lists Advanced Exercises/04. Office Chairs.py
463
3.671875
4
number = int(input()) free_chairs = 0 isEnough = True for num in range(1, number+1): room = input().split() chairs = room[0] people = int(room[1]) diff = abs(len(chairs) - people) if len(chairs) > people: free_chairs += len(chairs) - people elif len(chairs) < people: print(f"{diff} more chairs needed in room {num}") isEnough = False if isEnough: print(f"Game On, {free_chairs} free chairs left")
63c1b0a0fa507248f8b064fe6c98ad4049e48697
bus1029/HackerRank
/Statistics_10days/Day4/GeometricDistribution2.py
754
3.65625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT # Task # The probability that machine produces a defective product is 1/3. # What is the probability that the 1st defect is found during the first 5 inspections? # 첫 5개 검사에서 첫 번째 결함이 발견될 확률은 얼마입니까? # # => 첫 5개의 검사에서 최소 하나의 결함이 발견될 확률은 얼마입니까? # 첫 번째에서 발견될 확률 + 두 번째에서 발견될 확률 + 세 번째에서 발견될 확률 + 네 번째에서 발견될 확률 + 다섯 번째에서... numer, denom = list(map(int, input().split())) inspect = int(input()) px = numer / denom print(round(sum([((1-px)**(i-1))*px for i in range(1, inspect+1)]), 3)) # 혹은
70e50a44d8497d7b18d8c9e0f2b78eefc99bbc19
arshdeepsinghsandhu/lab7
/task.py
159
3.53125
4
import math class cal(): def __init__(self,a,b): self.a = a self.b = b def sum(self): return self.a + self.b inst = cal(2,3) print(inst.a + inst.b)
a3401d21d8eb870b808d6ae62353f87e3f8b67e4
gregorybrooks/BetterQueryBuilder2
/programfiles/get_noun_phrases_from_spacy_daemon.py
687
3.5625
4
import spacy import sys """Calls spaCy to extract noun_phrases from a string. Pass the string to extract from via STDIN. This script returns the extracted phrases in STDOUT. """ # Load English tokenizer, tagger, parser, NER and word vectors nlp = spacy.load("en_core_web_sm") # Get query from stdin: while True: text = "" for line in sys.stdin: if line.startswith('EOF'): sys.exit(0) elif line.startswith('EOD'): break text += line doc = nlp(text) nouns = [] nouns = [chunk.text.strip() for chunk in doc.noun_chunks] for a in set(nouns): print(a) print('EOL') sys.stdout.flush() sys.exit(0)
7ed47818311ed2b45e245341dc907f6f7bed9c97
mehuman/GitGeo
/geolocation.py
1,458
3.921875
4
"""geolocation functionality.""" from geographies_list import ( ALL_COUNTRIES, CITY_COUNTRY_DICT, CODE_COUNTRY_DICT, STATE_ABBREV, STATE_NAMES, ) def get_country_from_location(location_string): """Return country (Hungary, United States, etc) from user location text This function implements an admittedly imprecise text matching method. Args: location_string: a text containing user-supplied location Return: str: a country """ country = "None" if location_string is None: country = "None" else: # Loop through different typical separators of city, country, etc. for separator in [",", " "]: # Check different positions of the token for position in [-1, 0]: pieces = location_string.split(separator) token = pieces[position].strip() # Use returns as a way of exiting double loop if token in ALL_COUNTRIES: # pylint: disable=no-else-return return token elif token in CITY_COUNTRY_DICT.keys(): return CITY_COUNTRY_DICT[token] elif token in CODE_COUNTRY_DICT.keys(): return CODE_COUNTRY_DICT[token] elif token in STATE_NAMES or token in STATE_ABBREV: return "United States" # if no matches are found, will return "none" return country
1e5fa231d85312cd8f076c1c30477f061871f7e3
kimjane93/udemy-python-100-days-coding-challenges
/day-3-adventure-game/adventuregame.py
926
4.21875
4
print("Welcome to Treasure Island.\nYou're mission is to find the treasure.\nYou're at a cross road.") first_choice = input("Where do you want to go? Type 'left' or 'right'\n") if first_choice == "right": print("Game Over") else: print("You come to a lake.\nThere is an island in the middel of the lake.") second_choice = input("Type 'wait' to wait for a boat. Type 'swim' to swim across.\n") if second_choice == "swim": print("Game Over") else: print("You arrive at the island unharmed. \nThere is a house with 3 doors.\nOne red, one yellow and one blue.") third_choice = input("Which color do you choose?\n") if third_choice == "red": print("Game Over") elif third_choice == "blue": print("Game Over") elif third_choice == "yellow": print("You Win!") else: print("User Error - Game Lost By Default")
940a48063b1d87ba947ae77e2d196408a92e4f72
AmitGupta700/Python
/set of first N prime no.py
227
3.703125
4
n=int(input("Enter The n prime no: ")) count=0 i=1 l=[] while count<n: for d in range(2,i,1): if i%d==0: i+=1 else: l.append(i) i+=1 count+=1 s=set(l) print(s)
c499117826e31a4c9354311775bd645b3cc60910
Mr-Nicholas/udacity-studies
/python-intro/secret-names/secret-names.py
605
3.875
4
import os def rename_files(): # get all the names from folder path file_directory = os.listdir("/Users/Heath/Downloads/prank") saved_path = os.getcwd() print saved_path os.chdir("/Users/Heath/Downloads/prank") saved_path = os.getcwd() print saved_path # for each file, remove the integers and save the new file for file_name in file_directory: os.rename(file_name, file_name.translate(None, "0123456789")) print file_name os.chdir(saved_path) print os.getcwd() # reorder the items by letter rename_files()
d838d1c8c89173a94d58006819b878398d0fa841
gentle-potato/Python
/17_exception/exception_처리.py
2,296
3.953125
4
# 예외 발생 상황 처리 # ZeroDivisionError: division by zero # print(10/0) try : print(10/0) # print(10/2) except : print('ZeroDivisionError') finally : # 오류 발생 여부와 관계 없이 항상 나오는 부분 print('나누기') # 예외처리 클래스 지정 try : print(10/0) # print(10/2) except Exception : print('ZeroDivisionError') finally : print('나누기') try : print(10/0) # print(10/2) except ZeroDivisionError : print('0으로 나누었네요...') finally : print('나누기') try : print(10/0) # print(10/2) except ZeroDivisionError as e : print('0으로 나누었네요... : ', e) # 에러에 대한 구체적인 설명 : 별칭 e 사용 finally : print('나누기') # TypeError: can only concatenate str (not "int") to str # print('age=' + 23) try : print('age=' + 23) except TypeError as e : print(e) # 예외처리를 여러 개 지정하더라도 가장 먼저 나온 에러만 처리 try : print('age=' + 23) print(10 / 0) except ZeroDivisionError as e: print('0으로 나누었네요... : ', e) # 가장 먼저 발생한 오류에 대한 것만 반환 except TypeError as e : print(e) # 여러 개의 예외처리 : 함께 처리 가능 try : print('age=' + 23) print(10 / 0) except (ZeroDivisionError, TypeError) as e: print(e) # try : num = int(input('input number : ')) except ValueError : print('정수가 아닙니다.') else : # 에러가 아니면 실행 print(num) finally : print('종료') try : f = open('testex.txt', 'r') except FileNotFoundError : pass else : data = f.read() print(data) f.close() finally : print('종료') # NameError: name 'x' is not defined # print(x) # ValueError: incomplete format # a = 100 # print("%d%" % a) # SyntaxError: invalid syntax # if x>10 # print('Kim') # IndexError: list index out of range # a = [1, 2, 3] # print(a[3]) # unboundLocalError # def add() : # a += 1 # ModuleNotFoundError: No module named 'modd' # import modd # FileNotFoundError: [Errno 2] No such file or directory: 'readfile.txt' # f = open('readfile.txt', 'r') # data = f.read() # OSError: [Errno 22] Invalid argument: 'd:\readfile.txt' # f = open('d:\readfile.txt', 'r')
79b3185e486b884470c1641b6c89eda1dfa8443d
Frankiee/leetcode
/dp/140_word_break_ii.py
3,069
3.765625
4
# https://leetcode.com/problems/word-break-ii/ # 140. Word Break II # History: # Facebook # 1. # Aug 18, 2019 # 2. # Mar 12, 2020 # 3. # Apr 24, 2020 # Given a non-empty string s and a dictionary wordDict containing a list of # non-empty words, add spaces in s to construct a sentence where each word # is a valid dictionary word. Return all such possible sentences. # # Note: # # The same word in the dictionary may be reused multiple times in the # segmentation. # You may assume the dictionary does not contain duplicate words. # Example 1: # # Input: # s = "catsanddog" # wordDict = ["cat", "cats", "and", "sand", "dog"] # Output: # [ # "cats and dog", # "cat sand dog" # ] # Example 2: # # Input: # s = "pineapplepenapple" # wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] # Output: # [ # "pine apple pen apple", # "pineapple pen apple", # "pine applepen apple" # ] # Explanation: Note that you are allowed to reuse a dictionary word. # Example 3: # # Input: # s = "catsandog" # wordDict = ["cats", "dog", "sand", "and", "cat"] # Output: # [] class SolutionDP(object): def _dfs(self, s, wordDict, i, curr, ret, dp): if i == -1: ret.append( " ".join(reversed(curr)) ) return for w in wordDict: if ((i - len(w) == -1 or (i - len(w) >= 0 and dp[i - len(w)])) and s[i - len(w) + 1:i + 1] == w): self._dfs(s, wordDict, i - len(w), curr + [w], ret, dp) def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ dp = [False] * len(s) for i in range(len(s)): for w in wordDict: if (i - len(w) == -1 or dp[i - len(w)]) and s[i - len(w) + 1:i + 1] == w: dp[i] = True break if not dp[-1]: return [] ret = [] self._dfs(s, wordDict, len(s) - 1, [], ret, dp) return ret class SolutionDPSet(object): def _dfs(self, s, wordDict, ret, curr_result, curr_idx, dp): if curr_idx < 0: ret.append(curr_result) return for w_i in dp[curr_idx]: self._dfs( s, wordDict, ret, wordDict[w_i] + " " + curr_result if curr_result else wordDict[w_i], curr_idx - len(wordDict[w_i]), dp, ) def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ dp = [set() for _ in range(len(s))] for i in range(len(s)): for w_i, w in enumerate(wordDict): if ((i - len(w) == -1 or (i >= len(w) and dp[i - len(w)])) and s[i - len(w) + 1:i + 1] == w): dp[i].add(w_i) if not dp[-1]: return [] ret = [] self._dfs(s, wordDict, ret, "", len(s) - 1, dp) return ret
542c42f76a11656ad3652fa1e995be5e3519bc1f
vincentzhang/coding-practice
/linked_list/node.py
2,683
3.828125
4
# My own class Node(object): def __init__(self, key=None, next_ptr=None): self.key = key self.next_ptr = next_ptr def getKey(self): return self.key def getNext(self): return self.next_ptr def setKey(self, key): self.key = key def setNext(self, ptr): self.next_ptr = ptr def __repr__(self): # overwrite return str(self.key) class LinkedList(object): def __init__(self, head=None): self.head = head def isEmpty(self): return self.head == None def add(self, item): temp = Node(item) temp.setNext(self.head) self.head = temp def search(self, key): current = self.head while current is not None and current.getKey() != key: current = current.getNext() if current is None: return False else: return current def size(self): current = self.head count = 0 while current is not None: count += 1 current = current.getNext() return count def getItem(self, key): current = self.head while current is not None and current.getKey() != key: current = current.getNext() if current is None: return "Not found" else: return current def remove(self, key=None): if key is None: self.head = self.head.getNext() else: current = self.head previous = None while current is not None and current.getKey() != key: previous = current current = current.getNext() # now the item has been found if current is None: return if previous == None: # this item is the head self.head = current.getNext() else: previous.setNext(current.getNext()) def printList(self): head = self.head while head is not None: print head.getKey() head = head.getNext() if __name__ == '__main__': new_node = Node(12) print new_node.getKey() print type(new_node.getKey()) # print new_node new_list = LinkedList() print "Is the new_list empty?", new_list.isEmpty() new_list.add(21) new_list.add(14) new_list.add(16) new_list.add(26) new_list.add(-2) new_list.printList() print new_list.size() #result = new_list.search(14) #print result new_list.remove(14) new_list.printList() print new_list.size() print "Is the new_list empty?", new_list.isEmpty()
990293afbcb90ebae7f66a7775cadf8894eacec7
iniudin/baris-kode
/python/tgs_tabungan.py
777
3.6875
4
""" Goal: Membuat program peritungan tabungan input: tahun ouput: jumlah tabungan tiap bulan dan tahun. """ # Preparation tahun : int bulan : int = 12 # Diasumsikan sebulan ada 4 minggu minggu : int = 4 # Setoran tetap adalah Rp 50.000 setoran : int = 50000 # Mula-mula tabungan adalah 0 tabungan = 0 tahun = int(input("Masukkan jangka kamu menabung (tahun): ")) # Looping 1, adalah lama user menabung (dlm tahun). for thn in range(1, tahun+1): # Looping 2, untuk menampilkan tabungan per bulan. for bln in range(1, bulan+1): # Looping 3, menambahkan tabungan dari setoran. for _ in range(minggu): tabungan += setoran print(f"- Bulan ke {bln} adalah Rp {tabungan}") print(f"Tabungan tahun ke {thn} adalah Rp {tabungan}")
0380de1ab287baae48c99551e02d3769b9e6c2a0
sakshi978/Competitive-Platforms
/Hackerrank/Permutation.py
713
4.1875
4
''' Question: Task You are given a string S. Your task is to print all possible permutations of size k of the string in lexicographic sorted order. Input Format A single line containing the space separated string S and the integer value k. Output Format Print the permutations of the string S on separate lines. Sample Input HACK 2 Sample Output AC AH AK CA CH CK HA HC HK KA KC KH Explanation All possible size permutations of the string "HACK" are printed in lexicographic sorted order. ''' from itertools import permutations string,size = input().split() size = int(size) lst = list((permutations(string,size))) lst.sort() for i in range(len(lst)): string = ''.join(lst[i]) print(string)
b4f8a0e75abd8d06c43c5852ce417e412b95a98f
eungju/kata
/CodeDojo/srp.py
1,499
3.765625
4
import unittest WIN = 1 LOSE = -1 TIE = 0 class Rock: def match(self, other): return other.matchWithRock() def matchWithPaper(self): return WIN def matchWithRock(self): return TIE def matchWithScissors(self): return LOSE ROCK = Rock() class Scissors: def match(self, other): return other.matchWithScissors() def matchWithRock(self): return WIN def matchWithScissors(self): return TIE def matchWithPaper(self): return LOSE SCISSORS = Scissors() class Paper: def match(self, other): return other.matchWithPaper() def matchWithScissors(self): return WIN def matchWithPaper(self): return TIE def matchWithRock(self): return LOSE PAPER = Paper() class GameTest(unittest.TestCase): def testTie(self): self.assertEquals(TIE, SCISSORS.match(SCISSORS)) self.assertEquals(TIE, ROCK.match(ROCK)) self.assertEquals(TIE, PAPER.match(PAPER)) def testWin(self): self.assertEquals(WIN, SCISSORS.match(PAPER)) self.assertEquals(WIN, ROCK.match(SCISSORS)) self.assertEquals(WIN, PAPER.match(ROCK)) def testLose(self): self.assertEquals(LOSE, SCISSORS.match(ROCK)) self.assertEquals(LOSE, ROCK.match(PAPER)) self.assertEquals(LOSE, PAPER.match(SCISSORS)) if __name__ == "__main__": unittest.main(argv=('', '-v'))
57d44fda64399e9de3e4bf10f266323f8a6e5f90
tadeze/goproject
/ds/quicksort.py
631
3.984375
4
""" Quick sort implemetnation. The idea of quick sort is to partition the whole array based on the pivot point. The pivot is selected such that the left side is less than the large side of the arra. a = [2, 8, 7,20, 12, 4] """ def quick_sort(a, l, h): if l < h: p = partition(a, l, h) quick_sort(a, l, p -1) quick_sort(a, p+1, h) def partition(a, l, h): i = l - 1 for j in range(l, h): if a[j] < a[h] : i += 1 a[i], a[j] = a[j], a[i] a[i+1], a[h] = a[h], a[i+1] return i + 1 a = [2, 9, 1,10, 3,9] quick_sort(a, 0, len(a) - 1) print(a)
179c75625f4e3a25ce879ad6400e4ef1c4d6843a
Acejoy/LeetcodePrep
/62. Unique Paths/pythonSolution.py
234
3.71875
4
import math def uniquePaths(m,n): return math.factorial(m+n-1-1)//(math.factorial(m-1)*math.factorial(n-1)) if __name__ == "__main__": rows = 3 cols = 7 print(f'The no of unique paths are:{uniquePaths(rows,cols)}.')
afa4982d7020e4059ff660e19128842c93c00e58
rashi174/Codewars
/iq_test.py
727
3.640625
4
def iq_test(string): #your code here numbers = string.split() noOdds = 0 noEvens = 0 position = 0 for i in range (0, len(numbers)): if(int(numbers[i]) % 2 == 0): noEvens = noEvens + 1 else: noOdds = noOdds + 1 if(noOdds > noEvens): for i in range(0, len(numbers)): if (int(numbers[i]) % 2 == 0): position = i+1 else: for i in range(0, len(numbers)): if (int(numbers[i]) % 2 != 0): position = i+1 return position """ Best approach iq_test = lambda numbers: (lambda l: l.index(sum(l)==1)+1)([n%2 for n in map(int, numbers.split())]) """
9b394726a4aa21e3bb99afccafedd948d31851e7
ypliu/leetcode-python
/src/044_wildcard_matching/044_wildcard_matching_DpTable.py
1,093
3.5
4
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if None == s: return None == p elif None == p: return False if 0 == len(p): return 0 == len(s) return self.checkDp(s, p) def checkDp(self, s, p): table_dp = [[False for j in xrange(len(p)+1)] for i in xrange(len(s)+1)] table_dp[0][0] = True for j in xrange(len(p)): table_dp[0][j+1] = ('*' == p[j] and table_dp[0][j]) for i in xrange(len(s)): for j in xrange(len(p)): if '?' == p[j] or s[i] == p[j]: table_dp[i+1][j+1] = table_dp[i][j] elif '*' == p[j]: table_dp[i+1][j+1] = table_dp[i+1][j] or table_dp[i][j+1] return table_dp[len(s)][len(p)] # debug s = Solution() print s.isMatch("aa", "a") print s.isMatch("aa", "*") print s.isMatch("cb", "?a") print s.isMatch("adceb", "*a*b") print s.isMatch("acdcb", "a*c?b") print s.isMatch("", "*")
ff4c16a0ff8ededd95e7773f6c76adb1dddf80f7
CryFR/dz
/PyDZ/Task 4/str_op.py
230
3.671875
4
s = "У лукоморья 123 дуб зеленый 456" if 'я' in s: print(s.index('я', 1)) print(s.count('у')) if s.isdigit(): print(s.upper()) if len(s) > 4: print(s.lower()) print(s.replace(s[0], 'О'))
00665b71ffc7a3fa1d85a794fc3f49037a0c62f1
philipwoodward/Practicals
/Prac01/tarrifElectricityBillEstimator.py
710
4.15625
4
""" Program to calculate and display the electricity bill. Inputs will be price per kWh in cents, daily use in kWh and the number of days in the billing period """ TARIFF_11 = 0.244618 TARIFF_31 = 0.136928 tariff = 1 while tariff == 1: tariff = int(input("Enter which tariff please - 11 or 31: ")) if tariff == 11: tariff = TARIFF_11 elif tariff == 31: tariff = TARIFF_31 else: tariff = 1 print(tariff) daily_use = float(input("Enter the kilowatt hours of electricity use per day: ")) number_days = int(input("Enter the number of days in the billing period: ")) print("The estimated electricity bill is $", round(tariff * daily_use * number_days,2)) print("Thank you.")
193ab79cf396a5fceb5e5fe05740850709b83a13
pmsorhaindo/adventOfCode2019
/day5/day5.py
6,084
3.59375
4
f = open('input.txt') line = f.readline() ADD_OP_CODE = 1 MULT_OP_CODE = 2 INPUT_OP_CODE = 3 OUTPUT_OP_CODE = 4 JMP_IF_TRUE_OP_CODE = 5 JMP_IF_FALSE_OP_CODE = 6 LESS_THAN_OP_CODE = 7 EQUALS_OPCODE = 8 def load_program(): return [int(s) for s in line.split(',')] def ammend_program(noun, verb, program_list): program_list[1] = noun program_list[2] = verb return program_list def run_add_operation(program_list, instruction_pointer, parsed_instruction): a = program_list[program_list[instruction_pointer+1]] if int(parsed_instruction[2]) == 0 else program_list[instruction_pointer+1] b = program_list[program_list[instruction_pointer+2]] if int(parsed_instruction[1]) == 0 else program_list[instruction_pointer+2] program_list[program_list[instruction_pointer+3]] = a + b return (program_list, 4, False) def run_mult_operation(program_list, instruction_pointer, parsed_instruction): a = program_list[program_list[instruction_pointer+1]] if int(parsed_instruction[2]) == 0 else program_list[instruction_pointer+1] b = program_list[program_list[instruction_pointer+2]] if int(parsed_instruction[1]) == 0 else program_list[instruction_pointer+2] program_list[program_list[instruction_pointer+3]] = a * b return (program_list, 4, False) def run_input_operation(program_list, instruction_pointer, parsed_instruction): program_list[program_list[instruction_pointer+1]] = 5 return (program_list, 2, False) def run_output_operation(program_list, instruction_pointer, parsed_instruction): print('>>', program_list[program_list[instruction_pointer+1]]) return (program_list, 2, False) def run_if_true_operation(program_list, instruction_pointer, parsed_instruction): condition = program_list[program_list[instruction_pointer+1]] if int(parsed_instruction[2]) == 0 else program_list[instruction_pointer+1] location = program_list[program_list[instruction_pointer+2]] if int(parsed_instruction[1]) == 0 else program_list[instruction_pointer+2] if condition != 0: return (program_list, location, True) return (program_list, 3, False) def run_if_false_operation(program_list, instruction_pointer, parsed_instruction): condition = program_list[program_list[instruction_pointer+1]] if int(parsed_instruction[2]) == 0 else program_list[instruction_pointer+1] location = program_list[program_list[instruction_pointer+2]] if int(parsed_instruction[1]) == 0 else program_list[instruction_pointer+2] if condition == 0: return (program_list, location, True) return (program_list, 3, False) def run_if_less_operation(program_list, instruction_pointer, parsed_instruction): first = program_list[program_list[instruction_pointer+1]] if int(parsed_instruction[2]) == 0 else program_list[instruction_pointer+1] second = program_list[program_list[instruction_pointer+2]] if int(parsed_instruction[1]) == 0 else program_list[instruction_pointer+2] if first < second: if int(parsed_instruction[0]) == 0: program_list[program_list[instruction_pointer+3]] = 1 else: program_list[instruction_pointer+3] = 1 else: if int(parsed_instruction[0]) == 0: program_list[program_list[instruction_pointer+3]] = 0 else: program_list[instruction_pointer+3] = 0 return (program_list, 4, False) def run_if_equal_operation(program_list, instruction_pointer, parsed_instruction): first = program_list[program_list[instruction_pointer+1]] if int(parsed_instruction[2]) == 0 else program_list[instruction_pointer+1] second = program_list[program_list[instruction_pointer+2]] if int(parsed_instruction[1]) == 0 else program_list[instruction_pointer+2] print(first, second, program_list[program_list[instruction_pointer+3]], parsed_instruction[0], program_list) if first == second: if int(parsed_instruction[0]) == 0: program_list[program_list[instruction_pointer+3]] = 1 else: program_list[instruction_pointer+3] = 1 else: if int(parsed_instruction[0]) == 0: program_list[program_list[instruction_pointer+3]] = 0 else: program_list[instruction_pointer+3] = 0 return (program_list, 4, False) def run_operation_at_pointer(program_list, instruction_pointer): print(program_list[instruction_pointer], instruction_pointer, program_list) parsed_instruction = list(str(program_list[instruction_pointer])) while len(parsed_instruction) != 5: parsed_instruction.insert(0,0) if(program_list[instruction_pointer] % 100 is ADD_OP_CODE): return run_add_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is MULT_OP_CODE): return run_mult_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is INPUT_OP_CODE): return run_input_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is OUTPUT_OP_CODE): return run_output_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is JMP_IF_TRUE_OP_CODE): return run_if_true_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is JMP_IF_FALSE_OP_CODE): return run_if_false_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is LESS_THAN_OP_CODE): return run_if_less_operation(program_list, instruction_pointer, parsed_instruction) if(program_list[instruction_pointer] % 100 is EQUALS_OPCODE): return run_if_equal_operation(program_list, instruction_pointer, parsed_instruction) def process_program(program_list, instruction_pointer): program_list, param_jump, absolute_jump = run_operation_at_pointer(program_list, instruction_pointer) if absolute_jump: instruction_pointer = param_jump else: instruction_pointer = instruction_pointer + param_jump if (program_list[instruction_pointer] is 99): return program_list[0] else: return process_program(program_list, instruction_pointer) process_program(load_program(), 0)
5d13ff162ea2edae798b43a18bc516e824d0d752
jangui/Implementations
/problems/leetcode/1441-buildArrayStack/Solution.py
847
3.546875
4
class Solution: def __init__(self): pass def buildArray(self, target: List[int], n: int) -> List[str]: """ :param target: list of ints we want to build using stack :param n: limit of iteration :return: list of stack operations """ # edge case if len(target) == 0: return [] solution = [] current_ind = 0 current_val = target[current_ind] for i in range(1, n+1): if i == current_val: solution.append("Push") current_ind += 1 if len(target) == current_ind: return solution current_val = target[current_ind] else: solution.append("Push") solution.append("Pop") return solution
861d83f5bdc40f1c83fe96efde61b6187bf4fed3
Draymonder/Practices-on-Pyhton
/Day_7/property.py
719
3.8125
4
class Student(object): #@property装饰器将方法变成属性调用,本身又创建了另一个装饰器@score.setter,可以限制赋值,避免属性的暴露 @property def score(self): return self._score @property def name(self): return "chengkang" @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value s = Student() s.score = 60 #s.score = "2" #报错 print(s.name) #s.name = "CK" #报错,未定义setter方法。这里@property起到了只读的作用
eed1bc0ea3f640ea3422f794010bf3293dde4af1
franklingu/leetcode-solutions
/questions/random-pick-index/Solution.py
1,116
3.96875
4
""" Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Note: The array size can be very large. Solution that uses too much extra space will not pass the judge. Example: int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1); """ class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: choice = -1 count = 0 for i, e in enumerate(self.nums): if e != target: continue if random.randint(0, count) == 0: choice = i count += 1 return choice # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target)
4d27abec8c3be964b81eec05cd9b5c00ac22faca
jsonkao/mks22
/hw/mks22-hw0404.py
1,274
3.859375
4
# Problem 5: def replaceAll(astring,lookfor,replaceWith): pos = -1 for c in astring: pos += 1 if lookfor == astring[pos:pos + len(lookfor)]: astring = astring[:pos] + replaceWith + astring[pos+len(lookfor):] return astring # Test results: # 1. Pass # 2. Does not pass. # 3. Pass # Problem 6: def is_prime(n): if n < 2: return False elif n == 2 or n == 3: return True elif n % 2 == 0: return False for i in range(3,int(n**0.5) + 1,2): if n % i == 0: return False return True def primesUnder(n): if n <= 2: return "There are no primes less than " + str(n) + "." primes = [] for i in range(2,n): if is_prime(i): primes.append(i) if len(primes) == 1: return "The prime less than " + str(n) + " is 2." pt1 = "The primes less than " + str(n) + " are " pt2 = '' for elem in primes: if elem == primes[-1]: pt2 += str(elem) + '.' continue pt2 += str(elem) + ' and ' return pt1 + pt2 # Test results: # 1. Pass # 2. Pass # 3. Pass # 4. Pass # Problem 7: def countWords(s): return len(s.split()) # Test results: # 1. Pass # 2. Pass # 3. Pass # 4. Pass # 5. Pass
36869f1f039ab14be6e656c223e9bdcdfac86a58
heitorchang/learn-code
/pangloss/code/interview/sorting/radix_sort.py
483
3.984375
4
# Algorithms (Cormen) from operator import itemgetter def radix_sort(lst): """Sort a list of integers, first sorting by the ones place, then the tens, and so on""" # set up the list, separating numbers into digits lst_str = list(map(str, lst)) len_longest = len(max(lst_str, key=len)) lst_pad = [s.zfill(len_longest) for s in lst_str] for i in range(len_longest - 1, -1, -1): lst_pad.sort(key=itemgetter(i)) return list(map(int, lst_pad))
619ed2a92374dfbfd07be06c45b9a7e5e5a41560
wan-catherine/Leetcode
/problems/N2594_Minimum_Time_To_Repair_Cars.py
841
3.875
4
import math from typing import List """ Key point is : All the mechanics can repair the cars simultaneously. So for some times, we can calculate the cars all mechanics together can repair. If the number of cars >= given cars , then we reduce the times, or we increase the times. So perfect binary search . """ class Solution: def repairCars(self, ranks: List[int], cars: int) -> int: l, r = 1, 100 * 10 ** 6 * 10 ** 6 + 1 def check(mid): cur = 0 for r in ranks: cur += int(math.sqrt(mid / r)) if cur >= cars: return True return False while l < r: mid = (r - l) // 2 + l # print(r, l, mid) if check(mid): r = mid else: l = mid + 1 return l
44e95c72e35ddf07eb964fe944f4721e51c2956a
paulyun/python
/Schoolwork/Python/In Class Projects/3.24.2016/test.py
702
4.09375
4
current_tuition = 15000 for p in range(1,11): increase_rate = float(input("What is your tuition's increase rate for year")) current_tuition = current_tuition + current_tuition*increase_rate print("The Current Tuition for year ", p, "is $", format(current_tuition, '.2f')) current_tuition = 15000 increase_rate = float(input("What is your tuition's increase rate for year")) current_tuition = current_tuition + current_tuition*increase_rate print("The cost of your tuition is", current_tuition) for p in range(1,10): increase_rate = increase_rate + 0.05 current_tuition = current_tuition + increase_rate print("The cost of your tuition is", current_tuition)
ff8851fe44f1205398b4874fcbc89bd1422fe71a
Frky/p-euler
/src/p54.py
9,255
4.0625
4
#-*- coding: utf-8 -*- from src.p import Problem class Hand(object): """ Object representing a poker hand (i.e. five cards) Contains methods to evaluate the hand and to compare to hands. """ def __init__(self, hand): # a card is a tuple (value, color) self.hand = hand # set of possible values self.values = ['0', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] # set of possible colors self.colors = ['S', 'H', 'C', 'D'] # set of possible scores self.scores = ['H', 'P', 'TP', 'T', 'Fl', 'Fo', 'Fu', 'S', 'SFl', 'RFl'] # sorting hand self.sort() self.highest = self.hand[0] self.lowest = self.hand[1] # definition of some fields for more info about the value self.full_cards = list() self.four_of = '' self.three_of = '' self.two_pairs_of = list() self.pair_of = list() return def highest_value(self): return self.highest[0] def lowest_value(self): return self.lowest[0] def sort(self): self.hand = sorted(self.hand, key=lambda a: -self.values.index(a[0])) def is_pair(self): for card in self.values: if [c[0] for c in self.hand].count(card) == 2: self.pair_of = card return True return False def is_two_pairs(self): pairs = list() for card in self.values: if [c[0] for c in self.hand].count(card) == 2: pairs.append(card) if len(pairs) == 2: self.two_pairs_of = sorted(pairs, key=lambda a: self.values.index(a)) return True else: return False def is_three(self): for card in self.values: if len([c for c in self.hand if c[0] == card]) == 3: self.three_of = card return True return False def is_flush(self): return [color for card, color in self.hand].count(self.hand[0][1]) == len(self.hand) def is_four(self): for card in self.values: if [c[0] for c in self.hand].count(card) == 4: self.four_of = card return True return False def is_full(self): for card in self.values: if [c[0] for c in self.hand].count(card) == 3: second_card = [c[0] for c in self.hand if c[0] != card][0] if [c[0] for c in self.hand].count(second_card) == 2: self.full_cards = [card, second_card] return True return False def is_straight(self): ref_ind = self.values.index(self.hand[0][0]) for k, card in enumerate(self.hand): if -k != self.values.index(card[0]) - ref_ind: return False return True # it is a straight if all values are different and there is a gap of 4 values between the highest and the lowest value return (len(list(set([c[0] for c in self.hand]))) == len(self.hand) and self.values.index(self.highest_value()) - self.values.index(self.lowest_value()) == 4) def is_straight_flush(self): # it is a straight flush if it is a flush and all colors are the same return self.is_straight() and len([c for c in self.hand if c == self.hand[0][1]]) == len(self.hand) def is_royal_flush(self): # it is a royal flush if it is a flush and the highest card is an A return self.is_straight_flush() and self.highest_value() == self.values[-1] def evaluate(self): if self.is_royal_flush(): return 'RFl' elif self.is_straight_flush(): return 'SFl' elif self.is_straight(): return 'S' elif self.is_full(): return 'Fu' elif self.is_four(): return 'Fo' elif self.is_flush(): return 'Fl' elif self.is_three(): return 'T' elif self.is_two_pairs(): return 'TP' elif self.is_pair(): return 'P' else: return 'H' def __lt__(self, other_hand): hand_values = (self.scores.index(self.evaluate()), self.scores.index(other_hand.evaluate())) if hand_values[0] < hand_values[1]: return True elif hand_values[0] > hand_values[1]: return False else: if hand_values[0] == 0: return self.values.index(self.highest_value()) < self.values.index(other_hand.highest_value()) elif hand_values[0] == 1: if self.values.index(self.pair_of) < self.values.index(other_hand.pair_of): return True if self.values.index(self.pair_of) > self.values.index(other_hand.pair_of): return False elif self.highest_value() != self.pair_of: return self.values.index(self.highest_value()) < self.values.index(other_hand.highest_value()) else: raise NotImplemented else: raise NotImplemented class p54(Problem): """ In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: High Card: Highest value card. One Pair: Two cards of the same value. Two Pairs: Two different pairs. Three of a Kind: Three cards of the same value. Straight: All cards are consecutive values. Flush: All cards of the same suit. Full House: Three of a kind and a pair. Four of a Kind: Four cards of the same value. Straight Flush: All cards are consecutive values of same suit. Royal Flush: Ten, Jack, Queen, King, Ace, in same suit. The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on. Consider the following five hands dealt to two players: Hand Player 1 Player 2 Winner 1 5H 5C 6S 7S KD 2C 3S 8S 8D TD 2 Pair of Fives Pair of Eights 2 5D 8C 9S JS AC 2C 5C 7D 8S QH 1 Highest card Ace Highest card Queen 3 2D 9C AS AH AC 3D 6D 7D TD QD 2 Three Aces Flush with Diamonds 4 4D 6S 9H QH QC 3D 6D 7H QD QS 1 Pair of Queens Pair of Queens Highest card Nine Highest card Seven 5 2H 2D 4C 4D 4S 3C 3D 3S 9S 9D 1 Full House Full House With Three Fours With Three Threes The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner. How many hands does Player 1 win? """ def __init__(self, id): self.data = list() return super(p54, self).__init__(id) def parse_file(self, file_path): with open(file_path, 'r') as f: for line in f.readlines(): cards = line[:-1].split(" ") hand_p1 = list() hand_p2 = list() for i, card_colored in enumerate(cards): card = card_colored[0] color = card_colored[1] if i < 5: hand_p1.append((card, color)) else: hand_p2.append((card, color)) self.data.append((hand_p1, hand_p2)) def solve(self): self.parse_file("data/p54.txt") res = 0 for nround in self.data: hand_p1 = Hand(nround[0]) hand_p2 = Hand(nround[1]) if hand_p1 > hand_p2: res += 1 return res
966fbf4d60cff653a3b1851dc9ee7289b5bff448
xuezhizeng/hwang_robot_works
/RIK_simulator/src/lbd_playback/bin/MikesToys/timer.py
1,551
3.578125
4
# -*- coding: utf-8 -*- import time def ms(f): return round(f,9) class Timer(): def __init__(self, _name="Timer"): self.name = _name self.count = 0 self.total = 0 self.min = -1 self.max = -1 self.create = time.time() self.lastEnd = -1 self.lastStart = -1 def start(self): t = time.time() self.lastStart = t def end(self): e = time.time() dur = e - self.lastStart self.lastEnd = e if (self.min < 0) or (self.min > dur): self.min = dur if dur>self.max: self.max = dur self.count += 1 self.total += dur def stop(self): self.end() def __repr__(self): if self.count > 1: str = "<Timer %s(%g sec/%d) Avg:%g Elap:%g range[%g %g]>" % (self.name,ms(self.total),self.count, ms(float(self.total)/float(self.count)) if self.count>0 else 0, ms(self.lastEnd - self.create), ms(self.min), ms(self.max) ) elif self.count==1: str = "<Timer %s(%g sec/%d)>" % (self.name,ms(self.total),self.count) else: str = "<Timer %s (0)>" % (self.name) return str def totalString(self): return "<Timer %s (%g s)>" % (self.name,self()) def __call__(self): """ :return: average time (in milliseconds) """ return ms(float(self.total)/float(self.count))
0013c9ea1ddc3f662af8f2ca4a9eda65e3ec554c
Naimulnobel/python-learning
/ignorcasesensitive.py
262
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 20 15:03:32 2019 @author: Student mct """ import re r = re.compile(r'nobel', re.I) m=r.search('nobel is a programmer').group() print(m) search1=r.search('Nobel is a programmer').group() print(search1)
af953c5aea0480c3529d362a062b76ff9e86f23f
eessm01/100-days-of-code
/python_para_todos_p2/paquete/subpaquete/moduloo.py
895
3.984375
4
""" Si los módulos sirven para organizar el código, los paquetes sirven para organizar los módulos. Los paquetes son tipos especiales de módulos (ambos son de tipo module) que permiten agrupar módulos relacionados. Mientras los módulos se corresponden a nivel físico con los archivos, los paquetes se representan mediante directorios. Para hacer que Python trate a un directorio como un paquete es necesario crear un archivo __init__.py en dicha carpeta (es raro, en este ejemplo funcionó sin el archivo __init__.py) """ def func(): print("función que viene de moduloo") def func2(): print("función 2 que viene de moduloo") class Clasee(): def __init__(self): print("constructor de Clasee (moduloo)") print("Se imprime siempre (paquete.subpaquete.moduloo)") if __name__ == '__main__': print("Esto funciona como un static void main de Java, woow")
7c71bff585dac4e841f0f0f5561dc29bb728b6c7
Coni63/CG_repo
/training/easy/the-descent.py
281
3.875
4
import sys while True: mountain_h = [int(input()) for _ in range(8)] # represents the height of one mountain, from 9 to 0. print(mountain_h.index(max(mountain_h))) # Write an action using print # To debug: # The number of the mountain to fire on.
f76d3aca1ba400957d0c1229ab9745d8e2dd3cba
kaikoh95/leetcode-solutions
/solutions/easy/q7-reverse-integer.py
610
3.515625
4
""" https://leetcode.com/problems/reverse-integer/ """ def reverse(x: int) -> int: group = list(f"{x}") if len(group) == 1 or (len(group) == 2 and group[0] == "-"): return x if group[-1] == "0": return reverse(int("".join(group[:-1]))) index = 1 if group[0] == "-" else 0 reverse_group = group[index:] reverse_group.reverse() if index == 1: reverse_group = [group[0]] + reverse_group result = int("".join(reverse_group)) return result if -2 ** 31 <= result <= (2 ** 31 - 1) else 0 print(reverse(-123)) print(reverse(901000)) print(reverse(8192))
82710975144f557d6bb09cad4e6d307e41f49d8a
Levintsky/topcoder
/python/leetcode/divide_conquer/843_guess_word.py
3,802
3.90625
4
""" 843. Guess the Word (Hard) This problem is an interactive problem new to the LeetCode platform. We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret. You may call master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters. This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead. For each test case, you have 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or less calls to master.guess and at least one of these guesses was the secret, you pass the testcase. Besides the example test case below, there will be 5 additional test cases, each with 100 words in the word list. The letters of each word in those testcases were chosen independently at random from 'a' to 'z', such that every word in the given word lists is unique. Example 1: Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"] Explanation: master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. master.guess("abcczz") returns 4, because "abcczz" has 4 matches. We made 5 calls to master.guess and one of them was the secret, so we pass the test case. Note: Any solutions that attempt to circumvent the judge will result in disqualification. """ # """ # This is Master's API interface. # You should not implement it, or speculate about its implementation # """ class Master(object): def __init__(self, secret): self.secret = secret def guess(self, word): """ :type word: str :rtype int """ res = 0 for i in range(6): if word[i] == self.secret[i]: res += 1 return res from collections import Counter class Solution(object): def findSecretWord(self, wordlist, master): """ :type wordlist: List[Str] :type master: Master :rtype: None """ def distance(word1, word2): res = 0 for i in range(6): if word1[i] == word2[i]: res += 1 return res n = len(wordlist) dis = [] for i in range(n): dis.append([-1] * n) for i in range(n): for j in range(i + 1, n): tmpd = distance(wordlist[i], wordlist[j]) dis[i][j] = tmpd dis[j][i] = tmpd candidates = [i for i in range(n)] for i in range(10): # pick the one with min(max(#group)) minidx, minmax_ = -1, n for idx in candidates: tmpdis = [dis[idx][j] for j in candidates] memo = Counter(tmpdis) tmp_max = max(memo.values()) if tmp_max < minmax_: minidx = idx minmax_ = tmp_max tmp_w = wordlist[minidx] res = master.guess(tmp_w) if res == 6: return new_candidates = [] for idx in candidates: if dis[minidx][idx] == res: new_candidates.append(idx) candidates = new_candidates if len(candidates) == 0: return if __name__ == "__main__": a = Solution() master = Master("acckzz") a.findSecretWord(["acckzz", "ccbazz", "eiowzz", "abcczz"], master)
423004e85f8ded34e4b4cc2a7aca4f78454b7af9
AbdulAbdullah/Data-Science-Journey-
/My Project/python classes/class example.py
647
3.796875
4
class Student: perc_raise = 1.6 def __init__(self, first, last, grade): self.first = first self.last = last self.grade = grade self.email = first + '.' + last + '@gmail.com' def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.grade = int(self.grade * 2) Std_1 = Student('Abdul', 'Abdullah', '60') Std_2 = Student('Aisha', 'Aliyu', '90') print(Std_1.grade) Std_1.apply_raise() print(Std_1.grade) print(Std_2.grade) Std_2.apply_raise() print(Std_2.grade) #print(Std_1.fullname()) #print(Std_2.fullname())
846f963f3b5a7c8c7c07b041f36900c8245f8fb3
MrN1ce9uy/Python
/multiply2.py
201
4.1875
4
#! usr/bin/python3 num1 = int(input('Enter the number to be multiplied: ')) num2 = int(input('Enter the number to multiply by: ')) result = num1*num2 print(num1, 'multiplied by', num2, '=', result)
bd46705fd7bb92a37d3eb7d1761a81f3cf64a672
logd-py/simple-calc
/python-progs/py_palindrome.py
242
4.34375
4
#Python program for palindrome. x=input("Enter the string to be checked for Palindrome: ") y=x[::-1] if (x==y): print("The entered string",x,"is a Palindrome.") else: print("The entered string",x,"is not a palindrome.")
2aace637253c628f725df5b6f482b3121bc57e93
yuispeuda/pro-lang
/python/calısma-soruları/liste_topla.py
320
3.703125
4
# -*- coding: cp1254 -*- def liste_topla(liste): m = 0 for i in liste: toplam = 0 if type(i) == list : for k in range(len(i)): toplam += int(i[k]) print "d[",m,"]'nin elemanlar toplam",toplam m += 1 liste_topla([[2,3,4],4,[8,9],67])
b846d9d9a0e1603f10678e9e12c606f90507600d
mssubha/practice
/practice.py
1,927
4.15625
4
def checkPossibility(nums): print(nums) non_decreasing_count = 0 max_value = 0 if len(nums) <3: return True for i in range(len(nums)-1): if max_value > 0 and i > 0: if nums[i+1] < max_value: print ("Inside 1") return False if (nums[i] > nums[i+1]): if i > 0: max_value = nums[i-1] non_decreasing_count += 1 if non_decreasing_count == 2: print ("Inside 2") return False # if nums[-3] > nums[-1]: # return False # print ("Inside 3") return True def thirdMax(nums): if len(nums) <3: return max(nums) else: unique_nums = list(set(nums)) unique_nums.sort() return (unique_nums[-3]) def canPlaceFlowers(flowerbed, n): """You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. """ plants = n if n == 0: return True if n == 1 and len(flowerbed) == 1 and flowerbed[0] == 0: return True if len(flowerbed) < (n*2-1) : return False i = 0 if (flowerbed[i] == 0 and flowerbed[1] == 0): plants -= 1 if plants == 0: return True i += 1 while i < len(flowerbed) - 2 : if (flowerbed[i-1] == 0 and flowerbed[i] == 0 and flowerbed[i+1] == 0): plants -= 1 if plants == 0: return True flowerbed[i] = 1 i += 1 if flowerbed[-1] == 0 and flowerbed[-2] == 0 : plants -= 1 return plants == 0
e2b92a81bcfd7cdd5135ed7eca22087359f428bf
Aasthaengg/IBMdataset
/Python_codes/p02711/s527728491.py
64
3.609375
4
N=input() if N.find("7")!=-1: print("Yes") else: print("No")
454882e6a840b4d90d4c687e4c67e164f8cce57d
EugeneShell/python_for_dqe
/functions.py
6,089
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 02 12:17:25 2021 @author: Yauheny_Shaludzko """ # HW2 Refactor using functional approach ''' Task: Create a list of random number of dicts (from 2 to 10) dicts random numbers of keys should be letter, dicts values should be a number (0-100), example: [{'a': 5, 'b': 7, 'g': 11}, {'a': 3, 'c': 35, 'g': 42}] ''' def dict_list_creation(): import random as r import string d_list = [] # initialization of list letters = string.ascii_lowercase # method returns all lowercase letters for i in range(r.randint(2, 10)): # loop is used to fill list with random number of dictionaries ''' Generator is used to create dictionary. r.choice(letters) is responsible for key generation, r.randint(0, 100) - for value generation. Number of key: value pairs inside dictionary is variable and determined by r.randint(2, 10) ''' random_dict = {r.choice(letters): r.randint(0, 100) for i in range(r.randint(2, 10))} d_list.append(random_dict) # generated dictionary is added into dict_list return d_list dict_list = dict_list_creation() print("dict_list:", dict_list) # print output result def index_return(key1): # creating func which returns index of dict, where key from parameter with max value kv_list = [] # create empty list vmax = 0 # variable for saving max value for current key for i in range(len(dict_list)): # consider each dict separately # if key from parameter exists in this dictionary, this pair added into kv_list as dictionary if key1 in dict_list[i].keys(): kv_list.append({key1: dict_list[i][key1]}) # if this key doesn't exist in dict, pair {key:-1} will be add into kv_list # (-1 might not be in initial dict according to the task) else: kv_list.append({key1: -1}) ''' for example if we had initial list as [{a:1,b:3},{a:5,c:9},{q:1,z:2}] f.e. for key1=a we will receive kv_list = [{a:1},{a:5},{a:-1}] , it means that we leave only one pair in dictionary, and number of dict stay the same (if key was not in initial dict, we add key and value -1 for this case) it will helps to receive index of key:value (it equals to index of initial dict, which contain this kay:value''' for j in range(len(kv_list)): # here we will find max value for current key if kv_list[j][key1] > vmax: vmax = kv_list[j][key1] # print(kv_list.index({'c': max})) # we receive index of dictionary, which contain pair {key1: max}, where key1-key from parameter, max-it's max value return kv_list.index({key1: vmax}) + 1 # here we count how much times some key appears in initial list of dict # empty dict for saving pair key: number_of_times num_of_keys = {} for i in range(len(dict_list)): for key in dict_list[i].keys(): # if key already exists in num_of_keys, we add 1 to it's value (as another one time, when it appears) if key in num_of_keys.keys(): num_of_keys[key] = num_of_keys.get(key) + 1 # if not, just add key with value = 1 else: num_of_keys[key] = 1 # here we can print result - how much times key appeared # print(num_of_keys) # define new empty dictionary for combining all the dictionaries result_dict = {} # create cycle for each dictionary in previously defined list for i in range(len(dict_list)): # create cycle which consider each pair of key and value in dictionaries from list for key, value in dict_list[i].items(): # we compare current value with value of this key already existing in result_dict, if it's not exist # get(key, value) will return current value (second parameter), and max will be = value result_dict[key] = max(value, result_dict.get(key, value)) # we received final dict, but without changed names, below is a loop, which finds which keys appear more than once # and change name of this key with the help of function, created above # for each key in result dict (previously changed to list of keys)... for key in list(result_dict): # print(key) # print(num_of_keys.get(key)) # if this key appears more than once... if num_of_keys.get(key) > 1: # we change it's name according to the pattern key_index_of_dict result_dict[key + "_" + str(index_return(key))] = result_dict.pop(key) # print result dictionary to console print("Common dict with max values of repeated keys and number of dict in name:\n", result_dict) # HW3 Refactor using functional approach def normal_text(text): """Function which refactor given text according to homework 3 tasks""" sentences = text.split(".") # split text to sentences on dots sentfixed = [i.strip(' \t\n\r').capitalize() for i in sentences] # trim whitespaces, capitalize sentences via gen addsent = [] # creating empty list for additional sentence for i in sentfixed: wordlist = i.split(' ') # splitting sentence to words addsent.append(wordlist[-1]) # getting the last word and appending it to the list addsent1 = ' '.join(addsent).capitalize().rstrip() + '.' # creating additional sentence with join&capitalize next_text = ('. '.join(sentfixed) + addsent1).replace('iz', 'is') # replacing iz/is print(next_text) print('Number of whitespace characters in given text:', text.count(' ') + text.count('\n ')) # counting whitespaces text = ''' tHis iz your homeWork, copy these Text to variable. You NEED TO normalize it fROM letter CASEs point oF View. also, create one MORE senTENCE witH LAST WoRDS of each existING SENtence and add it to the END OF this Paragraph. it iZ misspeLLing here. fix“iZ” with correct “is”, but ONLY when it Iz a mistAKE. last iz TO calculate nuMber OF Whitespace characteRS in this Tex. caREFULL, not only Spaces, but ALL whitespaces. I got 87.''' print(normal_text(text))
438767e8fe6e3f7315da5a5d276fa7dc8241ef14
FiberJW/hsCode
/guess_my_number_v3.py
3,930
3.96875
4
def guess_user_num(): import random, time print('\t\t\tGuess My Number!\nI will think of a number between 1 and 100 (Inclusive)\n\nTell me what you think the number is. I\'ll give you hints\n\n') def main(): #define main instructions as function for calling later num = random.randint(0, 100) print('\nI\'m thinking of a number...') def con(): response = str(input("Do you want to try again? Type 'yes' to continue or press the enter key to exit\n\t=>")).lower() if response == 'yes' or response == 'y': main() elif response == '': print('\nThanks for playing!') time.sleep(2) raise SystemExit else: print('Invalid Response', end='\n') con() def dec(): # Gets input and decides upon it what to do nonlocal num try: guess = int(input('What am I thinking of?\n\t=>')) except ValueError: print('I don\'t think you entered a number-- try again.\n') guessNum() if guess == num: con() elif guess > num: print('Too high') guessNum() elif guess < num: print('Too low') guessNum() def guessNum(): time.sleep(1) dec() guessNum() main() def guess_cpu_num(): from random import randint import time print("\tEnter a number from 1 - 100. I'll try to guess it. Bring it on!") num = 0 # Init Sentry Variable # Checks if number is in proper range while num < 1 or num >100: try: num = int(input("\n\t\tInput your number (I'm not looking):\n\t=>")) except ValueError: print('\n\t\t\tYou didn\'t input an integer') continue if num > 100: print("Number is too high!") if num < 1: print("Number is too low!") cpu_guess = randint(1, 100) print('I think that your number is: ', cpu_guess) sentry = 0 while cpu_guess != num: res = input('\nType (1) if my guess is too high, or (2) if my guess is too low:\n\t=>') if res == '1': high_guess = cpu_guess cpu_guess = randint(1, high_guess) elif res == '2': low_guess = cpu_guess cpu_guess = randint(low_guess, 100) else: print('\nInvalid input.') res = input('\nType (1) if my guess is too high; or (2) if my guess s too low:\n\t=>') print("I'll try again...", cpu_guess) time.sleep(0.1) sentry += 1 if sentry > 4: print('FINE. I\'LL DO IT BY MYSELF') time.sleep(0.2) while cpu_guess != num: if cpu_guess > num: high_guess = cpu_guess - 10 cpu_guess = randint(1, high_guess) print("\nI'll try again...", cpu_guess) elif cpu_guess < num: low_guess = cpu_guess + 10 cpu_guess = randint(low_guess, 100) print("\nI'll try again...", cpu_guess) else: break print("FINALLY! I got it!\n") print('Your number is: ', cpu_guess) print('\n\tI was actually looking after all...') def menu(): res = input('Do you want to [1] Have the computer guess your number, ' \ '[2] Guess the computer\'s number, or [3] Exit the program?\n\t=>') if res == '1': guess_user_num() elif res == '2': guess_cpu_num() elif res == '3': raise SystemExit else: print('\nBad choice.\n') menu() def main(): print('Welcome to the Guess My Number program!\n') menu() main()
c6f1a9ed7c4748a0b4e414181e47241f49fa6a5b
szat/Blackjack
/game21/Hand.py
2,930
4.15625
4
__author__ = "Adrian Szatmari" __copyright__ = "Copyright 2018" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Adrian Szatmari" __status__ = "Production" class Hand: """ This class implements the a hand, i.e. a set of cards of a player belongin together. A hand has a list of cards, a last card added, a bet. Moreover, a hand has a list of scores associated, since an Ace can have value 1 or 11. The most important function is addCard(), adding a card to the hand and updating the scores. """ values = [1,2,3,4,5,6,7,8,9,10,1,2,3,11] def __init__(self): self.last_card = -1 #index of the last card, no cards yet self.cards = [0,0,0,0,0,0,0,0,0,0,0,0,0] #the actual hand self.scores = [0] #in case of one or multiple Aces self.bet = 0 def setBet(self, bet): self.bet = bet def bestScore(self): """ This function returns the score closest to 21, but under it. In case the hand has no card or if all the scores are above 21, the function return -1. """ #restrict to the scores under 21 temp_scores = [i for i in self.scores if i <= 21] if(len(temp_scores) == 0): #if the hand is empty or all scores are above 21 return -1 else: return max(temp_scores) def addCard(self,card): """ This function adds a card to the current hand. In particular, it updates the scores correctly. One has to be careful because Aces are worth 1 or 11, and one should not decided a priori. """ self.last_card = card self.cards[card] += 1 #actually put the card into the hand if(self.last_card != 0): #not an ace val = Hand.values[self.last_card] self.scores = [x + val for x in self.scores] else: #last card is an ace temp1 = self.scores temp2 = self.scores temp1 = [x + Hand.values[0] for x in temp1] #if ace is worth 1 temp2 = [x + Hand.values[-1] for x in temp2] #if ace is worth 11 #restrict to the unique set of possible scores self.scores = list(set().union(temp1,temp2)) def toString(self): """ This function returns a string that prints the current state of the hand. """ names = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"] string = "[Scores:" for i in self.scores: string += str(i) string += "," string = string[:-1] string += "|Bet:" string += str(self.bet) string += "|" string += "Cards:" for index, i in enumerate(self.cards): if(i > 0): for x in range(i): string += names[index] string += "," string = string[:-1] string += "]" return string
597325f5eea09ec904a078b766903584ba0b9e0a
IceDerce/learn-python
/learning/2.py
470
3.625
4
a = [45, 67, 23] b = [] if a[0] < a[1] and a[0] < a[2]: b.append(a[0]) if a[1] < a[2]: b.append(a[1]) b.append(a[2]) else: b.append(a[2]) b.append(a[1]) elif a[0] > a[1] and a[0] > a[2]: if a[1] < a[2]: b.append(a[1]) b.append(a[2]) b.append(a[0]) else: b.append(a[2]) b.append(a[1]) b.append(a[0]) else: b.append(a[2]) b.append(a[0]) b.append(a[1]) print(b)
3c9060f17337d2ede40c2f74a14ca16f166ed092
krnets/codewars-practice
/6kyu/Find the odd int/index.py
920
3.96875
4
# 6kyu - Find the odd int """ Given an array, find the integer that appears an odd number of times. There will always be only one integer that appears an odd number of times. """ # from collections import Counter # def find_it(seq): # return [x for x, y in Counter(seq).items() if y % 2][0] # from functools import reduce # from operator import xor # def find_it(seq): # return reduce(xor, seq) # from functools import reduce # def find_it(seq): # return reduce(lambda x, y: x ^ y, seq) def find_it(seq): return [x for x in set(seq) if seq.count(x) % 2][0] q = find_it([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]) # 5 q q = find_it([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]) # -1 q q = find_it([20, 1, 1, 2, 2, 3, 3, 5, 5, 4, 20, 4, 5]) # 5 q q = find_it([10]) # 10 q q = find_it([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]) # 10 q q = find_it([5, 4, 3, 2, 1, 5, 4, 3, 2, 10, 10]) # 1 q
56a5dd1f71386790f84ec2fa784abc8a5d14d905
itzelot/CYPItzelOT
/libro/problemas_resueltos/capitulo2/problema2_8.py
698
3.921875
4
compra = float(input("Ingresa el monto de la compra: $")) if compra < 500: pagar = compra print(f"El total a pagar es de: ${pagar}") else: if compra <= 1000: pagar = compra-(compra * 0.05) print(f"El total a pagar es de: ${pagar}") else: if compra <= 7000: pagar = compra-(compra * 0.11) print(f"El total a pagar es de: ${pagar}") else: if compra <= 15000: pagar = compra-(compra * 0.18) print(f"El total a pagar es de: ${pagar}") else: pagar = compra-(compra * 0.25) print(f"El total a pagar es de: ${pagar}") print("FIN DEL PROGRMA")
e81d9762dce142337e149945b7c4b68d7ba8cd12
Yasmin-Core/Python
/Mundo_2(Python)/elif/aula12_desafio40.py
235
3.953125
4
nota1= float(input('Digite uma nota: ')) nota2= float(input('Digite a segunda nota: ')) a= (nota1 + nota2) / 2 if a >= 7.0: print(' APROVADO ') elif a < 5.0: print (' REPROVADO ') elif 7 > a >= 5: print(' RECUPERAÇÃO ')
ecc56471276e1a396daf61a369b443e0e3619937
henryZe/code
/leetcode/daily/2285_maximumImportance.py
482
3.734375
4
from typing import List class Solution: def maximumImportance(self, n: int, roads: List[List[int]]) -> int: degree = [0] * n for w, v in roads: degree[w] += 1 degree[v] += 1 degree.sort() res = 0 for d, i in enumerate(degree, 1): res += d * i return res # n = 5 # roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] n = 5 roads = [[0,3],[2,4],[1,3]] print(Solution().maximumImportance(n, roads))
c477b544b3dc0e8a64e66aee4e93d719df59717e
HyoHee/Python_month01_all-code
/day14/commdity_manager_system.py
3,543
3.890625
4
""" 商品信息管理系统 """ class CommodityModel: def __init__(self, cid=0, name="", price=0): self.cid = cid self.name = name self.price = price def __str__(self): return f"商品编号:{self.cid},商品名称:{self.name},商品价格:{self.price}" def __eq__(self, other): return self.cid == other.cid class CommodityView: def __init__(self): self.__controller = CommodityController() def __display_menu(self): print("1) 添加商品") print("2) 显示商品") print("3) 删除商品") print("4) 修改商品") def __select_menu(self): number = input("请输入选项:") if number == "1": self.__input_commodity_info() elif number == "2": self.__display_commodity_info() elif number == "3": self.__delete_commodity() elif number == "4": self.__modify_commodity() def __input_commodity_info(self): commodity = CommodityModel() commodity.name = input("请输入商品名称:") commodity.price = int(input("请输入商品价格:")) self.__controller.add_commodity_info(commodity) print("添加成功") def main(self): while True: self.__display_menu() self.__select_menu() def __display_commodity_info(self): for item in self.__controller.commodity_list: print(item) def __delete_commodity(self): cid = int(input("请输入需要删除的商品编号:")) if self.__controller.remove_commodity(cid): print("删除成功") else: print("删除失败") def __modify_commodity(self): commodity = CommodityModel() commodity.cid = int(input("请输入需要修改的商品编号:")) commodity.name = input("请输入需要修改的商品名称:") commodity.price = int(input("请输入需要修改的商品价格:")) if self.__controller.update_commodity_info(commodity): print("修改成功") else: print("修改失败") class CommodityController: def __init__(self): self.__commodity_list = [] self.start_id = 1001 @property def commodity_list(self): return self.__commodity_list def add_commodity_info(self, commodity): """ 添加商品 :param commodity: 需要添加的商品 """ commodity.cid = self.start_id self.start_id += 1 self.__commodity_list.append(commodity) def remove_commodity(self, cid): """ 删除商品 :param cid: 需要移除的商品编号 :return: 是否删除成功 """ commodity = CommodityModel(cid) if commodity in self.__commodity_list: self.__commodity_list.remove(commodity) # for item in self.__commodity_list: # if item.cid == cid: # self.__commodity_list.remove(item) return True return False def update_commodity_info(self, new_commodity): """ 修改商品信息 :param new_commodity: 新商品 :return: 是否修改成功 """ for item in self.__commodity_list: if item.cid == new_commodity.cid: item.__dict__ = new_commodity.__dict__ return True return False view = CommodityView() view.main()