blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
405b3a996998adc8c7cd1f6eeb6cd3d1c60ea4fb | green-fox-academy/judashgriff | /Week 3/Day 4/bunnies.py | 368 | 4.1875 | 4 | # We have a number of bunnies and each bunny has two big floppy ears.
# We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication).
def get_bunny_ears(bunnies):
if bunnies == 1:
return 2
else:
return 2 + get_bunny_ears(bunnies-1)
bunnies =... |
69a13a5414faea8ddb924b4acecc22af914fc1da | ElliottBarbeau/Leetcode | /Problems/2Sum.py | 1,743 | 3.5 | 4 | #Brute force
#Time complexity: O(N^2)
#Space complexity: O(1) -> this is outweighed by awful time complexity
class Solution1:
def twoSum(self, nums, target):
for i, num in enumerate(nums):
for j, num2 in enumerate(nums):
if num + num2 == target and i != j:
ret... |
cc52f9c1da3ee39127b1014dabed5ac7c7e64e36 | aiko91/taskpart2 | /Part2task17.py | 901 | 3.609375 | 4 | def receive_complain (x):
with open(f'google_{x}.txt', 'a') as file:
file.write(input('Give your complain here: '))
print('Thank you!')
greetings = input('Say "Hello" ').lower().strip()
if greetings == 'hello':
print("""Hello! Pls, choice your office:
Kazakstan
Paris
UAR
Kyrgyzstan
San-Francis... |
fdb51cee9c0171864734fcc0657b7691f585fb58 | Shubhampy-code/Data_Structure_Codes | /LinkedList_Codes/circular_linkedlist.py | 1,269 | 3.984375 | 4 | class node:
def __init__(self,data):
self.data = data
self.next = None
class circular_linkedlist:
def __init__(self):
self.head = None
def printlist(self):
temp = self.head
if self.head != None:
while(temp):
print(temp.dat... |
836f160e3f5872c0da48dae2d5fa76f89dde582f | ofgulban/minimalist_psychopy_examples | /future/csv_related/03_csv_read_organize_data_save_pickle.py | 933 | 3.765625 | 4 | """Basic text read, organize by column, create pickle."""
import csv
import pickle
csv_name = 'Test_01.csv'
pickle_name = 'Test_01.pickle'
# create empty arrays to append elements later
state_ide = []
state_dur = []
# read & display csv
file = open(csv_name)
data = csv.DictReader(file)
# instead of... |
38f453d960544b9f7031a86def569b541fa92deb | ezebunandu/Shopify-ds-internship-challenge | /etl.py | 825 | 3.578125 | 4 | import os
import sqlite3
import pandas as pd
from sqlalchemy import create_engine
DATA_PATH = "data/"
def copy_csv_to_table(conn, file, table):
"""Copies data from the file into the table using the insert_query"""
df = pd.read_csv(file, encoding='utf-8', quotechar='|')
engine = create_engine('sqlite:///... |
f74fc49767a9a5ca171f5a5fc14a27a651243632 | nikita1610/DSA_in_Python | /Sorting Techniques/Selection_Sort.py | 272 | 3.625 | 4 | def selection_sort(a):
n=len(a)
for i in range(n):
min=i
for j in range(i+1,n):
if a[min]>a[j]:
min=j
a[min],a[i]=a[i],a[min]
return a
l=[5,1,2,7,8,4,9,3,6]
ans=selection_sort(l)
print(*ans)
|
d5d7a7c7d77269533e93b21127ad1087d9265493 | Aasthaengg/IBMdataset | /Python_codes/p03496/s189029857.py | 1,737 | 3.625 | 4 | #!/usr/bin/env python3
import sys
INF = float("inf")
def argmax(a):
index, value = -1, -float("inf")
for i, v in enumerate(a):
if value < v:
index, value = i, v
return index, value
def argmin(a):
index, value = -1, float("inf")
for i, v in enumerate(a):
if value > v:
... |
5d93760a59301b1dcf67a694f833a2ac71aa6100 | ThiruMuth/DataScience-Python-Class-Exercises | /answeek2_exercise.py | 1,033 | 4 | 4 | def human2dog(dogageinhumanyr):
"""This function returns dog's age in human years"""
dogageindogyr=0.0
if(dogageinhumanyr)<=2:
dogageindogyr = dogageinhumanyr*10.5
else:
dogageindogyr = 2*10.5 + (dogageinhumanyr-2)*4
return dogageindogyr
def maxof3num(input_number_array):
""" Th... |
0f934d221c233e5ebb4c030766600f8263640618 | A-xiaocai/store | /三角形.py | 468 | 3.96875 | 4 | a = int(input("a边为:"))
b = int(input("b边为:"))
c = int(input("c边为:"))
# 不能构成三角形的形成条件
if a+b<=c or a-b>=c :
print("不能构成三角形")
# 等边三角形形成条件
elif a==b==c:
print("等边三角形")
# 等腰三角形形成条件
elif a==b!=c or a==c!=b or b==c!=a:
print("等腰三角形")
elif a^2+b^2==c^2 :
print("直角三角形")
# 普通三角形形成条件
else :
print("普通三角形")
|
28c04385cd908f3562402e821d8f179c1631a102 | PressSergo/AlgoritmsPython | /nonukaz.py | 794 | 3.796875 | 4 | class list:
def __init__(self,i):
self.array = []
for k in range(3):
self.array.append([None for s in range(i)])
self.free = []
self.initFree()
self.current = None
def initFree(self):
for i in range(len(self.array[0])):
if self.array[0][i]... |
cbe2bd8c4b1cf7a9fac23ca150c4505d6cb38c51 | yacih/education | /pon/instance.py | 997 | 4.15625 | 4 | # class IO類別名稱(首字英文大寫):
# supportedSrcs=["console","file"]定義封裝的變數
# def read(src):定義封裝的函數
# print("Read from",src)
#Point 實體物件的設計:平面座標上的點
class Point:
def ___init__(self,x,y):
self.x=x
self.y=y
p1=Point(7,8)
print(p1.x,p1.y)
p2=Point(5,6)
print(p2.x,p2.y)
# 實體物件的設計
class FullName:
... |
3936229d6b6410c7115904ee6d273115d974f667 | jameygronewald/python_challenges | /guessing_game.py | 1,041 | 4.21875 | 4 | import random
random_num = random.randint(1, 9)
attempts = 1
guess_is_correct = False
while guess_is_correct == False:
try:
user_guess_string = input(f"Try to guess the random number from 1-9. Type your response and hit enter or respond with 'exit' to quit the game. ")
if user_guess_string == "ex... |
5ee901aada1284d912c5cd4e03024d2d8d98e847 | abhishekbunnan/test | /problem1.py | 252 | 3.859375 | 4 | a=int(input("enter the 1st no:"))
b=int(input("enter the 2nd no:"))
c=str(input("enter the type of operation:"))
if(c=="add"):
sum=a+b;
elif(c=="sub"):
sum=a-b;
elif(c=="mul"):
sum=a*b;
elif(c=="div"):
sum=a/b;
print(sum);
|
e1defa04c2165c19ded5ad8b174722cd1123d30a | sixthcodebrewer/PythonForKids | /Class 1/Hangman/Solution.py | 2,683 | 3.96875 | 4 | from turtle import *
import getpass
def turtle(x, y, color):
turtle = Turtle()
turtle.shape("turtle")
turtle.color(color)
turtle.speed(10)
turtle .pu()
turtle.goto(x, y)
turtle.pd()
return turtle
def init(hangman):
screen = Screen()
screen.setup(804, 608)
hangman.fd(50)
hangman.bk(25)
hangma... |
fed816d30aaf6a0a193a4761864fddd5488f1d8a | eddyxq/Intro-to-Computer-Science | /Full A5/manager.py | 3,448 | 3.890625 | 4 | # Author: Eddy Qiang
# Student ID: 30058191
# CPSC 231-T01
"""
Patch History:
Date Version Notes
June 16, 2017 Ver. 1.0.0 created the Target and Pursuer class
June 18, 2017 Ver. 1.0.1 defined methods that allows interaction
"""
"""
This program is a datin... |
a15134895ba32fd09f79b3bdb09aa979699216a6 | vahidsediqi/Python-basic-codes | /Data-Structures/lists/list-unpacking.py | 299 | 3.9375 | 4 | number1 = list(range(3))
# it unpack out list in save them in sprat variable
first, second, third = number1
print(second)
# if we have so money items we can do like this
number2 = [1,2,5,2,3,5,8,6,5,9,5,7,5,6,5,8,5,6]
# can only stor some of them
a, b, c, *others = number2
print(others)
print(a) |
493d67ed0078e1e4604892ae359dd536882d7162 | JoRoPi/Udacity | /CS253/Pruebas/src/Classes.py | 1,001 | 4.21875 | 4 | # This Python file uses the following encoding: utf-8
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
"""An other comment"""
return 'hello world'
def __init__(self):
"""This is the class init method, similar to a constructor"""
self.data = []
... |
a1a894a8e5510990006aa78c32cbd591f90b06fc | tangkaiq/uclass | /w3/lc.py | 537 | 4.03125 | 4 | '''
#ex1
lst = [1,2,3,4,5]
[element+5 for element in lst]
'''
'''
#ex2
for pair in (zip([1],[3,4])):
print(pair)
'''
'''
#ex3
x=[1,2]
y=[3,8]
print([a*b for a,b in zip(x,y)])
'''
'''
#ex4
print([(x,y) for x in range(2) for y in range(3)])
'''
'''
#ex5
lst = [1,2,3,4]
less2 = [num for num in lst if (num<2)]
pr... |
16618b6cbb02a802756c51c18fdd4b437275e7f9 | qiqimaochiyu/tutorial-python | /leetcode/subsets(回溯).py | 301 | 3.609375 | 4 | class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
res = [[]]
nums.sort()
while nums:
a = nums.pop(0)
res += [p+[a] for p in res]
return res
|
19c164445d338f87cebd1577d89d087b4e6f61ce | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day06/demo02.py | 814 | 4.53125 | 5 | """
元组
基础操作
"""
# 1.创建元组
# 空
tuple01 = ()
# 具有默认值
tuple01 = (1, 2, 3)
print(tuple01)
# 列表 --> 元组
tuple01 = tuple(["a", "b"])
print(tuple01)
# 元组 --> 列表
list01 = list(tuple01)
print(list01)
# 如果元组只有一个元素
# tuple02 = 100
# print(type(tuple02)) # int
tuple02 = (100,)
print(type(tuple02)) # tuple
# 不能变... |
d1a286d32b6fc1782fa9517859585b02f1dd302a | abc123me/nasa_dsn | /cli/ui.py | 3,720 | 3.9375 | 4 | def clearTerm():
print(chr(27) + "[2J" + chr(27) + "[0;0H", end = "")
def doNothing(selection):
pass
'''
Are you sure you would like to continue? [y/N]
The message parameter determines the message
Returns True if yes, False if no
'''
def areYouSure(message = "Are you sure you would like to continue [y/N]? "):
res... |
1091343454119c08848b559682f0147aae30bfc0 | arthuregood/Ports-Scanner | /scanner.py | 1,085 | 3.59375 | 4 | #! /bin/python3
import sys
import socket
from datetime import datetime
#define target
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1])
else:
print("Invalid number of elements.")
print("Syntax: python3 scanner.py <ip>")
sys.exit()
#just pretty ok
print("-" * 30)
print(f"scanning {target}")
print(... |
3f01a366f95bcf5ce65999da87c719a0eefd7a75 | syedmujahedalih/LeetCode-Submissions | /sortedSquaresarray.py | 272 | 3.859375 | 4 | '''
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
'''
class Solution:
def sortedSquares(self, A):
res = [i**2 for i in A]
return sorted(res) |
ee8031fddd50cce13e9ba7fdef74f96457bf4ef5 | PrakharimaSingh/prakharimasingh | /program1.py | 253 | 3.625 | 4 | name=inpu("enter name:")
gender=("enter gender:")
branch=input("enter branch:")
college=("enter college:")
age=int(input("enter age:")
print("name: ", name)
print("gender: ",gender)
print("branch: ",branch)
print("college: ",college)
print("age: ",age)
|
268302f0d9446252fc016b5461ab45cd35843247 | aats0123/su_python_fundamentals | /E02_lists/p07_remoce_negative_and_reverse.py | 366 | 3.65625 | 4 | if __name__ == '__main__':
nums = [int(value) for value in input().split()]
positive_nums = []
for num in nums:
if num >= 0:
positive_nums.append(num)
if len(positive_nums) > 0:
positive_nums.reverse()
message = ' '.join([str(item) for item in positive_nums])
else... |
c6c44313c22db6d937d4e5d4fe2aecc34f2eb18b | a865143034/mini-dfs | /ceshi.py | 197 | 3.546875 | 4 | #coding:utf-8
siz=1024*1024*2
def read_bigFile():
f = open("text1",'r')
cont = f.read(1)
while len(cont) >0 :
print(cont)
cont = f.read(1)
f.close()
#read_bigFile() |
4b4e7b3ed7912caea40d038731e23c2068f89551 | MrinmoySonowal/Small-Projects | /Leetcode/OneEditAway.py | 1,215 | 3.59375 | 4 | def oneEditReplace(s1: str, s2: str) -> bool:
found_diff_char = False
for i in range(len(s1)):
if s1[i] != s2[i]:
if found_diff_char:
return False
else:
found_diff_char = True
return True
def oneEditInsert(larger_text: str, smaller_text: str)... |
56d333b9af01f0e1eeedac863a93e0dc67c14ea2 | TUTElectromechanics/mm-codegen | /modelbase.py | 6,049 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Interface for models.
See splinemodel.py for a real-world usage example.
Created on Thu Nov 9 10:39:51 2017
@author: Juha Jeronen <juha.jeronen@tut.fi>
"""
from abc import ABCMeta, abstractmethod
import sympy as sy
from sympy.core.function import UndefinedFunction... |
0c67b1c9f07a7779dd4ec1af65050cffd0286a0d | samhita101/Python-Practice | /User_Age_DOB.py | 305 | 4.03125 | 4 | import datetime
print("Please enter your name after the colon:")
users_name = str(input())
print("Enter the year you were born:")
users_DOB = int(input())
print("Here is the year you will turn 100 in.")
print(users_DOB + 100)
print("You will turn 100 in this many years:")
print(users_DOB + 100 - 2020)
|
ca9b25d13200ee0c4c6dfd8d221dd7b1c16f4b4b | kolavcic/Basic-Python_Code | /Code Academy/4. cas/zadatak10.py | 448 | 3.96875 | 4 | # Napisati program koji za uneti pozitivan ceo broj n, ispisuje zvezdice i tako iscrtava odgovarajuću sliku.
# Slika predstavlja pravougli trougao sastavljen od zvezdica.
# Kateta trougla je dužine n, a prav ugao nalazi se u gornjem desnom uglu slike.
n = int(input("Unesite broj: "))
for red in range(0, n+1):
f... |
02401ed3d204d84e9544907b1aac7e1c7efc51e9 | KamalAres/HackerRank | /ProblemSolving/Python/2DArrayDS.py | 827 | 3.75 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'hourglassSum' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def hourglassSum(arr):
# Write your code here
sum = -63
for i in range(4):... |
8f75f61e237432e049a9e925b061ab1e07e656dc | Vincent105/python | /01_Python_Crash_Course/0901_class/favorite_languages.py | 414 | 3.984375 | 4 | from collections import OrderedDict
favorite_languages = OrderedDict() #此Method將創建一個有序字典
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['vincnet'] = 'python'
print(favorite_languages)
for name, language in favorite_languages.items... |
45df217510730605b7d6366944e49a543d506e91 | M4ttoF/Misc. | /HackerRank/Cracking The Coding Interview/Stacks Balanced Brackets.py | 513 | 3.953125 | 4 | def is_matched(expression):
pass
dic1={'}':'{',')':'(',']':'['}
arr=[]
for c in expression:
if c in dic1:
if arr==None or len(arr)==0:
return False
c2=arr.pop(0)
if not c2==dic1[c]:
return False
else:
arr.ins... |
76b5bc08efb5632fa13329ad59b4582365f22031 | ManzanasMx/git-prueba | /prueba.py | 279 | 4 | 4 | #Lectura de Datos Flotantes
a=float(input("ingresa valor de A:"))
b=float(input("ingresa valor de B:"))
#Operaciones
c=a+b
c1=a-b
c2=a*b
c3=a/b
#Impresion de resultado5
print("RESULTADO")
print"suma:",c
print"resta:",c1
print"multiplicacion:",c2
print"division:",c3
print"\n"
|
c7355ed714d4c7f28949f2ad15a763a9c3b5b043 | sandyrepswal/MyProject | /Main/Utility/SortingAlgos.py | 2,511 | 3.859375 | 4 | class SortingAlgos:
def bubbleSort(self,inpArr):
for i in range(0,len(inpArr)):
for j in range(0,len(inpArr)-1-i):
if inpArr[j]>inpArr[j+1]:
temp=inpArr[j]
inpArr[j]= inpArr[j+1]
inpArr[j+1]=temp
def printSortArr(s... |
ed6fd54b796032dc241b1abaf0e00c5dceb30b33 | mingyue33/python_base | /09-类和对象2/i上课代码/07-类属性.py | 590 | 3.8125 | 4 | class Cat(object):
#设计一个类
#1. 类名
#2. 属性
#3. 方法
#类属性
num = 0
def __init__(self):
#实例属性
self.age = 1
#如果类属性的名字和实例属性的名字相同,那么
#通过对象去获取num的时候,那么会获取实例属性的值
self.num = 100
#方法
def run(self):
print("-----猫 在跑----")
mao = Cat()
#用对象去访问类属性是可以的... |
09c0d3a4db54bd9a0a606087a9315e82bc45ed69 | rodrigobmedeiros/Coursera-Introdution-To-Scientific-Computing-With-Python | /Exercises/ImparPar.py | 146 | 3.890625 | 4 | numero = int(input('Entre com um numero inteiro: '))
RestoDivisao = numero%2
if RestoDivisao ==0:
print('par')
else:
print('impar')
|
a533542a9d211d911386f50e2dbba6e0b87b8731 | gasgit/OOPYTHON | /UniT/my_unit_test.py | 839 | 3.671875 | 4 | #!/usr/bin/python
import unittest
''' funcs to test'''
def square(val):
return val * val
def whatAmI(val):
return val
class MyFirstTest(unittest.TestCase):
''' test func sq pass'''
def test_pass(self):
self.assertEqual(square(2),4)
''' test func sq fail'''
def test_fail(self):
... |
203a782a278e5966618243ea55f20022b5462133 | a-poorva/testingdemo | /minus.py | 71 | 3.65625 | 4 | def subtract(a, b):
return a - b
a = 4
b = 5
print(subtract(a,b))
|
ed90f21f54e50f01334f2349db540b4f9767f553 | heloisaldanha/PythonExercises | /CursoEmVideo/Mundo_2/Aula #13 - Repetições/aula013_exe#53.py | 170 | 4 | 4 | # saber se o que foi digitado, ao contrário, é a mesma coisa.
phrase = input('Type a phrase: ').strip().upper()
for c in range(len(phrase) - 1, - 1, - 1):
print(c) |
4389ce35b9e5557537a592ed01d6659bdf937be3 | lucthomas/myRepository | /Python/Trading Machine Learning/trade_code5.py | 1,708 | 3.734375 | 4 | '''Build a dataframe in pandas'''
import pandas as pd
def test_run():
#Create dates
start_date = '2010-01-22'
end_date = '2010-01-26'
dates = pd.date_range(start_date,end_date)
print(dates)
print(dates[0])
#Create an empty dataframe
df1 = pd.DataFrame(index=dates)
print(df1)
#... |
a399ef5d20f8837629e27deec4a7b8d8132021d5 | yandryvilla06/python | /ejercicios_b2/eje3.py | 321 | 3.984375 | 4 | """
Ejercicio 3. Programa que compruebe si una variable esta vacia
y si esta vacia , rrellenarla con texto en minusculas y mostrarlo en mayusculas
"""
valor=""
if not valor:
print("Esta vacia")
rrelleno=input(" Dime algo para rrellenarla ").lower()
print(rrelleno.upper())
else:
print("variable llena"... |
77ae35a8cc1edd652192e984161e29692b40a040 | chekhov4/Python-lessons | /ksr-8.py | 574 | 3.984375 | 4 | def find_biggest_in_array(source_array):
all_values = []
def expand(source_array):
for i in range(len(source_array)):
if type(source_array[i]) == list:
expand(source_array[i])
else:
all_values.append(source_array[i])
expand(source_a... |
26311bcbdc664f353a75f755b496e94a7e916fe4 | pzp1997/Heschel-CS | /Math/Fibonacci Generator.py | 104 | 3.8125 | 4 | x = 1
y = 1
z = 1
print ("0")
print (x)
print (y)
while True:
print (x+y)
z=x
x=y
y=z+x
|
877168a842feb58575a09c9d1a4aeb3cea0b21be | dukeofdisaster/HackerRank | /Staircase.py | 379 | 4.28125 | 4 | # STAIRCASE---
# Given an integer N, print a staircse of N steps high and N steps wide.
# Ex: Given N = 3
# output: #
# ##
# ###
import sys
n = int(input())
def staircase():
space = " "
tempVal = n
stairSize=1
for i in range(n):
print(space * ((tempVal)-1) + '#'*stairSize... |
b1efabac78b858c36868ea2c0f8e292264748a8f | Xvpher/PracticeCodes | /C++/udaan.py | 2,462 | 3.9375 | 4 | '''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['... |
5df383dd0a3677e70c7dbea5c8790e94d50aad90 | MrMyerscough/Coding-Course-Stuff | /python/unit 5/test.py | 2,032 | 4.21875 | 4 | class Dog:
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
self.tricks = []
def introduce(self):
print(f'Hello! My name is {self.name}. I am {self.age} years old. My fur is {self.color}.')
print(f'I know {len(self.tricks... |
e9d6cd060c56f91c5063185d12df06461a1eebb0 | lmc-eu/demo-recommender | /recommender/baseline_recommender.py | 3,091 | 3.796875 | 4 | """A baseline recommender implementation."""
from collections import defaultdict
class User(object):
""" Data class that represents one user in the recommender network.
"""
def __init__(self, user_id):
self.user_id = user_id # String identifier of the user.
self.user_profile = defaultdic... |
f0bb31ae46407bb4298851f6792b7193a4adb521 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/3094/codes/1747_1532.py | 202 | 3.75 | 4 | from math import *
x = 0
z = 0
y = 0
k = 0
senh = (x / factorial(1)) * k
x = float
while(senh != k):
x=float(input("x: "))
k = int(input("k: "))
senhx = senh * (x**2 / 1 + 2)
print(round(senh, 9)) |
c459a5bfb6427bb215a67ce6c74b2e6f2cab813f | ljia2/leetcode.py | /solutions/hashtable/244.Shortest.Word.Distance.II.py | 1,603 | 4.09375 | 4 | import collections
class WordDistance:
def __init__(self, words):
"""
Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repe... |
6c0642b807005ea45b8fffc55f7161fc3f3fd0a5 | jonsongoffwhite/AlgorithmsCoursework | /Coursework_1/CW1-2 Levenshtein Distance.py | 5,944 | 4.03125 | 4 |
# coding: utf-8
# # Algorithms 202: Coursework 1 Task 2: Levenshtein Distance
# Group-ID: 32
# Group members: Jonathan Muller, Louis de Beaumont, Jonny Goff-White
# # Objectives
# The aim of this coursework is to enhance your algorithmic skills by mastering the divide and conquer and dynamic programming strategie... |
a82ae2c1d002410f8f1a22e3ead617223e935259 | GuilhermeLaraRusso/python_work | /ch_8_functions/8_2_passing_information_to_a_function.py | 644 | 4.1875 | 4 | # Modified slightly, the function greet_user() can not only tell the user Hello!
# but also greet them by name. For the function to do this, you enter username
# in the parentheses of the function’s definition at def greet_user(). By adding
# username here you allow the function to accept any value of username you
# sp... |
3f37cef135b11204eec5ee9aab0c17bbdb54f97b | ceparadise/Leecode | /reverseinter.py | 396 | 3.546875 | 4 | class Solution:
#yalin@return an integer
def reverse(self,x):
if x < 0:
sign = -1
elif x >= 0 :
sign = 1
result = sign * int(str(abs(x))[::-1])
if result > 2147483648 or result < -2147483648:
return 0
else:
return result
if... |
e76c609d6b4328adb7223505995041d2534f5dba | Digital-Lc/GUI_learning | /change_labels.py | 836 | 3.796875 | 4 | from tkinter import *
root = Tk()
def set_label1(text):
labeltext.set(text)
labeltext = StringVar()
labeltext.set("")
button1 = Button(root)
button1.config(text="Say hello!", command=lambda: set_label1("hello"), bg="Blue", fg="White", font=("Skia", 50))
button1.grid()
button2 = Button(root)
button2.config(te... |
f7189974f9b26f120e43f38cf4d78b37d1ff0fad | dpk3d/HackerRank | /NegativeElement.py | 1,240 | 4.03125 | 4 | """
Move all negative numbers to beginning and positive to end with constant extra space.
An array contains both positive and negative numbers in random order.
Rearrange the array elements so that all negative numbers appear before all positive numbers.
"""
# Complexity O( n * log(n))
def easyWay(arr):
arr.sort(... |
7d4a4da31a4949e39c14dde8d5c86e8211075de9 | c4rlos-vieira/exercicios-python | /Exercicio009.py | 187 | 3.921875 | 4 | carteira = float(input('Quanto de dinheir você tem na carteira? '))
dolar = float(3.27)
print('Você tem US$ {:.2f} equivalente aos seus R$ {:.2f}'. format(carteira/dolar, carteira))
|
f9912e387af182f1624ece94da06007a4cc5424c | akhileshgadde/Python-practice | /censor.py | 428 | 4.28125 | 4 | # simple censorship program that replaces the censored 'word' in the string with "****"
def censor(text, word):
words_list = text.split()
result = []
for each in words_list:
if each == word:
result.append('*' * len(word))
print result
else:
result.append(... |
08e72c506ad7c81b8295b6e3a2d16ff46cb3236d | sayanm-10/py-modules | /main.py | 3,660 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
__author__ = "Sayan Mukherjee"
__version__ = "0.1.0"
__license__ = "MIT"
import unittest
import os
from datetime import datetime, timedelta
from directory_analyzer import print_dir_summary, analyze_file
def datetime_calculator():
''' A helper to demonstrate the datetim... |
e126336c16326552771e8544fbfd6205731712c6 | youhusky/Facebook_Prepare | /377. Combination Sum IV.py | 1,073 | 3.90625 | 4 | # Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
# Example:
# nums = [1, 2, 3]
# target = 4
# The possible combination ways are:
# (1, 1, 1, 1)
# (1, 1, 2)
# (1, 2, 1)
# (1, 3)
# (2, 1, 1)
# (2, 2)
# (3, 1)
# Not... |
7201b79d716549a8afe1f06b2d63b10a3f5fa8aa | chrish42/python-profiling | /slow_program.py | 1,169 | 3.890625 | 4 | #!/usr/bin/env python3
"""A slow program... or really, any program that hasn't been profiled yet."""
import time
def fib(n: int) -> int:
"""A recursive implementation of computation of Fibonacci numbers in Python. Will be slow in pretty much all languages, actually."""
# These will be needlessly evaluated o... |
8e683cea341d0a3fb2633c00817b541aad4e048c | jasonmh999/LeetCode | /add-two-numbers/add-two-numbers.py | 1,252 | 3.640625 | 4 | """
Time: O(max(N,M))
Space: O(max(N,M))
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry=False
returnlis... |
3957038560de40849926f31dc45c05eab37ba204 | cosiq/codingChallenges | /Codility/MissingInteger.py | 644 | 3.828125 | 4 | # Write a function that, given an array A of N integers,
# returns the smallest positive integer (greater than 0) that does not occur in A.
# For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
# Given A = [1, 2, 3], the function should return 4.
# Given A = [−1, −3], the function should return 1.... |
86235f3224799eb00ea074017b73aa199c9f3ccc | Kimbsy/project-euler | /python/problem_010.py | 379 | 3.859375 | 4 | import math
"""The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
def is_prime(num):
for i in range(2, int(math.sqrt(num)) + 1):
if num % i is 0:
return False
return True
target = 2000000
total = 2
for i in range(3, target, 2):
... |
2ab339c4a92b1c41bbcb2375e04626ef303f4ad3 | sjsawyer/aoc-2020 | /q1/q1.py | 1,455 | 3.828125 | 4 | def part1(data, target_sum):
'''
Assumes data is sorted.
Runtime (with sorting): n + n*log(n) = n*log(n)
'''
i, j = 0, len(data) - 1
while i < j:
if data[i] + data[j] == target_sum:
return data[i], data[j]
if data[i] + data[j] > target_sum:
j -= 1
... |
5ca3c45235cff034329daa64810420b6b39aac49 | daniel-reich/ubiquitous-fiesta | /PCtTk9RRPPKXCxnAx_8.py | 206 | 3.828125 | 4 |
def modulo(x, y):
# Your recursive solution here.
if (y == 0):
return None
if (y < 0):
y = -y
if (x < 0):
return -modulo(-x, y)
if (x < y):
return x
return modulo(x - y, y)
|
4a11d5a75a446f2407383d9b29a9383251269abe | watachan7/ToyBox | /Python_works/normal_code/ifcode.py | 163 | 3.546875 | 4 | def if_test(num):
if num > 100:
print('over 100')
elif num > 50:
print('over 50')
else:
print('elses')
if_test(50)
if_test(101)
if_test(70)
|
182e51cf2f30cdaf4747b531d0b8013660d10563 | ikatar/practice | /Censor_dispenser/censor_dispenser.py | 2,037 | 3.546875 | 4 | import re
def censor(text,words_to_censor,double_occurrences):
#removes words and negative words after 2 occurrences
original_text = text
text = text.lower()
to_remove=[]
for word in words_to_censor:
word = re.compile(rf"\b{word}\b")
for m in word.finditer(text):
to_remove.append([[m.group()],[m.start(),m... |
196af9daf348dae788eb5f976dd36c3e6bd177a5 | dilekkaplan/Alistirmalar_2 | /soru_4.py | 364 | 3.78125 | 4 | #ilk 30 Fibbonaci sayısını rekülsif olarak yazdıran program
def fibo(x):
if x==1:
return 1
elif x==2:
return 1
else:
return fibo(x-2)+ fibo(x-1)
for i in range(1,31):
print(fibo(i), end=" ")
... |
a0d7695cb6be224fea862daf962a2e01823fc1d5 | Jasenpan1987/Python-Rest-Api | /1.python-refresh/list-comparhenson.py | 333 | 3.84375 | 4 | # list comparehenson is a way to build list
list1 = [x for x in range(5)]
print(list1)
list2 = [x**2 for x in range(5)]
print(list2)
list3 = [x for x in range(1, 10) if x % 2 == 0]
print(list3)
name_input = ["Anna ", "Bill", " Josh", "steve"]
normalized_people = [p.lower().strip() for p in name_input]
print(normal... |
9f6f2a457ec34e70a00ad23011bc8f195380035f | cashmane/Homework12 | /dice.py | 1,303 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
n = 100000 #number of rolls of d dice
d = 3 #number of dice in each roll
rolls = []
for i in range(n):
indivRoll = []
for j in range(d):
roll = np.random.randint(6) + 1
indiv... |
0517046c279c4bfec89274c8e1538b11568dea09 | cirino/python | /CursoGuanabara/ex28_aula10_guanabara.py | 428 | 3.875 | 4 | print("""
Exercício 28 da aula 10 de Python
Curso do Guanabara
Day 7 Code Python - 06/05/2018
""")
from random import randint
from time import sleep
numero = int(input('Adivinhe o número: '))
computador = randint(0, 5)
print('-=-'*30)
sleep(2)
if numero == computador:
print('Acertou, Uhuuu: {}'.form... |
caec78489981d610fc19e2f550554390786d6608 | Annika0401/PDF | /for-schleife.py | 141 | 3.5625 | 4 | colors = ["green", "red","blue", "yellow", "black"]
'''for x in colors:
print(x)'''
for x in range(len(colors)):
print(colors[x])
|
8c0e69311f0d25c61f92b95049ae753ab243f87a | CNZedChou/python-web-crawl-learning | /spider/codes/35_thread_count.py | 1,267 | 3.59375 | 4 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Zed
@Version : V1.0.0
------------------------------------
@File : 35_thread_count.py
@Description :
@CreateTime : 2020-5-8 13:10
------------------------------------
@ModifyTime :
"""
import threading
import time
impo... |
7f915f77d29b95d15dba3e56ef542deed43325ea | nisepulvedaa/curso-python | /11-ejercicios/ejercicio2.py | 544 | 3.984375 | 4 | """
Ejercicio 2
Escribir un programa que añada valores a una lista
mientras que su longitud sea menor a 120 y luego mostrar la lista
pluss usar while y for
"""
coleccion = []
for contador in range(0,120):
coleccion.append(("elemento-{}".format(contador)))
print("Mostrando el elemento : {} ".format(contador... |
e5994139b27f8a6865998a6530914c4a037f969d | CrazyAlan/codingInterview | /cc150/chapter4/4.py | 935 | 3.90625 | 4 | '''
1. For each layer, have a result variable to store all data, then have a list for
each layer, then loop through that list and new a list to store all it's left and right
child, finally check if the list is empty, if it is, then jump out, otherwise loop again
2. Append is wrong, need to append the left or right nod... |
eacd9fbe4f1b5151315dc964ef1218ccca517556 | samirsaravia/Python_101 | /Python_for_beginners_Mdev/error_handling.py | 893 | 4.21875 | 4 | x = 42
y = 0
print()
try:
print(x / y)
except ZeroDivisionError as identifier:
print('Not allowed to divide by zero')
else:
print('Something else went wrong!')
finally:
print('This is our cleanup!')
print()
'''
when an exception occurs in the 'try' suite, a search for an exception handler is started.
T... |
c0583550e7db4069442ad77f5561609c6d880e49 | thisguycodez/python-madlibs | /test1.py | 1,353 | 4.4375 | 4 | ''' 1. comments - For python, use with a '#' symbol
or 3 quotes nesting your comment:
-helps explain what the code is doing
-great for jogging your memory if you are editing old code
-helps keep code organized
'''
# this is a comment
''' 2. prints - A function Used to send data to the console/terminal/screen
... |
a5d9e1e0cff85be7691b2e4967cf99d10801e4ec | warsang/CCTCI | /chapter5/5.4/nextNumber.py | 1,098 | 3.59375 | 4 |
def getBit(number,index):
return (number & (1<< index) !=0 )
def flipBit(number,index):
return( number | (1 <<index))
def nextNumber(anumber):
#Flip last bit that is 1
ones_counter = []
for i in range(0,8):
res = getBit(anumber,i)
if res:
ones_counter.append(i)
#G... |
6d099cedb1760c81594199936a50219dcfbf285d | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/mdlcar002/question2.py | 551 | 3.921875 | 4 | # test program for Ndom calculations
import ndom
option = input ("Choose test:\n")
choice = choice[:1]
print ("calling function")
if choice == 'n' or choice == 'd':
num = int(option[2:])
if choice == 'n':
answer = ndom.ndom_to_decimal (num)
else:
answer = ndom.decimal_to_ndom(num)
elif action == ... |
8dd5d207c5b08d9a0ec9124b17b08a26d98aacc2 | statham/portfolio | /number_theory.py | 894 | 3.65625 | 4 | #This function should compute a^(b^c) % p where p is a prime.
#runs in polynomial time in log(a), log(b), log(c), and log(p)
#helper function: computes x^n for large x and n
def exp_by_squaring(x, n):
if n == 1:
return x
#if n is even, recurse on squared x and halved n
elif (n%2) == 0:
re... |
af0587798c987ace23bf67733d111526429a331b | kbrain41/class | /psevdocod/psevdocod2.py | 114 | 3.8125 | 4 | A = 4
B = 7
if A%2==0:
print ("Число четное")
if A%2==1 and A<4:
print ("Число Простое")
|
2b728a5269149d8104ea4bb64c07249928904c38 | valerii2020/valerii2020 | /starter/lesson 3/Masha Horb/task2.py | 137 | 3.9375 | 4 | import math
p=3.14
x=input("введите число x")
x=int(x)
if -p<=x<=p:
y=math.cos(x*3)
elif x<-p or x>p:
y=x
print(y)
|
250173e6cb9f4a7fb54254b3619fe783ac2a3a6c | JaegerJochimsen/PolySolvy-Version-X-----Bivariate-Interpolation | /graph_bivariate.py | 4,371 | 3.671875 | 4 | import math
import bivariate
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
%matplotlib notebook
def Graph_Bivariate(vvector: np.array, orig_x: np.array, orig_y:np.array, orig_z: np.array):
"""
A function which plots an original set of (x,y,z... |
8c722f918afe8c417ee7d3b830734324b2fe2829 | dipalira/LeetCode | /String/125.py | 466 | 3.765625 | 4 | s= "A man, a plan, a canal: Panama"
a = "ab@a"
def isPalindrome( s):
"""
:type s: str
:rtype: bool
"""
if len(s) <0 : return True
r,l = len(s)-1,0
while l<r:
if s[r] == ' ' or s[r] in '()[].,:;+@-*/&|<>=~$':
r-=1
continue
elif s[l] == ' ' or s[l] in '()[].,:;+-*/&|<>=~$':
l+=1
continue
if s[r]... |
6a5a66972ec8a8e7fb16609bb7dc747e796d4535 | KikiPadoru/PraktikaSaltAndPepper | /1.py | 541 | 4.125 | 4 | import re
def is_palindrome(word):
if (type(word) is not str and type(word) is not int): return False
word = str(word) if type(word) is int else re.sub(r'[^\w]', '', word).lower()
for i in range(len(word) // 2 + 1):
if len(word) < 2: return True
if word[0] != word[-1]: return False
... |
d769f566d027c2f25c33b7c8d69787a5cbb86580 | arara90/Python-FastCampusWebPythonBasic | /code04_list_dict/task_삽입정렬/3_insertion.py | 1,181 | 3.671875 | 4 |
#내코드
print("================for=============")
a = [1, 5, 4, 3, 2]
print("시작 : " , a)
for i in range(1,len(a)):
print("pivot index :" , i , "value :" , a[i])
pivot=a[i] #pivot값 저장
for j in range(i,0,-1):
if( pivot < a[j]):
print(" swap[%d , %d] " % ( pivot, a[j] ) )
a[j+1... |
88d13f66fdf9c1373d79c07a27bab32dc4fc1593 | anjihye-4301/python | /ch07data/ch07_06dic.py | 1,335 | 3.6875 | 4 | # dictionary -> {key: value[, key: value....]}
# -> js : json 형식
#key 값은 중복이 안되기 때문에 같은 key의 경우 뒤의 데이터로 덮어쓰기가 된다.
dic1 = {1: 'a', 2: 'b', 3: 'c', 3: 'd'}
print(dic1, type(dic1))
# 학생 딕셔너리 생ㄷ성
student ={"학번": 1000, "이름": '홍길동', "학과": "파이썬학과"}
print(student,type(student))
#학생의 이름 데이터 가져오기
print(student["이름"])
print(... |
468da1efd2195d81641cb9c313d0330b8ed80a3a | lelencho/Homeworks | /Examples from Slides/Lesson 10 Regular Expression/23_Finditer.py | 172 | 3.671875 | 4 | import re
statement = 'Please contact us at: levon-grigoryan@gmail.com, lgrigor@submarine.com'
addresses = re.finditer(r'[\w\.-]+@[\w\.-]+', statement)
for address in addresses:
print(address)
|
815aea1680d8c32b58e5fbbf7f0a83f3671cfa80 | TPei/jawbone_visualizer | /plotting/Plot.py | 807 | 3.546875 | 4 | __author__ = 'TPei'
from abc import ABCMeta, abstractmethod
import matplotlib.pyplot as plt
class Plot(metaclass=ABCMeta):
"""
abstract plot superclass
"""
def set_ydata(self, ydata):
"""
setter of ydata
:param ydata:
:return:
"""
self.ydata = ydata
... |
7d1135c0e34b4214358cb60fcbfc354da9a2ebb2 | roldanj/python | /dictionary_homework.py | 1,258 | 4.53125 | 5 | # Create a variable called student, with a dictionary.
# The dictionary must contain three keys: 'name', 'school', and 'grades'.
# The values for each must be 'Jose', 'Computing', and a tuple with the values 66, 77, and 88.
student = {'name': 'jose', 'school': 'computing', 'grades': (66, 77, 88)}
# Assume the argument... |
d697d21b3e25225c7989919d5edc3fecdb6f0ce9 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/SortNumber.py | 1,320 | 3.875 | 4 | #Sorting of ListNumbers
n=int(input("count of ListNumbers: "))
numbers=[]
TypeSorting=input("Accending or Decending: ")
i=0
while(i<n):
numbers.insert(i,input("Enter numbers of {}:".format(i+1)))
i+=1
print(numbers)
def accending(ListNumbers):
n=len(ListNumbers)
i=0
while(i<n):
... |
87e4318addf2c28a4fd39467c2acd7ea205e4168 | Navesz/python | /Exercícios/ex011.py | 230 | 3.984375 | 4 | print("Coloque os valores em metros!")
largura = float(input("Largura: "))
altura = float(input("Autura: "))
area = largura * altura
tinta = area / 2
print(f"Aréa da parede: {area}m². \nTinta necessária: {tinta} litros.") |
8d2f39771908494dad05b6cf35e6468ba016ae13 | zmj/Euler | /025.py | 167 | 3.59375 | 4 | current = 1
prev = 1
n = 2
digits = 1000
while True:
num = current + prev
prev = current
current = num
n += 1
if len(str(current)) == digits:
break
print n
|
4720c3eb1eb2946626ef8d83030d87f241aabb0b | jbell1991/code-challenges | /challenges/codewars/counting_duplicates/counting_duplicates.py | 797 | 4.34375 | 4 | def duplicate_count(text):
'''Takes in string of text and returns the count of
duplicate characters in the string.
'''
# empty dictionary
dict = {}
# make text lowercase
text = text.lower()
# iterate over each character in the text
for char in text:
# if the character is not... |
9b588779c7e7eac9bb926a67fd9fce059b686178 | xCrypt0r/Baekjoon | /src/9/9933.py | 437 | 3.90625 | 4 | """
9933. 민균이의 비밀번호
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 25일
"""
def main():
N = int(input())
words = [input() for _ in range(N)]
for i in range(N):
for j in range(i, N):
if words[i][::-1] == words[j]:
print(len(words[i]), words[i][... |
37e3e7aa509433f1d28bd80a129251be3eda8314 | ChezzOr/codeFightsSolves | /makeArrayConsecutive2.py | 303 | 3.515625 | 4 | def makeArrayConsecutive2(statues):
'''Search for max and min, then compare size of array with difference between min and max'''
min = 11
max = -1
for x in statues:
if x > max:
max = x
if x < min:
min = x
return (max - min) - len(statues) + 1
|
fa640b593699c4fc4edb6024799adecd2c3a6c46 | CosmicQubit/type-2 | /gui_txt_text.py | 3,659 | 3.703125 | 4 | txt_help_text = """
This app will predict the probability of you developing type-2 diabetes.
In order to use it, fill in all the fields and press send. To make sure
everything runs smoothly, there are some restrictions:
1) Negative numbers cannot be given.
2) The correct type of information must be entered e.g no ... |
74494c92fb4962ee56894be13779be2fe96dd594 | rohanwarange/Python-Tutorials | /Sets/intro_set.py | 501 | 3.984375 | 4 | # Set Data type
# unorder collection of uniqe items
s={1,2,3,4,4}
print(s)
# set uses...............................
# remove duplicate
l=[1,2,3,4,4,3,2,1,1,2,3,4,4,3,2,1,345,22,678,33,5,42,8,5,2,4,5,6,4,3,5,7,4,3,4,5,6,4]
s2=set(l)
# print(s2)
# add element in set
s.add(9)
print(s)
# remove from set
s.remove(4)
pri... |
53ff3dcb7ca6d60e7ddb1dcc3136ae89024adb47 | ryhanlon/legendary-invention | /labs_Applied_Python/ari/main.py | 3,656 | 4.03125 | 4 | """
Creating an ARI (automated readability index) to evaluate the reading level of a book for age and grade.
# evaluate the text, compute the ARI score
#4.71 9(characters/words) +.(5 (words/sentences) -21.43)
# ari_scale = {...}, this is used to apply the score to the age and grade
"""
import os
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.