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
caf22b203ec297143d41235bd8e1c6231e47dc6b
USussman/rambots-a19
/Classes/direction.py
1,420
3.75
4
import board import busio import adafruit_lsm303 from math import atan2, sqrt, cos, degrees class Compass: """ A class for reading heading from LSM303 Methods ------- heading() :returns: heading of board heading2() :returns: heading of board offset() :returns: offs...
f5b1f4781d71dcc4c47acd802edd2610bf4ff75a
jborlik/AdventOfCode2015
/day24.py
1,524
3.546875
4
# -*- coding: utf-8 -*- import itertools def evaluateGroup(packages, grouping): firstcount = 0 qe = 1 weight = [0,0] for i in range(len(packages)): weight[ grouping[i] ] = weight[ grouping[i] ] + packages[i] if (grouping[i] == 0): firstcount = firstcount + 1 qe...
81bd65fc946e79d7a56fafe268a7df082b1e7fe1
Jnnsm/ChatRedes
/main.py
991
3.640625
4
""" Eduardo Júnior Dias dos Santos Moreira 89395 Mateus Armond Santos 89399 """ import argparse from connection import server, client def main(): parser = argparse.ArgumentParser(description='Main do programa para Cliente/Servidor da troca de mensagens') parser.add_argument('type', help='Tipo de execução de p...
672fb1e68bb46e476d1ed90b968899128ab8bacb
JMartJonesy/Python
/Knuth.py
1,311
3.875
4
""" Jesse Martinez HW #1 """ from math import sqrt, floor, factorial from collections import deque from numbers import Integral maxFac = 200 maxRoot = pow(10,300) "Runs a Breadth First Search with the given goal" def bfs(goal): Q = deque() parents = {} parents[4] = None Q.append(4) while len(Q) != 0 and Q...
9010bd80fd883bdd79e28f4021dfef5a8e550afc
JMartJonesy/Python
/totient.py
1,070
3.53125
4
import math primes = [] #Parses a txt file with all prime between 100000 and 110000 def parsePrimes(fileName): for line in open(fileName): line = line.strip().split(" ") for prime in line: if prime.strip().isdigit(): primes.append(int(prime.strip())) def findFactors(n): index = 0 factors = [] while pr...
a84550279791d0607f73f7422fef2f650271aa4d
syamajala/euler
/p34.py
265
3.59375
4
import math def equal_factorial(n): l = map(int, list(str(n))) l = map(math.factorial, l) if sum(l) == n: return n def main(): r = map(equal_factorial, range(3, 100000)) r = [i for i in r if i is not None] print(sum(r)) main()
07645309c9a3df6bbe7636ad48b20c92330de3f8
syamajala/euler
/nonworking/p18.py
479
3.515625
4
def process(): with open("p18.txt", 'r') as f: return [map(int, i.split()) for i in f] def traverse(triangle): r = triangle[0][0] idx = 0 for i in triangle[1:]: if i[idx] > i[idx+1]: print(idx, i[idx]) r = r + i[idx] else: print(idx+1, i[idx...
9ce72a118bc9f3ea3fa704bcacd146c2dc81f3db
syamajala/euler
/p1.py
185
3.609375
4
import functools def main(): l = [] for x in range(0, 1000): if x%3 == 0 or x%5 == 0: l.append(x) print(functools.reduce(lambda x, y: x+y, l)) main()
0189bb8f00c9ef668e63a40b4c2ffacd3cbf54b8
DoFy73/test_repo
/second.py
128
3.65625
4
print("Hello World......0") sum = 0 for i in range(10): sum += i print(sum%10) x = [1,5,4,7,1,3,25] x.sort() print(x)
7cd669a320517c2659e97c1e7efa09ce459163c7
byrne-saw/mit-inro-cs-programing-python
/problem_sets/solutions/ps0.py
213
3.734375
4
import math, numpy print('Enter number x:') x = int(input()) print('Enter number y:') y = int(input()) print('x**y = ' + str(x ** y)) print('log(x) = ' + str(math.log2(x))) print('log(x) = ' + str(numpy.log2(x)))
46d4776ff2f4f8e2ef19cc040e06a854e218b24d
chrisluey/algo-practice
/src/LCS230.py
570
3.625
4
# 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int: nums = [] def checkNode(node...
591e2dfc7f0a4747aee4e854be63fc77378adbc2
chrisluey/algo-practice
/src/LCS71.py
390
3.609375
4
class Solution: def simplifyPath(self, path: str) -> str: split = [p for p in path.split("/") if p != "." and p != ""] stack = [] print(split) for ele in split: if ele == "..": if len(stack) > 0: stack.pop() else: ...
612009dfa751d3055c5268edefcf66a25eb96aac
yanmarques/python-testing
/db.py
1,578
3.625
4
from user import User class DataBase(): # Lista onde ficarao armazenado os usuarios global DB DB = [] def __init__(self): self.table = DB # Retorna uma lista com instancia de cada usuario def all(self): global DB if(len(DB) != 0): users = [] ...
3b0b86c557c50cb8b78dbec0151dd59af01a6676
annanymouse/python1project
/final.py
1,062
3.734375
4
#!/usr/bin/env python3 '''finding word length and frequency of word length''' import sys import math x = "***" o = " " def cleanup(myInput): freq = {} for punc in ".,!?:;'-": myInput = myInput.replace(punc, "") words = myInput.lower().split() wordlen = [len(word) for word in words] MAXC...
c53665dc7aa7fac0e519e7ca4bb6211c35415b75
liuxiaofeii/mm_python_mail
/mm/dataDao.py
1,221
3.9375
4
""" 连接mysql数据库 """ import pymysql#调用模块 def dao1(database=None): if database==None: return False db = pymysql.connect(host='172.17.187.201',port=3306,user = 'mm',password='Mysql@123',database=database,charset='utf8')#打开数据库连接 return db def close(db): db.close() #查看 def getAddressListByUsername(d...
d3075a86a63b8fa4b649aefaacee1ff999cd6138
HakujouRyu/School
/Lab 5/nextMeeting.py
1,084
4.3125
4
todaysInt = 8 while todaysInt < 0 or todaysInt > 7: try: todaysDay = input("Assuming Sunday = 0, and Saturday = 6, please enter the day of the week: ") todaysInt = int(todaysDay) except ValueError: if todaysDay == "help": print("Monday 0") print("Tuesday 1") ...
90072d413085b1e5c5ddcad6bd28708cf28e9a77
HakujouRyu/School
/Assignment 5/MyRectangle.py
931
4.03125
4
def isValid(width, height): if (width + height) > 30: return True else: return False def my_area(width, height): if isValid(width, height) is True: area = width * height return area else: return False def my_perimeter(width, height): if isValid(width, heig...
9037b9e61c62d70cea58c93f3b5305f11dfebe3a
HakujouRyu/School
/Lab 3/sumValue.py
198
4.03125
4
print("Please enter values below") x = int(input("x = ")) y = int(input("Y = ")) z = int(input("Z = ")) print("X = ", x) print("Y = ", y) print("Z = ", z) avg = (x + y +z)/3 print("Average = ", avg)
939f29b67a331d80df1c32d99cbb4497cb3af7aa
HakujouRyu/School
/Assignment 3/Palindrome.py
1,327
4.0625
4
userInput = 0 while userInput > 99999 or userInput < 11111: try: userInput = int(input("Please enter a number between 11111 and 99999: ")) except: print("Error: Follow the rules!") userInput = -1 onesDigit = int(userInput % 10) userInput = int(userInput / 10) tensDigit = int(userInput % ...
86b359ad684f49caaf8fb4995f1668f0c2db07ab
HakujouRyu/School
/Assignment 4/largestOccurenceCount.py
626
3.953125
4
userBank = [] reDo = True print("Lets play maths.") while reDo == True: try: userIn = int(input("Please enter a whole number (0 to quit): ")) if userIn == 0: reDo = False if userIn > 0: userBank.append(userIn) except ValueError: print('Please enter whole n...
ce2e6dbeb942b64dbb4e840158da4d6fae52380d
KTMorton/Linear_AI
/Classify_Point_Given_Line.py
1,081
3.75
4
import math,random def sigmoid(x): return 1 / (1 + math.exp(-x)) class Neuron: def __init__(self, weights, bias): self.weights = list(weights) self.bias = bias self.activateValue = 0 def activate(self, input): output = 0 for idx, element in enumerate(self.weights...
4745c7f14f075265e3fb53a7521ac33f69f8bb7d
yangkai1990/python-code
/generate.py
118
3.859375
4
mylist = [x*x for x in range(3)] print(mylist) mygen=(x*x for x in range(3)) print(mygen) for i in mygen: print(i)
bad58aefb147a11e5138541e327d3e031c4a0463
shantanu/python_projects
/chapter_6/favorite_numbers.py
431
3.953125
4
favorite_numbers = { 'josh': 5, 'dan': 64, 'anish': 59, 'tom': 7, 'prad': 69, } print ("Josh's favoite number is: " + str(favorite_numbers['josh'])) print ("Dan's favoite number is: " + str(favorite_numbers['dan'])) print ("Anish's favoite number is: " + str(favorite_numbers['anish'])) print ("Tom's favoite numb...
571d67e0fd6d72cb76929ae6e0af44aacb0f7860
shantanu/python_projects
/chapter_11/employee.py
241
3.53125
4
class Employee(): def __init__(self, first, last, money): self.first_name = first self.last_name = last self.salary = money def give_raise(self, amount=''): if amount: self.salary += amount else: self.salary += 5000
ffcbdd6be804b693b241f7661374fc0bcec7b1b3
shantanu/python_projects
/chapter_3/names.py
218
3.625
4
names = ['josh', 'aditya', 'niranjana', 'mehak'] print('Hello ' + names[-1].title() + '!') print('Hello ' + names[-2].title() + '!') print('Hello ' + names[-3].title() + '!') print('Hello ' + names[-4].title() + '!')
b01129cae44eff44d793976e60dbed8db69630fe
shantanu/python_projects
/chapter_5/toppings.py
552
3.8125
4
availible_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'extra cheese', 'green peppers', 'french fries'] #requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: if requested_topping in avail...
34ca930f77410dfda01dddb101f95ef5c9b83719
bigcat2014/Intro_to_Graduate_Algorithms
/fib.py
617
4.3125
4
#!/usr/bin/python3 # Calculates the nth fibonacci number recursively # Inputs: n >= 0 # Outputs: The nth fibonacci number # Running Time O(n^2) def FIB1(n): if n == 0: # O(1) return 0 elif n == 1: # O(1) return 1 else: # O(n^2) return FIB1(n - 1) + FIB1(n - 2) # O((n-1)...
5af9f2d341e1e8f7359ca93222b64c62d322df10
addy024/Dice-Stimulator
/dicestimulator.py
1,199
3.796875
4
import random print("DICE STIMULATOR!!!") play = "y" while play == "y": number = random.randint(1,6) if number == 1: print("-----------") print("| |") print("| 0 |") print("| |") print("-----------") if number == 2: print("-----...
a2ae62a94418f6982c259be38c60ba380f4451c6
seanxu229/LeetCodeSummary
/Tree/669.py
461
3.59375
4
'''check the null tree check the root node use the same function for 2 child node Mysolytion: ''' class Solution: def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return None if root.val<L: return self.trimBST(root.right,L,R) if root...
59cbcc053840c0ca8a16795ea1eeee2cc6e97f00
seanxu229/LeetCodeSummary
/566.py
785
3.8125
4
‘’‘ 多用append函数啊啊啊啊 先遍历把所有数放进list, 然后再按要求分别取出 ’‘’ class Solution: def matrixReshape(self, nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ matlist=[] res=[] if r*c!=len(nums)*len(nums[0]): ...
633a0fb0c44c0c19130d992b80199e37d51f3192
seanxu229/LeetCodeSummary
/Tree/563.py
465
3.859375
4
'''Notes: the tree tilt is the sum of all node tilt!! for each node, tilt is the difference between two subtree total values build a sum function to calculate the sum value''' class Solution: def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def _sum(node): if not node: return ...
e7ff7a4c3bce7795e3c78ab13a92b1690fdee19a
seanxu229/LeetCodeSummary
/414. Third Maximum Number.py
385
4.0625
4
''' 这里注意用set,set是没有.sort函数的。用了sorted(set)以后得到 的实际是一个list 并且要知道set是没有办法slicing的 ''' class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ n=set(nums) if len(n)<3: return max(nums) b=sorted(n) return b[-3]
1cae3a5e73e82b664160653a2fdcef003a5203bc
seanxu229/LeetCodeSummary
/344.py
144
3.703125
4
'''make sure how to use slicing''' class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ return s[-1:-len(s)-1:-1]
f6f47c7b7704b65307d6a714185ca671f850ecec
DgrinderHZ/1mac-fullstack-with-python-track
/variables/index_slice.py
329
3.78125
4
""" indexing : <string>[index] index = ..., -1, 0, 1, ... slicing/selecting : <string>[start : end] """ my_string = "DgrinderHZ" print my_string[0] print my_string[-1] hz = my_string[-2:] print hz def udacity(my_string): """ returns Udacity """ return "U" + my_string[2:] my_string = "audacity" print udacity(m...
5ab5d8b0eba888e2226174d18af4c9ec7fbc6de9
emakhankov/UAI_ML_Integration_11_Lite
/task01.py
427
3.546875
4
""" Создайте .txt файл, прочитайте файл с помощью Python """ with open('data01.txt', 'r') as f: line = f.readline() cnt = 1 while line: print(line.strip()) line = f.readline() cnt += 1 print() with open('data01.txt', 'r') as f: line = f.readline() cnt = 1 while line:...
2cd8d5e8ea291569622575fc42d95500ad1ad300
AP-MI-2021/lab-567-dariussandru
/Logic/undo_and_redo.py
962
3.609375
4
def do_undo(undo_list, redo_list, current_list): """ functia retine lista inaite de a fii apelata o functionalitate :param undo_list: lista de cheltuieli inaintea apelarii unei functionalitati :param redo_list: lista de cheltuieli dupa aplicarea unei functionalitati :param current_list: lista curent...
08f4f0031936322439180b6c3050e2be605250d5
marovira/marking
/test/python/root/Output, DiffC(outputdc)/Submission attachment(s)/Test.py
172
3.78125
4
# First open the file. print("Contents of file:") with open('test.txt', 'r') as inFile: lines = inFile.readlines() for line in lines: print(line.rstrip())
7d0df7467a4dc36f0ec5833cef30002d5935d660
vthorat1986/python-programs
/Regular_Expressions.py
1,182
4.21875
4
#!/usr/bin/python import re # ========== Search & Replace ============== phoneNum = '8149-13-80-26 # This is a phone number' num = re.sub(r'#.*$', '', phoneNum) print('Phone number after commet removal : ', num) num = re.sub(r'\D', '', phoneNum) print('Phone number ater removal of all non-digits : ', num)...
2cb2f96460ed06c9a585f3cf1198573d4885c533
vthorat1986/python-programs
/bmi_calculator.py
326
3.65625
4
#!/usr/bin/python height = [1.87, 1.87, 1.75] weight = [81.3, 75.5, 82.2] import numpy as np np_height = np.array(height) np_weight = np.array(weight) print(np_height) print(np_weight) bmi = (np_weight / np_height ** 2) print(bmi) print(bmi[bmi > 23]) addition = np_height + np_weight print(add...
b468784efb30f0a48ba46137eb289645b6b0d16d
vthorat1986/python-programs
/file_operations.py
1,194
3.953125
4
#!/usr/bin/python import os print('Opening file in write mode...') f = open("test.txt", "w+") print('Name of the file : ', f.name) print('Closed or not : ', f.closed) print('Opening mode : ', f.mode) f.write("My name is Anthony Gonzalvis. Main duniya me akela hoon..") print('Closing file...') f.close() ...
9ee9b98d6c5e22bc7d5f67e2e9e876eb38187195
xsaco07/Proyecto02-Analisis-Algoritmos
/Individual.py
1,081
3.546875
4
class Individual: ops = [] #Representaciones numericas de cada palabra a operar result = 0 #Representacion numerica de la palabra resultado def __init__(self): self.__aptitude = 0 self.__representation = [] def set_aptitude(self, new_aptitude): self.__aptitude = new_aptitude ...
fe703b6364b1835b433410da896166adaf129654
elijahsk/cpy5python
/practical04/q05_count_letter.py
509
4.1875
4
# Name: q05_count_letter.py # Author: Song Kai # Description: Find the number of occurences of a specified letter # Created: 20130215 # Last Modified: 20130215 # value of True as 1 and value of False as 0 def count_letter(string,char): if len(string)==1: return int(string[0]==char) return int(string[0]==char)+...
3692f79a509fa77f4f3aad338c2bb65c823364d1
elijahsk/cpy5python
/practical01/q1_fahrenheit_to_celsius.py
252
3.90625
4
# Name: q1_fahrenheit_to_celsius.py # Author: Song Kai # Description: Converting Fahrenheit to Celsius # Created: 20130121 f = float(input("Enter a Fahrenheit degree: ")) c = 5 / 9 * (f - 32) print("Converting to Celsius Degree:","{0:5.2f}".format(c))
66488b56ef595a4ce86f4936262ce9c47c2030d0
elijahsk/cpy5python
/practical03/q08_convert_milliseconds.py
813
4.1875
4
# Name: q08_convert_milliseconds.py # Author: Song Kai # Description: Convert milliseconds to hours,minutes and seconds # Created: 20130215 # Last Modified: 20130215 # check whether the string can be converted into a number def check(str): if str.isdigit(): return True else: print("Please enter a prope...
39878e089719efdb954a8c5f28da9f4efc8e50a3
elijahsk/cpy5python
/practical03/q05_compute_series.py
686
3.578125
4
# Name: q05_compute_series.py # Author: Song Kai # Description: Display the series in a table # Created: 20130215 # Last Modified: 20130215 import math def m_series(i): # find out the spaces neeeded by calculating the number # of digit of the largest number using log10 space=round(math.log10(i))+1 # s...
418174fe254b7be18494b11b506af44969f53bec
QuestTestAutomation/PersistentDesktop1python
/Oper Python/Oper Cobra/DateTime/Datetimeadd.py
278
3.828125
4
import datetime today = datetime.date.today() today_time = datetime.time(datetime.now()) print(today) print(today.weekday()) print(today_time) my_time = datetime.datetime.strptime(today_time, '%m/%d/%y') #my_time = my_time + datetime.timedelta(hours=3,minutes=59) print(my_time)
d59661cac0b3f3656d5e295c6bc2787d4aaa0477
JackFogerson/CS-156-Artificial-Intelligence
/Assignments/HW8/treasurehunt.py
11,183
4.375
4
# ---------------------------------------------------------------------- # Name: treasurehunt # Purpose: Homework 8 - Demonstrate probabilistic reasoning # # Author: Rula Khayrallah # # Copyright © Rula Khayrallah, 2020 # ---------------------------------------------------------------------- """ A Trea...
9256da2b4448b3c0d19a4ea4f239a580bc30316a
JackFogerson/CS-156-Artificial-Intelligence
/Assignments/HW5/csp.py
7,011
4.21875
4
# ---------------------------------------------------------------------- # Name: csp # Purpose: HW 5: implement the CSP class # ---------------------------------------------------------------------- """ Class definition for a Constraint Satisfaction Problem. To create a CSP object, we need to specify the following:...
ca037a6ae41f3476cfaccb70cc0daff5f99d7cef
xrw560/learn-pyspark
/basic_python/pandas_demo/pandas1.py
2,090
3.96875
4
#!/usr/bin/python # -*- encoding:utf-8 -*- """ @author: zhouning @file:pandas1.py @time:2018/5/9 11:42 """ import pandas if __name__ == '__main__': food_info = pandas.read_csv("food_info.csv") # print(type(food_info)) # print(food_info.dtypes) first_rows = food_info.head() # print(first_rows) ...
81e574eb00457ecea7afd1e15ebb8381b92970b8
gtzjesus/Hashing
/main.py
2,080
3.921875
4
# @Author: Jesus Gutierrez # # @Lab: Computer Security Password Cracking # # importing necessary libraries import sys # command line arguments import os # checking if files exist import crypt # crypt used to check MD5 hashes # set input and output files if len(sys.argv) != 4: print("Correct usage: main.py <dic...
d65a2a631b37740fdcca9e783b974878639eaa4b
nabilnabs1080/FIJ_Robotique
/00_algorithmique/01_python/exercices/jeux1.py
1,157
3.8125
4
# on a pour depart, un chiffre aleatoire qui est choisi # apres, le jeu nous demande de taper un nombre entre 0 et 100 # si la reponse est inferieur au nombre aleatoire # il doit afficher "le nombre est plus grand" # si la reponse est superieur au nombre aleatoire # il doit afficher " le nombre est plus petit" # et sin...
886ff998b5c69af0458c60f79a4db1017cea83f1
granitepillow/problems
/chess.py
1,053
3.5625
4
class QueensBoard(object): self.queens = [] self.m = None self.n = None def __init__(self, m, n, queens=[]): pass def rankfile_to_diag_forward(r, f): rout = 'a' fout = f + r.lower() - rout #eg (c,3) -> 3 + 'c' - 'a' = 5 if fout > 8: rout += chr(fout - 8 +...
ef2e114fe03548d3018d4ed56b190f1fc960a5da
belalmood/Python
/Examples/Misc/np_array_demo.py
2,541
3.921875
4
import numpy as np # # Different usage of numpy array # # Creating simple ndArray arr = np.array([1,2,3,4,5,6]) print(arr) # Array using arange funcation arr = np.arange(1,10,2) print(arr) print('Type:',arr.dtype) # Array using arange funcation arr = np.linspace(1,12,6) print(arr) print('\n\nSize:',arr.size) prin...
1762344607e9e1ab48889639eccba00368eb2cf9
jigonzalez124/stringsArraysExamples
/checkPermutation.py
830
3.90625
4
## Author: Jesus Ivan Gonzalez ## Date: August 29th 2015 ## Description: Given two strings, write a method to decide if one is permutation of the other def iq_0102(stringA, stringB): #Checks to see if inputs are strings. if true, return invalid if(type(stringA) != str or type(stringB) != str): ...
6db2c843983e94d59172e8a469d29fd117864be6
crazyapidev/question-analysis
/smart-learning/elastic_search_db/es_parse_results.py
2,399
3.671875
4
class ParseESResults(): def __init__(self,results,segment=None,lesson=None,section=None,sub_section=None): self.results = results self.segment = segment self.lesson = lesson self.section = section self.sub_section = sub_section self.parse_book_content(...
ac5d51b3f2f2540f8269fed53391debe5560666f
vaipatel/morphops
/morphops/io.py
5,064
3.5625
4
"""Provides IO functions to read from and write to files in common landmark data file formats. """ import numpy as np import morphops.lmk_util as lmk_util class MopsFileReadError(Exception): pass class MopsFileWriteError(Exception): pass def read_dta(filename): r"""Reads \*.dta files, as written by t...
96a0bfe381de5f7661388d076bfe4de49a61e359
bastien-hugon/Zappy
/bonus/IA_Python_Socket/General_comportement/foodHandling.py
264
3.78125
4
#!/usr/bin/env python3 def enough_food(level, food): if (food >= (level + 1)): return (True) else: return (False) def enough_food_incant(level, food): if (food >= (level + 8)): return (True) else: return (False)
c01942bcdee94cd47735b7788c0cb27b6b5c4225
Siremestir/data-scripts
/files_lib.py
3,024
3.8125
4
import csv def import_tsv(filename): """Parses a .tsv file into an array of arrays :param filename : the name of the file to parse :return : an array of arrays with the contents of the file """ csv = open(filename) print("Loading file " + filename) text_csv = csv.read() tmp_array = text...
d88ea2c13adeabcbbffe07d5b0d0d45224462e40
sleep1/DataCamp
/FundamentalDataTypes.py
7,272
4.4375
4
Create a list called baby_names with the names 'Ximena', 'Aliza', 'Ayden', and 'Calvin'. Use the .extend() method on baby_names to add 'Rowen' and 'Sandeep' and print the list. Use the .index() method to find the position of 'Aliza' in the list. Save the result as position. Use the .pop() method with position to remove...
d411058b53e707668075555abee42be244dc4fce
heliy/oj
/leetcode/addtwonumbers.py
1,478
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): ls = ListNode(0) pt = ls prev = ls while l1 is not None and l2 is n...
6dce3c4965f32564385623ffb9ef1528a180a016
siddk/hacker-rank
/miscellaneous/python_tutorials/mobile_number.py
469
4.125
4
""" mobile_number.py Given an integer N, and N phone numbers, print YES or NO to tell if it is a valid number or not. A valid number starts with either 7, 8, or 9, and is 10 digits long. """ n = input() for i in range(n): number = raw_input() if number.isdigit(): number = int(number) if (len...
102f802572ebef6713326047e794723f1a71b8da
siddk/hacker-rank
/algorithms/warmups/fibonacci.py
988
4.0625
4
""" fibonacci.py You are given an integer, N. Find out if the number is an element of fibonacci series. The first few elements of fibonacci series are 0,1,1,2,3,5,8,13…. A fibonacci series is one where every element is a sum of the previous two elements in the series. The first two elements are 0 and 1. Formally: f...
b90e89de330807f02410bee5f6faa321376c0a26
siddk/hacker-rank
/miscellaneous/python_tutorials/sets.py
684
4.3125
4
""" sets.py You are given two sets of integers M and N and you have to print their symmetric difference in ascending order. The first line of input contains the value of M followed by M integers, and then N and N integers. Symmetric difference is the values that exist in M or N but not in both. """ m = input() m_lis ...
940411a304b277be345feb633ba3986f70b688a4
Krishna-B5/Telusko-Python-for-Beginners
/Testing.py
698
3.9375
4
class Rectangle: def __init__(self, width, height ): self.width = width self.height = height print("When the object is created automatically get assigned:",self.width) print("When the object is created automatically get assigned:",self.height) # def compare(self): # if s...
451a11d9c6b1d2d0235b6a95cab41dcac46eb217
vadim-ivlev/STUDY
/coding/turtlle-tesr.py
2,769
3.53125
4
# import turtle # myTurtle = turtle.Turtle() # myWin = turtle.Screen() # def drawSpiral(myTurtle, lineLen): # if lineLen > 0: # myTurtle.forward(lineLen) # myTurtle.right(90) # drawSpiral(myTurtle, lineLen-5) # drawSpiral(myTurtle, 100) # myWin.exitonclick() # -------------------------...
ba0e5ea67d97a8bf79e15ac72b76b7ad02f30322
vadim-ivlev/STUDY
/coding/daily_temperatures.py
1,320
4.03125
4
# Given a list of daily temperatures, produce a list that, for each day in the input, # tells you how many days you would have to wait until a warmer temperature. # If there is no future day for which this is possible, put 0 instead. # For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], # your...
cbb33de2960bed126ad694a163a15aca703bc40a
askwierzynska/python_exercises
/exercise_2/main.py
702
4.125
4
import random print('-----------------------------') print('guess that number game') print('-----------------------------') print('') that_number = random.randint(0, 50) guess = -1 name = input("What's your name darling? ") while guess != that_number: guess_text = input('Guess number between 0 an 50: ') gues...
a03c8a55792d2b3e5432778da8659d031281e252
msitek/sql
/sqld.py
492
3.90625
4
# import from csv # import the csv library import csv import sqlite3 with sqlite3.connect("new.db") as connection: c = connection.cursor() # open the csv file and assign it to a variable employees = csv.reader(open("employees.csv", "rU")) # create a new table called employees c.executescript('''DROP TABLE IF ...
3bac677c151d0e24cf15799ecb5256f991c82aa9
Harue84/Translate
/Sixth chapter (2).py
1,576
3.578125
4
import easygui flavor = easygui.enterbox("What is your favorite ice cream flavor?") easygui.msgbox("You entered" + flavor) import easygui flavor = easygui.enterbox("What is your favorite ice cream flavor?", default = 'Vanilla') easygui.msgbox ("You entered" + flavor) import easygui name = ea...
8f457c56925085d1954cd406142e30c2006a138a
vbatiz/ejemplo-if
/assignments/01Triangulo/src/exercise.py
584
3.890625
4
import os def main(): #escribe tu código abajo de esta línea os.system("clear") angulo = int(input("Dame el ángulo en grados: ")) if angulo > 360: print("Error, el ángulo debe estar entre 0 y 360 grados") elif angulo > 180: print("Cóncavo") elif angulo == 180: print("Llan...
1607baf5554044a4870c9402e79c1ae0867faa0e
obayomi96/Algorithms
/Python/simulteneous_equation.py
786
4.15625
4
# solving simultaneous equation using python print('For equation 1') a = int(input("Type the coefficient of x = \n")) b = int(input("Type the coefficient of y = \n")) c = int(input("Type the coefficient of the constant, k = \n")) print("For equation 2") d = int(input("Type the coefficient of x = \n")) e = int(input("T...
d346fc8c3f801780ed6f55340d2c99693d192cd2
obayomi96/Algorithms
/Python/odd_even_numbers.py
160
4.3125
4
# Input any number to know if its an odd or even number x = int(input("Check number")) if (x % 2 == 0): print(x, " is even") else: print(x, " is odd")
9b6acd981eb913452c020d5bd66aac70f329fd6c
heyhenry/PracticalLearning-Python
/randomPlays.py
1,096
4.15625
4
import random randomNumber = random.randint(1, 10) randomNumber = str(randomNumber) print('✯ Welcome to the guessing game ✯') username = input('✯ Enter username: ') guessesTaken = 0 print(username, 'is it? \nGreat name! \nOkay, the rules are simple.\n') print('⚘ You have 6 attempts. \n⚘ Enter a number ranging betwe...
71fc7a06cbdd1a217e091440176371ce9bd24bad
masaru-ryumae/hackerrank
/10days-of-stats/findMode.py
928
3.5625
4
def findMode(readList): numCount={} highestNum=0 for i in readList: if i in numCount.keys(): numCount[i] += 1 else: numCount[i] = 1 for i in numCount.keys(): if numCount[i] > highestNum: highestNum=numCount[i] mode=i if highestNum != 1: print(mode) ...
74108fd80318938ebf19a38acb6308b0e768c030
CategorIAN/Perm
/src/main/perm/Grid.py
1,930
4.09375
4
class Grid: """ A class used to represent a grid of integers ... Attributes ------- phi: tuple tuple of integers encoding the row numbers of the grid psi: tuple tuple of integers encoding the column numbers of the grid Methods ------- points(Pi) Return...
9b7da202d5bee3b2eb3dab9cab262960794c979a
Asi4nn/Pygame-Graphing-Calculator
/pygrid.py
11,555
3.734375
4
# -------------------------------------------------------------------- # Program: Grid module for pygame # Author: Leo Wang # Date: April 12th # Input: Input attributes for grid objects, and parameters # for some methods # Output: Creates 3 child classes of grid that have click # detection, highlighting, and oth...
cf8dabb1cbb1db96711f0e17fb7446c279dbd564
Bayaz/LPTHW
/ex15.py
568
3.765625
4
#ex15.py reading files from sys import argv script, filename = argv txt = open(filename) print(script) print("Here's your file: %r and here is your script: %r " % (filename, script)) print(txt.read()) print("type the filename again") #allows for input of filename to be opened again #main difference is argv meth...
b97f066b9cc5904eb87b0e2c2b9248ee74386908
ccjameslai/Alg_Projects
/Data Science from Scratch/ch8.py
1,360
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 28 13:59:56 2017 @author: 2017041801 """ import matplotlib.pyplot as plt def sum_of_square(v): return sum(v_i**2 for v_i in v) def difference_quotient(f,x,h=0.00001): return (f(x + h) - f(x)) / h def extrem_point(f, ini_v, step = -0.1, e = pow(10, -7)): it...
dec491eb1ccfaf708497ed20c94f3d45aa1a4788
esergly/PythonStartLessonFour
/LessonFourAddTaskThree.py
497
4
4
vysota = int(input('Введите высоту фигуры (нечётное число): ')) if vysota%2==0: print('Введённое число не соответствует заданным условиям.') print('Картинка при выводе на экран не будет симметричной.') temp = vysota i = 0 while i < vysota: print('*' * vysota) vysota -= 2 vysota = 3 while vysot...
de5a9fdc707edaee79994df174ca98968d07228c
ivy-liu/re-Automation
/0311_01.py
980
4.34375
4
#算术运算符 a=21 b=10 c=0 c=a+b print("a+b=",c) c=a//b print("a//b=",c)#取整除 - 返回商的整数部分(向下取整) c=a/b print("a/b=",c) c=a**b print("a**b=",c) c=a*b print("a*b=",c) #条件语句,判断 jin=90 qu=75 ts=(jin-qu)/qu*100 print('小明成绩提升百分点:%.1f' % ts+'%') flag=False name="xiaoming" if name=='小明'or'xiaoming': flag=True print('是的,对...
65269b4c871e2c56508d8fbd8a9ae8c1b52f8bdc
ivy-liu/re-Automation
/0314_functionAndDict.py
3,633
4.09375
4
#函数、字典 #字典中的操作 print('取值\n') dict1={'name':'小强','age':18,'class':'first'} print("dict1['name'] 名字为",dict1['name']) print("dict1.get('name') 名字为",dict1.get('name')) print(dict1.get(18)) #修改 print("\n修改\n") print('原字典',dict1) dict1['name']='花花' print('现字典',dict1) #新增 print("\n新增\n") dict1['school']='啥啥大学' print('新增sc...
39f360ae4828952b4da6249bacfadda4671911d2
aryashah0907/Arya_GITSpace
/Test_Question_2.py
454
4.40625
4
# 3 : Write a Python program to display the first and last colors from the following list. # Example : color_list = ["Red","Green","White" ,"Black"]. # Your list should be flexible such that it displays any color that is part of the list. from typing import List color_list = ["Red", "Green", "White", "Black", "Pink", ...
ea89cb200526bdfc125ddf29a5a0ec7f48665cf9
ragingCow/leetcode
/src/RemoveNthNodeFromEndOfList/solution.py
859
3.65625
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ length = self.calLength(head) nth = le...
ab0d07e647ac649b45f2fe59f0368e1ed85e6c82
erin2722/PClassicComps
/PClassicSpringCompetition2016/CipherCracking.py
852
3.921875
4
def closest_vowel(s): vowels = ["a", "e", "i", "o", "u"] word = s i = 0 j = 0 f = 0 e = len(word) - 1 for i in range(0, len(word)): if word[f] is vowels[0] or word[f] is vowels[1] or word[f] is vowels[2] or word[f] is vowels[3] or word[f] is vowels[4]: return word[f] ...
c66ef016ff4530f21914ab5afeae22b17a2bb6d9
mouyleng2508/PycharmProjects
/week02:ex/25_sum_of_list.py
131
3.765625
4
def Sum_of_list(lists): sum = 0 for x in lists: sum += x return sum a = Sum_of_list([20, 15, 10, 30]) print(a)
c39aa67285ac5af367e662bb7b4b7b622fa3f097
mouyleng2508/PycharmProjects
/week04:projects/01_eight_queens.py
404
3.5
4
from itertools import permutations def eight_queens(N): sol = 0 cols = range(N) for combo in permutations(cols): if N == len(set(combo[i]+i for i in cols)) == len(set(combo[i]-i for i in cols)): sol += 1 print('Solution '+str(sol)+': '+str(combo)+'\n') print("\n"....
073bfcedf7851f258ecb0bfe400ca6cc3bf9300a
mouyleng2508/PycharmProjects
/week03:ex/60_message_converter.py
186
3.90625
4
import codecs def message_converter(string): converted = '' for i in string: converted += hex(ord(i))[2:].upper() return converted print(message_converter("Hello"))
7a5a664f4472a71673c91481cf77cfb0f5bf70ce
mouyleng2508/PycharmProjects
/BasicPython/list_exercise.py
744
3.5625
4
#Exercise1 # aLsit = [100, 200, 300, 400, 500] #my_solution # aLsit.sort() # aLsit.reverse() # print(aLsit) #other # aLsit = aLsit[::-1] # print(aLsit) #Exercise2 # list1 = ["M", "na", "i", "Ke"] # list2 = ["y", "me", "s", "lly"] # res = [i + j for i, j in zip(list1, list2)] # print(str(res)) #Exercise3 # aList = [1...
7f72176d156abb3005a42c781d4a0d2855d648d4
mouyleng2508/PycharmProjects
/week04:ex/66_delete_file.py
434
4
4
import os def delete_file(file): file = os.path.exists() while True: inputs = input(f"Are you sure you want to delete {file}?[Y/N]") if inputs != "Y" or inputs != "y" or inputs != "N" or inputs != "n": return "Invalid Option" continue else: if os.remov...
52314632a77e32984e1ca6a49628ff27799a7559
mouyleng2508/PycharmProjects
/week01:ex/14_str_upper.py
97
3.765625
4
string = input("Input a string") print(["The string is empty.", string.upper()][len(string) > 0])
ac9de1f5797579203874fef062220415cc7a3c13
cvhs-cs-2017/sem2-exam1-LeoCWang
/Function.py
490
4.375
4
"""Define a function that will take a parameter, n, and triple it and return the result""" def triple(n): n = n * 3 return (n) print(triple(5)) """Write a program that will prompt the user for an input value (n) and print the result of 3n by calling the function defined above. Make sure you include the neces...
886ed0c0e8ef5d4e8618262aadbdfc100fcd2552
GrumpyJun/Mit-6.00-OCW-Problem-Set-Solutions
/ps00 - if Exercises.py
413
3.953125
4
#!/usr/local/bin/python guess_count=0 password = 'taco' print ("This program requires a password. You can only guess three times.") while guess_count < 3: entry = raw_input("Password: ") if entry != password: guess_count = guess_count + 1 if guess_count == 3: print ("You have been denied access.") else: ...
e4dd5d3cedaebab916b6bc495e8cc9c974cb6d34
Ashishvella/PythonSamples
/deepshallow.py
742
3.921875
4
import copy #ReferenceCopy a=10 b=a print "Address of a", id(a) print "Address of b", id(b) #DeepCopy-- any changes made to Original object do not reflect in the copy object. list1=['Str1',1,'Str2',2.0,0xDDDD,1+5j] print "Original list1", list1 list2=copy.deepcopy(list1) print "Deep-copied list2", list2 list1.e...
94887c19e9e6254584bb16d17684226f6cf0e679
luffysk/coderesources
/python/1.base/2.const.py
135
3.75
4
# python中没有定义常量的方式,只有约定俗成的认为变量大写即为常量 PI = '3.14' print(PI) PI = '123' print(PI)
1ce5245bebfd0e12605f9a1fac47a3fd985c080c
luffysk/coderesources
/python/1.base/11.str_format.py
255
4.28125
4
# 格式化输出字符串有三种方式 # 第一种 a = 'str' b = 'str2' print('a is ' + a + ', b is ' + b) # 第二种 a = 's1' b = 's2' print('a is %s, b is %s' % (a, b)) # 第三种, 推荐此种 a = 'fstr' b = 'fstr2' print(f'a is {a}, b is {b}')
9c07a44d114c1dfe4674c231dab37484e08a6a37
dexterpengji/practice_python
/selfPractice/algorithm_001_twoSum.py
483
3.6875
4
nums = [3,2,4,15,65,231,11,20] target = 31 class Solution_1: def twoSum(self, nums, target): for inde_1,x in enumerate(nums): for inde_2,y in enumerate(nums): if x+y == target and inde_1 != inde_2: return([inde_1,inde_2]) class Solution_2: def twoSum(self, nums, target): dic = {} for i,x in enume...
9040c3eeb0c6b4bf7cdff293644912e879a07eee
dexterpengji/practice_python
/fishC/038_class_inherit.py
919
4.15625
4
# -*- coding: utf-8 -* import random as r class Fish: def __init__(self): self.x = 100 self.y = 100 def move(self): self.x += r.randint(-5,5) self.y += r.randint(-5,5) print("position",self.x,self.y) class Gold_Fish(Fish): def __init__(self): #Fish.__init__(self) # way 1 super().__i...
1e5d1a995c34932d9bb7ec1cc386e1fd7f8fdf9f
dexterpengji/practice_python
/selfPractice/algorithm_003_charStatistics.py
239
3.71875
4
str1 = ';lkasjdm;lkjsafkl;jdsal;fjldskajl;kasdf' print(str1) seen = [] for cha in str1: if cha not in seen: seen.append(cha) print(cha,str1.count(cha),str1.index(cha)) else: pass str2 = list(str1) str2.insert(0,'000') print(str2)
cb5c3693b6ca5fbb9de43b34aa33190f509579ee
minlee199709/coding
/Python_Practice/TimeConversion.py
1,137
4.03125
4
#Given a time in 12-hour AM/PM format, convert it to military (24-hour) time #!/bin/python3 import math import os import random import re import sys # # Complete the 'timeConversion' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def...
d18c8a6e5df6cba54cd3afc5922694e58ba0fe3e
abdurahmanadilovic/elements-of-programming-interviews
/hackathon/column0/problem_17_1_score_combinations.py
1,015
3.5
4
def solution(score): # solutions = {} # solve(0, score, [], solutions) # return len(solutions.keys()) return solve2(score) def solve(current_score, target_score, path, solutions): if current_score > target_score: return 0 elif current_score == target_score: path_sorted = str(so...