blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
4d6eb8e78bc43f41d81f423da6b9ac6b50c1e5ff
MauriceMorrey/Python
/names.py
1,236
3.703125
4
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def print_stu(list_a): #for i, student in enumerate(students):#why does this print e...
c7809326686e2ddaef640b85cc687020a3f2c97e
MauriceMorrey/Python
/OOP/product.py
1,185
3.796875
4
class Product(): def __init__(self, Price, Item_name, Weight, Brand, Status): self.price = Price self.name = Item_name self.weight = Weight self.brand = Brand self.status = Status def sell(self): self.status = "Sold" return self def add_tax(self): ...
aa924c29ffccde119c900b46c09cc8caa64efc1e
720315105009/python
/beginner/sum of natural num.py
134
4.125
4
n=int(input("Enter a number: ")) sum2 = 0 while(n > 0): sum2=sum2+n n=n-1 print("The sum of first n natural numbers is",sum2)
ba6ad8151b4b55726e3f7efbb3534973ee6f9fb7
harrisont/AdventOfCode2019
/day_2/part_2.py
1,538
3.734375
4
from pathlib import Path from typing import List def run_program(memory: List[int]) -> List[int]: instruction_pointer = 0 while True: opcode = memory[instruction_pointer] if opcode == 99: break input_pos_1 = memory[instruction_pointer + 1] input_pos_2 = memory[instr...
0f8d28d41438c64cbfeacbb8568a873493e934e6
MartinWinchester/Booking
/MongoDb/connect.py
993
3.5
4
# just some sample code that connect to mongoDB atlas and creates a database with one collection and one entry. from pymongo import MongoClient import datetime # TODO: Replace <user> with your username and <password> with your password client = MongoClient("mongodb+srv://<user>:<password>@cluster0.gqnq7.mongodb.net/my...
e08d71ec7e0d7244138baa31c97d40403d774b6a
Savitha2000/python
/eual,isolater,scalene.py
174
3.828125
4
a=int(input()) b=int(input()) c=int(input()) if(a==b and b==c and a==c): print("Equal") elif(a==b or b==c or a==c): print("Isolater") else: print("scalene")
cff2ff026097ddfa2a17a2293f3a6fe92d378f0d
Savitha2000/python
/check letters.py
184
3.5
4
d=input() l1=['c','e','r','s','u'] l=len(d) count=0 for i in d: if i in l1: count+=1 else: print("NO") if count==l: print("YES") ///ip cruse ,rucuse op yes
16a887b30b229817b3cb5fa2919133a243d29d9b
tayfunguven/Basic-Simulations
/Basic Simulations/Monte Carlo Simulations/MC-HitOrMiss.py
1,031
3.84375
4
import random import numpy as np import math a = int(input("Enter the lower limit of x, a: ")) b = int(input("Enter the upper limit of x, b: ")) sDev = int(input("Enter the standard deviation: ")) mean = int(input("Enter mean: ")) N = int(input("Enter the number of random points N: ")) #generates N random po...
e5b9ee02bc0975bf5f1c5ad326dcc48fb330161a
KaloyankerR/python-advanced-repository
/Assignments/Multidimensional Arrays/Exercise/08. Miner.py
1,812
3.546875
4
from collections import deque def get_start_position(count: int): for x_ind in range(count): if "s" in matrix[x_ind]: for y_ind in range(count): if matrix[x_ind][y_ind] == "s": return [x_ind, y_ind] def make_a_move(move: str): global game_over, coals_c...
104011150b004e584f5de45a6f824cdcb0e76ece
KaloyankerR/python-advanced-repository
/Assignments/File Handling/02. File Reader.py
241
3.71875
4
print(sum([int(x.strip()) for x in open("Resources/File Reader/numbers.txt")])) # file = open("numbers.txt") # numbers = file.readlines() # total = 0 # # for n in numbers: # number = int(n.strip()) # total += number # # print(total)
a02de1e1479fb0b296a5dfabf978c7c51b989e17
KaloyankerR/python-advanced-repository
/Assignments/Lists as Stacks and Queues/Exercise/06. Balanced Parentheses.py
940
3.984375
4
def balanced(text: str): stack = [] is_balanced = True for i in range(len(text)): if text[i] in "{[(": stack.append(i) elif text[i] in ")]}" and len(stack) > 0: start_ind = stack.pop() if text[start_ind] == "{": if text[i] != "}": ...
a056f02535cf3903a26e9537711f73a78f5044c5
KaloyankerR/python-advanced-repository
/Assignments/Exam Preparation/Python Advanced Exam - 27 June 2020/01. Bombs.py
1,593
3.5625
4
from collections import deque datura_bomb = 0 cherry_bomb = 0 smoke_decoy_bomb = 0 bomb_effects = deque(int(x) for x in input().split(', ')) bomb_casings = deque(int(x) for x in input().split(', ')) bomb_effects_empty = False bomb_casings_empty = False while True: current_bomb_effect = bomb_effects.popleft() ...
dc5efce7f123ca1b81a7111fa5e3b35d570b35f9
KaloyankerR/python-advanced-repository
/Assignments/Exam Preparation/Python Advanced Retake Exam - 19 August 2020/01. Taxi Express.py
779
3.765625
4
from collections import deque customers = deque(int(x) for x in input().split(', ')) taxi_drivers = deque(int(x) for x in input().split(', ')) total_time = 0 while True: current_customer = customers.popleft() current_taxi_driver = taxi_drivers.pop() if current_customer <= current_taxi_driver: tot...
c72632fd52fa8545ba1c7b087bb9189c31d23985
KaloyankerR/python-advanced-repository
/Assignments/Lists as Stacks and Queues/Exercise/10. Cups and Bottles.py
791
3.625
4
from collections import deque cups = deque([int(x) for x in input().split()]) bottles = deque([int(x) for x in input().split()]) wasted_water = 0 while True: current_cup = cups[0] current_bottle = bottles.pop() if current_cup < current_bottle: current_bottle -= current_cup wasted_water +=...
34adf6a8b9306d9a9b5f27f9a1caf1ee06b04cb3
KaloyankerR/python-advanced-repository
/Assignments/Lists as Stacks and Queues/Lab/04. Water Dispenser.py
610
3.71875
4
from collections import deque water_in_dispenser = int(input()) people = deque() while True: cmd = input() if cmd == "Start": break else: people.append(cmd) while True: cmd = input() if cmd == "End": print(f"{water_in_dispenser} liters left") break elif cmd.st...
08f103f5f92e517917f3e3263016625e72e32179
vivek-ds/Predicting_House_Price
/3_Applying_ridge_lasso.py
2,758
3.53125
4
#Applying ridge and lasso on processed data %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import scale from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge, RidgeCV, Lasso, LassoCV from sklearn.m...
9b9eee583d04ba0fcb6d59f5079ea4fd211d3e22
haptikfeedback/PDX_Code_Guild
/basic/rain_data.py
877
3.53125
4
import datetime path = r'astor.rain' def parse_file(path): with open(path, 'r') as file: lines = file.readlines() start_line = 0 while '----' not in lines[start_line]: start_line += 1 start_line += 1 data = [] for i in range(start_line, len(lines)): data_line = lines...
60e49cf8111bfd17749f96b6275a694a6c776aa3
haptikfeedback/PDX_Code_Guild
/basic/lab16_word_count.py
685
3.875
4
# count-list-items-1.py import string frequency = {} with open('dracula.txt', 'r') as wordstring: # wordstring = 'I like, to "pet" puppies I also like to pet kittens!'.lower() punct = set(string.punctuation) sans_punct = ''.join(x for x in wordstring if x not in punct).split(' ') wordfreq = [sans_punct.co...
4508f4d59c289086ae288249126bf5d8e21d6ae4
haptikfeedback/PDX_Code_Guild
/basic/passwordgen.py
353
3.875
4
#Password Generator import random import string character_list = string.digits + string.ascii_letters + string.punctuation password = "" password_length = int(input("\n\nSecurity is 'Safety'.\nHow long should your password be?\n:")) for i in range(0, password_length): password = password + random.choice(characte...
404ae28d07f48df1eab7ff2ae1da7db99ad5d136
haptikfeedback/PDX_Code_Guild
/basic/lab9_guess_number.py
979
3.96875
4
import random def playagain(): print("\n******************************") print("* You have entered a game *") print("* Objective: guess my number *") print("* between 1 and 100 *") print("******************************\n") # user_input = input("Enter Guess: ") cnumber = range(1,...
42679e26d961779dc7a7a72e8aa97601c9149515
haptikfeedback/PDX_Code_Guild
/lpthw/reading_files.py
1,495
4.09375
4
# from sys import argv # # script, filename = argv # # txt = open(filename) # # print(f"Here's your file {filename}") # print(txt.read()) # # print("Type the filename again:") # file_again = input("> ") # # txt_again = open(file_again) # # print(txt_again.read()) # from sys import argv # # script, filename = argv # # ...
46da0fefc0e252e381d9cea7e20419cea9849ce5
haptikfeedback/PDX_Code_Guild
/basic/lab19_letter_locatorV2.py
416
3.640625
4
# word locator 2 list = {} class Locator: def __init__(self, phrase, letter): self.phrase = enumerate(phrase) self.letter = letter def return_letter(self): for letter in self.phrase: if letter[1] == self.letter: print(letter[1]) print(letter[...
bf1a959667f5e4371f3b48dbb9d7d4dccf6d118a
udeshmg/DQN-Pytorch
/external_env/vehicle_controller/base_controller.py
3,328
3.59375
4
import abc import numpy as np from external_env.vehicle_controller.vehicle_obj import Vehicle class BaseVehicleController(abc.ABC): def __init__(self, step_size): self.step_size = step_size @abc.abstractmethod def compute_acceleration(self, vehicle : Vehicle) -> int: """ compute the accel...
96d5bb1d11794871e749b62d63a534a59d854cbd
PatrickDekker98/aai
/opdracht1/kNearest.py
4,733
3.6875
4
import numpy as np import operator from collections import Counter """ read data from a file return array with data """ def dataReader(csvFile): return np.genfromtxt(csvFile, delimiter=';', usecols=[1,2,3,4,5,6,7], converters={5: lambda s: 0 if s == b"-1" else float(s), 7: l...
68f9f5dbcacb2b11ca64878e7b7c32ed3af9daf4
mat-yachikov/fibo
/fib.py
901
3.90625
4
# Рекурсивная функция для чисел Фибоначчи def fib(n): # Условия выхода из рекурсии if n == 1: return 1 elif n == 0: return 0 else: # Рекурсивный вызов return fib(n-1) + fib(n-2) # Ввод кол-ва чисел n = int(input()) # Список для чисел nums = [] # Открываем файл f = open(...
15a158bc7552232086905262d6064b90558e1098
HeontakKim/pandas
/Pandas004.py
1,275
3.71875
4
import pandas import mymodule # 4. Dataframe을 file으로 저장하기 friends = [ {"name":"Kim", "age":20, "job":"Trash"}, {"name":"Lee", "age":30, "job":"Animal"}, {"name":"Park", "age":40, "job":"Streamer"}, {"name":"Ryu", "age":50} ] dataframe = pandas.DataFrame.from_dict(friends) mymodule.printline(...
332bd33ad0fd06ffefad13abd2cb4f694ee30013
HeontakKim/pandas
/Pandas007.py
2,206
3.671875
4
import pandas as pd import mymodule # 7. 행, 열 생성 및 수정하기 friends = [ {"name":"Kim", "age":20, "job":"Trash"}, {"name":"Lee", "age":30, "job":"Animal"}, {"name":"Park", "age":40, "job":"Streamer"}, {"name":"Ryu", "age":50} ] df = pd.DataFrame.from_dict(friends) print("New DataFrame:") mymodule.printline...
a211611d95ca4c8bb87c03d264f44fdc5482bf50
fluidesign/automate-using-python
/Working_with_text/regext_replace.py
729
3.546875
4
# !python3 ## regext replace - http://www.regexr.com/ import re namesRegex = re.compile(r'Agent \w+') output = namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.') print(output) agentNamesRegex = re.compile(r'Agent (\w)\w*') output = agentNamesRegex.sub(r'\1****', 'Agent Alice told Agent ...
57c5c7ffc24b776eb6036eb8f44d70e4f29f273c
ritvikp22/TweetBotTesting
/get_tweet.py
639
3.59375
4
import tweepy # API and Tokens from Twitter Developer api_key = '' api_secret = '' token_key = '' token_secret = '' auth = tweepy.OAuthHandler(api_key, api_secret) auth.set_access_token(token_key, token_secret) api = tweepy.API(auth) # Arbitrary username test = api.get_user("elonmusk") #Choose username choice = inp...
59c01793d5d77174e35f6ce68f025bb3a84ad574
DeanDro/monopoly_game
/cards_classes/cards_super_class.py
3,528
4
4
# All cards will be instances of this class class CardsMegaClass: """ The goal of CardsMegaClass is to create one class that all game cards will be children of. """ def __init__(self, card_name, saleable, board_loc, owner=None, money_receive=None, money_pay=None, action=None, card_co...
f9903ec29ccad276cb744bef6f818199f7d2b3e2
gdifiore/xkcd
/src/download.py
1,098
3.53125
4
# # download.py - xkcd # # (c) 2018 gdifiore <difioregabe@gmail.com> # import urllib.request import json url = "https://xkcd.com/info.0.json" # url is link to json to latest xkcd response = urllib.request.urlopen(url) # open url with urllib.request data = json.loads(response.read()) # load and parse json latest = da...
2c11698fbd9eab83ba958392658f1c60226ccdda
DVkap/infa_2021_morgaiangelina
/8.py
181
3.703125
4
import turtle import math turtle.shape('turtle') a = 10 while a < 250: turtle.forward(a) turtle.right(90) turtle.forward(a) turtle.right(90) a += 10
7faa1c3913ea13ab7405b65e4bcf8712da744317
vsamoili/distributed_optimization_tf
/topology.py
2,115
3.703125
4
import random import argparse def get_graph(n_nodes, topology): n_nodes = int(n_nodes) nodes = [i for i in range(n_nodes)] if topology == "full": graph = {i: nodes[:] for i in nodes} elif topology == "ring": graph = {i: [] for i in nodes} ...
3667fe3935484f27411ba2d9522f282b98cd9d26
adsr652/Python
/fact2.py
534
4.1875
4
def recu_fact(num): if num==1: return num else: return num * recu_fact(num-1) num= int(input("Enter any no. : ")) if num < 0: print("Factorial cannot be found for negative integer") print("Reenter the value again ") num= int(input("Enter any no. : ")) if num==0: ...
e17e75ff91a5d8429709a8dbe65dff7f167b8a8f
AxelGoetz/intent-classifier
/question_answering/utils/clean_text.py
2,005
3.875
4
""" Cleaning raw sentence data. """ # TODO: Should we stem/lemmatize? # TODO: Paired words (New_York)? from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from string import punctuation import re def tokenize(sentence): """ Returns tokens """ return word_tokenize(sentence) def...
85431090e2ab550c00202d23d26a3eb98bee6de3
YukeshA/Maximllabs
/smallestsubstring.py
843
3.75
4
def unique_count(st): unique = [] for char in st[::]: if char not in unique: unique.append(char) return len(unique) def length_smallest_sub(s): n = len(s) d = {} for i in range(n): for j in range(i,n+1): sub = s[i:j] unique_count(sub) ...
028e4ec3b472c20a895cf59cd78fbe8f2bef2820
Phyopyosan/Exercises
/Fibonacci/Fibonacci.py
359
3.984375
4
# Fibonacci number module # n = int(intput('please enter a number: ')) def fib(n): #write fibonacci series up to a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() # fib(200) def fib2(n): #return Fibonacci series up to n result = [] a , b =0 , 1 while a < n: result.append(a) ...
6c8cb118721a066d8d31a7df10d030c5371a36f4
Phyopyosan/Exercises
/If_Else_Statements.py
2,063
4.15625
4
#Boolean Expression print(20 > 10) print(20 == 10) print(20 < 10) print(bool("Hello World")) print(bool(20)) Python Condition Equals -> x == y Not Equals -> x != y Less Than -> x < y Less Than or Equals to -> x <= y Greater than -> x > y Grater than or equal to -> x >= y Boolean O...
5f96767b6e4a28fb5c1f487708e23236b93e3e02
syyunn/Kelpie
/model.py
6,368
3.765625
4
from typing import Any, Tuple import numpy from dataset import Dataset class Model: """ The Model class provides the interface that any LP model should implement. The responsibility of any Model implementation is to - store the embeddings for entities and relations - impl...
ef7bf55fa66a02245c45f2d263a69ee811ffbb7f
PatrickWMoore88/htx-immersive-08-2019
/02-week/1-tuesday/labs/patrick-moore/patrickwmoore88-phonebook.py
2,509
4.3125
4
#Phone Book App #Phonebook phonebook = { 'A':{'Alex': '123-456-7890', 'Amy': '234-567-8901'}, 'B':{'Brian': '345-678-9012', 'Bobby': '456-789-0123'}, 'C':{'Chelsea': '567-890-1234', 'Candy': '678-901-2345'}, 'D':{'Derrick': '789-012-3456', 'Donnie': '890-123-4567'}, 'E':{'Erik': '901-234-5678', 'Er...
0e9ae93f5575d1c3c5a05125f0b0d6e44fb9ed21
PatrickWMoore88/htx-immersive-08-2019
/02-week/1-tuesday/labs/patrick-moore/phonebook/phonebook.py
845
3.609375
4
import functionality import menu import data import view selection = menu.menu_selection() while selection: if selection == 1: results = functionality.lookup_by_name(input("Search by First or Last name: ")) view.line_break() print("We have found the following results: ") view.view...
2f5fb6af6a621a52c62895fd9743ec6631a38682
Farzan-ul-haq/Recipe-App-API
/app/app/calc.py
142
3.96875
4
def add(x, y): '''Add Two numbers together''' return x + y def sub(x, y): '''Subract Two numbers together''' return x - y
dd9902dd302b8d998f6240e6c89794f053da7f97
nagahamaVH/Liar-s-Dice
/src/player.py
494
3.6875
4
from abc import ABCMeta, abstractmethod from tokenize import String from typing import Tuple, final, Union class Player(metaclass = ABCMeta): """The Player class is an abstract base class from which all game playing AIs must inherit.""" @final def __init__(self, index) -> None: self.ind...
51cacaf5bbcf435c73bf4cee2ec881295fd1501f
chengguobiao/myBlogCodeProject
/getListMaxNumIndex/testfunc.py
2,284
3.71875
4
#!usr/bin/env python #encoding:utf-8 from __future__ import division ''' __Author__:沂水寒城 功能:获取列表中最大/最小的前n个数值的位置索引 ''' import copy import heapq def getListMaxNumIndex(num_list,topk=3): ''' 获取列表中最大的前n个数值的位置索引 ''' max_num_index=map(num_list.index, heapq.nlargest(topk,num_list)) min_num_index=map(n...
8e757f757a440c1ba2ee67674e3a5891b020d6ec
LinTrieu/cfg-python
/examples/session_1/cats_3.py
116
3.625
4
cats = 10 cans = 2 total_cans = cats * cans output = "{} cats eat {} cans".format(cats, total_cans) print(output)
a4010f27f052ed2812e99bfc2cb6f218860561ce
LinTrieu/cfg-python
/examples/session_1/oranges_1.py
143
3.625
4
oranges = 12 cost_per_orange = 0.3 total_cost = oranges * cost_per_orange print(str(oranges) + " oranges") print("costs " + str(total_cost))
4b48473e42ba3cc59add28ff122e9add98bcb53f
LinTrieu/cfg-python
/examples/session_1/oranges_2.py
152
3.6875
4
oranges = 12 cost_per_orange = 0.3 total_cost = oranges * cost_per_orange output = "{} oranges costs £{}".format(oranges, total_cost) print(output)
a163381bc605613e9fec22f8983328598a621983
semkarim/My-Trainings
/Data structures/SeparateWordToChars.py
184
4.0625
4
chars = [] word = input("Enter the word: ") print(len(word)) for i in range (0,len(word)): chars.append(word[i]) print(chars) for i in range (0,len(chars)): print(chars[i])
7bf3ded502ca212e55ebdb24b40b27cdf9c020df
shillwil/cs-module-project-iterative-sorting
/src/searching/searching.py
908
4.125
4
def linear_search(arr, target): # Your code here if len(arr) is not 0: for i in range(len(arr)): if arr[i] == target: return i return -1 return -1 # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here if l...
c4d63739921e80e3a75701755f6e93f3207b566f
moguoyi/httpApi
/studyTest/wapper.py
269
3.515625
4
#coding:utf-8 class One(object): def __init__(self,name,id): self.name=name self.id=id self.m=self.foo() def foo(self): a=self.name b=a+self.id return b if __name__=='__main__': mo=One(1,0) print(mo.m)
494cd084bf6397c172f368974a802a1acde1b88e
moguoyi/httpApi
/huaweiTest/python的正则匹配.py
461
3.890625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import re line = "This is a regular expression for python" matchObj = re.match(r'(.*) is (.*?) .*', line, re.M | re.I) if matchObj: print("matchObj.span() :",matchObj.span()) print("matchObj.group() : ", matchObj.group()) print("matchObj.group(1) : ", matchObj.group...
4c1b723486f0c3c51e7a4af6f5f5f42574f207c8
moguoyi/httpApi
/momo/cat.py
618
3.84375
4
import abc # class Animal(metaclass=abc.ABCMeta): #同一类事物:动物 # @abc.abstractmethod # def talk(self): # pass class Animal(): #同一类事物:动物 def talk(self): pass class People(Animal): #动物的形态之一:人 def talk(self): print('say hello') class Dog(Animal): #动物的形态之二:狗 def talk(self): ...
632bfebfdc1121527685c19fb02e939cf29a4b2d
moguoyi/httpApi
/huaweiTest/name_list.py
755
3.609375
4
def beautiful(lis): dic = {} lis = lis.upper() for i in lis: if i in dic: dic[i] = dic[i] + 1 else: dic[i] = 1 val = list(dic.values()) val.sort(reverse=True) weight = list(range(1, 27)) weight.sort(reverse=True) sum1 = 0 for i, j in zip(val, w...
2a1f1b041a1cdcd475fecbb2ec5e9a9d481b33ef
moguoyi/httpApi
/momo/MintesToHours.py
347
3.90625
4
#!/usr/bin/env python3 import sys def mo(): times=sys.argv[1] time=int(times) if time<0: try: raise ValueError("Input number cannot be negative") except ValueError: print("Input number cannot be negative") else: hour=time//60 minute=time%60 print("{} H, {} M"...
7418e636f25bc8f5d28232d6ca9ecdc1d20902c4
moguoyi/httpApi
/huaweiTest/statistical_number.py
478
3.703125
4
#coding:utf-8 """统计字母、数字、空格的数字""" while True: try: line=input() num=0 digit=0 space=0 other=0 for i in line: if i.isalpha(): num+=1 elif i.isdigit(): digit+=1 elif i.isspace(): space+=...
45f2560a263995316a0536cde179ada588512b42
moguoyi/httpApi
/studyTest/classTestTwo.py
375
3.8125
4
class Phone(object): """一个简单的类实例""" def __init__(self,brand,size): self.brand = brand self.size = size # 实例化类 x = Phone("MI","5寸") # 访问类的属性和方法 print("类对象 brand:%s" % x.brand) print("类对象 size : %s" % x.size) print("Phone类的对象对象 x 所有的属性和方法: %s" % x.__dir__())
e78c768167310c3b33f661e93d40de405c69b8b1
moguoyi/httpApi
/studyTest/foo.py
593
4.0625
4
class Foo: def f1(self): print('Foo.f1') def f2(self): # self=obj print('Foo.f2') # 在父类中找到发 f2属性,第3步打印这一行 self.f1() # obj.f1() 第4步再去掉用self的f1属性 class Bar(Foo): def f1(self): # 第五步, 在回到object自身的名称空间找f1属性,找到后调用 print('Bar.f1') # 第6步 执行 obj = Bar() # 第一步 :类的实例化, 先得到一...
e7a9e87fa556bdd93eab9b8944d4c42c120b785e
moguoyi/httpApi
/momo/123test.py
297
4.03125
4
#!/usr/bin/env python3 import math a=int(input("Enter value of a:")) b=int(input("Enter value of b:")) c=int(input("Enter value of c:")) d=b*b-4*a*c if d<0: print("无解") else: root1 = (-b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) print("值1="+root1) print("值2="+root2)
d2fc93102423f874df2e8a36ebd20c0644dfdeb2
huilizhou/kemu_shuati
/algorithms/1-100/077.combinations.py
728
3.578125
4
# 组合 class Solution: def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ # from itertools import combinations # return list(combinations(range(1, n + 1), k)) # 人家的解法,回溯算法 if k > n: return [] ...
3125411239c665aeb80b35aec4312794f7c38740
huilizhou/kemu_shuati
/algorithms/1-100/003.longest-substring-without-repeating-characters.py
569
3.640625
4
# 无重复字符的最长子串 class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ # 使用哈希表 hash = {} max_length = 0 start = 0 for i, string in enumerate(s): if string in hash and start <= hash[string]: ...
924b784727a69fe3d6eea129acf88d550a1867e3
huilizhou/kemu_shuati
/algorithms/201-300/0000_test.py
2,112
3.75
4
# L = [1, 2, 3, 4, 5] # print(L.pop(0)) # print(L.pop(0)) # print(L) # class Solution: # def merge_sort(self, list): # """合并""" # def merge(left, right): # res = [] # while left and right: # if left[0] < right[0]: # res.append(left.pop(0)...
9dd3a83e8b53b7df6b09998fbe56c6a9ff235d9a
huilizhou/kemu_shuati
/algorithms/101-200/137.single-number-ii.py
1,132
3.890625
4
# 只出现一次的数字II ''' 人家的思路 如果能设计一个状态转换电路,使得一个数出现3次时能够自动抵消为0,最后剩下的就是只出现一次的数。 开始设计,一个二进制位只能表示0或者1。也就是天生可以记录一个数出现了一次还是两次。 需要记录出现3次,需要两个二进制位。我们需要两个变量,每个变量取一位。 ''' class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ # s = {} # for ...
6bf42b13aa01c5f2f48f0cf8b21f2782a09cfdac
sdp-team-1/AzeriTTS
/Normalization/normalizer_with_lib.py
2,463
3.671875
4
from num2words import num2words import pandas as pd import numpy as np import re def normalize_num(num: str, is_ordinal: bool): """Converts the given number to words""" if num == "0": return 'sıfır' turkish_str = num2words(int(num), lang='tr', ordinal = is_ordinal) aze_str = translate_to_aze(turkish_str) ...
79b011cc2283541ee94d64681e2d398f2a205bfc
budaLi/jianzi
/tutle数字.py
605
3.8125
4
# @Time : 2020/6/24 20:39 # @Author : Libuda # @FileName: tutle数字.py # @Software: PyCharm # import turtle as t # t.hideturtle() # t.setup() # t.penup() # t.pencolor('red') # t.write('2',font=("Times", 33, "normal")) # t.fd(40) # t.pencolor('blue') # t.write('6',font=("Times", 33, "normal")) # t.fd(40) # t.pencolor(...
c1072268bdad30e10217c7171957d42b528dc63e
budaLi/jianzi
/7분반_기말시험-1/q4.py
240
3.90625
4
# Q4 ## variables #### DON'T CHANGE!! num_list = [1,2,3,4,5,6,7,8,9,10] sumOdd = None ################################ ## your code here! sumOdd=0 for one in num_list: if one%2!=0: sumOdd+=one ## # print output print(sumOdd)
a581660fc592c90fde13b606f5584ac4f8194725
budaLi/jianzi
/Seven-sorting-methods-master/insert_sort.py
1,246
3.984375
4
import math import copy as cp class InsertSortMethod(): # construction method def __init__(self, array): self.array=array # the original method that insert the number to the proper position of sorted subset one by one def insert_sort1(self): array=cp.deepcopy(self.array) n=len(array) for i in range(n-1): ...
6a6df5c88959549ecf5c129c23b02de9675a2174
budaLi/jianzi
/7분반_기말시험-1/q2.py
192
3.84375
4
# Q2 ## variables #### DON'T CHANGE!! sayHello = "Hello, Kim Chung Ang" name = None ################################ ## your code here! name = sayHello.split(",")[1] ## # print output print(name)
be7482a998f69bafdeb63adb3cc2376c3382c26f
budaLi/jianzi
/python代码规范demo讲解/2.8生成器/demo_08_old.py
291
3.53125
4
""" 生成器和迭代器 """ # @Time : 2020/10/27 10:42 # @Author : Libuda # @FileName: demo_08_old.py # @Software: PyCharm def odds(n): ret = [] for i in range(1, n + 1): if i % 2 == 1: ret.append(i) return ret for i in odds(1000): print(i)
e356570685ea58338a1a05f2ef6f1fd147c3a342
budaLi/jianzi
/leetcode/最长回文子串.py
883
3.53125
4
# coding=utf-8 # Copyright (c) 2020 ichinae.com, Inc. All Rights Reserved """ Module Summary Here. Authors: lijinjun1351@ichinae.com """ # 动态规划 时间超限 class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ n = len(s) ans = "" dp...
3feb8418eda00072433c911fc79984ff78cb77ba
799898961/python-learn-note
/python学习笔记/第6章-循环控制/6.1遍历循环.py
1,029
4.21875
4
# 6.1遍历循环.py # 字符串遍历: for c in "python123": print(c, end=",") print() # 列表遍历: for item in [123, "python", 456]: print(item, end=",") print() # 遍历某个结构形成的循环运行方式 # for <循环变量> in <遍历结构>: # <语句块> # 每次循环,能从遍历结构中逐一提取元素,放在循环变量里 # 并执行一次语句块 # 计数循环n次 # for i in range(n): # <语句块> # 遍...
e4f1503ab452d0616cbd346aa56e3bee08249104
MarianaOzorio/CS50-problem-sets
/pset7/houses/roster.py
517
3.8125
4
from cs50 import SQL from sys import argv, exit db = SQL("sqlite:///students.db") if len(argv) != 2: print("Error") exit(1) students = db.execute(f"SELECT first, middle, last, birth FROM students WHERE house = '{argv[1]}' ORDER BY last, first") for row in students: first = row["first"] middle = row...
26e1d9474f07030b12b6f9983f75924564631582
rupeshpatil/python
/email_sender_python/miltipart_email.py
2,356
3.625
4
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import csv def send_mail(SUBJECT, BODY, TO, FROM): """With this function we send out our html email""" # Create message container - the correct MIME type is multipart/alternative here! MESSAGE = MIMEMultipa...
334a4d6c71ca0346d3497335d0c0c9c13419d47e
yejianye/programming-problems
/spoj/PALIN/solution.py
845
3.828125
4
import sys def get_half(number): return number[:(len(number)+1)/2] def expand_half(number, is_even): if is_even: return number + number[::-1] else: return number[:-1] + number[::-1] def inc(number): for i in xrange(len(number) - 1, -1, -1): if number[i] != '9': break else: return '1' + '0' * len(numb...
0b72ec1036dc8c0a9923eac37c4da35099c4c5d8
rodennis22/Pirple
/PythonHW3IfStat.py
256
3.984375
4
#Python Homework 3 If statements def EqualityCheck(a,b,c): #check for any equality return true if any equality exists, false if none. if int(a) == int(b) or int(a) == int(c) or int(b) == int(c): return True else: return False
1df31db0f914e299d2d6f5fb65e71909b115ceb2
Redpike/advent-of-code
/2016/d13/d13.py
1,148
3.84375
4
input_data = 1358 def is_wall(x: int, y: int): value = x * x + 3 * x + 2 * x * y + y + y * y + input_data one_bits = bin(value).count('1') return one_bits % 2 == 1 def get_possible_moves(old_x: int, old_y: int): possible_moves = [(old_x + 1, old_y), (old_x - 1, old_y), (old_x, old_y + 1), (old_x, ol...
d26400de4a7a834151832343ada33e06fd07b3e3
Redpike/advent-of-code
/2015/d12/d12.py
715
3.703125
4
import json part = 0 def read_input_file(): return json.load(open('input', 'r')) def sum_of_objects(json_data): if type(json_data) is int: return json_data elif type(json_data) is list: return sum(map(sum_of_objects, json_data)) elif type(json_data) is dict: values = json...
a45ada33f4e34cf8c615e084c8d4033c2a6fb014
Redpike/advent-of-code
/2015/d05/d05.py
2,426
3.5625
4
import re test_input = [ 'ugknbfddgicrmopn', 'aaa', 'jchzalrnumimnmhp', 'haegwjzuvuyypxyu', 'dvszwmarrgswjxmb', 'qjhvhtzxzqqjkmpb', 'xxyxx', 'uurcxstgmygtbstg', 'ieodomkazucvgmuy' ] def readInputFile(): input_file = open('input', 'r').read() input_data = [] for line in...
f10392ff039785447bc6e396aec5ba3c244bbd07
Redpike/advent-of-code
/2015/d02/d02.py
1,430
3.515625
4
test_input = [ '2x3x4', '1x1x10' ] def readInputFile(): input_file = open('input', 'r') input_data = [] for line in input_file.read().splitlines(): input_data.append(line) return input_data def computeSquareFeets(input_data): l, w, h, sum_of_values = 0, 0, 0, 0 for line in i...
732f041770cb141ffd12ec2ba2d9780c748a38a4
Redpike/advent-of-code
/2018/d05/d05.py
1,292
3.8125
4
def read_input(): return open('input', 'r').readline() def get_remaining_units(_input: str): line = _input temp_line = None while temp_line != line: temp_line = line for i in range(0, 26): line = line.replace(chr(ord('a') + i) + chr(ord('A') + i), '') line = lin...
ec747b85a18d2962577e2e24547981b3d70be38b
kemar1997/TSTP_Programs
/Chapter13_TheFourPillarsOfObjectOrientedProgramming/Inheritance.py
2,766
4.90625
5
""" Inheritance in programming is similar to genetic inheritance. In genetic inheritance, you inherit attributes like eye color from your parents. Similarly, when you create a class, it can inherit methods and variables from another class. The class that is inherited from is the parent class, and the class that inherit...
ced65aca9c260388d36e6d84939b29e3d60660c2
kemar1997/TSTP_Programs
/Loops/range.py
750
4.90625
5
""" You can use the built-in range function to create a sequence of integers, and use a for-loop to iterate through them. The range function takes two parameters: a number where the sequence starts and a number where the sequence stops. The sequence of integers returned by the range function includes the first paramete...
52c6816d339f1140d7da3fd7c97c9df468084f7f
kemar1997/TSTP_Programs
/String_Manipulation/Concatenation.py
321
4.25
4
""" You can add two (or more) strings together using the addition operator. HTe result is a string made up of the characters from the first string, followed by the characters from the next string(s). Adding strings together is called concatenation: """ print("cat" + "in" + "hat") print("cat" + " in" + " the" + " hat"...
56329c35e37e044922969f696523bd39b76281fb
kemar1997/TSTP_Programs
/Challenges/Ch12_Challenges/Triangle.py
565
4.1875
4
# Create a Triangle class with a method called area that calculates and returns # its area. Then create a Triangle object, call area on it, and print the result. # a,b,c are the sides of the triangle class Triangle(): def __init__(self, a, b, c): self.s1 = a self.s2 = b self.s3 = c def...
17601476e7b674a9900d695a47a4cecc327ae2cf
kemar1997/TSTP_Programs
/Challenges/Ch13_Challenges/Challenge4.py
415
4.34375
4
""" Create a class called Horse and a class called Rider. Use composition to model a horse that has a rider """ class Horse: def __init__(self, name, owner): self.name = name self.owner = owner class Rider: def __init__(self, name): self.name = name ...
25da8767ef0a8ec27bfc216ca40c4cdf9967adf9
kemar1997/TSTP_Programs
/Challenges/Ch4_Challenges/ch4_challenge1.py
236
4.25
4
""" 1. Writing a function that takes a number as an input and returns that number squared. """ def square_a_number(): num = input("Enter a number: ") num = int(num) return num*num result = square_a_number() print(result)
8daeee49efdae40965c65dffbc1dc10a44b8410b
kemar1997/TSTP_Programs
/Challenges/Ch5_Challenges/ch5_challenge4.py
197
3.625
4
me = { "height": "5'2", "fav_color": "red", "fav_author": "Orwell" } answer = input("Type height, fav_color, or fav_author") if answer in me: result = me[answer] print(result)
b5388042f0d3f885271dfdaff1178553dd4f6a75
yowrong/ACSports
/nfl_2020_data_summary.py
4,585
3.546875
4
# import csv files downloaded from pro-football-reference.com # create a data summary table (file) using python scripts import pandas as pd from csv import reader team_data = pd.read_csv("nfl_2020_team_summaries.csv", index_col='Tm') # print(team_data.head()) offense_data = pd.read_csv("nfl_2020_team_offense.csv", ...
dc343268031f44a5970c79d59f6f886a2084745a
cupton15/GameOfLifePython
/gameboard.py
2,641
3.578125
4
from cell import * from copy import deepcopy class GameBoard: gridsize = 0 cells = [] def __init__(self, gridsize): self.gridsize = gridsize self.populateboard() def drawboard(self): print("-" * self.gridsize) rows = range(self.gridsize) for n in rows: ...
427ce2fb058dd49aa34beee0129d81db08b80390
eugenecartwright/hthreads
/src/platforms/xilinx/vivado_archgen/scripts/generate_config.py
1,055
3.75
4
#!/usr/bin/python from random import shuffle #-----------------------------------------------------------------------------# # Main program # #-----------------------------------------------------------------------------# def main(): slave_num = 0 ...
eca18492df102c9a0a55318b88ab9fc8d03fcaa5
deFox22/sea-c28-students
/Students/CameronDeVos/session04/mailroom.py
4,055
3.78125
4
#!/usr/bin/python from __future__ import print_function def safe_input(prompt): try: response = raw_input(prompt) except (EOFError, KeyboardInterrupt): print (u"Sorry, unable to preform that action.") return safe_input(prompt) else: return unicode(response) def float_che...
44865017c61c8ebb6dcf359b533ee2a34c00ffea
deFox22/sea-c28-students
/Students/CameronDeVos/session04/dict_set.py
2,297
4
4
# session04 - Dictionaries and Sets from __future__ import print_function # Section 1 # Create a dictionary with Chris from Seattle who likes Chocolate dictionary1 = {u'name': u'Chris', u'city': u'Seattle', u'cake': u'Chocolate'} # Display dictionary print (dictionary1) # Delete the entry for Cake del dictionary1[u'ca...
f7b9467d12f237e1838f9a81beddd5bec5aa8306
Samruddhi17/Data-Structure-and-Algorithms
/Array/Rotate Array/try.py
367
3.71875
4
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(0,k): nums.insert(0,nums[-1]) #move last to first index nums....
421d4578ba610abec919388d26a063dab4a9ab71
Samruddhi17/Data-Structure-and-Algorithms
/Binary Search/Sqrt(x)/bs - temp1 .py
599
3.59375
4
class Solution(object): def mySqrt(self, x): """ Return the truncated square root of x AKA Return the max integer such that integer**2 <= x :type x: int :rtype: int """ low, hi = 0, x # Binary search for the truncated square root of ...
8f74b6189e5a187701b3b2d0e15fa01081dc9e85
Samruddhi17/Data-Structure-and-Algorithms
/Array/Remove Duplicates from Sorted Array/search_inplace_remove.py
560
3.859375
4
class Solution: def removeDuplicates(self, nums): if not nums: #empty array return 0 else: start = nums[0] #unique element assigned j =1 for i in nums[j:]: #search until new element not found if start == i: #if duplicate remove element...
d2ab58d282b2de9012a7b403d378a2b706734282
Samruddhi17/Data-Structure-and-Algorithms
/Linked List/Rotate LL/steps formula.py
995
4
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not hea...
ad094bde2c51cd2895351fce2d4ae16799aabdd1
Samruddhi17/Data-Structure-and-Algorithms
/Array/Intersection of 2 arrays II/set_counter.py
400
3.625
4
class Solution: def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ from collections import Counter n1 = Counter(nums1) n2 = Counter(nums2) common = set(nums1)&set(nums2) res = [] ...
8cf91ef216fbdfd27c7d528438672f68b2b314ea
Josephchinedu/univelcity_cohort
/forloop.py
100
3.5625
4
nubers = [6,5,19,5,7,4] sum = 0 for val in nubers: sum = sum + val print("The sum is :", sum)
d6caf49c26cd5aa529996efa65e3a0a6c72d16fb
karamcnair/tic-tac-toe
/board.py
2,566
4.09375
4
class Board(object): """ It's easier to deal with list operations on a 1D So instead I'll 'mock' the indexes for the columns & rows. """ # some helper variables for identifying each possible winning trio. row = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] col = [[0, 3, 6], [1, 4, 7], [2, 5, 8]] downD...
a0f645bba389c29795ad2c640f3e9dadfcb621aa
KonovalovPS/python
/homeworks/grep/grep.py
4,889
3.546875
4
import argparse import sys def output(line): print(line) def search(line, pattern, k, params): #функция поиска строки(паттерна) for i in range(len(line) - len(pattern) + 1): counter = 0 for j in range(len(...
c71c8797f7ccc26fcd5943d862fff47d06ca2446
Ambition-L/PythonSensei
/pythonProject1/com/ambition/work/sort/work2.py
1,043
3.546875
4
# 课后第一题 # 接受第一行数据 数组长度 和 显示长度 a = input("请输入数组长度:") # 定义接收数据数组 nums = [0] * int(a) # 定义输出数据角标数组 nums2 = [0] * int(a) # 接收数据 for i in range(0, len(nums)): nums[i] = int(input("请输入第" + str(i + 1) + "个数:")) # 循环接收输出数据的角标 并放入数组 d = 0 # 最多输入数据不超过数组长度 while d < len(nums): num = int(input("请输入需要输出的第" + str(d + 1...