blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
7ca7a468dcc8aea1cc45757f9430b5fa0c0d736f | JuanHernandez2/Ormuco_Test | /Ormuco/Strings comparator/comparator.py | 1,188 | 4.25 | 4 | import os
import sys
class String_comparator:
"""
Class String comparator to compare two strings and
return which is greater, less or equal than the other one.
Attributes:
string_1: String 1
string_2: String 2
"""
def __init__(self, s1, s2):
"""
Class constr... |
c0ed1fdb6dfa3fa3c880af25c18e281354276737 | mwbelyea/Dictionary | /fun.py | 437 | 3.5625 | 4 | def mike():
for i in range(0,1):
print("Choose your own adventure")
print("Dad's trip to work")
print("-*-*-*-*-*-*-*-*-*-*-*-*")
print("Lisa gone, Mike could finally start a new adventure.")
print("Should he?")
response_1 = raw_input("Reply: (Y)es (N)o: ")
if response_1.lower == "y":... |
e5524037b810b62eca82b3b75c27260fd77e1b21 | Sharmaanuj10/Phase1-basics-code | /python book/book project 2/class & module/lottery.py | 168 | 3.78125 | 4 | from random import choice
name = ["jack","jill","qwerty","Anuj","Aditya"]
# you can also also use tuples instead of the list
winner = choice(name)
print(winner) |
1ed4ea179560b5feec261b094bdbe5b2848b4e03 | Sharmaanuj10/Phase1-basics-code | /python book/book projects 1/4-7/input while loop/flag.py | 321 | 4.1875 | 4 | active = True
print("if you want to quit type quit")
while active:
message = input("Enter your message: ")
if message == 'quit':
# break # to break the loop here
active = False
#comtinue # to execute left over code exiting the if
else:
print(message)
... |
f0b8df90473a9d20d78162dc0da0e37bad461061 | Sharmaanuj10/Phase1-basics-code | /python book/book projects 1/4-7/input while loop/whileloop.py | 363 | 3.984375 | 4 | message = ''
# you can use this for game to run as long as user want
while message != 'quit':
message = input('hi : ')
# in her i use user input and store to number and pass through the loop Again
if message != 'quit':
print(message)
elif message == 'quit':
p... |
0227e6263035a7b7e6cf67dadde3eb91576afc0b | Sharmaanuj10/Phase1-basics-code | /python book/book projects 1/4-7/input while loop/deli.py | 710 | 4.28125 | 4 | user_want = {}
# fistly define a dictonairy empty
poll_active = True
while poll_active:
name = input('Enter your name: ')
want = input('if you visit one place in the world where you visit? ')
repeat = input('waant to know others wnats (yes,no)? ')
# after input store the data at dictionar... |
8592b3147c28ef1b09589c048dfa30e0eb87aa5a | Sharmaanuj10/Phase1-basics-code | /python book/Python/password.py/password 1.5.py/password1.5.py | 1,287 | 4.28125 | 4 | name = input("Enter your username: ")
passcode = input("Enter you password: ")
# upper is used to capatilize the latter
name = name.upper()
# all the password saved
def webdata():
webdata= input("Enter the key word : ")
user_passwords = {
'youtube' : 'subscribe', # here now you can save... |
e591a0397c93d835d46d6780ad0c7d71b97975b7 | schin7/Rosalind-Problems | /Bioinformatics Stronghold/011 - FIBD - Mortal Fibonacci Rabbits/011_FIBD.py | 828 | 3.5 | 4 | with open('C:/Users/Owner/Desktop/rosalind_fibd.txt') as input_data:
n,m = map(int, input_data.read().split())
# Populate the initial rabbits.
Rabbits = [1]+[0]*(m-1)
# Calculate the new rabbits (bunnies), in a given year.
# Start at use range(1,n) since our initial population is year 0.
for year in range(1, n):
... |
a1308f390e918ed81896ed2fcdee02f9cc0dd03d | coolroboticsmaster/Class | /class7.py | 571 | 3.9375 | 4 | def canyoudriveacar():
x = input(" what is your name ")
y = int(input(" what is your age "))
if y >= 18:
return" You are eligble to drive a car"
else:
return" You can not eligble drive a car"
print(canyoudriveacar())
def leapyear():
x = int(input(" which year is going on "))
... |
404f12ef160e037fa2c28006d41bdae7f996627d | coolroboticsmaster/Class | /class6.py | 632 | 3.90625 | 4 | # import math
# y = int(input(" please enter a number as your radius "))
# peremeter = 2*math.pi*y
# print( "The permeter of ",y, " is " ,peremeter)
# a=math.ceil(peremeter)
# print(a)
# x = input(" enter your name ")
# z = input(" enter your age ")
# print (" your name is ",x,"and your age is ",z)
# print (" your na... |
6c8f4e352e21d4203902d5da9441a0162d7c0134 | alexoch/python_101_course | /py_course/1-4/test4.py | 259 | 3.53125 | 4 | """
:10
: python lab3_1.py 10
: 55
: 0
:python lab3_1.py 0
: 0
"""
import sys
X = int(sys.argv[1])
P = 0
C = 1
if X == 0:
print P
elif X == 1:
print C
else:
for count in range(int(X)-1):
R = C + P
P = C
C = R
print R
|
946af25e363f71c279bc2a06d9862461aa7d9a04 | The-Xceros/Earthsupasin-CS01 | /CS01-16.py | 114 | 3.625 | 4 | import numpy as np
arr = np.array([1,2,3,4,5,6,7,8,9,10])
newarr = arr.reshape(5,2)
print(newarr)
print(newarr+10) |
213ebf4489f815cf959de836a11e2339ca8bcfaa | rsleeper1/Week-3-Programs | /Finding Max and Min Values Recursively.py | 2,148 | 4.21875 | 4 | #Finding Max and Min Values
#Ryan Sleeper
def findMaxAndMin(sequence): #This method finds the max and min values of a sequence of numbers.
if len(sequence) < 2: #This catches a sequence that doesn't have enough numbers to compare (less than 2) and returns the invalid sequence.
print("Ple... |
e79bebbfef3ecb282ae91f22f81dbab1aed8bd2a | therealnacho19/SecondDay | /magicMaze.py | 829 | 3.734375 | 4 | moves=0
fails=0
lives=3
lock=['S', 'S', 'N', 'W', 'E', 'S']
flag=True
lockRecord=0
while flag:
play=input("You are in the magic maze. Which way (N,S,E,W) do you want to go?: ")
moves +=1
lockRecord +=1
if moves <= (len(lock)-1):
if play != lock[lockRecord - 1]:
lockRecord=0
... |
d075b9df570b98066efa80959ee3d102bca91614 | chigozieokoroafor/DSA | /one for you/code.py | 259 | 4.28125 | 4 |
while True:
name = input("Name: ")
if name == "" or name==" ":
print("one for you, one for me")
raise Exception("meaningful message required, you need to put a name")
else:
print(f"{name} : one for {name}, one for me") |
28e8f771a7968081d3ced6b85ddec657163ad7d1 | avi527/Tuple | /different_number_arrgument.py | 248 | 4.125 | 4 | #write a program that accepts different number of argument and return sum
#of only the positive values passed to it.
def sum(*arg):
tot=0
for i in arg:
if i>0:
tot +=i
return tot
print(sum(1,2,3,-4,-5,9))
|
f94cb136e8f293d2a204dc22442a04c16ddf6e9a | avi527/Tuple | /variable_length_argument_tuple.py | 556 | 4.09375 | 4 | #programm to manipulate efficiently each value that is passed to the tuple
#using variable length argument
def display(*args):
print(args)
Tup=(1,2,3,4,5,6)
Tup1=(7,8,9,10,11,12)
display(Tup,Tup1)
#agr krke aap kitna bhi variablepass kr skte hai
#NOTE :- if youhave a function that displays all the par... |
f80b9e983eaaa1f4473aa1916a38e0faef027d81 | aldayanid/python | /guess.py | 425 | 4.0625 | 4 | import random
n = int(random.random() * 10)
i = int(input("Please enter your number: "))
attempts = 1
while True:
attempts += 1
if attempts == 3:
print("max number of attempts reached.")
break
if i > n:
print("Enter lesser")
elif i < n:
print("Enter higher")
else:... |
f84fdcc10c21393862a7c726a5073b608e929b06 | aldayanid/python | /validator.py | 273 | 3.734375 | 4 | def is_compliant(psswrd:str)->bool:
return len(psswrd)>=8 and any(chr.isdigit() for chr in psswrd)
def main():
psswrd=input("Password: ")
if is_compliant(psswrd):
print("OK")
else:
print("Wrong")
if __name__ == '__main__':
main() |
2c64aa987fb60710b4c1f47d0837853f3dc232fa | khlidar/Concrete_Beam_Program | /Shapes.py | 5,457 | 3.90625 | 4 | '''
Description:
Definition of shapes class and sup classes
Information on authors:
Name: Contribution:
--------- ------------------
Jacob Original code
Kristinn Hlidar Gretarsson Original code
Version histo... |
7c371a69d4aa59583b2ab9ffb24bd4047f378a14 | Renatkg20/CodewarsofTask | /RBB.py | 461 | 3.734375 | 4 | import re
def rgb(r, g, b):
for i in [r,g,b]:
if r > 255: r = 255
elif r < 0: r = 0
elif g > 255: g = 255
elif g < 0: g = 0
elif b > 255: b = 255
elif b < 0: b = 0
t = "#{:02x}{:02x}{:02x}".format(r,g, b)
result = re.findall('[a-z0-9]', t)
result1 = ''.join(result)
return res... |
ce0ae5c217bde3ff4b5a55f3ba3de206cf724068 | angelrpb/Py-AI | /AI-Assistant.py | 6,557 | 3.5 | 4 | # Este es el asistente AIpy en proceso (iniciado pero falta el ML, AI, etc)
# Este asistente todavia no cuenta con el complemento de la IA o AI
# La mente arquitecta (yo) aun no cuenta con esos conocimientos
#engine.say("Hello world. My name is December.")
#engine.runAndWait()
#ajuste de veloc de hablado
# y camb... |
2482c28267330bb414ebc2542de92589f26a1779 | Jurph/aoc2018 | /day1/day1p1.py | 1,649 | 4.03125 | 4 | #!/usr/bin/python
# Solves (https://adventofcode.com/2018/day/1) given input.txt in the same path
def tuner(frequency, seenbefore, tuned):
with open('input.txt', "r") as inputfile:
while tuned == False:
inputline = inputfile.readline()
if inputline == "":
return fr... |
ada5b9a0682efc8b27bbd0b12d199c7d0751efcb | mikossheev/qa-tools | /lession_2/test_string.py | 981 | 4.0625 | 4 | """Here are the tests with string"""
def test_string_length_and_space(string_prepare, random_number):
"""Test checks the length of string, depending on random text length,
and that string does not start with a space"""
assert len(string_prepare) == 22 + random_number
assert not string_prepare.startswi... |
95100b93ecb1d5fc9fe936869b7fc50f56c0f859 | k-schmidt/Insight_Data_Engineering_Coding_Challenge | /src/pkg/trie.py | 3,513 | 4.09375 | 4 | """
Trie Implementation
Kyle Schmidt
Insight Data Engineering Coding Challenge
"""
from typing import Optional, Tuple
class Node(dict):
def __init__(self, label: Optional[str]=None):
"""
Node class representing a value in the Trie class.
Node inherits from dict providing dictionary funct... |
f8cb9b51b864de1687f94faaf863cc32c355dc08 | iggy18/oop_tic_tac_toe | /hang/hang.py | 1,394 | 3.828125 | 4 | import random
from words import words
class Hangman:
def __init__(self):
self.word = random.choice(words)
self.display = ['_' for letter in self.word]
self.guesses = 0
def show(self):
display = ' '.join(self.display)
print(f'the word is: {display}')
def get_wo... |
28d8091a488554191c40bb32dfd42a6d4ecaa4ee | Hana-Noorudheen/CG_LAB | /Extra_works/pattern.py | 97 | 3.578125 | 4 | for i in range(1,6):
for x in range(i):
print("*",end=" ")
print("\n")
|
2bc983fc4b50355f771b34dc909b3c7b1eb607dd | technolingo/AlgoStructuresPy | /queue/index.py | 503 | 3.96875 | 4 | '''
Create a queue data structure. The queue
should be a class with methods 'enqueue' and 'dequeue'.
--- Examples
q = Queue()
q.enqueue(1)
q.dequeue() # returns 1;
'''
class Queue:
''' A rudimentary queue '''
def __init__(self):
self.lst = []
def enqueue(self, elem):
self.ls... |
a75f041e351186c86ba29f4d12aa3ab4c3439b1a | technolingo/AlgoStructuresPy | /weave/queue.py | 369 | 3.640625 | 4 | #!/usr/bin/env python3
class Queue:
def __init__(self):
self.data = []
def enqueue(self, elem):
self.data.insert(0, elem)
def dequeue(self):
try:
return self.data.pop()
except:
return None
def peek(self):
try:
return self.... |
ceda1a0f1e1cae42099a7f86803e12bbf987c757 | arresejo/enigma | /validation.py | 2,468 | 3.703125 | 4 | import re
from abc import ABC
from abc import abstractmethod
class Validatable(ABC):
@abstractmethod
def validate(self, item):
pass
class Validator(ABC):
def __init__(self, *validators):
self.__validators = validators
def validate(self, item):
return all(map(lambda x: x.val... |
dc06fc22506a86cbb14537349fffb4fbe1769394 | jonasrauber/plotspikes.py | /example.py | 859 | 3.828125 | 4 | #!/usr/bin/env python
from plotspikes import plotspikes
from matplotlib import pyplot as plt
import numpy as np
def main():
"""Example how to use plotspikes"""
# create a figure and plot some random signal
plt.figure(0, figsize=(15,3))
np.random.seed(22)
xsignal = 20 * np.arange(100)
ysig... |
383b602071ce487d64fe5c3302c64a10a3adb8a6 | ltnguy16/Python-Practices | /Sudoku_Solver.py | 1,592 | 3.8125 | 4 |
board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
... |
7884efac3e626ba6884d5e2d55d80582796b3552 | Viswalahiri/Preprocessing-boilerplate | /feature_scaling.py | 786 | 3.921875 | 4 | ## Feature Scaling
import sklearn
# we perform feature scaling since we must ensure that none of the dependant variables overlap on each other and thus are considered more important.
# For example, when we perform euclidean distance on two columns, then we see that one is very much larger than the other, in which case... |
529681e15d29d0a98e1e4ac2c4c3309e82390219 | aleche01/Travelling-Salesman-Problem | /Project/project_code.py | 5,653 | 3.6875 | 4 | # ENGSCI233: Project
# Alex Chen
# 500193517
# ache934
from project_utils import *
import networkx as nx
from time import time
import numpy as np
# start time
t0 = time()
# initial reading of files
auckland = read_network('network.graphml')
rest_homes = get_rest_homes('rest_homes.txt')
# function... |
b3d7df6708a1c331b0632c1688a6fdddfba8fe16 | tvarol/leetcode_solutions | /medianTwoArrays/findMedianSortedArrays_numpy.py | 557 | 3.96875 | 4 | #There are two sorted arrays nums1 and nums2 of size m and n respectively.
#Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
import numpy as np
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
... |
d2a852feb91c2ca56b39ca06588281110e325624 | tvarol/leetcode_solutions | /addTwoNumbers/addTwoNumbers.py | 1,188 | 3.90625 | 4 | #You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#Input... |
b2c6835595f629bba3d6f59879d00c8948006522 | tvarol/leetcode_solutions | /sortColors/sortColors.py | 1,332 | 4.03125 | 4 | #Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
#Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
#Note: You are not suppose to use the libr... |
3b8cdcb53800ece9e490f95c50ea0bb4f3a1d8df | pratamawijaya/learnpython | /helloworld/stringFormatting.py | 412 | 3.953125 | 4 | '''
%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)
'''
name = "John Cenna"
age = 30
pr... |
4214b85a8864f4e177baab65cc99e3ef264a5f2c | KenMatsutaka/pythonSample | /sample14.py | 394 | 3.578125 | 4 | import numpy as np
#1次元配列の生成
arr = np.asarray([1,2,3])
print('①', arr)
#2次元配列の生成
arr = np.asarray([[1, 2, 3],[4, 5, 6]])
print('②', arr)
#平均の取得
print('③', np.mean(arr))
# #最大値、最小値の取得
print('④', np.max(arr))
print('⑤', np.min(arr))
#和の取得
print('⑥', np.sum(arr))
#標準偏差の取得
print('⑦', np.std(arr))
|
9e6ce9d59e9dc0cfd0830e47723f1dd638fb7f26 | KenMatsutaka/pythonSample | /sample09.py | 786 | 3.578125 | 4 | # csv : csvファイルを扱うライブラリ
import csv
import sys
try:
# CSVファイル書き込み
# ファイルを開く
with open('sample09.csv', 'w', encoding='utf8') as csvfile:
#writerオブジェクトの生成
writer = csv.writer(csvfile, lineterminator='\n')
#内容の書き込み
writer.writerow(["a","b","c"])
writer.writerow(['あ','い','... |
704e58c261aca0dedc7e1cb5a00c1f11b54d0f5f | JitendraDandekar/BasicPrograms | /Rolling Dice/RollingDice.py | 774 | 3.515625 | 4 | from tkinter import *
import random
root = Tk()
root.geometry("300x350")
root.title("Rolling Dice")
photo = PhotoImage(file = "dice5.png")
root.iconphoto(False, photo)
header = Label(root, text="Hello..!!", font="Times 25 bold")
header.pack(pady=10)
#Images
dice = ['dice1.png','dice2.png','dice3.png','dice4.png','di... |
655e38557a1241686644ce8c74b9d43e68740f87 | maelhos/InductorGen | /module/polygon.py | 809 | 3.875 | 4 | #!/usr/bin/env python3
# -.- coding: utf-8 -.-
# InductorGen.polygon
from module.utils import snaptogrid
from math import cos,sin,radians
# Defining the "poly" function wich take :
# rad : radius of the circle
# s : number of sides of the geometry
def poly(radius, sides,a,s,ggg): # this function return an array on p... |
baf7ec342ee0f56065d7e05a9cd67be4f936a367 | allonbrooks/cainiao | /No4/未使用的最小的ID.py | 1,264 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/20 11:00
# @Author : HandSome
# @File : 未使用的最小的ID.py
'''
你需要管理大量数据,使用零基础和非负ID来使每个数据项都是唯一的!
因此,需要一个方法来计算下一个新数据项返回最小的未使用ID...
注意:给定的已使用ID数组可能未排序。出于测试原因,可能存在重复的ID,但你无需查找或删除它们!
def next_id(arr):
#your code here
测试用例:
verify.assert_equals(next_id([0,... |
0c72edf860392975f00af289e83e860a16349892 | allonbrooks/cainiao | /No11/1.用函数计算.py | 2,795 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/27 9:29
# @Author : HandSome
# @File : 1.用函数计算.py
'''
这次我们想用函数编写计算并得到结果。我们来看看一些例子:
例如:
seven(times(five())); // must return 35
four(plus(nine())); // must return 13
eight(minus(three())); // must return 5
six(dividedBy(two())); // must return 3
'''
... |
d5286f33dd6d3b53406f9bc4df05f60700ba2bab | ashrafishaheen/python_mini_projects | /rename.py | 572 | 3.640625 | 4 | import os
def rename_files():
#(1) get file names from folder
file_list = os.listdir(r"C:\Users\shahid\Downloads\Compressed\prank")
#print(file_list)
save_path = os.getcwd()
print("Current Working Directory is"+save_path)
os.chdir(r"C:\Users\shahid\Downloads\Compressed\pr... |
f6970056797126b940373ecf3fd7f3092575b1e6 | Yashkhatsuriya/java | /empinsert.py | 917 | 3.78125 | 4 | import mysql.connector;
print("establish connection with mysql now");
con = mysql.connector.connect(host="localhost",
database="employee",
user="root",
password="");
print("connection mydb",con);
eno=input("enter employee... |
73261a25fbcbfac443b2f251ae11d9cc9557c541 | ppkantorski/Astro_121 | /Lab_1/Code/central_limit.py | 3,355 | 4.21875 | 4 | #!/usr/bin/env python
# ========================================================================== #
# File: central_limit.py #
# Programmer: Patrick Kantorski #
# Date: 02/09/14 ... |
5d8dcb0e6652829d9db011912689507f9c876fd6 | dpalma9/cursoITNowPython | /conceptos/11-operaciones-masivas-colecciones.py | 776 | 3.828125 | 4 | lista=[1,2,3,4,5,6,7,8,9]
pares= [item for item in lista if item % 2 == 0]
print(pares)
diccionario={"clave1":"valor1", "clave2":"valor2", "clave3":"valor3"}
lista2=[valor for clave, valor in diccionario.items() if clave == "clave1" or clave == "clave2"]
print(lista2)
otro_diccionario={clave:valor for clave, valor ... |
5a6da2154ad5803c1f50e463547ce8b76dfed593 | dpalma9/cursoITNowPython | /conceptos/10-orientacion-a-objetos-4.py | 329 | 3.609375 | 4 | class Servicio:
def __init__(self,nombre,servidor):
self.nombre=nombre
self.servidor=servidor
def __str__(self):
return "Soy el servicio: "+self.nombre +", disponible en el servidor: "+self.servidor
un_servicio=Servicio("Google","google.es")
print(un_... |
4927e7e65dbc4c19d8b03e6e57827c3b9bd2fc6f | sirisha-8/Array-3 | /h_index.py | 436 | 3.578125 | 4 | #Time Complexity: O(N)
#Space Complexity: O(N)
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
counts = [0]*(n+1)
for item in citations:
if item>=n:
counts[n]+=1
else:
counts[item]+=1
papers =... |
d22c3655414193408a1207fc0e310473a3da7257 | lyz21/MachineLearning | /SIR_Model_1/test/test1.py | 3,126 | 3.546875 | 4 | # encoding=utf-8
"""
@Time : 2020/4/19 16:32
@Author : LiuYanZhe
@File : test1.py
@Software: PyCharm
@Description:
"""
import numpy as np
from scipy.optimize import minimize
import pandas as pd
def test_zip():
np1 = np.random.rand(5, 2)
print(np1)
# a = [1, 2, 3]
# b = [5, 6]
# c = [7, 8, 9]
... |
410707b20bf8289a43f7f2a9c151631ae0db6440 | lyz21/MachineLearning | /SIR_in_Model_1/test/test_data.py | 834 | 3.609375 | 4 | # encoding=utf-8
"""
@Time : 2020/5/6 17:08
@Author : LiuYanZhe
@File : test_data.py
@Software: PyCharm
@Description: 关于数据的测试
"""
import pandas as pd
import numpy as np
def test_pd1():
df = pd.read_csv('../data/History_country_2020_05_06.csv')
list1 = df[df.name == '突尼斯'].index.tolist()
df2 = df.iloc[li... |
711646003de502ae59915ebcd3fff47b56b0144d | Wh1te-Crow/algorithms | /sorting.py | 1,318 | 4.21875 | 4 | def insertion_sorting(array):
for index in range(1,len(array)):
sorting_part=array[0:index+1]
unsorting_part=array[index+1:]
temp=array[index]
i=index-1
while(((i>0 or i==0) and array[i]>temp)):
sorting_part[i+1]=sorting_part[i]
sorting_part[i]=temp
... |
a450f6ff1ab86cad9d68483c879268fa73c7881e | HoneczyP/Sal-s-Shipping | /ss.py | 1,503 | 3.953125 | 4 | # Cost of ground shipping
def cost_ground_ship(weight):
flat_charge = 20.00
if weight <= 2:
return flat_charge + 1.50 * weight
elif 2 < weight <= 6:
return flat_charge + 3.00 * weight
elif 6 < weight <= 10:
return flat_charge + 4.00 * weight
else:
return flat_charge + 4.75 * weight... |
16a3e3acee1e28ba12e638c7dff9dedb0a5a4056 | cwczarnik/Python_Practice | /Project Euler/probtest2.2.py | 279 | 3.734375 | 4 | import numpy
from numpy import *
a = []
for i in range(1,6):
print(i)
a.append(i)
print(a)
a.append("hello")
print(a)
##
##def fib(n):
## fibarray = []
## a, b = 0, 1
## while b < n:
## fibarray.append(b)
## a, b = b, a+b
## print fibarray
|
df89b847a4ea040e1d373e19b7b345ead0ee7d8e | cwczarnik/Python_Practice | /Computational/sodiumchloride.py | 336 | 3.6875 | 4 | from visual import sphere,color
count = 3
R=0.3
for x in range(-count,count+1):
for y in range(-count,count+1):
for z in range(-count,count+1):
if ((x+y+z)%2) == 0:
sphere(pos=[x,y,z],radius=R,color=color.green)
else:
sphere(pos=[x,y,z],radius=R,colo... |
6013c234451639ee65be29212fb9a46b1f52af8e | ManaliKulkarni30/Python_Practice_Programs | /Iteration1.py | 372 | 3.640625 | 4 | def StartDynamic(No,message = "Jay Ganesh"):
iCnt = 0
while iCnt < No:
print(message)
iCnt = iCnt + 1
def main():
print("How many times do you want output:")
no = int(input())
print("Enter a message you want to print:")
msg = input()
StartDynamic(no,msg)
Star... |
714c641e13e016bf79f45239f2cd031aa0eb8701 | ManaliKulkarni30/Python_Practice_Programs | /file.py | 215 | 3.640625 | 4 | def main():
name = input("Enter the name of file:")
fobj = open(name,"w")
str = input("Enter the data you want to write in file")
fobj.write(str)
if __name__ == '__main__':
main()
|
b147f4dd4bc5cb2cb53beb8aa5a3925dca541265 | ManaliKulkarni30/Python_Practice_Programs | /Exc1.py | 204 | 3.8125 | 4 |
def main():
no1 = int(input("Enter first number: "))
no2 = int(input("Enter second number: "))
ans = no1 / no2
print("Divison is: ",ans)
if __name__ == '__main__':
main()
|
3d1c22b0705f618b43e9a19f93a54bcb91b88c7f | ManaliKulkarni30/Python_Practice_Programs | /Exc2.py | 317 | 3.640625 | 4 |
def main():
no1 = int(input("Enter first number: "))
no2 = int(input("Enter second number: "))
try:
ans = no1 / no2
except Exception as eobj:
print("Exception occurs:",eobj)
else:
print("Divison is: ",ans)
if __name__ == '__main__':
main()
|
0ebeaa2cd19ec1f27932f32447af1ea72268f8b5 | ManaliKulkarni30/Python_Practice_Programs | /selection.py | 352 | 3.875 | 4 | #14 Feb 2021
#Selection
import MrvellousNumber as mn
def main():
no = int(input("Enter a number:"))
bRet = m.chkEven(no)
if bRet == True:
print("No {} is even".format(no))
else:
print("No {} is odd".format(no))
if __name__ == "__main__":
main()
#Camel Case: chkEve... |
1ecd5f97b22e0044c21d614dc6390bf0c978f1aa | ManaliKulkarni30/Python_Practice_Programs | /List1.py | 338 | 3.765625 | 4 | def DisplayL(list):
iCnt = 0
for iCnt in range(len(list)):
print(list[iCnt])
def main():
arr = [10,20,30,40,50]
print(arr)
print(arr[3])
#we can store heterogenous data in list
Brr =[10,"Manali",66.48,"Pune"]
print(Brr)
DisplayL(arr)
if __name__ == "__main... |
833e39fe7b287f67970d39eca9dbb911a5da9220 | KevOrr/Tide-Clock | /control/station_selector.py | 1,467 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
from math import sin, cos, acos, radians, sqrt, pi
import json
from control.util import get_abs_path
USAGE = '%s lat lon' % sys.argv[0]
IN_FILE = get_abs_path('stations.json')
# https://en.wikipedia.org/wiki/Great-circle_distance#Formulas
# All angles in radians
def get_angle(lat1,... |
315bc09a11f42cd7b010bee38ac8fa52d06e172c | calazans10/algorithms.py | /basic/var.py | 242 | 4.125 | 4 | # -*- coding: utf-8 -*-
i = 5
print(i)
i = i + 1
print(i)
s = '''Esta é uma string de múltiplas linhas.
Esta é a segunda linha.'''
print(s)
string = 'Isto é uma string. \
Isto continua a string.'
print(string)
print('O valor é', i)
|
e47ac33a8196b93669f7ee2217eefeafbe99ef45 | calazans10/algorithms.py | /data structs/str_methods.py | 368 | 3.984375 | 4 | # -*- coding: utf-8 -*-
nome = 'Jeferson'
if nome.startswith('Jef'):
print('Sim, a string começa com "Jef"')
if 'e' in nome:
print('Sim, ela também contém a string "e"')
if nome.find('son') != -1:
print('Sim, ela contém a string "son"')
delimitador = '_*_'
minhalista = ['Brasil', 'Russia', 'Índia', 'C... |
ac6d580d3ae712924c44bd4bdffbf4b15e3cf88e | calazans10/algorithms.py | /functions/func_doc.py | 292 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def printMax(x, y):
"""Imprime o maior entre dos números.
Os dois valores devem ser inteiros."""
x = int(x)
y = int(y)
if x > y:
print(x, 'é o maior')
else:
print(y, 'é o maior')
printMax(3, 5)
print(printMax.__doc__)
|
34ae06f5fea1a3886a7208998a729c3900280424 | gugry/FogStreamEdu | /lesson1_numbers_and_strings/string_tusk.py | 261 | 4.125 | 4 | #5.Дана строка. Удалите из нее все символы, чьи индексы делятся на 3.
input_str = input()
new_str = input_str[0:3];
for i in range(4,len(input_str), 3):
new_str = new_str + input_str[i:i+2]
print (new_str)
|
358cd42a66be05b4606d01bcb525afa140181ccc | PRASADGITS/shallowcopyvsdeepcopy | /shallow_vs_deep_copy.py | 979 | 4.5 | 4 | import copy
'''
SHALLOW COPY METHOD
'''
old_list = [[1,2,3],[4,5,6],[7,8,9]]
new_list=copy.copy(old_list)
print ("old_list",old_list)
print ("new_list",new_list,"\n")
old_list.append([999])
print ("old_list",old_list)
print ("new_list",new_list,"\n")
old_list[1][0]="x" # both changes Bec... |
6f68a4199b712c59b6edcce230f7946e8b1ed612 | rad5ahirui/data_structure_and_algorithms | /chapter5/hanoi.py | 355 | 3.625 | 4 | #!/usr/bin/env python3
# coding: utf-8
a = []
b = []
c = []
def move(n, x, y, z):
if n > 0:
move(n - 1, x, z, y)
z.append(x.pop())
print('Move:', a, b, c,sep='\n')
move(n - 1, y, x, z)
def main():
global a
a = [3, 2, 1]
print(a, b, c,sep='\n')
move(3, a, b, c)
if ... |
83c79053f124896efc381a7e5f60a9ad0c1ce1fa | rad5ahirui/data_structure_and_algorithms | /chapter6/p6_1.py | 1,326 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
from p6_2 import Stack
from p6_3 import Queue
class A(ABC):
@abstractmethod
def add(self, x):
pass
@abstractmethod
def pop(self):
pass
@abstractmethod
def empty(self):
pass
class AStac... |
f91cfa00ce619f708d72448c83c1f76a704448fe | a6741/some-python-code-which-was-wrote-when-I-was-boring | /untitled12.py | 530 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
time = [i for i in range(0,19)]
number = [9.6,18.3,29,47.2,71.1,119.1,174.6,257.3,
350.7,441.0,513.3,559.7,594.8,629.4,640.8,
651.1,655.9,659.6,661.8]
plt.title('Relationship between time and number')#创建标题
plt.xlab... |
ba0bf77d3202493747e94c0a686c739d6cb98e9f | srisreedhar/Mizuho-Python-Programming | /Session-18-NestedConditionals/nestedif.py | 510 | 4.1875 | 4 | # ask user to enter a number between 1-5 and print the number in words
number=input("Enter a number between 1-5 :")
number=int(number)
# if number == 1:
# print("the number is one")
# else:
# print("its not one")
# Nested conditions
if number==1:
print("number is one")
elif number==2:
print("num... |
3b413b76a9d13081098a6305627c63da576d5a28 | lgigek/alura | /python3-oo-avançado/model.py | 1,805 | 3.75 | 4 | class TvShow:
def __init__(self, name, year, ):
self._name = name.title()
self.year = year
self._likes = 0
def like(self):
self._likes += 1
@property
def name(self):
return self._name
@property
def likes(self):
return self._likes
@name.sett... |
4a4f19c2ab1fe0b6079b4954d0697cb0f8433b3e | tarzioo/AnAlgorithmADay2018 | /Day-24/isSameTree.py | 1,194 | 3.6875 | 4 | # Day 24/365 #AnAlgorithmAday2018
# Problem is from Leetcode 100
#
# Same Tree
#
#GGiven two binary trees, write a function to check if they are the same or not.
#
#Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
#
#
#Example 1:
#
#Input: 1 1
# ... |
242a80f4856b65906c9c51d8a0ee2d1b0bc63ec5 | tarzioo/AnAlgorithmADay2018 | /Day-4/reverseBits.py | 642 | 3.53125 | 4 | # Day 4/365 #AnAlgorithmAday2018
# Problem is from Leetcode 190
#
# Reverse bits of a given 32 bits unsigned integer.
#
#For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as #00111001011110000010100101000000).
#
#Follow up:
#If this fu... |
363363bf8cfe4a9e583310722c2657693a15648e | tarzioo/AnAlgorithmADay2018 | /Day-11/containsDuplicate.py | 749 | 3.640625 | 4 | # Day 11/365 #AnAlgorithmAday2018
# Problem is from Leetcode 217
#
# Contains Duplicate
#
#Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least #twice in the array, and it should return false if every element is distinct.
#
#
#############... |
6331a3de630ca916cee1eb3294bf9153b059824a | himichael/Cracking_the_Coding_Interview | /10.01.合并排序的数组/sorted-merge-lcci.py | 502 | 3.625 | 4 | class Solution(object):
def merge(self, A, m, B, n):
"""
:type A: List[int]
:type m: int
:type B: List[int]
:type n: int
:rtype: None Do not return anything, modify A in-place instead.
"""
if not A or not B:
return A if A else B
i = m-1
j = n-1
tail = m+n-1
while i>=0 or j>=0:
if i==... |
858e0b0d2aa236a806f37a17fb11beef01c9d365 | muskankhurana053/games | /tictactoegame.py | 2,191 | 3.9375 | 4 | import sys
print("""hey player yu can enter your input by choosing a number from 1-9
1|2|3
-----
4|5|6
-----
7|8|9
""")
board=[" "," "," "," "," "," "," "," "," "]
def disp():
print(f"{board[0]}|{board[1]}|{board[2]}")
print("_____")
... |
cfdd7c6c577c38c42822bc9ec361d948e0adb63c | H-Cavid/LessonTasks | /task06.py | 329 | 3.765625 | 4 | # sort methodundan istifade olunacaq
# sort()elifba sirasi ve ya artan sira ile gosterir
# sort(reverse=True) elifba sirasinin eksi,azalan sira ile gosterecek
L = [3, 6, 7, 4, -5, 4, 3, -1]
#1.
if sum(L)>2:
print(len(L))
#2.
if abs(max(L)-min(L))>10:
print(sorted(L))
else:
print("Ferq 10-dan kichik-bera... |
a3c3b97acacaa48621f0fd0339d3695176bb56f7 | JuanLengyel/mintic_learning_python_contact_directory_interface | /contact_book.py | 2,348 | 3.734375 | 4 | import csv
from contact import Contact
class ContactBook:
def __init__(self):
self._contacts = []
self._load()
def add(self, name, phone, email):
self._contacts.append(Contact(name, phone, email))
self._save()
def remove(self, name):
try:
self._contact... |
13257e9375fe5674e7940b95610a68fa2ee8c79e | lruczu/learning | /natural_language_processing/ner/training/processing.py | 490 | 3.546875 | 4 | import re
def normalize(text: str) -> str:
text = re.sub('\([^\s]*?\)', '', text) # one word in bracket
text = re.sub('\[[^\s]*?\]', '', text)
text = re.sub('\{[^\s]*?\}', '', text)
text = text.strip()
text = re.sub(' +', ' ', text)
text = re.sub(' ,', ',', text)
text = re.sub(' ;', ';'... |
2b2b2dcc0c42190451e919ae7297fe633087fa7e | sthasuman/Assign | /File.py | 1,435 | 3.6875 | 4 | import csv
class VDC(object):
def __init__(self, district, name, number ,pop_male,pop_female):
self.district = district
self.name = name
self.number = number
self.pop_male = pop_male
self.pop_female = pop_female
def __str__(self):
return str("District: %s, Name:... |
9284b5980c6c04f0a322cdab5ed48ae617a16c59 | varnitsaini/python-graphs | /AdjacencyList.py | 3,280 | 4.375 | 4 | """
Illustrating adjacency list in undirected graph
Two classes are used, one for adding new Verted and
one for Graph class.
Space Complexity : O(|V| + |E|)
Time Complexity : O(|V|)
Where |V| -> vertex
|E| -> edge
"""
"""
Creating vertex for adjacency list
"""
class Vertex:
"""
defining the constructo... |
69b56300410df2703f37c21f0b7c473b51b22538 | Herringway/twittersearch | /oauthsign.py | 1,093 | 3.53125 | 4 | import oauth2
import sys
import time
import settings
# Build an oauth-signed request using the supplied url
# Use .to_url() on the return value to get an URL that will authenticate against the
# Twitter API. Build your URL, then call this function to get the URL that you will
# send to Twitter.
def sign_oauth_requ... |
23c2533773c90efe45b80b05153f00bf2f09a055 | artmaks/HeadHunterTask | /island/island.py | 4,935 | 3.609375 | 4 | # coding: utf-8
import numpy as np
from numpy import sum
# Проверяем, является ли клетка низиной
# И все ее соседи с той же высотой (функция рекурентная)
# Если не является (вода уходит) => False
# Если явлется (вода остается) => набор клеток являющихся низиной (частный случай, когда 1 клетка)
def isBottom(map, x, y,... |
04c4b07e6e7e980e7d759aff14ce51d38fa89413 | davelpat/Fundamentals_of_Python | /Ch2 exercises/employeepay.py | 843 | 4.21875 | 4 | """
An employee’s total weekly pay equals the hourly wage
multiplied by the total number of regular hours, plus any overtime pay.
Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage.
Write a program that takes as inputs the hourly wage, total regular hours, and total overtime hours
an... |
618b0630f3a7f64378a0ce82502753fe4b28ffb8 | davelpat/Fundamentals_of_Python | /Ch11 exercises/merge_sort.py | 2,041 | 4.09375 | 4 | def merge(lyst, copybuffer, low, middle, high):
# lyst liist being sorted
# copybuffer temp space needed during the merge
# low beginning of the first sorted sublist
# middle end of the first sorted sublist
# middle + 1 beginning of the second sorted sublist
# hig... |
a5396eb5f2d7009e92844031778dd176abf12ab3 | davelpat/Fundamentals_of_Python | /Student_Files/Ch_09_Student_Files/die.py | 597 | 3.890625 | 4 | """
File: die.py
This module defines the Die class.
"""
from random import randint
class Die:
"""This class represents a six-sided die."""
def __init__(self):
"""Creates a new die with a value of 1."""
self.value = 1
def roll(self):
"""Resets the die's value to a random number
... |
d5367ee9332da2c450505cb454e4e8dac87b2bf8 | davelpat/Fundamentals_of_Python | /Student_Files/ch_11_student_files/Ch_11_Student_Files/testquicksort.py | 1,817 | 4.15625 | 4 | """
File: testquicksort.py
Tests the quicksort algorithm
"""
def quicksort(lyst):
"""Sorts the items in lyst in ascending order."""
quicksortHelper(lyst, 0, len(lyst) - 1)
def quicksortHelper(lyst, left, right):
"""Partition lyst, then sort the left segment and
sort the right segment."""
if left ... |
65284af9158c3db8a764b7cb07296d2b89a4c93c | davelpat/Fundamentals_of_Python | /Student_Files/ch_08_Student_Files/counterdemo.py | 1,424 | 3.75 | 4 | """
File: counterdemo.py
"""
from breezypythongui import EasyFrame
class CounterDemo(EasyFrame):
"""Illustrates the use of a counter with an
instance variable."""
def __init__(self):
"""Sets up the window, label, and buttons."""
EasyFrame.__init__(self, title = "Counter Demo")
sel... |
1a7183d7758f27abb21426e84019a9ceeb5da7c7 | davelpat/Fundamentals_of_Python | /Ch3 exercises/right.py | 1,344 | 4.75 | 5 | """
Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is a right
triangle.
Recall from the Pythagorean theorem that in a right triangle, the square of one
side equals the sum of the squares of the other two sides.
Use "The t... |
82808ac569c685a2b864fd668edebbb7264cd07d | davelpat/Fundamentals_of_Python | /Ch9 exercises/testshapes.py | 772 | 4.375 | 4 | """
Instructions for programming Exercise 9.10
Geometric shapes can be modeled as classes. Develop classes for line segments,
circles, and rectangles in the shapes.py file. Each shape object should contain
a Turtle object and a color that allow the shape to be drawn in a Turtle
graphics window (see Chapter 7 for detai... |
f9a84cff7e4e9c4a92167506a09fcf09726ecfc1 | davelpat/Fundamentals_of_Python | /Ch3 exercises/salary.py | 1,387 | 4.34375 | 4 | """
Instructions
Teachers in most school districts are paid on a schedule that provides a salary
based on their number of years of teaching experience.
For example, a beginning teacher in the Lexington School District might be paid
$30,000 the first year. For each year of experience after this first year, up to
10 ye... |
2ee467b7f70e740bce32e857df97bd311034e494 | davelpat/Fundamentals_of_Python | /Ch4 exercises/decrrypt-str.py | 1,106 | 4.5625 | 5 | """
Instructions for programming Exercise 4.7
Write a script that decrypts a message coded by the method used in Project 6.
Method used in project 6:
Add 1 to each character’s numeric ASCII value.
Convert it to a bit string.
Shift the bits of this string one place to the left.
A single-space character in the encrypt... |
5b3f98828c1aa52309d9450094ecb3ab990bae91 | davelpat/Fundamentals_of_Python | /Ch4 exercises/encrypt-str.py | 1,246 | 4.53125 | 5 | """
Instructions for programming Exercise 4.6
Use the strategy of the decimal to binary conversion and the bit shift left
operation defined in Project 5 to code a new encryption algorithm.
The algorithm should
Add 1 to each character’s numeric ASCII value.
Convert it to a bit string.
Shift the bits of this string on... |
8b70613ee7350c54156a4eb076f11b82356055f7 | davelpat/Fundamentals_of_Python | /Ch3 exercises/population.py | 1,828 | 4.65625 | 5 | """
Instructions
A local biologist needs a program to predict population growth. The inputs would be:
The initial number of organisms
The rate of growth (a real number greater than 1)
The number of hours it takes to achieve this rate
A number of hours during which the population grows
For example, one might start wi... |
ac12b691a1035565a9359b767f64815f34704622 | davelpat/Fundamentals_of_Python | /Ch5 exercises/doctor.py | 3,622 | 4.21875 | 4 | """
Instructions for programming Exercise 5.9
In Case Study: Nondirective Psychotherapy, when the patient addresses the
therapist personally, the therapist’s reply does not change persons
appropriately. To see an example of this problem, test the program with “you are
not a helpful therapist.” Fix this problem by repa... |
2027688365d98d030c980e3ebff511be738f6816 | aditya-c/leetcode_stuff | /N_Queens.py | 543 | 3.546875 | 4 | import numpy as np
size = 4
board = np.zeros((size, size))
# backtrack
def iter(board, column):
for row in range(board.shape[0]):
if is_stable(board, row, column):
board[row][column] = 1
iter(board, column + 1)
board[row][column] = 0
print(board)
def is_stable(b... |
3863a109340c593950fe070133e5f4cc60342b5c | aditya-c/leetcode_stuff | /numpy_tests.py | 2,008 | 3.984375 | 4 | import numpy as np
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
# Create a new array from which we will select elements
a = np.arange(1, 13).reshape(4, 3)
print(a) # prints "array([[ 1, 2, 3],
# [ 4, 5, 6],
# [ 7, 8, 9],
# [10... |
91d17b10301f316f489e218c8cf69749efceed98 | aditya-c/leetcode_stuff | /numDecodings.py | 323 | 3.796875 | 4 | def decodeNumber(s):
if not s:
return 0
prev, curr, prev_value = 0, 1, ""
print(prev, curr, prev_value)
for digit in s:
prev, curr, prev_value = curr, (digit > '0') * curr + int(10 <= int(prev_value + digit) <= 26) * prev, digit
return curr
print("*" * 10)
print(decodeNumber("1234"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.