blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7b68aa8a5333bc5a7b27b6aaf6db413119d9244f
timManas/PythonProgrammingRecipes
/project/src/Functions/ReturnMultipleValues.py
1,107
4.25
4
class TestObject: def __init__(self): self.str = "HelloWorld" self.x = 10 self.y = 20 self.z = 30 pass pass def usingObject(): print("\nReturn multiple values using Object") testObj = TestObject() print("Str: ", testObj.str) print("X: ", testObj.x) ...
485edcf3a9e86352bcb7ecacd38f3dc0613cbd14
bran0144/lab-exercise-2
/solution/solution/further-study/calculator.py
2,072
4.125
4
"""CLI application for a prefix-notation calculator.""" from arithmetic import (add, subtract, multiply, divide, square, cube, power, mod, ) def my_reduce(func, items): result = func(items[0], items[1]) for item in items[2:]: result = (func(result, item)) return result ...
01c1e9293b639a1c219eba7419233de92cec25ad
czx94/Algorithms-Collection
/Python/JianzhiOffer/question65_1.py
389
3.5625
4
''' construct a func add without +-*/ leetcode 371 ''' import random def solution1(n1, n2): while n2: sum = n1 ^ n2 carry = (n1 & n2) << 1 n1 = sum n2 = carry return n1 if __name__ == '__main__': for i in range(5): n1 = random.randint(0, 20) n2 = random.rand...
cc8084e3ac3a171d74554b8c84330654009ed58f
gaohongsong/flush_me
/1.设计一个有getMin功能的栈_1.py
3,698
3.71875
4
# -*- coding:utf-8 -*- """ 题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素 要求: 1.pop、push、getMin操作的时间复杂度都是O(1) 2.设计的栈类型可以使用现成的栈结构 """ class MyStack(object): """ 解法二:基本栈进出操作的同时,选择性进出最小栈 入栈基本元素的同时,如果基本元素小于等于最小栈的栈顶元素,则同时入栈当前元素到最小栈 出栈基本元素的同时,如果基本元素等于(不会小于)最小栈的栈顶元素,则同时从最小栈...
1af3d40db65c153853de89a98f726384ebde38aa
YuedaLin/python
/StudentManagerSystem/managerSystem.py
5,714
3.953125
4
# 需求:系统循环使用,用户输入不同的功能序号执行不同的功能 """ 步骤: 一、.定义程序入口函数 1.加载数据 2.显示功能菜单 3.用户输入功能序号 4.根据用户输入的功能序号执行不同的功能 二、.定义系统功能函数,添加、删除学院等 """ from student import * class StudentManager(): def __init__(self): # 存储数据所用的列表 self.student_list = [] # 一、程序入口函数,启动程序后执行的函数 def run(self): # 1...
d1aa5baa2a2eef7390ddd58720bc0d0c283327c6
lxyxl0216/sword-for-offer-solution
/codes/python/28-对称的二叉树.py
732
3.90625
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 isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ # 先...
0bcea099f189dbf2d06626999ed0d2d0d2d431d8
georgeteo/Coding_Interview_Practice
/chapter_11/11.2.py
886
4
4
''' CCC 11.2: Write a method to sort an array of strings so that all anagrams are next to each other. ''' from collections import defaultdict class anagram_hash: def __init__(self): self.dictionary = defaultdict(list) def hash_word(self, word): ''' Time Complexity: O(nlogn) # Merge sor...
12d1395cb6e410c7d5856e6aabd85e746756e806
pingjuiliao/solver
/n_queen/constraint.py
1,102
3.578125
4
#!/usr/bin/python import sys from z3 import * def solve_n_queens(n) : ## message out print "solving %d queens problem" % n ## create symbols symbols = [Int("q_%d" % i) for i in range(n)] bounds_c = [ And(0 <= symbols[i], symbols[i] < n ) for i in range(n) ] rows_c = [ Distinct(symbols) ] ...
41f8299540dcbb0de546348d07f39c9a3ce15d26
meppps/PyJunk
/fourth_file.py
191
3.859375
4
user_play = "y" while user_play == "y": user_number = int(input("How many numbers? ")) for x in range(user_number): print(x) user_play = input("Continue: (y)es or (n)o")
9cea8f08ea6f044800bf331733884b59494cac76
Questandachievement7Developer/q7os
/module/Assistant/extension/WeatherPredictPythonML/aa.py
26,940
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # Using Machine Learning to Predict the Weather: Part 3 # # This is the final article on using machine learning in Python to make predictions of the mean temperature based off of meteorological weather data retrieved from [Weather Underground](www.weatherunderground.com) as des...
444f1b1197e7bb61bda7aaf5dfffc7edaa15cf6b
khsc96/Sudoku
/Sudoku.py
4,159
3.828125
4
# Sudoku game and solver using python # solver uses backtracking algorithm import pprint from random import shuffle, randint from copy import deepcopy board = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0...
52f5de7bc705e86a0992a0ced83ca9f8b3398fef
Rider66code/PythonForEverybody
/bin/p3p_c2w4_ex_015.py
357
4.125
4
#Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return the first parameter multiplied by the second. def mult(num,sattr=6): mul_num=num*satt...
e1ebd94938b64474d79abcde011d26ba994920f4
TrySickle/Saugus
/Euler/euler7.py
508
4.0625
4
import math def isPrime(x): if x == 2 or x == 3: return True if x % 2 == 0: return False for y in range(3, x / 2, 2): if x % y == 0: return False return True counter = 2 check = 6 while True: if isPrime(check - 1): counter += 1 if counter == 100...
8cbf818524307d7f1aa7d3f1e5f8e98a9eb39d88
EliRuan/ifpi-ads-algoritmos2020
/LISTA Fábio 01_Parte 01/f1_q21.py
188
3.859375
4
#entrada temp_fahr = float(input('Digite a temperatura em °F: ')) #processamento temp_celsius = (5 * temp_fahr -160) / 9 #saída print('A temperatura em °C é:', temp_celsius)
1676ecd2614a5b80cc654a915ba5a666019ec7e6
rcmckee/InvalidPatents
/loopthroughURLlist.py
791
3.75
4
#https://docs.python.org/2.7/library/fileinput.html #file_input = testUrlList.txt #import fileinput #for line in fileinput.input(testUrlList.txt): # process(line) # print line #https://stackoverflow.com/questions/19140375/python-how-to-loop-through-a-text-file-of-urls-and-pass-all-the-urls-into-a-re #filename =...
91767dbc91951f8a111c7947367f8ab57d3c02e5
omkar1117/pythonpractice
/user_data_list.py
862
4.34375
4
import sys name = input("Enter your First Name:") lname = input("Enter your Last Name:") email = input("Enter a valid Email:") mobile = input("Enter a Valid No:") if not name or not lname or not email or not mobile: print("You need to enter all values") sys.exit(0) l=[name, lname, email, mobile] print("Your ...
9c1a126b42e855a236793ad486f6e11da92ed493
PSY31170CCNY/Class
/Justin Pearce/Final project-location.py
1,401
4.03125
4
from collections import Counter # Tried to use csv to make it easier to manage data but it can use without. e=open('data.csv','a') columnTitleRow = 'data' e.write(columnTitleRow) e=open('data.csv','r') w=e.readlines() data_set = "BRONX BROOKLYN BROOKLYN BRONX QUEENS MANHATTAN BROOKLYN MANHATTAN MANHATTAN STATEN I...
fe54141115a590bbe560602ca8fec3ce9d00cd1f
Toofifty/project-euler
/python/007.py
382
3.734375
4
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ import timer @timer.many(5) def main(): i = 3 n = 1 while n < 10001: if not any(d for d in range(2, 2 + int(i ** 0.5)) if not i % d): n += 1 ...
7a4fcb2f35adeb7e9a356c46cf9a794512b15c4d
yichenluan/LeetCodeSolution
/backup/Python/282.py
789
3.53125
4
class Solution(object): def addOperators(self, num, target): def handler(num, candidate): if not num: if eval(candidate) == target: res.append(candidate) return for i in range(1, len(num) + 1): if num[0] == ...
ee884175d5241aec3000ead6c27b84a08a5e1600
CSheets3/HudlPartB
/TestAPI.py
2,015
3.78125
4
import unittest import main # You could also import Json for this project and sift through the information that way # On success all cases would throw a 200 code class APITest(unittest.TestCase): def test_get_request(self): # If this test succeeds then the user would be able to look at the team informatio...
513167af78eb7771c8595f450dd004ec19863273
kennethisma/App_Brewery_Projects
/Day22_Pingpong_game/My Solution/ball.py
637
3.875
4
from turtle import Turtle import random POSITIONS = [10, -10] class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.penup() # Random start position of ball. self.yball_pos = POSITIONS[0] self.xball_pos = PO...
2fe8907240fd02ad467312f713b5c263419d124c
Haruka0522/AtCoder
/ABC/ABC134-C.py
475
3.5
4
'''TLE解答 N = int(input()) A = [] for i in range(N): A.append(int(input())) for num,a in enumerate(A): del A[num] print(max(A)) A.insert(num,a) ''' '''TLE解答 A = [int(input()) for i in range(int(input()))] for i in range(len(A)): print(max(A[:i]+A[i+1:])) ''' #解説を見て A = [int(input()) for i in range(...
5f6324aac4e9b5db450213bdf8c10966a0f445d1
nfonsang/circles
/circle.py
521
4.03125
4
# Developer A ## Create a function that computes the area of a circle def circle_area(radius): pi = 3.14 area = pi*(radius)**2 return area print("Testing the area function:") print("The area of a circle with radius=10 is: ", circle_area(10)) print("The area of a circle with radius=15 is: ", circle_area(15...
0337a500938f15a2e0a714d4390024ce0ed6e2df
GeoffreyRe/Project_3_macgyver
/Map.py
2,222
3.640625
4
import pygame import json import random # class that contains methods and attributes linked with the map list class Map(object): def __init__(self): with open("ressource/map.json") as f: # transform an json file into a python object self.map_list = json.load(f) # method that fi...
e8c7b968d9da165c75348cee504db62c877eddd1
ziyuan-shen/leetcode_algorithm_python_solution
/medium/ex1344.py
267
3.578125
4
class Solution: def angleClock(self, hour: int, minutes: int) -> float: minute_angle = 360 * minutes / 60 hour_angle = (hour % 12 / 12) * 360 + 30 * minutes / 60 angle = abs(minute_angle - hour_angle) return min(angle, 360 - angle)
df9bfa0e65d4d9e90311101bde0eb90e494be895
saehyuns/hw2
/hw2n1/parDBd.py
1,527
3.734375
4
# Importing all the necessary libraries. import socket import sqlite3 from sqlite3 import Error import sys from sys import argv # A main function that takes in two commandline arguments. def Main(argv): host = argv[1]; port = argv[2]; # Store data received into datas array. datas = []; mySocket = socket....
871fe8dd09b9f625c8c41714de7d2c79fa7c5157
sp2301-bot/CSES-Python-Solutions
/Introductory Problems/Palindrome Reorder.py
644
3.53125
4
s = input() first = "" second = "" res1 = set() odd = False count = 0 for i in s: res1.add(i) for i in res1: x = s.count(i) if(x & 1): count+=1 oddc = i oddcount = x odd = True if(odd): s = s.replace(oddc,'', oddcount) oddc = oddc*oddcount if(count>1):...
b164c78326a3133b83951afdd109b2e43127c59c
daniel-reich/ubiquitous-fiesta
/F77JQs68RSeTBiGtv_17.py
299
3.65625
4
def diamond_sum(num): if num == 1: return 1 ​ mid1 = (num + 1) // 2 mid2 = ((num ** 2 - num + 1) + (num ** 2)) // 2 res = mid1 + mid2 ​ for i in range(num - 2): s = num + (num * i) + 1 e = s + num - 1 res = res + (s + e) ​ return res
c64426fd7b0eb7c726bd6c27c1209085fb776f4e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/79ba2c6fc511491ea60fd6b8f3c99bba.py
510
3.65625
4
# wordcount.py import string def word_count(phrase): returnDict={} for word in phrase.split(): # split by spaces word=word.strip(' \n\r\t'+string.punctuation) # strip whitespace and punctuation word=word.lower() # lowercase everything if len(word)==0: # if there is nothing left, continue on to next ca...
0900358769f1d3f70c5b1d5f50985bb4fbb13b0c
mangesh-kurambhatti/Python-Programms
/Basic_Programs/36_isArmstrong.py
449
3.84375
4
def isArmstrong(num): remiander=0; sum1=0 num1=num while num>0: remainder=num%10 sum1=sum1+(remainder*remainder*remainder) num=num//10 if num1==sum1: return True #print("Success") else: return False #print("fail") def main(): num=eval(input("Enter the number :")) if isArmstrong(num): print(...
3ff87386a371a07b0c241d5608128b1551c1d507
tomparrish/Sandbox
/hangman.py
2,566
3.671875
4
# A Hangman style program that uses m-w.com's word of the day from urllib.request import urlopen from bs4 import BeautifulSoup import time def getword(): soup = BeautifulSoup(urlopen("https://www.merriam-webster.com/word-of-the-day"), "lxml") phrase = soup.title.string word = phrase.split()[4] word = w...
33051c63776b5a4323320d4fd184d78c5915b979
rafaelperazzo/programacao-web
/moodledata/vpl_data/148/usersdata/264/86624/submittedfiles/testes.py
360
3.859375
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO n= int(input('Digite o número de temos:')) numerador=1 denominador=1 soma=0 while numerador<n: if numerador%2==0: soma=soma-(numerador)/(denominador**2) else: soma=soma+(numerador)/(denominador**2) numerador= numerador+1 denominador= (...
f3330eca916c4e8fe1eb620b91eef5999504b690
anarsultani97/neural-networks
/machine-learning/multiple-linear-regression/example-2-car-prices/multiple-linear-regression.py
2,154
3.8125
4
# pandas library to get the data out of csv file import pandas as pd # datetime to get the current year import datetime # PyPlot to visualize the results import matplotlib.pyplot as plt # train_test_split method from cross validation library to split the dataset into train and test parts from sklearn.cross_validation ...
3965974695dbf3444df66b78117facc5c8dcf430
motiondepp/SmallReptileTraining
/ConcurrentSpider/demo_thread.py
1,173
3.734375
4
import _thread import time ''' Python 3.X _thread 模块演示 Demo 当注释掉 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 467195 等,并发问题。 当保留 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 1000000,锁机制保证了并发。 time.sleep(5) 就是为了解决 _thread 模块的诟病,注释掉的话子线程没机会执行了 ''' class ThreadTest(object): def __in...
3a98718ac3346b15849cb4c79987afc72b0ff8f1
gpuweb/gpuweb
/tools/extract-idl-index.py
2,165
3.515625
4
#!/usr/bin/env python3 # Extracts the text from the "IDL Index" section of a Bikeshed HTML file. # Does so by first finding the "IDL Index" header <h2> element, then printing # all the text inside the following <pre> element. import argparse from datetime import date from html.parser import HTMLParser HEADER = """ //...
b8345eba7203b7813d64ed29b968ca1a0d39f39f
MalachiBlackburn/CSC221
/Blackburn_CW_3-27-18.py
888
3.640625
4
def main(): ## my_string= "One two three four" ## #print(my_string) ## ## word_list = my_string.split() ## ## print(word_list) ## date_string = "03/27/2018" ## ## date_list = date_string.split('/') ## print(date_list) ## print("Month:", date_list[0]) ## print("Day:", date_...
490b086dc08524fb64bd20e4f0f74b4481469dd1
cclindsay/py3-twentyone
/blackjack.py
1,975
3.703125
4
# BlackJack Simulation - Main User Interface # Cameron Lindsay, COSC 1336 021 # December 2016 #!python3 def main(): import playhand title() playAgain = True winCount = 0 lossCount = 0 gameCount = 0 while playAgain: if playhand.PlayHand(): winCount += 1 else: lossCount += 1 ...
7e9f0c8c4801bcd3ead02a66213d51c50ea1abd6
xixixixixiC/LeetCode_explore
/math/13_roman_integer.py
523
3.765625
4
class solution: def reverse(self,s:str)->int: dict={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} s=s.replace('IV','IIII').replace('IX','VIIII') s=s.replace('XL','XXXX').replace('XC','LXXXX') s=s.replace('CD','CCCC').replace('CM','DCCCC') sum=0 for i in s: ...
b8d4aabf4d7ffd6d560182886b08c565aaebeafd
Deepak11python/Python_Code
/ex1_variable.py
314
3.84375
4
## Date : 01-APR-2019 ## Variable, accept input from users ## ## ## ## Name = str(input("Enter your name:")) Age = int(input("Enter your age:")) Ht = int(input("Enter your Height in cms:")) wt = int(input("Enter your Weight in KG:")) print ("Welcome Mr.", Name, "Your age is ", Age, "weight,height are", wt,Ht)
4a7104c35965d9ac751e47c80304d17675704b77
zupercat/python-projects
/weektwo/day1/zodiaccalc.py
1,957
3.984375
4
print("Hello and welcome to zupercat's almighty zodiac calculator.") while True: birth_year = input("Please state your birth year.") if birth_year.isdigit(): break print("Calculating...Beep boop...") def calculate_zodiac(birth_year): remainder = int(birth_year)%12 if remainder == 0: zodiac = "Monkey" elif ...
282ece308538c6a47e39d90207863a358d2f0905
bakunobu/exercise
/python_programming /Chapter_1.3/checker_board.py
600
4.21875
4
""" Составьте программу checkerboardру, получающую один аргумент ко­мандной строки n и использующую вложенный цикл для вывода двумер­ного узора n х n, наподобие шахматной доски с чередующимися пробела­ми и звездочками. """ def checker_board(n): for x in range(n): if x % 2 == 0: print(* list('*...
be03b82424accd320e3c1d62b54225cf929f3a48
Danieldev28/Leap_year
/my_test.py
533
3.8125
4
# # test to check if two values are equal # def test(actual,expected): # assert actual == expected, "So here {} was not equal to {} as expected".format(actual,expected) # print("passed all tests!") assert leap_year("") == False, "not an even number" assert leap_year("somthing") == False, "Please enter a number" as...
f4a1641318e9fd9896775ab1a9a9997d504bc7ce
dbsehgus94/Pythonstudy
/PythonTest/test_281-290.py
1,545
4
4
class Car: def __init__(self, wheel, price): self.wheel = wheel self.price = price def info(self): print("바퀴수", self.wheel) print("가격", self.price) #car = Car(2, 1000) #print(car.wheel) #print(car.price) class Bicycle(Car): def __init__(self, wheel, price, dr...
b63ca0fb6d9b54a0bf8a11b16f442411be373069
elp2/advent_of_code_2019
/6/6.py
2,123
3.921875
4
class Orbits: def __init__(self, filename): self.planets = {} self.add_orbits(filename) def add_orbits(self, filename): lines = open(filename).readlines() for line in lines: line = line.strip() [parent, child] = line.split(')') p = self.add_pl...
c9f770222d1b994cc2e306b9fa64cfa15779c8a4
alineberry/alcore
/alcore/data/vocab.py
2,784
3.65625
4
from ..utils import * from collections import Counter from itertools import chain import copy def calc_token_freq(series): """Function to quickly compute all token frequencies in a corpus. Assumes the text has already been tokenized. Args: series (iterable): An iterable (typically a pandas series) c...
76a97dfec25d11326eefadf7b850694e0d361ba7
utkarsh192000/PythonBasic
/211membershipOperator.py
292
3.8125
4
# in and not in are membership operator a=[10,20,30,40,50] b={1,2,3,4} c=(1,2,36,8) stu={ 101:"Rahul", 102:"raj", 103:"Sonam", } print(10 in a) print(10 not in a) print(1 in b) print(10 not in b) print(36 in c) print(101 in stu) print("Rahul" in stu) print("Suresh" not in stu)
3260dc202a1f0df2621ffc621a1a6c31d979cdad
clarkngo/python-projects
/archive-20200922/leetcode-contests/diagonal_sort.py
938
3.984375
4
# Sort the Matrix Diagonally # User Accepted:1012 # User Tried:1103 # Total Accepted:1020 # Total Submissions:1432 # Difficulty:Medium # Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array. # Example 1: # Input: mat = [[3,3,...
7190828dd59e7883559730d316eb796b3831cd1e
anuragseven/coding-problems
/online_practice_problems/Circular and doubly linked list/Doubly linked list Insertion at given position.py
350
3.96875
4
# Given a doubly-linked list, a position p, and an integer x. The task is to add a new node with value x at the position just after pth node in the doubly linked list. def addNode(head, p, data): p1=head while p1.next is not None and p!=0: p1=p1.next p-=1 t=Node(data) t.next=p1.nex...
f6dd773ad1114493bf81279f06bc447d8eaa7db1
aruba8/packetfabric-test
/util.py
2,254
3.640625
4
import base64 import codecs import configparser import hashlib import hmac from urllib.parse import quote_plus def generate_hash(key_secret, query_string=None): """ key_secret: The secret key associated with the API key you'll be passing in the `api_key` parameter. It is a tuple with the following for...
61487b9cf0841b277e4a0e4a1baf951f5ef20208
AbhishekTiwari0812/python_codes
/BucketSort.py
604
3.828125
4
import pdb def InsertionSort(bucket): for i in range(len(bucket)): pivot=bucket[i] j=i-1 while j>=0 and bucket[j]>pivot: A[j+1]=A[j] j-=1 A[j+1]=pivot def BucketSort(A): #pdb.set_trace() B=[[]]*len(A) #make all the elements ranging from 0 to 1 MAX=max(A) MAX+=1 for i in range(len(A))...
08dceffe39e75c55ae69cc9c66c7a558c79fa15d
reedx8/Python-Demonstrations
/series_sum.py
632
3.9375
4
'''Sum of the first nth term of Series''' from decimal import Decimal def series_sum(x): series = [] b = 1.00 # series must start with '1' number, so I hardcoded it in. c = 1 # increments the denominator thru each iteration. See c in loop below. for series_number in range(0,x): series.appe...
1a64000c3659b602d6e3a192cff55dbea389171c
hwadhwani77/python_lab
/dp.py
596
3.6875
4
def fib_dp(n: int, memo: list): result = 0 if memo[n] != None: return memo[n] if n == 1 or n==2: result = 1 else: result = fib_dp(n-1, memo) + fib_dp(n-2, memo) memo[n] = result print(memo) return result def fib_bottom_up(n): if n ==1 or n ==2: return 1 ...
d6267d9b4c9ae3cd79b9b6a3e40b32f139e08fa3
SaiRithvik/Python_mycaptain
/triangle.py
335
4.15625
4
a = float(input()) b = float(input()) c = float(input()) if(a==b and a==c): print("the triangle with length of sides as a,b,c is EQUILATERAL ") elif(a==b or b==c or c==a): print("the triangle with length of sides as a,b,c is ISOSCELES ") else: print("the triangle with length of sides as a,b,c is SC...
bcf2c82d4fa2eb1159e635122d8a63ebae4efbb4
SixuLi/Leetcode-Practice
/First Session(By Tag)/Hash Table/138.Copy List with Random Pointer.py
1,882
3.875
4
# Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random # Solution 1: Hash Table # We solve this problem in two loops: # In the first loop, we scan the original linked list and make ...
63385330ac70bdb875cbc6ff178d687872846f9a
theomeli/Mathesis-apps
/diavgeia app/diavgeia app.py
5,017
3.703125
4
# mathesis.cup.gr course with title "Introduction to Python" # Final Project: Data retrieval from diavgeia.gov.gr import re import urllib.request import urllib.error authorities = {} def rss_feed(url): ''' Opening of rss feed, :param url: the address of rss feed. This function creates a file with th...
a83d1dc7a1835e3e29e27b86f585735b5ef6f48d
mkarimi20/python
/while_loop.py
1,344
4.28125
4
# count = 0 # while(count < 9): # print('the count it: ', count) # count = count+1 # print('Out of loop') # The Infinite Loop # A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious # when using while loops because of the possibility that this condition never resolves to a # F...
c5449a4b765d6bb700ef2eeaf68736c1e4d08cbf
ywtail/codeforces
/112_785A.py
450
3.6875
4
# coding=utf-8 # 785A. Anton and Polyhedrons 安东和多面体 n = int(raw_input()) re = {'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20} ans = 0 for i in range(n): polyhedron = raw_input() ans += re[polyhedron] print ans """ input 4 Icosahedron Cube Tetrahedron Dodecahedron output 4...
868b429f6a19a26596684c5d7515818acd47688d
syeluru/MIS304
/Notes/HW2/CompoundInterest.py
943
3.9375
4
# Program to compute compound interest import math import tkinter.messagebox def main(): a = 1000 #Initial amount n = 10 #Number of years r = 5 #first rate of interest final_message = '' final_message += print_header_line() + '\n' line = "----------" final_message += "----%12s%12s%12s%1...
78d8c53b9c5da1b557ec9ec694221ea201625c5c
mindovermiles262/codecademy-python
/11 Introduction to Classes/05_instantiating_your_first_object.py
396
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 8 08:23:11 2017 @author: mindovermiles262 Codecademy Python Outside the Animal class definition, create a variable named zebra and set it equal to Animal("Jeffrey"). Then print out zebra's name. """ class Animal(object): def __init__(self,...
e8b123973285dad6fb2f3e5a8eb8993bfd7ed464
yz830620/oop_prctice
/chapter3/house_project/propety/propety.py
3,098
3.765625
4
"""file define class which define propety""" def get_valid_input(input_string, valid_options): response = input(f"{input_string}({', '.join(valid_options)}) ") while response.lower() not in valid_options: print(f"please choose within ({', '.join(valid_options)}) ") response = input(input_str...
a274a778cd4a281359b940c8e06d079c15f6e97a
lcwspr/Python
/999_test/python复习/python 基础/8 python 函数/4 高阶函数.py
869
3.734375
4
""" a, b 形参 , 2 变量 传递数据 就是指 给变量赋值 def test(a, b): print(a + b) 其实函数名也是一个变量名 开辟空间 将函数体拷贝到内存出 键地址赋给 2 变量 函数本身也可以作为数据 传递给一个变量 概念 当一个函数A的参数 接受的又是另一个函数时 则把这个函数A称为高阶函数 例如 sorted 函数 案例 动态的计算两个数据 比较列表中的字典 """ l = [{"name": "sz", "age": 28}, {"name": ...
e1618bbf96246099811f4e6e56112301acd78ca6
plcx/python-
/静态方法.py
279
3.84375
4
class Person(object): __count = 0 @staticmethod def how_many(): return Person.__count def __init__(self, name): self.name = name Person.__count = Person.__count + 1 print(Person.how_many()) p1 = Person('Bob') print(Person.how_many())
0b8f395421c478cc39f1d771d056b7f7c75ccccd
droy78/Leetcode
/70.ClimbStairs.py
1,792
3.84375
4
class Solution(object): #As a lazy manager, I just want to focus on the number of ways a person can reach #my level i. There are actually just 2 possible ways someone can reach at level i : By #taking 1 step from level i-1 or by taking 2 steps from level i-2. I am assuming that #the no. of ways of reach...
08d455f445ba10a25c0a08c4f28e65ad4e9e1cc0
getachew67/CSE-163-Education
/CSE 168 - Intermediate Data Programming/Homework/hw2/hw2_manual.py
3,616
4.125
4
def parse(file_name, int_cols): """ Parses the CSV file specified by file_name and returns the data as a list of dictionaries where each row is represented by a dictionary that has keys for each column and value which is the entry for that column at that row. Also takes a list of column names ...
23aaf3c7e5ca46f25bc0730c6b9453331ee4bf7d
lumbduck/euler-py
/p060.py
3,282
4.0625
4
""" Prime Pair Sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with ...
e4cf3137b728a344099302db43d1a24087784ce3
kbcmdba/pcc
/ch9/ex9-6.py
1,942
4.71875
5
# Ice Cream Stand: An ice cream stand is a specific kind of restaurant. Write a # class called IceCreamStand that inherits from the Restaurant class you wrote # in Exercise 9-1 or Exercise 9-4. Either version of the class will work; just # pick the one you like better. Add an attribute called flavors that stores a # li...
b095a8285577eb3c9f26ed70d918059d04b77897
niteesh2268/coding-prepation
/leetcode/Problems/709--To-Lower-Case-Easy.py
318
3.515625
4
class Solution: def toLowerCase(self, str: str) -> str: answer = '' for ch in str: if ord(ch) <= ord('Z') and ord(ch) >= ord('A'): answer += chr(ord(ch) - ord('A') + ord('a')) else: answer += ch return answer
7a0dde25fc8ef1e272ee9e1ccde7bb575684c20f
tanu312000/Python
/QuickSort.py
620
3.984375
4
def partition(A, p, r): i = (p - 1) # index of smaller element x = A[r] # last element for j in range(p, r-1): if A[j] <= x: i = i + 1 A[i], A[j] = A[j], A[i] A[i + 1], A[r] = A[r], A[i + 1] return (i + 1) # Function to do Quick sort def quickSort(A, p, r): ...
2abd6277a89395ac7e5b2a561e20ff0e535dc486
fandoghi/lambda
/main.py
377
4
4
double = lambda x : x *2 x=double(5) print(x) double = lambda x : x +2 x=double(5) print(x) double = lambda x : x -2 x=double(5) print(x) double = lambda x : x /2 x=double(5) print(x) double = lambda x : x *2 x=double(5) print(x) double = lambda x : x %2 x=double(5) print(x) double = lambda x : x //2 x=double(5) ...
5154433717b1223ec523fd81077b32a4f150c402
Saradippity26/Beginning-Python
/functions.py
848
4.21875
4
"""Learn about functions/(python: Definitions) use the keywords: def <name> (parameters): ((function skeleton)) Between functions you should have two spaces of blank lines """ def even_or_odd(number): #should return the string even or odd """ Find if number is even or odd print "even" on even numbers ...
09bf6505cd40db0a087d79e1906009003737658e
EduardoMachadoCostaOliveira/Python
/CEV/ex005.py
225
3.96875
4
#Faça um programa que leia um número Inteiro e mostre na tela o seu sucessor e seu antecessor n1 = int(input('Digite um número: ')) print(f'O sucessor de {n1} é {n1+1}', end='. ') print(f'O antecessor de {n1} é {n1-1}')
176af8c6492e40cb1072c08f41157d371a7a3f75
jinleiTessie/Citadel_DataOpen
/resources/models/Data_Preparation.py
492
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 16 20:43:38 2019 @author: jinlei """ import pandas as pd def load_data(path): return pd.read_excel(path) df=pd.read_excel(r"..//data//testing//Color.xlsx") print (df.head()) print (df.shape) print (df.describe()) dummy_df=pd.get_dummies(df) pr...
13fc764102ea38b6381c7ffc7f9bd137094f7a01
jingrui/leetcode_python
/ReorderList.py
2,394
4.0625
4
# Definition for singly-linked list. def printList(head): while head!=None: print head.val,'->', head = head.next print class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return nothing def findMid(...
b3c2975d24f4e26bdc13a895110b8030b189a676
ChenSaijilahu/Adjusting-Traffic-Flow-Optimization
/FullGraph.py
2,036
3.703125
4
class AdjacencyGraph(): def __init__(self, edges, n_vertices, directed=False): self.edges = [True]*len(edges) self.vertices = [] self.directed = directed self.visited = [False]*n_vertices for i in range(n_vertices): self.vertices.append([]) f...
e3befb922f421d30c6b2fd0cfab1120767688c56
albertogcmr/data-analytics-examples-lessons-stuff
/unittesting/main.py
1,097
3.90625
4
import unittest from functions import suma from random import randint class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split...
93924247145ad3aa523ea9210b3572f0f2ec824c
maiman-1/hackerrank-dump
/Getting started/Sales by Match.py
2,475
4.1875
4
""" Objective: Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. Example: 7 socks, [1,2,1,2,1,3,2]. There's 1 pair of 1s and 1 pair of 2s. So, it should output number of pairs = 2. """ """ Original Code: #!/bin/python3 import m...
ae3c6407a8e87d878b7008d4735520517e0dfcfd
pravin-asp/Python-Learnings
/ExceptionHandling.py
2,542
4.3125
4
# Exception Handling # Error: # Syntax Error and Exception is different # print(10 / 0) this is an exception '''try: n1 = int(input()) n2 = int(input()) print(n1 / n2) # risky code except ZeroDivisionError: print('Check It seems like zeor in denominator') except ValueError: print('Check the numbers') print('H...
1d588a1fd2364c689f30aa83ea8d318756d3161f
maelic13/beast
/src/heuristic/piece_values.py
627
3.734375
4
from chess import BISHOP, KNIGHT, PAWN, QUEEN, ROOK class PieceValues: """ Values of chess pieces based on human theory. """ PAWN_VALUE = 100 KNIGHT_VALUE = 350 BISHOP_VALUE = 350 ROOK_VALUE = 525 QUEEN_VALUE = 1000 @classmethod def as_dict(cls) -> dict[int, int]: """ ...
8c5e007963af73ff8cd8eeb9dc028e8476829f40
Mreggsoup/Python3
/virus.py
469
3.796875
4
import time mylist = ["MUSIC", "BURGER"] one = input("MUSIC y/n:") two = input("BURGER y/n:") view = input("View Survey Results y/n:") if view == "y": mylist.insert(1, one) mylist.insert(2, two) print(mylist) for i in mylist: mylist.append(one) mylist.append(two) time.sleep(0) print(...
7d07c4ba40d7165d5883adc4d06eabc3038e7ef0
elizazhang21/LeetCode
/0034. First and Last Position of Element in Sorted Array.py
923
3.515625
4
# 34. Find First and Last Position of Element in Sorted Array.py class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if not nums: return [-1,-1] # binary search l = 0 r = len(nums) - 1 while l <= r: mid = (l + r) //...
a49a249ebb0928e3f3920941a93fbbd4982b17b1
mrizwan18/Data-Science
/Data Science/Linear Regression/gradient_descent.py
8,074
3.890625
4
import time import matplotlib.pyplot as plot # To plot the data import numpy as np import pandas as pd # For reading data from file def read_data(path): """[Function to read data from txt file] Arguments: path {[String]} -- [relative path to the dataset.txt] Returns: [Pandas Dataframe...
abb1d8e27c20dea40645bd86898ae8e465ce6083
abhimaprasad/Python
/Python/ObjectOrientedProgramming/DemoPrograms/Employeedemo.py
1,702
3.921875
4
from functools import * class Employee: def __init__(self, employid, name, salary, experience, designation): self.id = employid self.name = name self.salary = salary self.experience = experience self.designation = designation def printstudent(self): print("The ...
0a57c8ecc5c85953b11d734dd3dea4b0212c6c57
dailesjsu/python_study
/diagonals.py
587
3.9375
4
#Given a square matrix, calculate the absolute difference between the sums of its diagonals. import os import random import re import sys def diagonalDifference(arr): sum1=0 sum2=0 for i in range(0,n): for j in range(0,n): if i==j: sum1=sum1+arr[i][j] if i== n ...
c23e599084c0dc0fb02568d5a2a3535dd24781d5
RRisto/learning
/algorithms_learn/what_can_be_computed/src/multiply.py
648
3.859375
4
# SISO program multiply.py # Computes the product of two integers provided as input. # inString: a string consisting of two integers separated by whitespace. # returns: The product of the input integers. import utils; from utils import rf def multiply(inString): (M1, M2) = [int(x) for x in inString.split()] ...
fa771c9ec2d8614d27b589e30c0afe286f0e1140
vanonselenp/Learning
/Python/LPTHW/ex12.py
156
3.5
4
age = raw_input("age:") height = raw_input("height:") weight = raw_input("weight:") print "entered(age, height, weight): %s, %s, %s" % (age, height, weight)
e7cb6140348156333a2c3f553c83909c1fa4031e
MohamadShafeah/python
/Day1/02Formatting/O004formattingBasics.py
339
3.65625
4
# 1 classical printf emulate frm_str = "Hello Mr.%s %s talented Guy" val_info = ('Scahin', "Super") print(frm_str % val_info) val_info = ('Scahin', 1000) # 1000 convered as string print(frm_str % val_info) frm_str = "Hello Mr.%s %.3f talented Guy" val_info = ('Scahin', 1000) # 1000 taken as float print(fr...
7a4029dfea981a1d4ba85655b6b3c5bde9c73309
kevinshenyang07/Data-Structures-and-Algorithms
/algorithms/dfs/reconstruct_itinerary.py
995
3.6875
4
from heapq import heappush, heappop # Reconstruct Itinerary # the tickets belong to a man who departs from JFK # each ticket is an array of [from, to] # get the itinerary with the smallest lexical ordering # approach: dfs and build the Eulerian path backwards when the search returns # assume there's at least one vali...
7d791ca320b2e7d7a0f602ae65715b38ca614294
harashtaht/FundamentalExercise
/PCC/Part_1_Basics/ch5.py
2,357
4.21875
4
# -- Part 5 : If Statements -- # cars = ['audi', 'bmw', 'subaru', 'toyota'] # for car in cars: # if car == 'bmw': # print(car.upper()) # else: # print(car.title()) # a - Conditional Tests ''' At the heart of every if statement is an expression that can be evaluated as True or False and is ca...
a4a0e1cea5aba959a5a0d49df0ba1dcb96cc40da
omidziaee/DataStructure
/Algorithm_And_Data_Structure/backtracking_dp/partition_equal_subset_sum.py
1,224
3.859375
4
''' Created on Oct 10, 2019 @author: omid Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: I...
7b84c7846ea81d76866f8e477316d0a6928a2f94
EmmanuelPure0x1/Python_Projects
/dictionaries.py
2,084
4.65625
5
# What is a Dictionary ? # Dictionary is a set of data which operate as a Key Value Pair # Dictionaries (arrays) is another way of managing data but more dynamically. # Syntax: {"key":"value", key:"value"} # What type of data can we store/manage # Dictionary #1 devops_student_data = { "name": "Emmanuel", "s...
f644625592e271fa67a67e38f66ba59b91bfa2ea
tcbegley/advent-of-code
/2015/day05.py
858
3.671875
4
import re import sys from string import ascii_lowercase DOUBLE_PAIR = re.compile(r"([a-z]{2}).*(\1)") SANDWICH = re.compile(r"([a-z]).(\1)") def load_data(path): with open(path) as f: return f.read().strip().split("\n") def is_nice_1(s): vowel_count = sum(s.count(c) for c in "aeiou") >= 3 repea...
f32381bc5aff7590162964b0b268fab61450643d
mauriciocabreira/Udacity_DAND_Project_1_Create_report_cities
/project1v1.py
561
3.5
4
# We import Pandas as pd into Python import pandas as pd Temperatures = pd.read_csv('./temp_data_from_db.csv') print("data is of type:", type(Temperatures)) print("Temperature shape: ", Temperatures.shape) print(Temperatures) print(Temperatures.head(10)) print(Temperatures.tail(20)) print(Temperatures.isnull().an...
45ddf3072090e3b28cf58a838e2ee8ce8c0de918
emrehaskilic/tekrar
/introduction/lesson4/set.py
267
3.71875
4
# .set() unique değer tutar myset = set() print(myset) myset.add(1) myset.add(2) myset.add(3) print(myset) myset.add(1) myset.add(2) myset.add(3) print(myset) #set() unique deger tuttugu için 1,2,3 elemanlarını yalnızca 1 kere yazacak tekrarlamayacaktır
ba77ead3ff503e00b305d87bc294b902243d1abe
jiewu-stanford/leetcode
/393. UTF-8 Validation.py
999
3.640625
4
''' Title : 393. UTF-8 Validation Problem : https://leetcode.com/problems/utf-8-validation/ ''' ''' Reference: https://leetcode.com/problems/utf-8-validation/discuss/87494/Short'n'Clean-12-lines-Python-solution ''' class Solution: def validUtf8(self, data: List[int]) -> bool: def check(data, startinde...
0bb3d894c5d0f77dba078b40ba9e598799834182
max-graham/knn_from_scratch
/knn/knn.py
2,833
3.6875
4
import numpy as np from scipy import stats def main(k: int): # dummy data, replace with data from file(s) train = np.arange(4 * 4).reshape((4, 4)) train_labels = np.array(['a', 'b', 'c', 'd']) test = np.arange(2 * 4).reshape((2, 4)) test_labels = np.array(['a', 'b']) predicted = knn(k=k, test...
1597b0d21ba315b0d54fe6f0cd13a6068847c982
thedarkknight513v2/daohoangnam-codes
/C4E18 Sessions/Homework/Session_1/four_ex.py
133
3.625
4
# for i in range (2, 10, 3): # print(i) # print(*range(5)) # Cac so chan nho hon 100 for i in range (0, 100,2): print (i)
f88b98d49ded4384c1dbbf9b79a9c0445ed11cb2
TheSchnoo/gridgame
/character.py
7,021
3.640625
4
import random EMPTY_SPACE = 0 def print_attacks(attacks): for attack_key in attacks: print(attack_key + ": " + str(attacks.get(attack_key))) class Character(object): def __init__(self, name, pos, token, attack, defense, speed, endurance, health, strategy): self.name = name self.pos...
e5439b891e9c81193823092916303152b11587d5
manudeepsinha/daily_commit
/2021/01/python/12_queue.py
1,912
4.03125
4
''' the following code is of queue and if I add some new methods to the class i'll post in a what's new section. what's new: Queue class with following methods: add add_all pop pop_all print_que check...
c688f064e3435389b8bdf99ed8a6c336f804c70c
Dis-count/Python_practice
/Practice/code_class/Crossin-practices/python_weekly_question/eqip.py
2,112
3.71875
4
from itertools import combinations_with_replacement from itertools import permutations from itertools import combinations, product import itertools items = [ {'name':'影者之足','price':'690'}, {'name':'巨人之握','price':'1500'}, {'name':'破甲弓','price':'2100'}, {'name':'泣血之刃','price':'1740'}, {'name':'无尽战刃',...
5f1a98b30e386ba5b1250e18d897b654ae15b102
jyabka/PythonExam
/15.TryToDestroyTheWorld.py
196
3.8125
4
def DivideByZero(_number): try: _number = _number / 0 except ZeroDivisionError: print("Error! Attempt to divide by zero!!") num = input() DivideByZero(int(num)) input()