blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
503423d6683506ce9ff4fde7f73cfbd7b1cb5145 | tolaoner/Python_Exercises | /different_numbers.py | 613 | 4.125 | 4 | '''Create a sequence of numbers and determine whether
all the numbers of it are different from each other'''
import random
list_numbers=[]
different=True
for i in range(5):
list_numbers.append(random.randrange(1,10,1))
print(list_numbers[i])
for i in range(5):
for j in range(5):
if i==j:
continue
if list_nu... |
90c5465791774a88f040190a430944dc8dfa8200 | MJO7/PRO-97 | /pythonProject/qwerty.py | 545 | 3.5 | 4 | f=open('/Users/rachanajoshi/Desktop/pythonProject/sample1.txt' , 'w+')
data_a = f.read()
f=open('/Users/rachanajoshi/Desktop/pythonProject/sample2.txt')
data_b = f.read()
def swapFileData():
file1 = input("Enter the original file:")
file2 = input("Enter the file to be swapped:")
with open(file1 , 'r') as a:... |
8078abbe9340464de72f76feb34f14acbc61f869 | bplank/cog-sci-1-2014 | /ex2-p/perceptron.py | 1,750 | 3.59375 | 4 | #!/usr/bin/env python
# simple perceptron classifier
import sys
import numpy as np
def train(X,y,iterations,alpha=1.0):
# model with one weight for each feature plus additional bias term
model = np.zeros(X.shape[1]+1)
print "training..."
# train model
for iter in range(iterations):
print "I... |
5c5763e623fbf4b3a39ad03cdd815bef9e0bfebe | happyspace/aa-fullstack-catalog | /vagrant/sql_a_tutorial/tutorial.py | 1,741 | 3.703125 | 4 | import sqlalchemy
from sqlalchemy import create_engine
def create_table():
"""
>>> import sqlalchemy
>>> from sqlalchemy import create_engine
>>> from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
>>> sqlalchemy.__version__
'1.0.8'
>>> engine = create_engine('sqlit... |
d59f6e3bc65c4af38f9e09f089b9b74ccafa89eb | Legena/HackBulgaria | /exam1/math/expression.py | 625 | 3.5625 | 4 | from random import randint
class Expression():
def generate_expression():
signs = ['+', '-', '*', '/']
choice = randint(1, 4)
sign = signs[choice - 1]
left_number = randint(0, 100)
right_number = randint(0, 100)
answer = 0
if sign == '+':
answer ... |
852e3308b1b3030be7d066363b03dcb328dda5be | Legena/HackBulgaria | /week2/day3/song_tests.py | 921 | 3.65625 | 4 | import unittest
from song import Song
class SongTests(unittest.TestCase):
def setUp(self):
self.test_song = Song(
"Hells Bells",
"ACDC",
"Back in Black",
5,
312,
320
)
def test_song_init(self):
self.assertEqu... |
0ca943befe0321baf5c7c28c8dbd9452c01c8b7a | CLoouis/othelloEngine | /Tubes1_13517072/src/board.py | 1,105 | 3.671875 | 4 | global countO,countX
countO = 0
countX = 0
def showBoard(board):
"""Menampilkan papan permainan saat ini"""
print(' 1 2 3 4 5 6 7 8')
batas = '\n ' + '+---'*8 + '+\n'
ful = batas
for i in range(1, 9) :
sebaris = str(i) + " | "
for j in range(1, 9) :
... |
e836afa47ec9ea7496e071c6d79eac3819bee873 | gabriellacodes/Python_Homework_Week_4 | /loop_exercises_q4.py | 569 | 4.0625 | 4 | groceries = [
["Baby Spinach", 2.78],
["Hot Chocolate", 3.70],
["Crackers", 2.10],
["Bacon", 9.00],
["Carrots", 0.56],
["Oranges", 3.08]
]
for x in groceries:
item_number = input(f'How many {x[0]} did you buy? ')
[x][-1].append(float(item_number))
shopping_bill = 0
print(f"====I... |
7e4e7ffcbbb80e25787cfdecff601373a06eff8a | jeffslofish/tictactoe | /server_and_game_logic/game.py | 1,746 | 3.734375 | 4 | '''Will contains the all of the state for the back-end of the application -- and any
state needed for representing a tic-tac-toe game'''
#player constants
PLAYER_X = "X"
PLAYER_O = "O"
class Game:
gameCount = 0 #A python 'static variable' is not tied to an instance
#a game should always have a type by defaul... |
c41d7a698b67d07fe877456775074666b121502f | Budiprigunanda/Python-Programming-Overview | /5_function.py | 2,470 | 4.09375 | 4 | # f(x) = 2x + 3
# f(3) = 2(3) + 3
# f(3) = 9
# function hello world
# def hello():
# print("Hello World!")
# hello()
# # function pangkat 2
# def power():
# print(3**2)
# power()
# def power2(x):
# print('print dari dalam function', x**2)
# return(x**2)
# hasil_power = power2(4)
# print('print dar... |
9b7315b5ef8dda0a76ad60d404e1650ec194761c | NoSuchThingAsRandom/Arcade-Games | /Game_Select.py | 1,336 | 3.53125 | 4 | from Frogger import Frogger
from Snake import snake
import os.path
games = ["Snake (Standard)", "Snake (Speed)","Frogger"]
scores = []
def select():
global scores
print("\n"*3)
user = input("What is your name? ")
print("What game would you like to play? ")
for game in games:
print(game)
... |
0a9bc566b3d6ed0b8e162830da7fff0fcf4a75c0 | liuyaox/code_nlp | /Preprocessing/data_preprocessing.py | 1,907 | 3.640625 | 4 |
input_str = 'ddAdhxSlJk238sXkj'
# 2. ɾ
import re
input_str = re.sub(r'\d+', '', input_str)
# 3. ɾ string.punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
import string
input_str = input_str.translate(str.maketrans('', '', string.punctuation))
# 5. Stopword
from nltk.corpus import stopwords
from nltk.tokenize... |
c8ef802bcc4541287ecebb7512ede6b623aac004 | GuadalupeC09/bank_account | /index.py | 781 | 3.796875 | 4 | class BankAccount:
bank_name= "Dojo Bank"
def __init__(self, int_rate, balance):
self.int_rate = 0
self.balance = 0
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display... |
0228d7b77afbed3bb2e575e8c5113007cbe4f59b | Anatoliy91/python-lessons | /cycl4.py | 196 | 3.546875 | 4 | def added_list(listik):
a = len(listik)
listishe = []
for x in range(a):
listishe.append(listik)
print(listishe)
print(range(100))
added_list([1, 5, 9, 5, 8, 6, 3]) |
845047d98f02e292bf77160eb70803158003b914 | Anatoliy91/python-lessons | /list3.py | 360 | 3.859375 | 4 | def uniq(list1, list2):
#list1 = [1, 5, 9, 5, 8, 6, 3, 5, 6, 5, 6, 1, 6, 3, 5]
#list2 = []
a = 0
for x in list1:
if x not in list2 and x % 2 == 0:
list2.append(x)
for y in list2:
a = a+y
return a, list2
a, list2 = uniq(list2=[], list1=[1, 5, 9, 5, 8, 6, 3, 5, 6, ... |
34ea7ab3fbd44e871fac2cdee1f2b8e18adbc21a | limgeonho/Algorithm-1 | /BOJ/Brute-Force/[BOJ]9095-1.py | 280 | 3.671875 | 4 | # 1, 2, 3 더하기
# 재귀함수 사용
def dfs(n):
global cnt
if n < 0:
return
if n == 0:
cnt += 1
return
dfs(n-1)
dfs(n-2)
dfs(n-3)
for tc in range(int(input())):
n = int(input())
cnt = 0
dfs(n)
print(cnt)
|
f7486bd35248c69ef4e923d47a1a3f906539d77b | limgeonho/Algorithm-1 | /BOJ/Implementation/[BOJ]2445.py | 307 | 3.515625 | 4 | # 별 찍기 - 8
n = int(input())
# for i in range(1, n+1):
# print('*' * i + ' ' * 2*(n-i) + '*' * i)
# for i in range(n-1, 0, -1):
# print('*' * i + ' ' * 2*(n-i) + '*' * i)
for i in range(2*n - 1):
blank = abs((n - (i+1)))
star = n - blank
print('*'*star + ' '*2*blank + '*'*star)
|
670a674771e5c25d2903f5e8a52d7a9a05d2197e | limgeonho/Algorithm-1 | /BOJ/Implementation/[BOJ]2446.py | 224 | 3.578125 | 4 | # 별 찍기 - 9
# ' '와 '*'로 구분지어서 생각
num = int(input())
for i in range(num, 0, -1):
print(' ' * (num - i) + '*' * (2 * i - 1))
for i in range(2, num+1):
print(' ' * (num - i) + '*' * (2 * i - 1))
|
5830047cf3fec7c452127d6e2ba2f877edf8a2b2 | WagnerFLL/IA1 | /Inference Engine/engine.py | 2,477 | 3.75 | 4 | knowledge = {}
rule = {}
def build_knowledge(data, value):
if data[0] == '!':
knowledge[data[1:]] = not value
knowledge[data] = value
else:
knowledge[data] = value
knowledge['!' + data] = not value
def build_rules(data):
data = data.replace('^', ' ').split('... |
ed6047449756a75a9bfb80366fdd3ecf26109a11 | bsu-slim/pystlm | /sequence.py | 3,174 | 3.859375 | 4 | '''
Created on Oct 22, 2018
@author: casey
'''
from constants import Constants
class Queue(object):
#
# * Wrapper around a linked list
#
def __init__(self):
self.items = list()
def push_front(self, item):
self.items.insert(0,item)
def push_back(self, item):
... |
8bf612eea44c25dbce0e2487164fff8933aca62e | andres074/segundo_programa | /funciones_ej3.py | 361 | 4.03125 | 4 | '''Escribe una función que reciba una lista de números y devuelva otra pero conteniendo solo los números pares.'''
def lista_numeros_pares(numeros):
numeros_pares= []
for numero in numeros:
if numero % 2 ==0:
numeros_pares.append(numero)
return numeros_pares
print(lista_numeros_pares([... |
e1252400523a3378290f1da7febc33609379d2b1 | andres074/segundo_programa | /death_date.py | 1,923 | 3.5 | 4 |
import datetime
import random
MAX_LIFESPAN = 100
SMOKER_PENALIZATION = 10
DRINKER_PENALIZATION = 7
SEDENTARI_PENALIZATION = 3
BAD_NUTRITION = 10
CITY_CONTAMINATION = 15
days_week = {0: 'lunes', 1: 'martes', 2: 'miercoles', 3: 'jueves', 4: 'viernes', 5: 'sábado', 6: 'domingo'}
def str_with_underscore(message):
... |
e3f3984b77b3c470747389928e7b93eaa1cf4da5 | Liamtran1997/Python | /fibonacci.py | 423 | 3.75 | 4 | # Nhập vào 1 số
def my_fibonaccia(n):
if n < 2:
return 1
else:
f0 = 0
f1 = 1
fn = 0
while n >= 2:
fn = f0 + f1
f0 = f1
f1 = fn
n -= 1
return fn
n = -1
while n < 0:
n = int(input("Nhập số tự nhiên N : "))
... |
b219ded7240dec4d8654774b744fe5fe1149c01b | vinicius-lds/Python-programming-exercises | /Question030.py | 147 | 3.828125 | 4 | def print_largest(x, y):
l = x if len(x) > len(y) else y
l = l if len(x) != len(y) else f'{x}\n{y}'
print(l)
print_largest('a', 'bb')
|
12c9bf9787106f17356ae8b7e62ca4a5ab1a4fb0 | vinicius-lds/Python-programming-exercises | /Question019.py | 315 | 3.734375 | 4 | ts = list()
ext = False
while not ext:
name = input('Type in the name: ')
age = input('Type in the age: ')
score = input('Type in the score: ')
ts.append((name, age, score))
c = input('Press Y to continue... ')
ext = c.upper() == 'Y'
ts.sort(key=lambda t: (t[0], t[1], t[2]))
print(ts)
|
ba4dc4af8626c8d67ccaece054e19938cdde1609 | vinicius-lds/Python-programming-exercises | /Question006.py | 321 | 3.6875 | 4 | from util.Console import get_multiple_int_input
from math import sqrt
C = 50
H = 30
D = get_multiple_int_input(
message='Digite três números para serem usados como a varivel D na fórmula "Q = Square root of [(2 * C * D)/H]"\n',
max_length=3
)
for x in D:
print('Q={}'.format(int(sqrt((2 * C * x) / H))))
|
3dfc5ce84b734d3b6a2dacbe50de8cd9fb0a8756 | meiningerj/QRBCPythonArcade | /Circle.py | 702 | 3.640625 | 4 | import arcade
import os
#arcade uses pixels to measure eveything, so the below line of code
#create a game window that is 600 pixels wide and 600 pixels high
#the last variable gives the window its name
arcade.open_window(600, 600, "ArcadeIntroduction")
#you need this line of code to start drawing
arcade.start_render... |
249478d20a9c24e228aaf688701856fe50b48ee8 | s-ngo/pandas-homework | /pandas-exercises.py | 2,484 | 3.625 | 4 | import pandas as pd
import numpy as np
def pretty_print(name, to_print):
print(f'{name}:')
print(f'{to_print}\n\n')
insurance = pd.read_csv(filepath_or_buffer='insurance.csv',
sep=',', # optional
header=0) # optional
# Getting DataFrames information
# prett... |
f74fdcbc4d8ac08a14bce2b87fd0741cf77ad2f2 | 21gongyue/gy | /dk/continue.py | 446 | 3.796875 | 4 | #continue跳过本次循环
#100以内能被3整除的数
# for i in range(1,100):
# if (i % 3 )!=0:
# continue
# print(i)
#100以内不能被3整除的数
# for i in range(0, 100):
# if (i % 3) ==0:
# continue
# print(i)
# break中止循环
#定义一个求两个数商和余数的方法
# c=a/b
# d=a%b
# a=10
# b=20
def cd (a,b):
print('商:',a//b ,'.余数:... |
9e9a7f659e02166504a089881ac76fda038d4fec | SolidVanta/advent_of_code_2019 | /day1/fuel.py | 142 | 3.578125 | 4 | with open("input", "r+") as file:
summ = 0
for line in file:
summ = summ + int(line)/3-2
print("Total = {}".format(summ))
|
1af076986af764a0af1fb3c27057ba39158e59c7 | ganeshpop/Face-Recognition-Machine-Learning-Model | /e18_blurring.py | 2,782 | 3.765625 | 4 | import numpy as np
import argparse
import cv2
# WHY BLUR??
# Computer Vision function like thresholding and edge detection works better
# if bllurring is performed
# fetching the arguments and save in dictionary
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Enter path to the... |
8c4747c1ee5882480cfa2b64f66505200514615a | frankrolf/PangrammerHelper | /PangrammerHelper.roboFontExt/lib/PangrammerHelper.py | 3,798 | 3.59375 | 4 | '''
Pangrammer Helper
By Mark Simonson
Thanks to Frederik Berlaen for help with hooking up to Space Center
Simple Python version of a Flash/ActionScript "app" I first did in 2003:
http://www.ms-studio.com/Animation/pangrammerhelper.html
Purpose is to help you write pangrams--sentences that contain all the letters
of ... |
45ded7f6d7230ef8688702eec2dd3b5f624310bd | Yingyue321/DPL5211-Tri2110 | /Lab2.3.py | 270 | 4.0625 | 4 | # Student ID 1201201400
# Student Name: Tan Ying Yue
Celcius = float(input("Please enter the value for the number of temperature in Celcius: "))
Fahrenheit = (Celcius * 1.8) + 32
print("{:.2f} Celcius is equivalent to {:.2f} Fahrenheit".format(Celcius,Fahrenheit))
|
399474bdd93e47d000ed9ae9734dd2e5b85fe660 | Siddhant6078/Placement-Programs | /Python/factors_of_a_num.py | 214 | 4.25 | 4 | # Python Program to find the factors of a number
def print_factors(n):
print 'Factors of {0} are:'.format(n)
for x in xrange(1,n+1):
if n % x == 0:
print x
n1 = int(input('Enter a n1: '))
print_factors(n1) |
92f4bea4efbe1c7549407a44b85bf03ceeb25104 | Siddhant6078/Placement-Programs | /Python/swap two variables.py | 663 | 4.34375 | 4 | # Python program to swap two variables using 3rd variable
x = input('Enter value of x: ')
y = input('Enter value of y: ')
print 'The value of x: Before:{0}'.format(x)
print 'The value of y: Before:{0}'.format(y)
temp = x
x = y
y = temp
print 'The value of x: After:{0}'.format(x)
print 'The value of y: After:{0}'.fo... |
e3f91759b3e4661e53e1c5bb42f6525cef89b2d5 | Siddhant6078/Placement-Programs | /Python/Positive or Negative.py | 319 | 4.5 | 4 | # Program to Check if a Number is Positive, Negative or 0
# Using if...elif...else
num = float(input('Enter a Number: '))
if num > 0:
print 'Positive'
elif num == 0:
print 'Zero'
else:
print 'Negative'
# Using Nested if
if num >= 0:
if num == 0:
print 'Zero'
else:
print 'Positive'
else:
print 'Negative' |
1af20a79976737780e25d2d65f8cea95c32ed4eb | jmok81/TreehouseTechdegree | /Project 2 Battleship/ship.py | 4,006 | 3.875 | 4 | from board import Board, SHIP_INFO, BOARD_SIZE, HORIZONTAL_SHIP
from battleship import *
class Ship:
# -- SETOUT PLAYER BOARD --
# Player input for ship position
def ship_position(self):
self.ship_input = (
(input("Where would you like to place the {}? The {} takes up {} spaces: ".format(... |
4eddc40e697ff765c4bc1f5b99865e7c2363e324 | android1000/Stepic-Python | /1.6.9.py | 388 | 3.65625 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(list,Loggable):
def append(self, p_object):
list.append(self, p_object)
#super(LoggableList,self).append(p_object)
self.log(p_object)
a=[]
a.append(1)
print(a)
a=Logga... |
fadc451ea2860e54f2c04c6a42e00c62bc1f09eb | android1000/Stepic-Python | /2.1.7.py | 699 | 3.546875 | 4 | def fnd(classes, parrent, child):
if parrent == child:
return True
elif child not in classes:
return False
elif parrent in classes[child]:
return True
else:
for p in classes[child]:
if fnd(classes, parrent, p):
return True
return False
er... |
7ceedadf08a74b70aba89f5b89780df0e62b205b | OrtalRaz/VoiceRecognitionBackend | /db/users/base_users_db.py | 1,431 | 3.828125 | 4 | from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import overload
@dataclass
class User:
user_id: int
username: str
password: str
email: str
class BaseUsersDB(metaclass=ABCMeta):
@overload
def get_user(self, user_id: int) -> User:
...
@overloa... |
d0b1df0f3a94e89552717260dca3dfd95ca3943c | javsav/Project-Euler-Solutions | /Python Scripts/Problem 18.py | 3,000 | 4.03125 | 4 | tri = [[0 for x in xrange(15)]for x in range(15)] # Generating 2D array for triangle, followed by manual appending.
tri[0]=[75]
tri[1]=[95, 64]
tri[2]=[17, 47, 82]
tri[3]=[18, 35, 87, 10]
tri[4]=[20, 4, 82, 47, 65]
tri[5]=[19, 1, 23, 75, 3, 34]
tri[6]=[88, 2, 77, 73, 7, 63, 67]
tri[7]=[99, 65, 4, 28, 6, 16, 70, 92]
tri... |
db68cca9381a8e9d1f83479b7bc32e784cd77093 | AbhilashaBansal/python_d-s_ml | /Face Recognition/face_data_collection.py | 2,252 | 3.734375 | 4 | #Write a Python script to capture images from videostream, extract all faces (using haarcascades)
#Store the face information into a numpy arrays
# 1. Read the video stream, and capture images
# 2. Detect faces, and make a bounding box around them
# 3. Flatten and store information of the largest face by area, inside ... |
0f64ad2a86c8bbe6329296e94bd8b8ac563b95f9 | 156076769/spark-exam | /pyspark-s3-parquet-example/pyspark-scripts/nations-parquet-sql-local.py | 2,169 | 3.53125 | 4 | """
File name: nations-parquet-local.py
Author: Jonathan Dawson
Date Created: 6/8/2016
Date Modified: 6/8/2016
Python Version: 2.7
PySpark Version: 1.6.1
Example of loading .parquet formatted files into a in-memory SQLContext table and running SQL queries against it.
This script is configured to run against a local i... |
73fed6743975942f340fc78009c16b9e2cf7b875 | abhinavkuumar/codingprogress | /employeeDict.py | 1,049 | 4.1875 | 4 | sampleDict = {
'emp1': {'name': 'John', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Tim', 'salary': 6500}
}
while 1:
answer = input("Do you want to add or remove an employee? Select q to quit (a/r/q) ")
newlist = list(sampleDict.keys())
if answer == 'a':
... |
2da72ad227e82145ffd64f73b39620330c83c21d | greenhat-art/guess-the-number | /guessingGame.py | 604 | 4.3125 | 4 | import random
print("Number guessing game")
number = random.randint(1, 9)
chances = 0
print("Guess a number between 1 to 9:")
while chances < 5:
guess = int(input("Enter your guessed number:- "))
if guess == number:
print("Congratulation you guessed the right number!")
break
... |
0eecc1170b45dc06ea29970c760da0c3e3ee5417 | yodsatorn/code-python3-blog | /ai/chatbot-chatterbot.py | 1,671 | 3.546875 | 4 | # สร้าง Machine Learning โต้ตอบสนทนาด้วย ChatterBot ในภาษาไพทอน
# https://python3.wannaphong.com/2015/10/สร้าง-machine-learning-โต้ตอบสนทนา-python.html
__author__ = 'วรรณพงษ์'
from chatterbot import ChatBot
bot = ChatBot("Training Bot Example",
storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
... |
4ea7b9c234eb8fc013a071fe50845a16d46cdd0a | yodsatorn/code-python3-blog | /check-pid.py | 1,839 | 3.5625 | 4 | # โค้ดเซ็คความถูกต้องของบัตรประชาชน
# เขียนโดย วรรณพงษ์ ภัททิยไพบูลย์
# wannaphong@yahoo.com
# https://python3.wannaphong.com
def checkPID(pid):
if(len(pid) != 13): # ถ้า pid ไม่ใช่ 13 ให้คืนค่า False
return False
num=0 # ค่าสำหรับอ้างอิง index list ข้อมูลบัตรประชาชน
num2=13 # ค่าประจำหลัก
listdata=list(pid) # l... |
2ee1d159c31268c8006c383a50b3a493991c431c | yodsatorn/code-python3-blog | /บวกลบธรรมดา.py | 516 | 3.625 | 4 | __author__ = 'วรรณพงษ์'
#import re
print("Text")
a = input("Text")
if a.find("+"):
s = a.split("+")
in1 = int(s[0])
in2 = int(s[1])
cal = in1 + in2
elif a.find("-"):
s = a.split("-")
in1 = int(s[0])
in2 = int(s[1])
cal = in1 - in2
elif a.find("*"):
s = a.split("*")
in1 = int(s[0]... |
6a980b319f46b8c990cb5dfc967d8e9fa0d74528 | hnkingsolver/adventOfCode | /expenseReport.py | 1,142 | 3.828125 | 4 | # # def missingExpense(numbers):
# # sum = 2020
# # for i in range(len(numbers) - 1):
# # for j in range(i + 1, len(numbers)):
# # if numbers[i] + numbers[j] == sum:
# # return(numbers[i], numbers[j])
# # print(missingExpense(numbers))
# def twoSumNaive(num_arr, pa... |
d347de34c5058cfabd6dfc1ad64bebde56569461 | Solannis/Python-Examples | /list_test.py | 549 | 4.125 | 4 | #!/usr/bin/python
class test:
def __init__(self):
self.name = ""
self.code = ""
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
print len(list)
list2 = []
print list2
... |
b01578c44f6c8820b419aaebdfa9d8ad690e7f8c | Solannis/Python-Examples | /fileIO.py | 751 | 3.859375 | 4 | #!/usr/bin/python
# Open a file for writing
writeString = "This is text for the file writing and reading test."
writeFile = open("text.txt", "wb")
print "Name of the file: ", writeFile.name
print "Closed or not: ", writeFile.closed
print "Opening mode: ", writeFile.mode
print "Softspace flag: ", writeFile.softspace
pr... |
8c8e2e5f5e928457567e0be2d95f22618603b99a | valates/dotapick | /fileOperators.py | 1,382 | 4 | 4 | from os import listdir
from os.path import isfile, join, exists
""" For a file with string name FILENAME, splits the contents based on the
newline delimiter and returns the split lines as a list. """
def split_file_by_newline(filename):
with open(filename) as f:
lines = f.read().splitlines()
ret... |
cc776833aa93e419a7191f20205df8e5eb7fd14e | orithecoder/cos-and-sin-cordic-algorithm | /cordic.py | 575 | 3.515625 | 4 | from math import *
def angle(n):
return degrees(atan(1/2**n)),1/2**n
def c(n):
return 1.0/(sqrt(1+2**(-2*n)))
cf = 1
for i in range(39):
cf *= c(i)
req_angle = 50
x0 = 1
y0 = 0
radius_angle = 0
for k in range(40):
alpha,arc_angle = angle(k)
if radius_angle < req_angle:
radius_angle += alpha
new_x0 = x0 - ... |
36042e69e4f1b6eb6c7a35f6ac2bc58e77e4a93e | Sumobot1/advent_of_code | /02_program_alarm/solution.py | 1,898 | 3.703125 | 4 | # Link: https://adventofcode.com/2019/day/2
def intcode_add(idx, intcode):
intcode[intcode[idx+3]] = intcode[intcode[idx+1]] + intcode[intcode[idx+2]]
return intcode
def intcode_mult(idx, intcode):
intcode[intcode[idx+3]] = intcode[intcode[idx+1]] * intcode[intcode[idx+2]]
return intcode
def intcode_... |
7c64beecc014e6859f8261a5eaa7bb923631a20a | miragesky2049/AutoDeploy | /算法第4版.py | 1,447 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from TestCase import sorted_nums, random_nums
# # 插入排序
# class Insertion:
# @staticmethod
# def sort(a):
# length = len(a)
# i = 1
# while i < length:
# j = i
# while j > 0 and a[j] < a[j-1]:
# a[j], a[... |
f52025d32e6c6c046d489758f1ffc78c8e463cbb | jakow/algs | /python/test/heap.test.py | 2,422 | 3.59375 | 4 | """
Heap test
"""
import unittest
import operator
import random
from heap import Heap
class HeapTest(unittest.TestCase):
"""
Test Heap implementation
"""
def test_max(self):
heap = Heap()
items = [1, 2, 8, 13, 4, 6, 20, 6, 25]
for item in items:
heap.insert(item)
... |
28e7dc645d0ebd935ff9027e61e73210b49df51e | khoidnyds/Rosanlind | /FIBD.py | 1,874 | 3.984375 | 4 | class FibonacciDeath:
""" Problem Mortal Fibonacci Rabbits
Recall the definition of the Fibonacci numbers from “Rabbits and Recurrence Relations”,
which followed the recurrence relation Fn=Fn−1+Fn−2 and assumed that each pair of rabbits
reaches maturity in one month and produces a single pair of offspri... |
6729f6d367e1a58a295f7cb46755f596446bde92 | khoidnyds/Rosanlind | /IPRB.py | 3,061 | 4.25 | 4 | class Mendel:
""" Problem: Mendel's First Law
Probability is the mathematical study of randomly occurring phenomena. We will model such a phenomenon with
a random variable, which is simply a variable that can take a number of different distinct outcomes depending
on the result of an underlying random pr... |
959ab33ec17250396244db3c65a284a1acfe58d3 | khoidnyds/Rosanlind | /MRNA.py | 1,931 | 3.640625 | 4 | from functools import reduce
class MRNA:
""" Problem: Inferring mRNA from Protein
For positive integers a and n, a modulo n (written amodn in shorthand) is the remainder when a is
divided by n. For example, 29mod11=7 because 29=11×2+7.
Modular arithmetic is the study of addition, subtraction, multipl... |
3a2f79213330d8d59ebca6d2945141e613b22dc1 | drpuig/Leetcode-1 | /next-permutation/next-permutation.py | 938 | 3.609375 | 4 | class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-2, -1, -1):
if nums[i] < nums[i+1]:
# from tail, find the first decreasing pairs (i, i+1)
... |
b95e76c00e69648bb3e8c482d31f8b78c1bfffab | drpuig/Leetcode-1 | /shortest-word-distance-iii/shortest-word-distance-iii.py | 644 | 3.5 | 4 | class Solution:
def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
lastIdx1 = lastIdx2 = float('-inf')
minDistance = float('inf')
for i, word in enumerate(wordsDict):
if word == word1 == word2:
minDistance = min(minDistance, i - l... |
58ba6f86e620e6ede70171f6f563c9649fe5eebb | drpuig/Leetcode-1 | /the-maze/the-maze.py | 714 | 3.546875 | 4 | class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
q = deque([start])
visited = set([tuple(start)])
while q:
r, c = q.popleft()
if [r, c] == destination: return True
directions = [[-1, 0], [1, 0], [0... |
19619d9c6de55cb66dd940870b6e8e03d15c58ba | drpuig/Leetcode-1 | /simplify-path/simplify-path.py | 258 | 3.5625 | 4 | class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for d in path.split('/'):
if d not in ['.', '..', '']: stack.append(d)
elif stack and d == '..': stack.pop()
return '/' + '/'.join(stack) |
eb0ad41bc93cc91108f3ce8ed4d898ec943375e8 | drpuig/Leetcode-1 | /encode-and-decode-strings/encode-and-decode-strings.py | 660 | 3.625 | 4 | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string.
"""
return ''.join(["%d:" %len(s) + s for s in strs])
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings.
"""
ans = []
left... |
aac7e25e675ad5691e62d4877987af165eb3f2cc | drpuig/Leetcode-1 | /search-a-2d-matrix/search-a-2d-matrix.py | 737 | 3.78125 | 4 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
r = self.bisectLeftRow(matrix, target)
c = bisect_left(matrix[r], target)
if c == len(matrix[0]): return False
return matrix[r][c] == target
def bisectLeftRow(self, matrix, target):
... |
36a08117af06dd0761012b17e90d34c9963f8f7f | drpuig/Leetcode-1 | /reverse-words-in-a-string/reverse-words-in-a-string.py | 361 | 3.65625 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
lst, word = [], []
for i, ch in enumerate(s):
if ch != ' ':
word.append(ch)
if word and (ch == ' ' or i == len(s)-1):
lst.append(''.join(word))
word = ... |
1d1b75d15e2c13febf413d695d0a4bb909197400 | drpuig/Leetcode-1 | /power-of-two/power-of-two.py | 175 | 3.59375 | 4 | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1: return True
if n <= 0 or n % 2 == 1: return False
return self.isPowerOfTwo(n//2) |
9fcbb0ed5e0ec4f1b38765ed5f2f7afcc2506c47 | koladen/SolveTasks | /examples.py | 3,430 | 3.75 | 4 | def example_massiv():
things = ['mozarella', 'cinderella', 'salmonella']
things[1] = things[1].capitalize()
things[0] = things[0].upper()
# del things[2]
things.remove('salmonella')
anotherlist = ['Groucho', 'Chico', 'Harpo']
anotherlist[2] = anotherlist[2].lower()
# anotherlist[2] = (""... |
957d95428e0af1b303930e7071dfbe710f84f99b | anasm-17/DSA_collaborative_prep | /Problem_sets/fizzbuzz/fizzbuzz_jarome.py | 1,879 | 4.3125 | 4 | from test_script.test import test_fizzbuzz
"""
A classic Data Structures an algorithms problem, you are given an input array of integers from 1 to 100 (inclusive).
You have to write a fizzbuzz function that takes in an input array and iterates over it. When your function receives
a number that is a factor of 3 you ... |
741ff280e74c013de37eacb4f3c016396244ba2a | anasm-17/DSA_collaborative_prep | /Problem_sets/pyramid/test_script/solution.py | 293 | 3.53125 | 4 | # Author: Anas Muhammad - github: anasm-17
# date: 2020-02-03
def pyramid(n):
pyr_list = list(" "*((2*n) - 1))
out_list = []
for i in range(n):
pyr_list[(2*n - 1)//2 + i] = '#'
pyr_list[(2*n - 1)//2 - i] = '#'
out_list.append("".join(pyr_list))
return out_list |
cab5758f6b4d740b24a2653a0c4a2be2bc6a659a | hkrishna00/RecipeIngredients | /food.py | 2,628 | 3.90625 | 4 | #Importing the necessary libraries
import pandas as pd
#Obtain the list of available recipes and their ingredients along with their priority
dishes_df = pd.read_csv(filepath_or_buffer = '/Food.csv') #Enter the pathname to your food CSV file
#Columns - "Recipe", "Ingredient", "Priority"
#Asking for user to input a li... |
477cbdc71181b57de6e866c358f33c1084f8756e | cooltoast/spellcheck | /spellcheck.py | 4,730 | 3.53125 | 4 | from bisect import bisect_left
with open("/usr/share/dict/words") as dictionary:
library = dictionary.read().lower().splitlines()
print "Dictionary initialized with length", len(library)
#returns index of x in a_list, assuming a_list is sorted
def binary_search(a_list, x, lo=0, hi=None):
hi = hi if hi is not None... |
053ca740634a0ae1bee2889040fe3581a0b3af5c | udaykumarbhanu/letscode | /minimum-falling-path-sum.py | 1,743 | 3.6875 | 4 | """LC: 931. Minimum Falling Path Sum
Given a square array of integers A, we want the minimum sum of a falling path
through A.
A falling path starts at any element in the first row, and chooses one element
from each row. The next row's choice must be in a column that is different from
the previous row's column by at m... |
dd1027be8d528bf82becc3a35775afe54cf8f4fb | ndoshi83/DS-Unit-3-Sprint-1-Software-Engineering | /SC/acme_report.py | 1,945 | 3.609375 | 4 | # Import required libraries
from random import randint, sample, uniform
from acme import Product
# Create list of adjectives and nouns
adj = ['Awesome','Shiny','Impressive','Portable','Improved']
nns = ['Anvil','Catapult','Disguise','MouseTrap','Rocket']
# Create function to create product inventory
def gene... |
67a38065de2c054cd563a589892c248b8bc8398f | IsAlbertLiu/Data-analysis | /Code/chapter--01-Numpy/04--Array-operate.py | 1,492 | 3.828125 | 4 | import numpy as np
# 1.矢量化运算
data1 = np.array([[1,2,3],[4,5,6]])
data2 = np.array([[1,2,3],[4,5,6]])
# 数组相加
print(data1+data1)
# [[ 2 4 6]
# [ 8 10 12]]
# 数组相减
print(data1-data1)
# [[0 0 0]
# [0 0 0]]
# 数组相乘
print(data1*data1)
# [[ 1 4 9]
# [16 25 36]]
# 数组相除
print(data1/data1)
# [[1. 1. 1.]
# [1. 1. 1.]]
# ... |
3ca6f9294b0d8bfc84640f0b5bc0a09168b2148c | Ranjani2020/Python-project | /Sequences.py | 412 | 3.953125 | 4 | #name ="Harry"
#print(name[0]) # output is H you can give 1 output is a ,2-r,3-r
#names = ["Harry", "Ron", "Hermione"]
#print(names)
coordinateX = 10.0
coordinateY = 20.0
coordinate = (10.0,20.0) # in python grouping the values we can use tuple
#Data Structures
#list- Sequence of mutable values
#tuple- Sequence ... |
2c0db16146a9464068674804a2eeb5bb053cfc2c | yotamlevit/Holydays_Project | /Shape.py | 534 | 3.921875 | 4 | from abc import ABCMeta, abstractmethod
import math
class Shape:
__metaclass__ = ABCMeta
def __init__(self, color, poly):
"""
an initializer for the class
;ani: bool - animation on or off
;color: is the color that the user wants to fill the shape with
"""
self... |
3bca3c5351f86f3bad62218bee8817afe13d5475 | yotamlevit/Holydays_Project | /Circle.py | 794 | 3.75 | 4 | from ClosedCurve import *
BLACK = "black"
class Circle(ClosedCurve):
def __init__(self, x=100, y=200, rad=10, color=BLACK, poly=BLACK):
"""
an initializer for the class
;x: the x value center of the circle
;y: the x value center of the circle
;rad: the radius
;color... |
42bf6b7bb309d58f1ec0850c594ad1040d7482fa | pushyami-org/pinger | /computive.py | 1,958 | 3.671875 | 4 | import cmath
import math
from os import environ
from datetime import datetime
def main():
# a = float(environ['A'])
# b = float(environ['B'])
# c = float(environ['C'])
num = int(environ['NUM'])
# num = 40
# cmplx_computing(a, b, c, num)
begin = datetime.now()
if num <= 0:
prin... |
dd5b658e2716cbe158c8cd91b5dd47a2b6292c65 | maxschridde1494/Advanced-Data-Structures-Course | /CH7Stack/Stack.py | 645 | 3.9375 | 4 | class Stack():
def __init__(self):
self.data = []
def isEmpty(self):
"""returns True is self.data is empty"""
return len(self.data) == 0
def peek(self):
"""returns last item on stack if non-empty.
if Stack is empty, return error
"""
if self.data:
return self.data[len(self.data) - 1]
else:
ra... |
f200d837b5a36deabe59d4faf0b7f998c9990edc | kartiktanksali/Hackerrank_Problems | /hurdlerace_hackerrank.py | 470 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the hurdleRace function below.
def hurdleRace(k, height):
height.sort(reverse=True)
dose = height[0]-k
if dose>0:
return dose
elif dose<=0:
return 0
if __name__ == '__main__':
nk = input().split()
... |
b0cbbb9e4c4daaca8c98f9eae557643da876a995 | kartiktanksali/Hackerrank_Problems | /lists_in_python.py | 3,012 | 4 | 4 | #Lists in python
dif_list = ["Kartik","Shruti",24,26,True,99.999]
str_list = ["Cats","Dogs","Lion","Tiger","Cheetah"]
int_list = [12,24,36,48,60,12,34,56]
#print(dif_list)
#print(str_list)
#print(int_list)
#
#print(dif_list[0])
#print(str_list[3])
#print(int_list[-5])
#for d in dif_list:
# print(d)
#
#print("\n")
... |
b12f1cb91aad3661e7473a137507d289b41d5499 | kartiktanksali/Hackerrank_Problems | /logistic_regression.py | 3,752 | 3.5625 | 4 | import pandas as pd
import numpy as np
import statsmodels.api as sm
from sklearn import preprocessing
import matplotlib.pyplot as plt
plt.rc("font", size=14)
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
import seaborn as sns
sns.set(style="white")
sns.set(st... |
f2ba638b6d8b5382b550bb7920a09371437e51b1 | kartiktanksali/Hackerrank_Problems | /km_ml.py | 127 | 3.921875 | 4 | ml = float(input("Enter the miles"))
#1 = 0.621371
a = ml/5
b = ml-a
kms = b*2
print("The kms travelled is {}".format(kms))
|
2d0308e0d3c401873b31354050f8ffe3dd5b3eba | JcbBrtn/Evolution-Algorithm | /NeuralNetwork.py | 7,204 | 3.75 | 4 | import random
import math
import numpy as np
"""
Neural network class:
TODO List:
Add biases into each neuron before sent into activation function [X]
Add back prop [X]
Play around with mutating learning rate [X]
"""
class neuralNetwork:
#2 layer neural network, 10 neurons per layer
#Initilized w... |
dd80e66757066ef8d97911680ffb0e47411d9c25 | jineshshah101/Python-Fundamentals | /Casting.py | 580 | 4.3125 | 4 | # variable example
x = 5
print(x)
# casting means changing one data type into another datatype
# casting the integer x into a float
y = float(x)
print(y)
# casting the integer x into a string
z = str(x)
print(z)
# Note: Cannot cast a string that has letters in it to a integer. The string itself mu... |
6141bb86224dbc1c19efca92f530682d1a04e570 | jineshshah101/Python-Fundamentals | /Calendar.py | 1,448 | 4.46875 | 4 | import calendar
#figuring things out with calendar
# printing out the week headers
# using the number 3 so we can get 3 characters for the week header
week_header = calendar.weekheader(3)
print(week_header)
print()
# print out the index value that represents a weekday
# in this case we are getting the ind... |
bc997de77bdd8f6576c5d42f63ea6900e6491261 | vermaarun/codingChallenges | /LinkedList/find_middle.py | 326 | 3.9375 | 4 | from LinkedList import LinkedList
def find_middle(lst):
if lst.head is None:
return False
fast = lst.head
slow = lst.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.value
ll = LinkedList()
ll.generate(10, 1, 10)
print ll
print find_middl... |
3898fa5596220218140cc0f11feff0a7bb2ef08d | evanaze/balance-sheet | /balance_sheet/balanceSheet.py | 7,399 | 3.84375 | 4 | """ The balance sheet object.
Backend in SQL, persists in memory with Pandas.
"""
import os
from pathlib import Path
import pandas as pd
import sqlite3
class BalanceSheet:
"The balance sheet class"
def __init__(self):
self.sql_connection() # opens the connection to the database
sel... |
ce0cfdebf310432f6641ef77c298ebefefa2d2d6 | gihs-rpc/01-Sleeping-In | /challenge-1-sleeping-in-MoseliaTemp3/1.1 ~ Sleeping In.py | 1,612 | 4.34375 | 4 | #Repeatedly used things defined here for ease of modification.
EndBool = "\n (Y/N) > "
Again = "Incorrect input."
#Begin Program.
while True:
print("\n")
#Is tomorrow a school day?
SchoolTomorrow = input("Do you have school tomorrow?" + EndBool)
print()
#Repeat question until answe... |
27f4a18c698f39a6d476b2856a4e4e8754676cf8 | Sayaji911/python_oops | /stringtodate.py | 1,026 | 4.03125 | 4 | class time():
def __init__(self, hours, minutes, seconds):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def displaytime(self):
return ' The time is {} hours, {} minutes and {} seconds'.format(self.hours, self.minutes, self.seconds)
@classmethod #decorator the below method is a ... |
f7b1b92a8eef2f743bd3c9350445823a07dd6464 | 1974410167/python_projects | /pycharmproject/面试/动态规划/连续数列.py | 158 | 3.671875 | 4 | num = [-2,1,-3,4,-1,2,1,-5,4]
def ss(num):
for i in range(1,len(num)):
num[i] = max(num[i]+num[i-1],num[i])
return max(num)
print(ss(num)) |
0ce61552d8df10606e5e5dd0286655f3ec7ee170 | 1974410167/python_projects | /pycharmproject/面试/树/树的子结构.py | 523 | 3.640625 | 4 | class TreeNode:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
list1 = []
def dfs(root):
if not root:
return
list1.append(roo... |
e8cd6aec5f2664ec7f23067e4c9d657223957203 | 1974410167/python_projects | /pycharmproject/单例模式/基于函数装饰器.py | 324 | 3.515625 | 4 |
def f1(f):
instance = None
def inner(*args,**kwargs):
nonlocal instance
if not instance:
instance = f(*args,**kwargs)
return instance
return inner
@f1
class cls():
def __init__(self,num):
self.num = num
c = cls(10)
c1 = cls(10)
print(id(c))
print(id(... |
fd406d323fa4d649d80bfed1e45d8585f4c9952f | 1974410167/python_projects | /pycharmproject/数据结构/斐波那契数列.py | 382 | 3.5625 | 4 | def fib(n):
nums = [0, 1]
if n <= 1:
return n
t = 2
while t <= n:
target = nums[0] + nums[1]
nums[0] = nums[1]
nums[1] = target
t += 1
tt = 1*10**9+7
print(tt)
print(target)
if target<tt:
target = target%tt
else:
target = t... |
ab52660c45a4e8660afb23420531bdcaded09a09 | 1974410167/python_projects | /pycharmproject/魔法函数/tess.py | 749 | 3.5625 | 4 | import time
list = [
(1, 2),
(2, 3),
(2, 4),
(3, 5),
(4, 5)
]
dict_2 = {}
dict_1 = {}
for i in list:
if i[1] not in dict_1:
dict_1[i[1]] = 1
else:
dict_1[i[1]] += 1
if i[0] not in dict_2:
dict_2[i[0]] = [i[1]]
else:
dict_2[i[0]].append(i[1])
print(f"dict_... |
89c70c26c9b3b0936a74ef80064b8431efe2a173 | 1974410167/python_projects | /pycharmproject/爬虫/菜鸡/格式化输出.py | 424 | 3.953125 | 4 |
class Dog:
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print(f"{self.name} is eat")
def sleep(self):
print(f"{self.name} is sleep")
class dog1(Dog):
name="ss"
def __init__(self,scoure):
self.scoure=scoure
def play(self):
... |
1d89235aad1725dfb16638f43f1c14a21fd10878 | 1974410167/python_projects | /pycharmproject/多线程/多线程2.py | 470 | 3.546875 | 4 | from time import time,sleep
from threading import Thread
#执行用时4S
def loop1():
sleep(4)
print("loop1结束")
def loop2():
sleep(2)
print("loop2结束")
def main():
start=time()
p1=Thread(target=loop1,args=())
p1.start()
p2 = Thread(target=loop2, args=())
p2.start()
p1.join()
p2.join()... |
3262cbb69764bc02f348ad0d1fc3dcf71109f27c | 1974410167/python_projects | /pycharmproject/数据结构/二分查找.py | 726 | 3.796875 | 4 | target = 5
nums = [2,5,77,222,333,4444,22222]
class Solution:
def binary_search(t,nums):
left = 0
right = len(nums)
while left<=right:
mid = (left+right)//2
if nums[mid]>t:
right = mid - 1
elif nums[mid] == t:
return mid
... |
9145220c95472b055158c87b7268bee370a5d6ee | 1974410167/python_projects | /pycharmproject/面试/树/对称二叉树.py | 2,477 | 3.890625 | 4 |
# from data_structure import BinaryTree
# from set_data_structure import set_BinaryTree
# s = [1,2,2,3,4,4,3]
#
# tree = set_BinaryTree(s)
# print(tree)
#
# class Solution:
# def isSymmetric(self, root: BinaryTree) -> bool:
#
# if not root:
# return True
#
# result = [root]
# wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.