blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3b6bd280136b956016dc337102aa3b5b02491205
RituRaj693/Python-Program
/list_iinsertdata.py
331
4.03125
4
fruits = ['apple','lichi'] #fruits.insert(1,'grapes') #p fruits1 = ['hkh','jhjoj','hbkhkj'] #fruits3 = fruits+fruits1 #print(fruits3) #fruits.extend(fruits1)################################### extend method to add the lsit fruits.append(fruits1) ###################################list inside list by append prin...
050e1a31b63441fd859aa24e206ecf7ac93de753
pettan0818/Programing_Contest
/Atcoder/ABC009/2.py
750
3.78125
4
# -*- coding: utf-8 -*- """ABC 009 B Problem.""" def read_lines(): # _ = stdin.read() # each_cost = stdin.readline().split("\n").pop() num_of_menu = int(input()) each_cost = [input() for _ in range(num_of_menu)] return each_cost def choose_second_highest(cost_list: list) -> int: """Choose 2...
959e06ed17f747af3b2b62f5185f4dc464172ec5
mwehlast/cs9h
/Python-Powered Unit Converter/converter.py
4,300
4.3125
4
import sys def print_banner(): ''' Print the program banner. You may change the banner message. ''' # START OF YOUR CODE print(''' Welcome to our Python-powered Unit Converter v1.0 by Morten Wehlast Jørgensen! You can convert Distances, Weights, Volumes to one another, but only within units of the ...
b1d054a6e1e639b0d05bb1f84029bd157e07e2bb
SahooManoj/Python-Code
/set_in_python.py
362
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 27 19:50:35 2019 @author: Administrator """ s1=[1,1,1,2,2,2,3,3,3,4,4,4] example=set(s1) print(example) print(type(example)) s2={1,2,6,7} print(example.intersection(s2)) # & symbol for intersection print(example & s2) print(example.union(s2)) # | symbol for union print(e...
6108bacd6e358a0c358702911bf7b2b0e370f330
adrianrocamora/kng
/lc/py/combo2.py
230
3.53125
4
def combo2(lst, n): if n == 0: return [[]] l = [] for i in range(0, len(lst)): m = lst[i] remLst = lst[i+1:] for p in combo2(remLst, n - 1): l.append([m] + p) return l print(combo2(list('abc'), 2))
f89094dfdbaa4311ef88e66cd30974a045e88885
SebastianHalinski/the_worst_knight
/level_2.py
1,419
4.0625
4
file_name = r'/home/katarzyna/the_worst_knight/question_answer.txt' def display_question(file_name): question_file = open(file_name, 'r') question_list = [] for line in question_file: question_list.append(line) # print(''.join(question_list)) return question_list def questions(): ...
507ddca778201ed76624bc03cfab4492af2688da
rublen/Some_Python_exercises
/square_nums.py
405
4.0625
4
''' How many square numbers are between a (included) anb b (not included)? ''' import math def how_many_sqr(a, b): n = 0 a = int(math.ceil(math.sqrt(a))) b = int(math.ceil(math.sqrt(b+1))) for c in range(a, b): n += 1 return n print(how_many_sqr(1,10)) # 3 print(how_many_sqr(3,100)) ...
e7e540e545437de47916b9bb9168432d9834dc7b
Akintola-Stephen/formulated-mini-dataset
/algorithms.py
761
3.625
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 5 15:02:43 2020 @author: AKINTOLA """ import numpy as np import pandas as pd ''' Generating 10 random integer numbers between 0 - 20 to populate the price and unit field ''' price = np.random.randint(20, size = 10 ) unit = np.random.randint(5, size ...
4a226e4d938078c05125269c010493c0965137ee
MichelleZ/leetcode
/algorithms/python/increasingSubsequences/increasingSubsequences.py
617
3.59375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/increasing-subsequences/ # Author: Miao Zhang # Date: 2021-02-16 class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: res = set() self.dfs(nums, 0, res, []) return map(list,...
76b916d3eda53fb976697cb745c469efcf30bb39
DKLynch/HackerRank-Challenges
/Algorithms/Implementation/Grading Students/gradingStudents.py
304
3.578125
4
#Problem URL: https://www.hackerrank.com/challenges/grading/problem def gradingStudents(grades): for x in range (0, len(grades)): if(grades[x] >= 38): difference = 5 - (grades[x] % 5) if(difference < 3): grades[x] += difference return grades
a5189d0dbe74b549d310966216750e22fcee5c3c
Next0ne/homework1
/homework1.10.py
499
3.65625
4
# -*- encoding: utf-8 -*- ''' @File : homework1.10.py @Time : 2020/03/06 13:36:15 @Author : xdbcb8 @Version : 1.0 @Contact : xdbcb8@qq.com @WebSite : www.xdbcb8.com ''' # here put the import lib text = input("请输入一段英文文本:") textlist = text.split( ) record = {} for i in range(0,len(textlist)): if textlist[i] in reco...
f0e1d82b2606721a641b45e8c8bbbf336d15faa7
csharrison/Student-Final-Projects
/joseph_hester/asteroids_2.py
5,458
3.578125
4
#Joe Hester #Asteroids #final project import pygame from pygame.locals import * from math import cos,sin,pi,hypot import random class Ship(object): def __init__(self,x,y,vx,vy): self.x = x self.y = y self.vx = vx self.vy = vy self.angle = -pi/2 self....
f254e84d35024f3b190456d6d39ebd1cbc40d562
lollcat/RL-Process-Design
/Discrete/PFR or CSTR/PFRorCSTR.py
2,761
3.546875
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 18 11:18:00 2019 @author: meatrobot """ import numpy as np from gym import Env, spaces import matplotlib.pyplot as plt import matplotlib.animation as FuncAnimation from matplotlib import style class simulator(Env): def __init__(self, n_reactors=9, action_size=2, s...
0816c0db927a75284e5c3b788ce26c239e6af272
RahmaNiftaliyev/codewars-1
/solutions/simple_interactive_interpreter.py
17,487
3.84375
4
""" My solution for Simple Interactive Interpreter kata: https://www.codewars.com/kata/simple-interactive-interpreter Level: 1 kyu Good introduction to building an interpreter, was very helpful learning for this kata: https://ruslanspivak.com/lsbasi-part1/ """ import re import collections #--------...
bdbd3e74358bc1cef52b5da6514b15a09a9d6bd9
Puzyrinwrk/Stepik
/Поколение Python/Последовательность_чисел_3.py
945
3.96875
4
""" Даны два целых числа m и n (m > n). Напишите программу, которая выводит все нечетные числа от m до n включительно в порядке убывания. Формат входных данных На вход программе подаются два целых числа m и n, каждое на отдельной строке. Формат выходных данных Программа должна вывести числа в соответствии с условием ...
570241dbf131cf47dfbfc4d4340a1d16068f76fc
Dhana-Sunil-Yalampalepu/driveready
/Circular prime.py
572
3.90625
4
import math as m def factcount(num,a): if a==1: return 2 if num%a==0: if a==num//a: return 1+factcount(num,a-1) else: return 2+factcount(num,a-1) else: return 0+factcount(num,a-1) num=int(input()) n=num a=int(m.sqrt(num)) y=factcount(nu...
d9ab36fa0f894370fc7fec1773b06b1dbd46578f
seoljeongwoo/learn
/프로그래머스/네트워크.py
563
3.609375
4
def solution(n, computers): answer = 0 def find(u): if u == parent[u] : return u parent[u] = find(parent[u]) return parent[u] def merge( u , v ): u = find(u) v = find(v) if u == v: return parent[u] = v return parent = [i for...
8678b428ad13fda3d2259c8f91947871a5dac209
lperozin/Python
/Apply-n-Combine/Apply-Combine.py
626
3.671875
4
# coding: utf-8 # # Apply 'n Combine # In[1]: #Importing libraries import pandas as pd import numpy as np # In[2]: #loading into a dataframe using pandas data = pd.read_csv('file.csv',encoding='utf-8',sep=";") # In[3]: #exploring the dataframe data['Year_Month'].count() # In[4]: #reading top 10 rows da...
c508599710536896fcb2945bb47dde697824b1f9
Puneetdots/Python
/dict.py
622
4.34375
4
#“Python dictionary is an unordered collection of items. Each item of the dictionary has a key/value pair.” # Dictionary is nothing but key value pairs a= {2:"Puneet",3:"Gupta"} print(a[2]) d2 = {"Harry":"Burger", "Rohan":"Fish", "SkillF":"Roti", "Shubham":{"B":"maggie", "L":"roti", "D":"Chicken"}} #A...
43e2f894cad1d2b16ee42eec54f2ab79a3e59584
yamadathamine/300ideiasparaprogramarPython
/006 Matemática/conversao1.py
1,089
4.375
4
# encoding: utf-8 # usando python 3 # Conversão cm/pol 1 - # Faça um programa que mostra 10 linhas de uma tabela de conversão centímetro/polegada, # a partir de um valor lido e variando de 10 em 10 centímetros # (uma polegada equivale a 2,54 centímetros). num = int(input("Digite o valor em cm para converter para p...
2844459859439ccf43ec6a909d28adf1de9a9f44
ellieghorbani/Predict_Turnaround_Time_of_Flights
/src/codes/step_4_EDA_2.py
5,987
3.59375
4
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime, date, time from scipy import stats ## Read Data! data1 = pd.read_csv("flights_step_3.csv") data = data1 ##print('shape of data:', data.shape) #data.head(4) #functions##### #Sepe...
4f2703651a8f8949b5291860cd79ec8a75c5f9c8
Sierkinhane/LearningRecords
/LearningScipy/numpy/05-split.py
295
3.671875
4
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(np.split(a, 2, axis=0)) print(np.split(a, 3, axis=1)) # 不等量分割 print(np.array_split(a, 2, axis=1)) print(np.vsplit(a, 2)) #等于 print(np.split(a, 2, axis=0)) print(np.hsplit(a, 3)) #等于 print(np.split(a, 3, axis=1))
03794803e623e65978693c5bb0b3d96f4a37751e
FrancescoSRende/FrancescoSRende.github.io
/Python Contest Questions/1000DigitFibonacci.py
481
3.78125
4
def ThousandDigitFibonacci(): fibonacci = [1] i = 1 index = 0 while len(str(i)) < 1000: fibonacci.append(int(i)) i = i + fibonacci[index] index = index + 1 return index + 2 print(ThousandDigitFibonacci()) def ThousandDigitFibonacciB(): i = 1 j = 1 index = 1 ...
1921b6af6c4f2d31e9d9913f595830d49357e7b5
Bennett1234/Leetcode
/Maximum Subarray.py
448
3.953125
4
def maxSubArray(nums): maximum = running_sum = nums[0] if len(nums) == 1: return(nums[0]) for n in nums[1:]: running_sum = max(running_sum+n,n) maximum = max(running_sum, maximum) return maximum #Maintain a running_total of the array seen so far. #If the current value is greater ...
68b35cb9ef51fb98de277741169bfcc5df92c30d
C-VARS/cvars-back-end
/script/Facades/UserRegisterFacade.py
575
3.546875
4
from typing import Dict class UserRegisterFacade: def __init__(self, connection): self.connection = connection def register_user(self, user_info) -> Dict: """ An method to register a new user with user_info in the database :param user_info: JSON format argument that contains...
0c6b723a18c3b5f0ac86085e2e41322666f166da
ralster213/CyberSecurity
/Lab3-master/TempConvert.py
394
4.15625
4
#TempConvert.py #Name: #Date: #Assignment: from time import sleep def main(): #Prompt the user for a Fahrenheit temperature (tempF) = input("Type in a temperature in degrees Fahrenheit: ") #Convert that temperature to celsius, rounding to 1 decimal percision tempC = ((float(tempF)-32) *5/9 ) sleep...
cd1f56eca241fa4d966253a98526afe3f295e4c0
kbossert/pythonProject
/XML.py
1,066
3.5
4
import lxml import setuptools import pkg_resources # root.find() will navigate down the document tree to find children # root.xpath() will return a matching element using an XPATH query as a sting # root.tag will show the element’s name # root.text will show any text contained by the element # root.attrib will provide...
e7c1d7b6869b2641d715ca38d7cd7d66524a5181
Carlos-DOliveira/cursoemvideo-python3
/pacote-download/d044 - calculo do produto com condições.py
822
3.875
4
''' 044 Elabore um programa que calcule o valor a ser pago por um produto , considerando o seu proço normal e condição de pagamento à vista dinheiro/cheque: 10 % de desconto à vista no cartão: 5% de desconto em até 2x no cartâo: precço normal em 3x ou mais : 20 % de juros''' valor = float(input('Digite o valor do prod...
43be2c4999fda868675c4500473751497d0bf5ca
yokoyokohiyoko/python-drill-questions
/Chapter_7/Q7_02.py
679
3.5
4
from threading import Thread, Lock def add_value(value): """①""" cumulative lock."""②""" # 計算が正しくなるように追加した cumulative += value """③""" # 計算が正しくなるように追加した def add_all(fr, to): for n in range(fr, to + 1): add_value(n) cumulative = 0 lock = """④""" # 計算が正しくなるように追加した th = [None] * 10 for i...
2163772727720dadf24b813fc888d2f7d9c4ff8a
AntoineZappa/multiprocessing
/start.py
831
3.578125
4
#!/usr/bin/env python3 import concurrent.futures #different way to do multiprocessing import time start = time.perf_counter() # passing a variable throw the function def do_something(seconds): """""" print(f'Sleeping {seconds} second(s)...') #that is a sismple function to sleep 1 second = time.sleep(1) ...
6cccc315a51ebc9737bd91adedae4fcd86e91b6f
edwardzhu/checkio-solution
/EmpireOfCode/common/Adamantite Mines/placeQueens.py
2,980
3.53125
4
def place_queens(placed): COLS = "abcdefgh" ROWS = "12345678" THREATS = {c + r: set( [c + ROWS[k] for k in range(8)] + [COLS[k] + r for k in range(8)] + [COLS[k] + ROWS[i - j + k] for k in range(8) if 0 <= i - j + k < 8] + [COLS[k] + ROWS[- k + i + j] for k in range(8) if 0 ...
7e3a36ffa83f8208dab259741aab3b7f899c7696
ffgama/people_analytics
/modelling/tuning_params.py
1,032
3.578125
4
from sklearn.model_selection import RandomizedSearchCV from typing import Dict from pandas import DataFrame def get_best_parameters(pipe, X_train: DataFrame, y_train, grid_params: Dict) -> Dict: """As from the data training, search and evaluate to find the best \ training parameter...
797655969fde8b7a3707a4b730136a77931d6f6e
zaleskasylwia/RPG-hero
/item.py
539
4
4
class Item: def __init__(self, name, description, weight): if type(name) is str and type(description) is str and type(weight) is int: self.name = name self.description = description self.weight = weight else: raise TypeError def __str__(self): ...
ce95b8163fd8afc30c13818e3d4ed9839bc82135
jochenrui/learn-py
/oop/inheritance/vehicle.py
1,725
3.765625
4
# multiple inheritance possible class Vehicle: def __init__(self, TOP_SPEED=80, *warnings, model): self.TOP_SPEED = TOP_SPEED # __prefix for variable = private variable self.__warnings: set = set(warnings) self.__model: str = model self.__passengers: list = [] # simila...
df6ff1bfaad4600fa4d960ad762a8d48d068fd9b
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/beer-song/a4bb756a2441497bb300b2b54526f8fc.py
1,382
3.78125
4
class Beer(object): def verse(self, num): if num == 0: return self._zero_bottles() if num == 1: return self._one_bottle() if num == 2: return self._two_bottles() return self._multiple_bottles(num) def sing(self, start, end = 0): ver...
067214b491c3f1d188a15496141f9e17dead8bd6
baoshengzhu/Helloword
/re_sub.py
457
3.75
4
#!/bin/env/python #coding:utf-8 import re phone = "2004-959-559 # 这是一个国外电话号码" #删除字符串的python注释 num=re.sub(r'#.*$','',phone) print("电话号码是: "+num ) #删除非数字(-)的字符串 num=re.sub(r'\D','',phone) print("电话号码是: "+num ) #将匹配的数字乘以2 def double(matched): value = int(matched.group('value')) return str(value * 2) s = 'A23G4HF...
a84d22f95689978ced93b79b7f23dcce4f4262f7
NathanielBlairStahn/project-euler
/0001-multiples-of-3-and-5/mult3and5.py
456
4.375
4
"""Multiples of 3 and 5 Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.""" def mults_3_and_5(n): """ Returns a generator of the multiples of 3 and 5 that are less...
cdda2a4f2210ff743f5cc8bc1b7f1bdd288f2e4e
benjaminhuanghuang/tf-traffic-sign
/plot_test.py
571
3.6875
4
import numpy as np from sklearn.linear_model import LinearRegression import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt # Pizza diameter # X should be 2D array X_train = np.array([6, 8, 10, 14, 18]).reshape(-1, 1) # Pizza prices y_train = [7, 9, 13, 17.5, 18] plt.figure() plt.title('Pizaa pr...
07c80a6e600d370e0c56009adabac1a00a7e1bf5
Imipenem/Competitive_Prog_with_Python
/leetcode/balanced_binary_tree.py
439
3.546875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def isBalanced(root: TreeNode) -> bool: if not root: return True lh = get_depth(root.left) rh = get_depth(root.right) return abs(lh - rh) <= 1 and isBalanced(root.left) and isBalanced(ro...
e2b3107fcbb93178b9fee36f9aa1f7b8746c5040
gaoruiqing123/proj12
/day0012/one.py
1,316
4.03125
4
# 1. 八维学院三律一值考核一直是学生管理的方法之一,班长统筹全班,学委负责班级学习, # 书记负责文化方面内容,纪律班长控制自己班的违纪。 # 请编程实现一个投票统计程序,运行程序,分别输入“班长”,“学习委员”,“文化书记”,“纪律委员”, # 代表投给班长、学习委员、文化书记、纪律委员一票,输入“结束”终止投票。(60分) # 要求: # 1.用字典来存储投票结果 # 2.循环输入计票,直到输入“结束”后终止投票。 # 3.终止投票后,输出最高得票班委及得票数 # 3.将字典内存储得票结果按得票数目倒序排列,并输出。 # 4.一票未得的,最后输出显示为“xxx 0票” # 5.做好输入内容的错误与异常处理 a = 0...
ebbced0102492b9cd81b5faea6319dbe9816329e
wssyy1995/python_note
/helloworld.py
13,350
3.640625
4
'''count=1 sum=0 while count <= 100: sum = sum + count count=count+1 print(sum) ''' #input '''name = input("what's your name ? ") age = input("how old are you ?") print("your age is:"+age+",""your name is :"+name) ''' #while '''count=1 while True: print(count) count=count + 1 if count > 100: ...
fe772d27691789193f178ccb5fd8fbfc97b9db2b
DmitryVlaznev/leetcode
/86-partition-list.py
1,106
3.9375
4
# 86. Partition List # Medium # Given the head of a linked list and a value x, partition it such that # all nodes less than x come before nodes greater than or equal to x. # You should preserve the original relative order of the nodes in each # of the two partitions. # Example 1: # Input: head = [1,4,3,2,5,2], x = ...
11779bfcd4f330dbf3654fd52207aade44c1ea6d
AndrewZhang1996/Shortest-Path-Algorithm--Brute-Force-
/BruteForce.py
3,734
3.515625
4
from place import Place class brute_force(): global all_paths all_paths = [] def __init__(self, places_list, start, end): self.places = places_list self.start = start self.end = end self.paths = [] self.path = [] self.get_paths() def get_place_name(self, place): return place.get_name() def get_...
766dc5fc635b75f17f602613cf695470f6e94e7f
EzequielCosta/ifpi-ads-algoritmos2020
/capitulo7/exercicio18.py
184
3.90625
4
n = int(input("Digite um número n: ")) s = 0 cont = 1 while n > 0: s += cont / (n) cont += 1 n -= 1 print("A soma com duas casas decimais é {:.3} ".format(s))
25ce26e778a767c7244b64d22f14d41e2179edb8
gunjan1991/CSC-455---Assignments
/Final Exam - Gunjan - Part 1(a) Solution.py
2,098
3.90625
4
# Final Exam # Name: Gunjan Pravinchandra Pandya # Part: 1(a) """ 1 (a). Create a 3rd table incorporating the Geo table (in addition to tweet and user tables that you already have) and extend your schema accordingly. You will need to generate an ID for the Geo table primary key (you may use any value or combina...
75dc96bb39caf9d7f3267180432badb7d821ba99
LIU1514/dayday
/Gslution/5-dic.py
324
4.0625
4
""" what:散列函数,python 中的字典 字典无序,制动扩容,头秃 """ #book=dict() book={} flu={} flu["a"]=2 flu["b"]=3 book["apple"]=flu book["rice"]=7 print(book["rice"]) print(book.get("hello")) print(book["apple"]["b"]) """ ---- book | ---flu | ---a ---b ----rice """
a3f9a4b1ed11bcb749ff9b83716c4da66234a60b
opethe1st/CompetitiveProgramming
/CodeChef/2020/08/skmp.py
2,243
3.609375
4
# This solution thanks to Bolu from collections import Counter class TrueWhileLeftNotGreater(object): def __init__(self): self.__ever_false = False def __call__(self, left, right): if self.__ever_false: return False # return not self.__ever_false := not left <= right ...
08588972692f4213aea63bc85bc5693a904239d7
janakparmar9491/The-Complete-Python-Masterclass-Learn-Python-From-Scratch
/2-Control-Structure-In-Python/4-List-Functions.py
176
3.71875
4
fruits = ["Apple", "Mango", "Peach", "Orange"] fruits.append("Banana") print(fruits) print(len(fruits)) fruits.insert(1,"Jamun") print(fruits) print(fruits.index("Peach"))
ab1850680f35d6c223f1788554b7bbcff35d0dcf
jacobfitz99/proof2
/python intermediate/excepciones.py
253
3.984375
4
while True: try: #Toda aquella instrucción que pueda levantar una excepción x = int(input("Ingrese un número: ")) #12,A except ValueError: print('El caracter ingresado no es el requerido') else: print('Todo salio a la perfección')
d4cd7c6e3df4016c7956bb8c7e0650fcf3b85bff
jerry0chou/matplotlib
/basic/13添加两条Y轴.py
494
3.625
4
# -*- coding:utf-8 -*- # Author : JerryChu import matplotlib.pyplot as plt import numpy as np x=np.arange(2,20,1) y1=x*x y2=np.log(x) # 对x求对数 ''' # 面向过程 plt.plot(x,y1) plt.twinx() plt.plot(x,y2,'r') ''' # 面向对象 fig=plt.figure() # 第一条曲线 ax1=fig.add_subplot(1,1,1) # 加入位置 ax1.plot(x,y1) # 画出来 ax1.set_ylabel('Y1') ax1.se...
a6718ae24a132bf54dff90e3753f771bab2959b8
Eric035/BMI-Calculator
/BMI_Calculator.py
595
4.25
4
name = input ("Please enter your name: ") print ("Nice to meet you, " + name + " :)") height_cm = float ( input ("Please type in your height in cm: ") ) weight_kg = float ( input ("Thank you, " + name + ". Now please enter your weight in kg: ") ) bmi = weight_kg / ((height_cm / 100) ** 2) print (" ") if bmi >= 18.5 ...
a7c68e839e94ace40192e282fea1418e830ee8ab
x223/cs11-student-work-genesishiciano
/War(Card Game).py
408
3.65625
4
import random def player_turn(): player1= raw_input("What's the first players name?") player2= raw_input("what's the second players name?") print player_turn() cards=range(2,15)*4 random.shuffle(cards) print cards def Compare_score(card1, card2): if card1 >card2: print player1 elif card1<card2: ...
56a3a2e793112416a75851c336f8af9d9fc04b24
learndevops19/pythonTraining-CalsoftInc
/training_assignments/Day_04/day04_Assignment1.py
621
4.28125
4
''' 1)Write a program to subtract two numbers using magic method(__sub__). input1: 10 input2: 5 output: 5 Explanation: The first input will be the argument of one of the class and the other input will be just a variable. So when we print(obj of the class - variable) should give me the output. ''' class SubtractMag...
cd563fb61a03954d6d6f32d086bd71f7a0866375
Rohan2596/Mytest
/FunctionalPrograms/harmonic.py
286
3.9375
4
# Harmonic Series import math n=int(input("Enter the number to find the harmonic value of :")) if n==0: print("the harmonic value is zero") elif n!=0: for i in range(1,n): h2=1/i; print(i, " = ","{:10.4f}".format(h2)) i+=1 s=math.fsum(h2) else: print("Invalid series")
baf3df45aa90abf170f39805e62b08409450b821
ravi4all/Python_Reg_Dec_12-2
/ExceptionHandling/Assert.py
266
3.578125
4
def calc(x,y): c = 0 # Assert - Debugging...It is like if condition try: assert (x > y), "First value should be greater" c = x - y print("Value of c",c) except AssertionError as err: print(err) calc(10,50)
85ca03dce65118a9792d9631a35ed3b405c2f888
ianhom/Python-Noob
/Note_1/list2.py
273
3.875
4
#!/usr/bin/python list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : %d" % (list[2]); list[2] = 2001; print "Value available at index 2 : %d" % (list[2]); # result """ Value available at index 2 : 1997 Value available at index 2 : 2001 """
9769fec45be387595bdfcf1b6d4d517c6989f79b
LeoCo/PracticePython
/src/ex09.py
480
3.890625
4
import random num = random.randint(1,9) games = 0 victory = False while True: guess = int(input("Try to guess 1-9: ")) games += 1 if guess == num: victory = True break elif guess < num: print("Guess to low") else: print("Guess to high") # if input("exit or ...
663dc35ae89198a4b232e8c7f9516d4850138226
cylinder-lee-cn/LeetCode
/LeetCode/160.py
3,703
3.703125
4
""" 160. 相交链表 编写一个程序,找到两个单链表相交的起始节点。 例如,下面的两个链表: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 在节点 c1 开始相交。 注意: 如果两个链表没有交点,返回 null. 在返回结果后,两个链表仍须保持原有的结构。 可假定整个链表结构中没有循环。 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。 """ # Definition for si...
3eed146751177982480b2f42b87a6f977e209299
Anondo/algorithms.py
/sort/insertionSort.py
407
3.90625
4
lst = [35 , 44 , 42 , 27 , 10 , 14] print "The unsorted list: {}".format(lst) for i in range(0 , len(lst) - 1): if(lst[i] > lst[i+1]): lst.insert(i + 1 , lst.pop(i)) if(i > 0): for j in range(0 , lst.index(lst[i])): if(lst[i] < lst[j]): temp = lst[i] ...
7ef675ebf589ac7e36605bfc4bb7a1b5fe666d1e
leiteav/estudos-py
/aula2.py
578
4.21875
4
print('*** Operações Matemáticas ***') a = int(input('Insira o 1º valor: ')) b = int(input('Insira o 2º valor: ')) soma = a + b subtracao = a - b multiplicacao = a * b divisao = a/b resto = a % b print('Resultado em caso de Soma: ' + str(soma)) #Outras formas: #print('Soma {}' .format(soma)) #print('Soma {som}' .for...
1030c8ca75e3cc1c00322abec76d9fae8e0ef940
brickgao/leetcode
/src/algorithms/python/Bulls_and_Cows.py
1,085
3.5625
4
# -*- coding: utf-8 -*- from collections import Counter class Solution(object): def getHint(self, secret, guess): """ :type secret: str :type guess: str :rtype: str """ bull_cnt, cow_cnt = 0, 0 secret_counter = Counter(secret) for index in range(len...
b0241a69b26dbbac6bd16973a5705e53cb33b595
amitfld/amitpro1
/loop_targilim/loop2.1.py
538
4.125
4
grade = int(input('enter grade: ')) #קולט ציונים כל עוד הציון חוקי (בין 0-100) sum = 0 count = 0 max = 0 while 0 <= grade <= 100: if grade>max: max = grade sum += grade count += 1 grade = int(input('enter grade: ')) avg = sum/count print('highest grade is :', max, '\n', 'grades avg is ...
1dd12240f0bd7802eff82a8af3c3ed2e788e8565
sheruaravindreddy/Twitter-Sentimental-Analysis
/Sample_Codes/regex1.py
522
3.53125
4
import re import pandas as pd tweet = "model take all time friday smile user cookie people use cons con personalised booked" #...replacing old pattern with new pattern def func(pattern, tweet, replacement): r = re.findall(pattern, tweet) for i in r: tweet = re.sub(i, replacement, tweet) return twe...
1bb20347917a756c285a92d3001efe2dd95a2e54
Yhuang93/PyExercise
/TestandExercisePython/accessparentexercise.py
307
3.859375
4
class X(object): def __init__(self,a): self.a = a def doubleup(self): self.a *= 2 class Y(X): def __init__(self,a): X.a=a def tripleup(self): X.a *= 3 obj = Y(4) print(obj.a) obj.doubleup() print(obj.a) obj.tripleup() print(obj.a)
a4644f134226c0d9b0ef3f5ea1088e6a6d72921e
AnoopKunju/code_eval
/easy/without_repetitions.py3
1,670
3.9375
4
#!/usr/bin/env python3 # encoding: utf-8 """ Without Repetitions Challenge Description: In a given text, if there are two or more identical characters in sequence, delete the repetitions and leave only the first character. For example: Shellless mollusk lives in wallless house in wellness. Aaaarrghh! ↓ Sheles mo...
198805a833983e54bdca1524c8de9921ad816061
Shayennn/ComPro-HW
/13-Midterm/stat.py
1,020
3.53125
4
# -*- coding: utf-8 -*- #std35: Phitchawat Lukkanathiti 6110503371 #date: 4OCT2018 #program: stat.py #description: basic stat calculation def my_mean(iplist): return sum(iplist)/len(iplist) def my_mode(iplist): count_list = {} for i in iplist: if i in count_list: count_list[i] += 1 ...
bc036274d9816d233e264fef62988472b81f80bf
usman-personal-home/LeetCode
/Easy/922-Sort-Array-By-Parity-II.py
941
3.765625
4
class Solution(object): def sortArrayByParityII(self, a): """ :type A: List[int] :rtype: List[int] """ i = 0 # pointer for even misplaced j = 1 # pointer for odd misplaced sz = len(a) # invariant: for every misplaced odd there is misplaced even ...
7d036998f7157e503d699d462aed3170e035648b
MichaelJNorris/Golden
/fibonacci.py
1,669
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 23 18:18:56 2014 @author: michaelnorris """ from math import * from fractions import gcd from golden import * def fibonacci(n): """ non-recursive fibonacci """ phi = (1.0+sqrt(5.0))/2.0 return round(phi**n/(3-phi)) def fib_set(x): """ The...
14af45a020aea2ea3004e6299a2054fa56ccd46e
LearnPythonOrg/PythonAssignments
/assignment4.py
918
4.3125
4
#Assignment 4 ''' 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the ...
85856e404568a2646222bb247fb45e017ea00e6d
Aasthaengg/IBMdataset
/Python_codes/p03192/s657146150.py
49
3.65625
4
cnt=0 for i in input(): cnt+=(i=='2') print(cnt)
d8f02d24fe64dba0f114f5489cd23b70b003b0c5
Gurdeep123singh/mca_python
/MTCS/outer_product.py
1,418
4.8125
5
# program to find outer product # by taking n*1 and 1*m matrix # and making n*m matrix row = int(input("enter no of rows for matrix 1: ")) col = int(input("enter no of columns for matrix 2: ")) # making matrix1 by taking elements row wise matrix1=[] print("give the elements for matrix1 :") for i in range(row): l...
e42df0be53ed443be00c5b97f634cb1b79d4d7b7
sourav4455/Python
/repeated_string.py
1,706
3.890625
4
# # Lilah has a string, s , of lowercase English letters that she repeated infinitely many times. # # Given an integer, n , find and print the number of letter a's in the first n letters of Lilah's infinite string. # For example, if the string s='abcac' and n = 10 , the substring we consider is abcacabcac , the first ...
99c6cc51a541811c15eaada070816ba72187e946
SoumyaParida/Python-code-examples
/trees/question1.py
753
3.5625
4
import re def substring(str): valid = re.match('^[\w-]+$', str) is not None length = len(str) values = set() flag=0 pos = list() if valid: print range(length) for i in range(length): s = str[i: i + length] print s if any(x.isdigit() for x in s)...
6209b36dc2c634d100ba225e543e5595052d5c5d
NicolaiHerforth/advent_of_code
/day_2.py
1,608
4
4
def valid_passwords(pass_file_path): valid_old, valid = 0, 0 with open(pass_file_path) as file: for line in file: line = line.strip('\n') # set the lower value, higher value and the letter requirement variables. lower, higher, letter = int(line.split()[0].split('-')[0...
260ec8f0059f06e31850fd7820cd740ac5feb11e
u3aftab/Project-Euler
/Euler44.py
342
3.703125
4
# Find the smallest pair of pentagonal numbers # whose sum and difference is pentagonal. def p(n): return n*(3*n-1)/2 i=3 penta=[1, 5] sums=set() p_i=p(i) while p_i not in sums: for x in xrange(len(penta)): if p_i-penta[x] in penta[:x]: sums.add(p_i+x) penta.append(p_i) i+=1 p_...
ea0366e1af54f85b2fdf4f7667a30537ce69d515
fahadnajam1089/IS211_Assignment8
/IS211_Assignment8.py
5,596
4.03125
4
import random import time random.seed(0) class Player(): round = False def __init__(self, turn, name): self.name = name self.turn = turn self.score = 0 self.round_score = 0 def rolled(self): seed = random.randint(1, 6) return seed de...
b3a56b6143cc61106bf23a8de6756f874174a222
admin822/Python-Project-GitGud
/python_threading/Concurrency.py
574
3.5625
4
import threading import time class test_class: def __init__(self): self.threads=[] def func(self,secs:int): print("func started") time.sleep(secs) print("func ended in {} seconds".format(secs)) def thread_func(self,secs:int): self.threads.append(threading.Thread(...
9e3e64185b1dc9a04cfc0c27cd07d27f4875ae24
tberhanu/elts-of-coding
/LinkedList/delete_node.py
464
4.03125
4
from LinkedList.LL import LL def delete_this_node(node_to_be_deleted): node = node_to_be_deleted node.value = node.next.value node.next = node.next.next if __name__ == "__main__": ll, b, c, d, e, f, g, h = LL(1), LL(2), LL(3), LL(4), LL(5), LL(6), LL(7), LL(8) ll.next, b.next, c.next, d.next, e.nex...
5ecc2f55ef678958860c2410396bd3cc4a4d5a90
MESragelden/leetCode
/Counting Bits.py
288
3.609375
4
def countBits(num): def cal (de): bi = bin(de) sum = 0 for i in bi : if i == '1': sum+=1 return sum out = [] for i in range (0,num+1): out.append(cal(i)) return out print(countBits(2))
64e7ff2c6a9718b44ee8ef934bfd30e6319bf31c
m-lobocki/Python-ExercisesSamples
/ex27.py
144
4
4
# Define a function that can convert a integer into a string and print it in console. def print_int_as_string(integer): print(str(integer))
19ad6e87434a5bd7324837765abaf78b8a098bf4
bhamlin/hacker-rank-noodles
/welcome/compare-the-triplets.py
683
3.53125
4
#!/usr/bin/python3 import sys from functools import reduce from operator import add def trip_comp(p): u, v = p if u > v: return (1, 0) elif u < v: return (0, 1) else: return (0, 0) def trip_reduce(u, v): return tuple(map(lambda values: add(*values), zip(u, v))) def solve(...
961a21e79bcd758cef7e48d74069fc0019862d2b
nurmatthias/100DaysOfCode
/day21/inheritance.py
426
3.859375
4
class Animal: def __init__(self) -> None: self.num_eyes = 2 def breathe(self): print("inhale... exhale...") class Fish(Animal): def __init__(self) -> None: super().__init__() def swim(self): print("moving in water") def breathe(self): super().breathe(...
4f83405ed23e82b442f2f1a5a05ae4dff5f6ab9b
AmrAbdulSalam/Photoshop-GUI
/venv/Lib/site-packages/mt/base/zipfile.py
1,765
3.640625
4
'''Utilities dealing with a zip file.''' import zipfile as _zf import tempfile as _tf from .path import make_dirs, remove __all__ = ['extract_temporarily', 'ExtractedFolder'] class ExtractedFolder(object): '''A scope for use in a with statement. Upon exiting, the extracted folder is removed. The 'dirpath...
35215db4cd5bda91fe3618941bfd7f150acf91fb
TianyiZhang0315/EE415
/HW6/a6-starter-code/YourUWNetID_VI.py
4,213
3.59375
4
'''YourUWNetID_VI.py (rename this file using your own UWNetID.) Value Iteration for Markov Decision Processes. ''' from TowersOfHanoi import * import random # Edit the returned name to ensure you get credit for the assignment. def student_name(): return "Zhang, Tianyi" # For an autograder. Vkplus1 = {} Q_Values_Di...
d089443bd4dd1defe5db88a6fcf53963c70cb5c3
VincentVelthuizen/Week-3
/second_set/exercise_11.py
515
4.0625
4
import turtle screen = turtle.Screen() hour_turtle = turtle.Turtle() hour_turtle.shape("turtle") # the next line causes my turtle to end in the "wrong" position # I like it better to start at the top though hour_turtle.left(90) hour_turtle.penup() for hour in range(12): hour_turtle.forward(200) hour_turtle.p...
06900be0294e1b25e75732a7bd165767751eb284
cwcyau/PhD_DNNpractice
/code/PyTorch_tutorial.py
11,221
3.59375
4
##################################################################################### # PyTorch basics ##################################################################################### # import torch from __future__ import print_function import torch # create an uninitialized matrix x = torch.empty(5, 3) print(...
5ae2ac1c58df419660237e5223ab04c7e63a8ad6
apu031/Data-Structures-and-Algorithms-Specialization
/Course 3 - Algorithms on Graphs/Week 1 - Decomposition of Graphs - Undirected Graphs/Programming Assignment/week1_decomposition1/1_reachability/reachability.py
1,772
4.125
4
# Uses python3 import sys def reach(adj, x, y): """ This definition checks if there is a path from x to y. However, it does not consider any loop implementation. :param adj: Adjacency List :param x: Source :param y: Target :return: 1, if there is a path from x to y. Otherwise, 0. ...
aee49906a88499408a4d0fb09a07e78be3804e0b
Mandella-thi/Exercicios-Massanori-py
/exercícios-massanori-py/exercicios/papagaio.py
259
3.515625
4
# E. papagaio # temos um papagaio que fala alto # hora é um parâmetro entre 0 e 23 # temos problemas se o papagaio estiver falando # antes da 7 ou depois das 20 def papagaio(falando, hora): return falando and (hora<7 or hora>20) print(papagaio(True, 20))
2f21f592566730009d7fa191ad3aa07c973aed32
gdmgent-IoT-1920/labo-2-sensehat-nmdgent-robibeka
/nmd.py
783
3.671875
4
from sense_hat import SenseHat from random import randint from time import sleep import sys sense = SenseHat() def set_random_color(): return [randint(0,255), randint(0,255), randint(0,255)] def main(): letters = input("Enter your text: ") intervalBetween = float(input("How long do you want each letter t...
83ad417d2720126f294f7617f62187c2f0ef5fc1
tangdoufeitang/leetcode
/Python/42.trapping-rain-water.py
1,106
4.34375
4
from __future__ import print_function # 42. Trapping Rain Water # Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. # The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units o...
0e785ca16d03c89d2990db83ed8107842db8a984
Simjacs/space-sim
/src/utils.py
767
3.875
4
import pathlib import numpy as np def resolve_relative_path(file: str, path: str, parent_levels=0) -> pathlib.Path: """ returns absolute path to a file given its relative :param path from :param file :param file: path from root to a file :param path: relative path to file2 from the last common point i...
43e94b343980806630f3afbf3aac986290cb41da
JhaPrashant1108/leetcode
/leetCode442/442_Find_All_Duplicates_in_an_Array.py
445
3.53125
4
class Solution(object): def findDuplicates(self, nums): duplicate = [] for i in range(len(nums)): num = abs(nums[i]) if nums[num - 1] < 0: duplicate.append(num) continue nums[num - 1] = -nums[num - 1] return duplicate L = ...
a29c22488efac5b24d26fd54dbfd96ec8610c713
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s9.py
675
4.3125
4
# The parameterless method named # isalnum() # checks if the string contains only digits or alphabetical characters (letters), # and returns True or False according to the result. # Note: any string element that is not a digit or a letter causes the method to return False. An empty string does, too # Demonstrating the...
a9f089a91aa68feb67e15c23ad200129598d4b63
costcon/python-lesson
/Python超入門コース 合併版/Lesson13演習.py
211
3.84375
4
# 自分の回答 def average(num1, num2, num3): print((num1 + num2 + num3)/3) average(9, 4, 2) # 答え合わせ def div(a, b, c): return (a+b+c)/3 div_result = div(9, 4, 2) print(div_result)
6d32f5ddc3f4b1042aec6a231ac5a162e9a29cdc
adolfo-roman/FI_UNAM
/02_Estructuras_de_datos_y_algoritmos_1/P12/recorrido_recursivo.py
1,372
3.921875
4
import turtle import argparse #Declaración de la función #Recordar la importancia de la identación def recorrido_recursivo(tortuga, espacio, huellas): if huellas > 0: tortuga.stamp() espacio = espacio + 3 tortuga.forward(espacio) tortuga.right(24) ...
3fef2282ec4241d0b70c081cd8b734b1663285df
zhenjiaaa/kattis
/apaxiaaans.py
198
3.828125
4
def apaxiaaans(): line = input() new_line = line[0] for i in range(1, len(line)): if line[i] != line[i - 1]: new_line += line[i] print(new_line) apaxiaaans()
a841963a7bc9d21c9aa0225c14bb95d1b961610b
ibikimam/py4e
/largest.py
316
4.09375
4
largest_so_far = -1 print('Before', largest_so_far) for the_num in [9,41,12,3,74,15] : if the_num > largest_so_far : largest_so_far = the_num print('largest number so far is :',largest_so_far,'number tested in list is:',the_num) print('Largest number in the set is:', largest_so_far)
d3e55cdbe817ba851e0544effb70e19b7ad62a74
sunil9889/VS-Code-Repository
/statements/IfElse.py
125
4.0625
4
a=15 b=15 if a <b: print("A is smaller than B") elif a>b: print("A is greater than B") else : print("A==B")
ff71bca9b999a23aab5b943d753212cdbf340e5c
T-120/python
/test/1.py
342
3.53125
4
import re def fuzzyMatch(): value = '西西' list = ['大海西西的', '大家西西', '打架', '西都好快', '西西大化'] tempList = [] pattern = '.*' + value + '.*' for s in list: obj = re.findall(pattern, s) if len(obj) > 0: tempList.extend(obj) print(tempList) fuzzyMatch()
dd7b599547fa21809da21d2fae3407deae495409
JuliethOmbita/Code_Immersives-PY111-Intro-to-Python
/Day 9 - For loop/Activity9.2-JuliethOmbita.py
300
4.09375
4
## Activity 9.2 - Creation of max method using Loop def maxNum(myList): maxNumb = 0 for i in range(len(myList)): if myList[i]>maxNumb: #This condition line finds the bigest number. maxNumb = myList[i] print (maxNumb) myList = [6,1909,9,3,9] maxNum(myList)