blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
543e0535e7a308093e150a819ffbeb8ab2d09281
MounikaKV/PythonTraining
/try_except.py
388
3.84375
4
a = 5 b = 0 try: k = 5a if a == k: print("A == K") elif b == k: print("B == K") else: print("K is not the same as either A or B") except ValueError as e: print("Value Error : ", e) except NameError as e: print("NameError : ",e) except Exception as e: print("Somethi...
2249593cf24b99c4ea057f7d6f2509ee7b741d83
chikkuthomas/python
/array/intro.py
539
3.90625
4
import array as arr #here we alias array as arr, and we need to import the array package # we need to define which type # only one type of elements can be added in an array a = arr.array('d',[1.2,2.5,3.6,4.7]) # here float value hece defined as double = d print(a) #int type import array as arr a1=arr.array('i',[1,2,...
923c822073ccc6bb6c3bb7d756f006cc8671d94d
codingscode/curso_python
/ifsp/005 - rasc.py
2,160
3.765625
4
# continuação alunos = ['joao', 'vicente', 'paulo', 'ricardo', 'gabriel', 'vicente','larissa', 'geovana', 'fabiola'] print(alunos) #slicing print(alunos[1:6]) # do indice 1 a ?-1 print(alunos[3:7]) print(alunos[:4]) # 0 a ?-1 print(alunos[4:]) # 4 ao final print(alunos[1:-1]) print(alunos[2:-2]) pr...
6a5940bb731023b8d55755b34dc8b732607afa6d
poojataksande9211/python_data
/python_tutorial/excercise_4/range_in_tuple.py
386
3.90625
4
#range # num=tuple(range(1,11)) # print(num) #------------------------ num=list((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) #conert tuple to list print(num) num=str((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) #convert tuple to string print(num) print(type(num)) num_list=str([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])#convert list to string print(num_l...
fbe3fa1ec17e5afa3ec3ee24cdeb3778e02a3d88
Jatzek3/Python-Morsels
/perfect_square/perfect_square.py
288
3.78125
4
from math import sqrt from decimal import * def is_perfect_square(number): if number < 0: return False number = sqrt(number) print(number) if number == int(number): print("true") return True else: print("false") return False
1b61ab2434ccb7099b6f6ee9ccb4809519ce8472
pborgen/OFCP-AI
/helpers.py
16,405
4.03125
4
__author__ = 'Alastair Kerr' # -*- coding: utf-8 -*- import hands rank_dic1 = {'10':'T', '11':'J', '12':'Q', '13':'K', '14':'A'} # numerical value -> char value rank_dic2 = {'T':'10', 'J':'11', 'Q':'12', 'K':'13', 'A':'14'} # char value -> numerical value def reformat_hand_xyy_yx(hand, numCards): ''' Hand passed...
8b5cbeff37ce3b62ce52daf770cd4b90e77f53b0
oguipcj/ListaDeExercicios
/ExerciciosListas/10.py
685
3.953125
4
# 10. Faça um Programa que leia dois vetores com 10 elementos cada. Gere um terceiro vetor de 20 elementos, # cujos valores deverão ser compostos pelos elementos intercalados dos dois outros vetores. primeiro_vetor = [] segundo_vetor = [] terceiro_vetor = [] for posicao in range(10): primeiro_vetor.append(input("D...
fccaa80affc41996089bd480ae486f6a429d3970
chenlongjiu/python-test
/basketBall.py
997
3.9375
4
''' epic-systems-interview-questions Basket ball hit rates The hit rate of the basketball game is given by the number of hits divided by the number of chances. For example, you have 73 chances but hit 15 times, then your hit rate is 15/73=0.205 (keep the last 3 digits). On average, you have 4.5 chances in each basket...
8190b0f030b173d6091212fdc07b61a3af8b1956
Oscar-73/Python
/pruebas.py
13,861
4.21875
4
import math # Para poder hallar la raíz cuadrada de un número, es necesario que importemos la clase "math", para así usar la función "sqrt" # Funciones def evaluacionNota(): numero = input("\nIntroduce una nota:\n") print() try: if int(numero) == 0: print("¡A recuperar!") elif int(numero) >= 1 and int(numero...
888b114befdbce6cfbc8bced53d07a5aff266cb3
Aniket121397/Python
/Python/Num Problems/AREA.py
210
4.25
4
r=int(input("Enter radius of cicle:")) area=0 circum=0 if r>0: area=3.14*r*r print("Area of circle is:",area) if r>0: circum=3.14*2*r print("circumfernce of circle is :",circum)
31ffec16e81476e3aaf2ff13eb7c22b6c19e150b
JoonBeomLee/Algorithm_Python
/site/BAEKJOON/src/python/10_수학02/1978.py
303
3.8125
4
def isPrime(num): if num == 1: return False for i in range(2, num): if num % i == 0: return False return True T = int(input()) nums = list(map(int, input().split(" "))) count = 0 for num in nums: if isPrime(num): count += 1 print(count)
d54d7590c43510061f646c36aa9a7f65f9cb5ddf
ChuXiaoYi/python_high
/chapter08/property_test.py
784
3.859375
4
# -*- coding: utf-8 -*- # --------------------------------------------- # @Time : 2019/3/12 下午2:57 # @Author : cxy =.= # @File : property_test.py # @Software: PyCharm # @Desc : # --------------------------------------------- from datetime import date, datetime class User(objec...
17a943184f1cb3cdac909b9a188f12b970353786
khanhdodang/automation-training-python
/selenium_advanced/data_driven_testing/read_innovators.py
6,252
4.625
5
import csv print("\nBasic Usage of csv.reader()\n") with open('innovators.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) ''' CSV files with Custom Delimiters By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. F...
c20d622c8db6c2b7c528f467632b744a1534f06c
rutowskij/dailycodingchallenge
/Challenge 1.py
469
3.625
4
from itertools import permutations x = [10,15,3,7] perm = list(permutations(x,2)) map(sum, perm) #Final Function Pass# def sum_func(x, n): perm = list(permutations(x,2)) sum_tup = [x+y for (x,y) in perm] truth_table = [True if x == n else False for x in sum_tup] for i in range(len(truth_t...
80e6cf9c189a71dc9fd3d8416a1dea8b98a2ac82
Patricia888/data-structures-and-algorithms
/sorting_algos/selection_sort/selection.py
1,258
4.1875
4
# selection sorting is an in-place comparison sort # O(N^2) time, inefficient for large datasets # best when memory is limited def selection_sort(lst): ''' Implementation of selection sort. Efficient with space but not time. Finds the smallest unsorted index (index 0 in the first run) and compares it to all other...
925077af953d66ff6752032a877f8b51357fb53f
JustinMalvinIrawan/cp1404practical
/prac_08/unreliable_car_test.py
432
3.546875
4
from prac_08.unrealiable_car import UnreliableCar def main(): good_car = UnreliableCar("Tesla", 100, 95) worst_car = UnreliableCar("Junk", 100, 20) for i in range(1,20): print("Attempting to drive {}km:".format(i)) print("{:12} drove {:2}km".format(good_car.name, good_car.drive(i))) ...
512b1659e387ae5beabe7c32be5dcd2d0f487c1a
maohaoyang369/Python_exercise
/222.一个字符串排序.py
623
3.53125
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # 一个字符串排序,排序规则:小写<大写<奇数<偶数 # 原理:先比较元组的第一个值,FALSE<TRUE,如果相等就比较元组的下一个值,以此类推 # 小写<大写<奇数<偶数 # 偶数(True,True,False,False) # 奇数(True,False,False,False) # 大写(False,False,True,False) # 小写(False,False,False,True) s = '9a13C85c7B24A6b' # 正确的顺序应该为:abcABC135792468 lis = sorted(s, k...
655e3d82c91a84f730fb623833f4e73fed87559a
Anchal2096/Machine-Learning
/NAIVE BAYES/Weather_is_suitable_for Playing.py
1,285
3.625
4
# Import LabelEncoder import pandas as pd # Import Gaussian Naive Bayes model from sklearn.naive_bayes import GaussianNB from sklearn import preprocessing from sklearn.metrics import accuracy_score, confusion_matrix # creating labelEncoder for normalising the label le = preprocessing.LabelEncoder() # Converting stri...
a696645ce2bad270639f8d94c78913961e3820ab
menuka-maharjan/python_Basics
/Armstrong.py
132
3.71875
4
n=int(input()) s=0 t=n while t>0: digits=t%10 s+=digits**3 t//=10 if n==s: print("Armstrong") else: print("not")
ca29c13f590261018af751e83dd040063ce480f8
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/8 Problems on bits and masking/3_CheckFourBitsAreOff/Demo.py
712
3.609375
4
''' Write a program which checks whether 7th & 15th & 21st , 28th bit is On or OFF Input: 169301334 (1010000101110101010101010110) Output: True ''' def CheckBit(num,pos1,pos2,pos3,pos4): mask = 0x00000001; mask1 = mask<<(pos1-1); mask2 = mask<<(pos2-1); mask3 = mask<<(pos3-1); mask4 = mask<<(pos4-1)...
95c9971feb4b8f792a26079a3269846f5c7b09aa
dherath/udacityCourses
/programming_foundations_with_python/2_classes_turtle/flower/flower.py
526
3.703125
4
import turtle def drawSquare(size,angle,color) : t1=turtle.Turtle() t1.ht() t1.pencolor(color) t1.right(angle) for i in range (4) : t1.forward(size) if i%2==0 : t1.right(60) else : t1.right(120) def combinedShape(sz,colorVal): angleList = [x for x in range(360) if x%5==0] for i in angleList : drawSqua...
ad8d4010e214f20ac8601828986567c214377ece
jc304696/Practicals
/Lab5/countWords.py
369
4.03125
4
sentence = input("Type a sentence here: ") words_in_sentence = sentence.split() my_dict = {} for word in words_in_sentence: if word in my_dict: my_dict[word] += 1 else: my_dict[word] = 1 largest_word = max(len(word) for word in words_in_sentence) for word in sorted(my_dict): print("{:{}} :...
1e9927c97d35a585e794690c3da922a5955923d6
JANARDHANAN97/TopGear
/Asgn2_py6.py
1,167
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 1 14:39:24 2019 @author: janar """ class sqroot: def __init__(self,a,b): self.a=a self.b=b def sqroot(self): print(self.a**self.b) #def __init__(self,a,b) class addition: def __init__(self,a,b): self....
54fd76aa5d52e3f616f87c5eb7d2af25a9bc44ac
HenrykHaniewicz/MathFunctions
/Python/mathfunctions/co-ordinate_transformations.py
4,335
3.875
4
# Co-ordinate transformations # Imports import iterative_processes as ip import math import numpy as np # Functions def cartesian_to_polar( x, y ): r = math.sqrt( x**2 + y**2 ) theta = math.atan( y / x ) theta = theta % (2*math.pi) return r, theta def polar_to_cartesian( r, theta ): theta = theta...
b3497eda7b0cdb224ef7297ab39b30c47014e6a9
asingla/cognizance
/Workshop codes/day2/KNearestFromScratch.py
1,084
3.5625
4
from math import sqrt import numpy as np from matplotlib import style import matplotlib.pyplot as plt import warnings from collections import Counter import pandas as pd import random style.use('fivethirtyeight') dataset = {'k' : [[1,2],[2,3],[3,1]],'r':[[6,5],[7,7],[8,6]]} # Can see all the points using this code...
a29ad519912e73dfafcc55293ee77a779f432bad
KelineBalieiro/Python
/teste7.py
113
3.75
4
num1=int(input("digite o numero: ")) s = "par" if num1 % 2 == 0 else "impar" print("O número digitado é: ", s)
b985de055894f33bb106d9b99327d65e6697ad49
ameyanaik/DassaultPythonWorkshop
/basics/mymodule.py
349
3.53125
4
# This is a module class Person: def __init__(self, name, age): self.name = name self.age = age def print_info(self): print(self.name, self.age) message = "Hello World" x = "This is MyModule" def main(): print("printing from mymodule") print(x) print(message) if __name_...
60b3344a8c0ac71ce555cbf1ce3cae31479da455
cs13syy/snu-fira-bigdata-analytics
/bigdata-analysis-using-python/day2-lecture.py
1,300
4
4
# receive input as integer z = int(input('Enter integers : ')) print(z+1) # casting practice a=1 print(type(a)) x='1' y='2' print(x+y) # lab 2-3-1 i=1234 s='1234' print(i==s) s=int(s) print(i==s) # lab 2-3-2 print('What is your name?') x = input() print('Hi! '+x) print('The length of your name is:') print(len(x)) ...
5eff428d495899a57b49328ffe89bedbdcef41dc
mahespunshi/Juniper-Fundamentals
/Dictionary-HW.py
1,113
4.21875
4
# Create a dictionary called shopping_cart # shopping_cart = {'Airpods': [10, 234], 'Mouse': [5, 5], 'Keyboard': [20, 8], 'Pen': [200, 1], 'Belt': [20, 6], 'Jeans': [20, 10]} shopping_cart = {'Airpods': (10, 234), 'Mouse': (5, 5), 'Keyboard': (20, 8), 'Pen': (200, 1), 'Belt': (20, 6), 'Jeans': (20, 10)} # in above line...
3225d84ea096837a63c3db9fd46333cd78f978e7
dmodena/grokking-algorithms
/algorithms/tailrecursion/count.py
194
3.96875
4
def count(arr, result=0): ''' Counts the number of elements in an array. ''' if len(arr) == 0: return result arr.pop() result += 1 return count(arr, result)
993251fdb62446f10739e20434e11be2859d96b0
sechchr22/holbertonschool-higher_level_programming
/0x03-python-data_structures/5-no_c.py
195
3.65625
4
#!/usr/bin/python3 def no_c(my_string): ls = list(my_string) for i in range(0, len(my_string)): if ls[i] == 'C' or ls[i] == 'c': ls[i] = "" return(''.join(ls))
ae750b03a698138a823b3a98e160873c6aa6f3d4
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3986/codes/1798_2565.py
397
3.65625
4
from numpy import* m = array(eval(input("Medias finais: "))) p = array(eval(input("Horas presentes: "))) ch = array(eval(input("Carga horaria: "))) v = zeros(3, dtype=int) RF = 0 RN = 0 A = 0 for i in range(size(m)): if (p[i] < ch * 75/100): RF = RF + 1 v[2] = RF elif (p[i] >= ch *75/100): if(m[i] < 5): RN...
9b054b7c0bc980da185fc27c94716bef96edacb4
jayhsieh/algorithm
/SequenceComparison.py
1,113
4.09375
4
import numpy as np import sys def check_replace(a, b): return 0 if str(a) == str(b) else 1 def minimux_diff(mapfrom, mapto): x = (len(mapfrom) + 1) y = (len(mapto) + 1) matrix = np.zeros((x ,y), dtype=int) for i in range(x): matrix[i, 0] = i for j in range(y): matrix[0, j] ...
5e4896cb14fc8eb50a90e62aaf5b713f42d8a08c
ShourjaMukherjee/Dummy
/11thcodes/Lists/ASSIGN 77 - LIST - Cummulative Sum (1).py
542
3.78125
4
print "PLEASE TURN ON CAPS!!!!!!" def acceptList(L): choice='Y' while choice=='Y': n=raw_input("Enter Value:- ") n=float(n) L.append(n) choice=raw_input("Do you wish to continue?(Y/N):- ") if choice!='Y': break return L def sum(s): ...
08a19c173d5364a2f1b4f1de5e1645de2e4ba481
Jean-KOUAGOU/Programming
/programmingfiles/repeatint.py
460
3.734375
4
try: elemts=[] l=[] n=int(input('How many integers do you want to enter ?\n\n')) print('\nEnter them:\n') for i in range(n): l+=[int(input())] print('\nThe following numbers are repeated more than one times:\n') for i in range(len(l)): if not (l[i] in elemts)==True: for j in range(len(l)): if j!=i an...
f0ff04904913946057b156dbde69511b11015a63
GeoGateway/BuriedSAFSlip2010
/daynum2k.py
2,023
3.796875
4
# Date to day past y2k def daynum2k(date): """ Function daynum2k: date: string in format dd-Mmm-yyyy ie 13-Nov-2009 return day past y2k start (01-Jan-2000 => 1) Note: good for years 2000-2023 (easily generalized) """ yearc = [366,365,365,365,366,365,365,365,366,365,365,365, ...
f185a6d0c498d1520caee75991f7998e4cca22ac
gmossthebiologist/Old_Spyder_Files
/CCS_Ch6.py
6,854
4.28125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 10 18:11:32 2021 @author: MOSS """ ''' A loop executes the loop's statements (loop body) repeatedly. Each time through a loop's body is an interation. A while loop continually iterates as long as its loop expression remains true. A sentinal value is one that terminate...
16885a3a310a28d998fa914774678e4c055de730
Elkoumy/AlgorithmicsProject
/classes/pieceDisplay.py
1,842
4
4
class pieceDisplay: """ pieceDisplay: this is a helper class for the GUI, store information about the object which is should be displayed """ def __init__(self,pieceDisplayinfo,chess_coord,square_width,square_height): """ Args: pieceDisplayinfo: chess_coord...
0a5cc04ca0ae609084c6c7245fe15f2d560d9fdf
rer3/Coursera_RiceUni
/IIPP/IIPP_Assignments/IIPP2_Project5_Memory.py
24,633
4.1875
4
""" Rice University / Coursera: Intro to Interactive Programming in Python (Part 2) Week 1: Project 5 Memory """ #================================================================= # All code for this assignment is shown below with only essential imports. # Code provided by Rice University has been modified whenever app...
39b3554b2bd547466579e084e9e50b80aeb91bbf
elekdra01/30DaysofCode
/who likes it.py
489
3.84375
4
def likes(names): l=len(names) if(l==0): v="no one likes this" return v elif(l==1): v=str(names[0])+" likes this" return v elif(l==2): v=str(names[0])+" and "+str(names[1])+" like this" return v elif(l==3): v=str(names[0])+", "+str(names[1])+" ...
d0fa658d3298c17f6eabd73c3e7b62b47b2be07a
odevee/Framework
/Protoype/test2.py
4,707
3.59375
4
#import the pygame module, and the sys module #for exiting the window we create import pygame, sys import random #import some useful constants from pygame.locals import * pygame.init() #constants eventually representing some #tile porperty, e.g. walkable, non-walkable, etc. WALKABLE = 1 NONWALKABLE = 0 ...
e3281bb4c10beb5d56e3c83a8815c7d70d7c52ad
G-Sivley/snake-game
/score_board.py
1,121
4
4
from turtle import Turtle class ScoreBoard(Turtle): def __init__(self): super().__init__() self.color("white") self.penup() self.hideturtle() self.score = 0 self.high_score = 0 self.read_highscore() # Set the position to the top of the ...
53d72351ec041aa207c392282fe26a4381facc72
WardBrian/CS1101
/Code/Lecture22.py
893
3.765625
4
# pylint: disable=c # ALIASING OF IMMUTABLE OBJECTS first = 1000 second = first print first, second first += 3 print first, second first = 'Boston' second = first print first, second first += ' College' print first, second # ALIASING OF MUTABLE OBJECTS first = [1, 2] second = first print first, second first.append(3...
2cedaf019a68e6b47ff2b8298202e9cf911ee9ed
AymenSe/10-Days-of-Statistics-using-python
/Day 1 - Quartiles/quartiles.py
553
3.765625
4
def quartiles(arr): # Write your code here arr = sorted(arr) n = len(arr) if n % 2 == 0: median = (arr[n//2] + arr[n//2 - 1]) / 2 arr1 = arr[:n//2] arr2 = arr[n//2:] else: median = arr[n//2] arr1 = arr[:n//2] arr2 = arr[n//2 + 1:] l = len(arr1...
e63c87949aa1c98e005655b722c00638e76b7f10
iamYvette/mypython
/python2/yanzhengma.py
855
3.640625
4
#coding=utf-8 # 0010 使用python生成类似于下图中的字母验证码图片 from PIL import Image,ImageDraw,ImageFont,ImageFilter import random def randomChar(): return chr(random.randint(65,90)) def randomColor1(): return (random.randint(64,255),random.randint(64,255),random.randint(64,255)) def randomColor2(): return (random.randint(6...
f13e2da522816d058df2c81fb0c8970127413256
charli-polo/friendly-pi2go
/led.py
2,540
3.546875
4
# -*- coding: utf-8 -*- from __future__ import print_function import pca9685_p3 class Leds: def __init__(self): self.front = Led(3) self.right = Led(2) self.rear = Led(1) self.left = Led(0) self.all = [self.front, self.right, self.rear, self.left] self.off() def...
17753f9af755ab326df2c37a51139f377142a0f1
codywill/web
/projects/udacity-backend/lesson 4 - user accounts/hash_play.py
1,530
3.5625
4
import hashlib import hmac import random import string #def hash_str(s): # return hashlib.md5(s).hexdigest() # ----------------- # User Instructions # # Implement the function make_secure_val, which takes a string and returns a # string of the format: # s,HASH def make_secure_val(s): return "%s,%s" % (s, h...
b67cb85fecbf1e2dae4c7b58fb307ba36fd45aac
zhhy/auto
/tools/threadtest.py
479
3.65625
4
import matplotlib.pyplot as plt # data x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4] # trick to get the axes fig, ax = plt.subplots() # make ticks and tick labels xticks = range(min(x),max(x),2) xticklabels = ['2000-01-0' + str(n) for n in range(1, len(xticks) + 1)] # plot data ax.plot(x, y, color='green', linewidth=1...
9265e04d4535f7f397360fdc885b1b48f5c49870
MauriceKuenicke/NumA
/numa/RootFinder/_regulaFalsi.py
3,030
4.03125
4
from numa import utils def regulaFalsi(function, interval_start, interval_end, max_iterations=10000, giveIterations=False): """Approximate one root of a given one-parameter function using the Regula Falsi method; note that the root has to be inside the interval or the method won't yield any results. This ...
901034d1b2ca2bb00797302b16684dc299e504bd
Sagarnaikg/File-Analyser
/mostUsedKeyFind.py
1,012
3.921875
4
""" In this project to find the most used key word in the text """ # accesing the file file = open("sampleFile.txt", "r") data = file.read() # conversion of the string into list l = data.split(" ") countl = [] # fltering the non alphabets in the list for i in l: if not i.isalpha(): l.pop(l.index(i)) # c...
fdf51a9f65f0768f99ab19c2e1f8d2f9cb3e6d1d
Shadrock/code-snippets
/Python/Rename_files_asorderedlist.py
715
4.125
4
# Python 3 code to rename multiple files in a directory or folder as an ordered list, eg. IDCE_1, IDCE_2, etc. From https://www.geeksforgeeks.org/rename-multiple-files-using-python/ #!/usr/bin/env python # importing os module import os # Function to rename multiple files def main(): i = 0 for filename in os....
90e22195a325fb60ab0e2716da9769ca8f305f04
alex-ong/opalstatement-summarizer
/OpalSummarizer.py
2,004
3.78125
4
days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] STATE_DAY = 0 STATE_DATE = 1 STATE_MONEY = 2 from collections import namedtuple class DaySummarizer(namedtuple("DaySummarizer", ["day", "date", "amount"])): __slots__ = () def __str__(self): return str(self.day) + " " + str(self.date) + " " + str(rou...
a22e5342b67729d3936d8aeb0a89c5d5f6057b86
wiizard-chen/PythonExercise
/Python Crash Course/chapter6/6.1lesson.py
853
3.734375
4
# alien_0 = {'color': 'green', 'points': 5} # print(alien_0['color']) # print(alien_0['points']) # array = [] # array.append(1) # array.append(2) # print(array) # dic0 = {} # dic0['test1'] = 2 # dic0['test2'] = 3 # for key in dic0.keys(): # print(dic0[key]) # for key in dic0: # print(dic0[key]) # for key, v...
2c8c72f1536e3c9a0b417bf0052e5d004a4c9aa6
daltonwu/MKS22QJI-homework
/10/utils.py
7,303
3.671875
4
from urllib2 import urlopen, Request from urllib import quote_plus from json import loads from re import search from os import urandom def get_salary(first_name, last_name): '''Returns a dictionary with the keys 'full_name' and 'salary' Takes in the first and last names of the teacher (first_name cannot b...
091efaa9f59a87bd23d1a884e02692f59e50cdc8
VaniKancherla/PycharmProjects
/pythonPrgmspdf/pythondatastructure/listprograms/SixEightPrgms.py
474
4
4
stringList = ["cbc", "afa", "bvkb", 12, 6, "cbc", 6] # remove duplicates from a list finalList = [] for lst in stringList: if lst not in finalList: finalList.append(lst) # print(finalList) # list of words that are longer than n from a given list of words wordList = ["vani", "kancherla", "ab", "u", "abc"] ...
695124edc0006a7ec8abbd109a4fdd973c59ce0b
kmo12/general
/queue_abstract_data_structure.py
2,555
3.90625
4
from random import randint, choice class Queue: def __init__(self): self.__data = list() def size(self): return len(self.__data) def front(self): if self.size() > 0: return self.__data[0] return None def back(self): if self.size() ...
af5f98fd88492bf020aa5260855d9a6121efb13b
harsh25jai/Hangman
/hangman.py
1,900
3.859375
4
import random import time print"HANGMAN" print"\n" name = raw_input(" Type your Name : ") print "Hello! " ,name print "Ready to play HANGMAN" print "\n" time.sleep(1) print "Start Guessing Word .................to win the Game" time.sleep(0.5) def words(): w=['hangman','python','computer','fundamentals','methoth...
123b9a545d6746dabb99f10a8b0bea41eda1f636
Connor1996/Core-Python-Promgramming-Exercise
/Chapter9/9-5.py
719
3.578125
4
def diff(str1, str2): for i in range(len(str1)): if (str1[i] != str2[i]) or (i >= len(str2)): return i + 1 def filecmp(file1, file2): j = 0 for i, eachLine in enumerate(file1): string = file2.next() if eachLine != string: return (i + 1, diff(eachLine, string...
719dd45ac44b0f45640c65573f37796db7902d1e
JohnnyVip/PythonTest
/decorator_demo/deepcopy.py
509
3.859375
4
import copy t = [41, 42] a = [1, 2, 3, t] b = a #c = copy.copy(a) #浅拷贝 c = copy.deepcopy(a) #深拷贝 print(a) print(a, b, c) t.pop() print(a, b, c) import copy a = [1, 2, 3, 4, ['a', 'b']]#原始对象 b = a #赋值,传对象的引用 c = copy.copy(a) #对象拷贝,浅拷贝 d = copy.deepcopy(a) #对象拷贝,深拷贝 a.append(5) #修改对象a a[4].append('c') #修改对...
0c0268e637653875c52b70b18315e6c40f7d429c
dlingerfelt/DSC510Summer2020
/BANKAR_DSC510/Assignment_2.1.py
1,287
4.46875
4
#DSC 510 #Week 2 #Programming Assignment Week 2 #Author Dhiraj Bankar #06/12/2020 """ Fiber Optic Cable installation receipt Generator Purpose of Program: Generate a automated receipt for fiber optic cable installation program by getting input from user for company name and how much fiber optic cab...
77903998e23a42dba93a40094a8a6e52bda8be66
hammer-spring/PyCharmProject
/python 100天算法挑战/01_汉诺塔.py
739
3.9375
4
''' 如果我们要将最大的圆盘移动到最右边的柱子上。我们需要把除此圆盘的其他圆盘先移动到中间的柱子上。 因此这个问题就变成了如何将 N-1 个圆盘移动到中间的柱子上。 很容易我们就想到了递归的方法。 将 N 个圆盘从左边柱子移动到右边柱子: [递归的]将 N-1 个圆盘从左边柱子移动到中间柱子。 将最大的圆盘从左边柱子移动到右边柱子。 [递归的]将 N-1 个圆盘从中间柱子移动到右边柱子。 ''' def hannoi(height,left='left',right='right',middle='middle'): if height: hannoi(height - 1,left,middle,ri...
355c8ece800fc08bea372034d33149e3255aa48e
rentes/Euler
/problem3.py
1,956
3.703125
4
"""Project Euler - Problem 3 - http://projecteuler.net/problem=3""" import sys import time import tools.timeutils as timeutils def multiply_factors(l): """ Multiplies discovered prime factors of n Returns: int """ v = 1 for x in l: v *= x return v def factors(n): """ This...
c4971ef0c3bba43dc0b18a57b1d2501335afc89e
Pexet/ChervonyiPaulHomeWorkPMI23Pyrhon
/python_1sem/practice/Task4/main.py
2,051
3.8125
4
from Generator import generator from ClassIterator import Iterator def getNumber(): # inputing and ckecking number method while type: getTempNumber=input() # inputing try: # checking if all is right getTempNumber=int(ge...
befef6e2b3663e6967491f3d0beff6da53be9bfc
kaylani2/machineLearning
/src/simple_examples/visualizar_iris.py
2,797
3.546875
4
## Cortesia do professor Heraldo Almeida - https://github.com/HeraldoAlmeida #============================================================================== # Carga e Visualizacao do Conjunto de Dados IRIS (problema de classificacao) #============================================================================== #--...
4316f3e4e5e9f11eaa76b1b85b19b9a5c6961e0e
julielaursen/Homework
/ex3.py
2,623
4.375
4
#Define the main function that will call all other functions def main(): miles = float(input("Please tell me how many miles you want converted to kilometers?: ")) #ask the user how many miles to convert milesToKm() #call milesToKm function fahrenheit_temperature = float(input("Please tell me the ...
bd5e6826d57b75770d4dddc66b5cbb607b859ca9
kovalevcon/practice-code
/Deodorant Evaporator/deodorant-evaporator.py
436
3.8125
4
# Complete the evaporator function below. def evaporator(content, evap_per_day, threshold): """ :type content: int :type evap_per_day: int :type threshold: int :rtype: int """ days = 0 gas = 100 while gas > threshold: gas -= gas * evap_per_day / 100 days += 1 ret...
45e851848796eaf1957f7dc42301fe527546ff90
ebaek/Data-Structures-Algorithms
/LeetCode/longest_palindromic_substr.py
1,010
3.546875
4
# 5: Longest Palindromic Substring # Manacher's Algorithm class Solution: def longestPalindrome(self, s: str) -> str: lengths = [] for idx in range(len(s)): leftIdx = idx - 1 rightIdx = idx + 1 while s[leftIdx] == s[rightIdx]: ...
487a582309a552e28e5556707ef438010c403579
linkinpark213/leetcode-practice
/pysrc/10.py
682
3.6875
4
class Solution: def isMatch(self, s: str, p: str) -> bool: if len(p) == 0: return len(s) == 0 if len(p) > 1 and p[1] == '*': return self.isMatch(s, p[2:]) or (len(s) > 0 and (s[0] == p[0] or p[0] == '.') and self.isMatch(s[1:], p)) else: return len(s) > 0 ...
51c664edea8c72f7d3f3d8c0c322ac25a2f2e85c
zrstln/Python_lessons_from_ADV_IT
/Lesson-9-Lists2.py
1,070
4.21875
4
# 0 1 2 3 4 cars = ['mazda', 'bmv', 'shkoda', 'suzuki', 'audi'] for x in cars: print(x.upper()) for x in range(1, 6): print(x) mynumber_list = list(range(0, 10)) print(mynumber_list) print("________________________________________") for x in mynumber_list: x = x * 2 ...
674167d87a2db0875f1582dcc4889621ac1d3876
nhq-cs/PythonSolutions_Hackerrank
/Solutions/String/The Minion Game.py
404
3.59375
4
def minion_game(string): vowels = set('AEUIOU') stuart = kevin = 0 for i,c in enumerate(string): if c in vowels: kevin += len(string) - i else: stuart += len(string)- i if stuart > kevin: print("Stuart", stuart) elif stuart == kevin: ...
ceff626bb1460796020ad39c82942c0275cc60e8
srihariprasad-r/leet-code
/leetcode-solutions/P1932.Merge_BST.py
2,624
3.65625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def canMerge(self, trees): """ :type trees: List[TreeNode] :rtype: T...
7673e799a30557121d840b465f324357f15bd1e5
EthanCornish/Unit3Work
/Functions1.py
6,514
3.953125
4
import copy # Used in Function 5 # from FunctionsTutorial import LargestElement syntax to import functions from other files # x = LargestElement(list) x = return value from function # Function 1. Returns largest element def Function1ReturnLargest (list): largestElement = ...
fb4a9c71218d24f617ca33d591f26dc455926633
dave-vazquez/Algorithms
/stock_prices/stock_prices.py
1,639
3.953125
4
#!/usr/bin/python import argparse import os os.system('clear') ''' RUN-TIME COMPLEXITY: O(n) Justification: The first loop runs N-1 times. Drop the constant and you get O(n). The second loop runs N-k times, where k is the sell index. In a worst case scenario, k is the last index of the array ...
1a9178dd9749d00bfcc786488511a2a59e8a7bed
Janne-Lam/Python-Projects
/multi-threading/ex3.py
863
3.78125
4
import threading import time import inspect var = 0 global lock lock = threading.Lock() """ class Counter, where it increases the value of var by 1 and prints "hello world" then ran """ class HelloWorld(threading.Thread): def __init__(self): super().__init__() print('Inside hello_world') global lock ...
ec99f37a5f821fd4e03895d6a29d0f23587d6a5b
pedrosimoes-programmer/exercicios-python
/exercicios-Python/ex077.py
332
3.828125
4
palavras = ('garrafa', 'caneca', 'celular', 'computador', 'teclado', 'mouse', 'gabinete', 'escova') vogais = ('a', 'e', 'i', 'o', 'u') c = 0 for palavra in palavras: print(f'\nNa palavra {palavra.upper()}, as vogais são ', end='') for letra in palavra: if letra.lower() in 'aeiou': print(letr...
adcd47ede3e8a76f395ba7758726b17af2693ee5
katesorotos/module2
/count_words/textData/textData/similarity.py
3,851
3.625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 13:51:11 2019 @author: Kate Sorotos """ """Document similarity task""" ### Reads stopwords and appends them to empty list def read_stop_words(textfile): stops = [] stop_words = open(textfile, 'r') for line in stop_words: word = line.strip() ...
d02c5ac6f292f7336300b1a1278290cd4bdaace8
touhiduzzaman-tuhin/python-code-university-life
/Telusko/31.py
1,020
3.59375
4
from numpy import * ar = array([1, 2, 3, 4]) print(ar) print("---") ar = array([1, 2, 3, 4]) ar = ar + 5 print(ar) print("---") ar1 = array([1, 2, 3, 4, 5]) ar2 = array([6, 7, 8, 9, 1]) ar = ar1 + ar2 print(ar) print("---") ar1 = array([1, 2, 3, 4, 5]) ar2 = array([6, 7, 8, 9, 1]) print(concatenate([ar1, a...
414c62dcb86a3e471e328530d2d95354f8b42266
roshik2016/PythonPrograms
/python_hw2.py
775
4.15625
4
def gradecalc(score): if score >= 90 and score <= 100: return("Your Grade for the score of", score, " is A") elif score >= 80 and score < 90: return("Your Grade for the score of", score, " is B") elif score >= 70 and score < 80: return("Your Grade for the score of", score, " is C") elif score >= 60 and...
b450ac5490d59a037d51b0cdde5c37457a3e15c5
zhoupeng315/python-crash-course
/courses/ch3/excercises/chap3/3-1.py
261
3.5
4
names = ['Eric', 'Karen', 'CC', 'Tony'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) message = 'Hello, my friend' print(f'{message} {names[0]}') print(f'{message} {names[1]}') print(f'{message} {names[2]}') print(f'{message} {names[3]}')
7cca244e7500997d35e2c6749729bb2a1fbc3c9c
erjan/coding_exercises
/minimum_operations_to_make_the_array_k_increasing.py
2,507
3.921875
4
''' You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr...
4c02cf6fe7f1805d8aba199e1185400f0ac3eaf1
mutanara/pythonessentialtraining
/Operation(operators)/workingwithdecimals.py
344
3.75
4
# first_way from decimal import * a = Decimal(".101") b = Decimal(".30") x = a + a + a - b print(x) #second_way from decimal import * getcontext().prec = 2 # this perc number refers to the number of decimal places you want the result to show. x = Decimal(.10) + Decimal(.10) + Decimal(.10) - Decimal(.30) print(x) ...
e5eee0857bcd00cb193fb1bdc7247c0033107bab
aletrianti/codewars-solutions
/py/8kyu_opposite-number.py
182
3.859375
4
""" Very simple, given a number, find its opposite. Examples: 1: -1 14: -14 -34: 34 """ opposite = lambda number: -number # OR def opposite(number): return -number
59d3bd64fc141ca2a024d70a171f3c8fb8d1176c
EuganeLebedev/Python_for_test
/lections/lesson9/11_attrs.py
284
3.65625
4
class Person: def __init__(self, name): self.name = name def __getattribute__(self, attr): print(f"getattribute: attr={attr}") inner_dict = object.__getattribute__(self, "__dict__") return inner_dict[attr] p1 = Person("Ivan") print(p1.name)
d84685d6fad0a9c34baf510db966afc870c3a7b2
codewithgsp/text-based-browser
/Problems/The index of the last occurrence/task.py
139
3.703125
4
text = input() pattern = input() def find_last(text, pattern): index = text.rfind(pattern) print(index) find_last(text, pattern)
30152c1c9e1764e608bf02b7da86b403450e9a93
svanis71/codewars
/codewars.python/tests/reverse_words_test.py
703
3.6875
4
import unittest from reverse_words import reverse_words class ReverseWordsTests(unittest.TestCase): def test_something(self): self.assertEqual('olleH', reverse_words('Hello')) def test_1(self): self.assertEqual(reverse_words('The quick brown fox jumps over the lazy dog.'), ...
94d185ad78c02bba069d6def1ed73d09a1140627
mhelms44/lpthw
/ex16.py
1,165
4.4375
4
from sys import argv #sets arguments for argv, which we imported from sys. This gives us the script name and we supply a filename. script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") input("?") print...
01c548dd997d2b2e768c9fb7a956b64e71c12796
xxnbyy/mytools
/lin2win.py
808
3.515625
4
#换行转换 #linux下\n转换成windows下\r\n def main(): import sys input_file=sys.argv[1] f=open(input_file,"r+") urls=f.readlines() f.close() f1=open("outfile","a+") for url in urls: print url[0:-1] #print url is different with print url[0:-1] #print url[0:-1] can get the pure string ...
7dfd0574bf21b158156365d5bbacc57cbeef53db
jimmy050314/Herramientas1
/P2Ejercicio1.py
430
3.546875
4
def pys(): print("Bienvenido, ingrese los 5 valores para obtener su sumatoria y promedio") V1=float(input("Ingrese el primer valor: ")) V2=float(input("Ingrese el segundo valor: ")) V3=float(input("Ingrese el tercer valor: ")) V4=float(input("Ingrese el cuarto valor: ")) V5=float(input("Ingrese el último valor: "...
e9822c5f230837b75cb43077538ccbb2f7b5077b
IdiotCirno/MFTI
/If For While/C.py
804
3.609375
4
N = int(input('')) if N%100!=0: if N%4!=0: print('NO') else: print('YES') elif N%400: print('NO') else: print('YES') ''' Требуется определить, является ли данный год високосным. (Год является високосным, если его номер кратен 4, но не кратен 100, а также если он кратен 400). Формат в...
5c19cc80551183d0d3551b70818ac3bf03b358f8
WEEE-Open/peracotta
/parsers/read_decode_dimms.py
4,896
3.75
4
#!/usr/bin/python3 # initial_chars_to_ignore is the length of the feature whose name the line begins with # e.g. "Fundamental Memory Type" begins with 23 characters that are not all spaces, then n spaces to ignore, # and finally there's the value needed, e.g. "DDR3 SDRAM" from typing import List def _ignore_spaces(l...
450d56506865ab63f188eea9f7e80e205a230795
rescerchib/Education
/Python_Edu_20180912/dict.py
1,339
3.9375
4
class Interest: name = "My Interest" def __init__(self): self.interest = {"오버워치":"게임", "WOW":"게임", "Python":"프로그래밍"} def add(self, key, value): self.interest[key] = value def delete(self, key): del self.interest[key] def count(self): ''' dict...
c44c290dd8910869c35c042e36cb5cd9dc38a220
simhermansson/billiards_simulation
/main.py
3,226
3.921875
4
import pygame import ball import pool_table import cue """ Simulates a billiards game, where balls interact with each other through elastic collisions with the effect of friction. To set a ball in motion, place the cursor near the ball you want fired and take aim. The force applied grows as the distance from the ball ...
6005fe81ee5578714997ec9f5f82277ab13a654a
deepak3698/Python_Basic_Program
/matrix_subtraction.py
243
3.765625
4
from numpy import * matrix_1=matrix('1 2 3 ; 2 3 4 ; 5 6 7') ### its 3x3 matrix matrix_2=matrix('2 3 4 ; 8 5 4 ; 2 3 6') ### its 3x3 matrix add_matrix=matrix_1-matrix_2 print(f"{matrix_1} \n - \n {matrix_2} \n = \n {add_matrix}")
9b4aedef7c47beb029018e0c637741e760dae614
MSharique/competitive_codes
/CHEFSTUD.py
216
3.84375
4
t = int(input()) while t>0: t -= 1 talk = input() talk = talk.replace("<", "#") talk = talk.replace(">", "<") talk = talk.replace("#", ">") # print("final: ", talk) print(talk.count("><"))
5be388878c85138c184adf14e22a70fe4a0fad30
ricardo64/Over-100-Exercises-Python-and-Algorithms
/src/examples_in_my_book/general_problems/modules/using_time_module.py
462
3.8125
4
#!/usr/bin/python3 # mari von steinkirch @2013 # steinkirch at gmail import time def sumOfN2(n): ''' a simple example of how to time a function ''' start = time.time() theSum = 0 for i in range(1,n+1): theSum = theSum + i end = time.time() return theSum,end-start if __name__ == '__m...
5716ebf4efeeb4fd38a028d00d4b4553cc22c18b
EvianTan/Lintcode-Leetcode
/128 Longest Consecutive Sequence.py
967
3.9375
4
''' Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. ''' class Solution(object): def longestC...
ba0ee0e7c55fac5e222e8641fa3162ab06f42d66
sagarc03/Projects-Solution-Python
/Algorithm/CollatzConjecture.py
286
3.6875
4
collatz = {1: 0} def collatzConjeture(n): if n < 1: return 0 if n not in collatz: if n % 2 == 0: collatz[n] = 1 + collatzConjeture(n//2) else: collatz[n] = 1 + collatzConjeture(n * 3 + 1) return collatz[n] print(collatzConjeture(50)) print(collatz)
e659a203b454c66c4f394d63203e080f2c77074f
EricCWWong/ConductanceSimulator
/IntSimulator/conductance_graph.py
3,515
4.0625
4
from matplotlib import pyplot as plt import numpy as np """ The following section contains functions to plot the conductance plot when given energy of each energy level. """ def single_transmission(threshold_energy, x): """ This function gives a single transmission on a conductance plot ...
9943ed347d6aaeb431bd5c31e72990fdf704cbcb
QAlexBall/Python_Module
/Concurrency/yield_from_example.py
881
3.5625
4
def gen_func(): a = yield 1 print("a: ", a) b = yield 2 print("b: ", b) c = yield 3 print("c: ", c) return "finish" def gen_func2(): for i in range(4, 10): d = yield i print("d: ", d) return "finish2" def middle(): gen = gen_func() gen2 = gen_func2() ret...
f2660501d0fb88abea98b5558ab17d94c49a7ff2
LifelikeDev/python-notes
/user_input.py
439
4.125
4
# print("Hello there") # # # use the input method (Scanner class in Java) for user input # username = input("What is your name? ") # ####### OR # # username = input("""What is your name? # # """) # print("Welcome", username + "!") print("Hello there...") name = input("""What is your name? """) favourite_colour = input...