blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
81c10408415058039f483098bc459f6a0005725e | zhujs/codesnippets | /python.note/copyTest.py | 664 | 3.609375 | 4 | # coding: utf-8
import copy, weakref
a = [1,2,3]
b = [4,5]
c = [a,b]
# Normal Assignment, a strong reference
d = c
assert( id(c) == id(d) ) # d is the same object as c
assert( id(c[0]) == id(d[0]) )# d[0] is the same object as c[0]
# Shallow Copy
d = copy.copy(c)
assert( id(c) != id(d) ) # d is now a n... |
8c7b483631c707eae819c104564fbaf79ca9f0eb | Winrich76/exercises | /shopping.py | 2,123 | 3.75 | 4 | class Product:
id = 0
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
self.id = Product.set_number()
@classmethod
def set_number(cls):
Product.id += 1
return Product.id
def get_id(self):
... |
85da37b7bdc841be235df34472e840eb1f7066f0 | Mageer/concurrency_playground | /src/algorithms/fibonacci.py | 98 | 3.765625 | 4 | def fib(num: int):
if num < 1: return 0
if num == 1: return 1
return fib(num-1) + fib(num-2) |
babf1d6a749da90be285c1784262d898bffc63bd | m9s-rk/m9s-exercises | /python/renew_subscriptions.py | 1,860 | 3.890625 | 4 | '''
Below is some test data representing an imaginary subscription service.
Once a day, the subscriptions are passed to the get_renewed_subscriptions function.
If the 'expiresAt' date is in the past AND the subscription has been paid, the
subscription is renewed and included in the list returned by get... |
54396a1bb877ba0928125cd87b3e258172f9b299 | kbrennan711/interactive_programming | /Interactive_Visualization_MapOOP.py | 6,295 | 3.71875 | 4 | """
Kelly Brennan and Celine Ta
Software Design Spring 2015
Interactive Visualization Project
We aim to create an interactive map that displays each countries' happiness rating and GDP
"""
import state_boundaries
import xml.etree.cElementTree as et
import bokeh.plotting as bk
import numpy as np
from bokeh.m... |
001b96d868b9694411981a5cf2af80ac15f65c07 | tate11/pythoncw | /KunhadjiRahmata/intro/main.py | 1,256 | 3.828125 | 4 | """
keterangan siktaksis dasar
-squential
-branching dengan if
-loop
"""
from shape.persegi import Persegi
from shape.segitiga import Segitiga
print('hello world!')
# Sequential
print('contoh luas segitiga')
alas = 400
tinggi = 3
luas_segitiga = alas * tinggi / 2
print(luas_segitiga)
# branching dengan if
print('bra... |
788f0323a56da97fcbb0124a9f1542656c2e433a | elwyngalloway/NHLseasonML2 | /__practice_retrieval_from_database.py | 1,570 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 21:23:58 2018
@author: Galloway
"""
import sqlite3
import numpy as np
#import pandas as pd
db_name = "NHLseasonML_seasonstats.db"
# connect to our database that will hold everything, or create it if it doesn't exist
conn = sqlite3.connect(db_n... |
a8d07c6604fe969def6123472b00abd0a357a659 | Senuch-Uzair-Tariq/Workspace | /Python Mark Lutz- Volume 1/Python182.py | 156 | 3.796875 | 4 | def square(x):
for i in range(x):
yield i**2;
x=square(10)
i1=iter(x)
i2=iter(x)
print(next(i1))
print(next(i2))
print(next(i1))
print(next(i2)) |
bc56e8c7f451cd96993b6bc0ee6168037c3bc748 | calvar122/EXUAGO2021-VPE-L1 | /0929/juanl.magana/fibo_recursivo.py | 676 | 3.734375 | 4 | #!/usr/bin/env python3
# c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil
# vi: set shiftwidth=4 tabstop=8 expandtab:
# :indentSize=4:tabSize=8:noTabs=true:
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Ejemplo de un modulo
"""
def fibo(last, pen):
res = last + pen
return res
def main():
last = 1
... |
7f5ab1c59e16ff4d4712bb61fdbad4f020275227 | ShahriarXD/Junks | /09_pr_04.py | 89 | 3.578125 | 4 | a = str(input("Name: "))
if len(a) >10:
print (True)
else:
print(False)
|
cd23fb72a8427c665701aa35a0d80845b20abf16 | IamTheVine/CS-2 | /Chekpoint 1/chk1-sum_double.py | 512 | 4.09375 | 4 | # Python for Beginners Immersion Course
# Checkpoint 1.5
# Albert Molina
# 10-May-2018
# Description : Given two int values, return their sum. Unless the two values are the same, then return double their sum.
#
try :
InpNumber1 = int(input('Input 1st Number: '))
InpNumber2 = int(input('Input 2nd Nu... |
2b0f6ffe65ca771f5fa24d974310eaa9f51b281e | weizhen167/Deep-Learning | /numpy_practice/np4_copy.py | 708 | 3.828125 | 4 | import numpy as np
a = np.arange(3,15)
print 'a is: '
print a
b = a
print 'b is: '
print b
c = a
print 'c is: '
print c
d = b
print 'd is: '
print d
print '\n____________________________ change start_________________'
print 'now a[0] = 11'
a[0] = 11
print 'a is: '
print a
print 'b is: '
print b
print 'c is: '
pr... |
9c9bd29446f1719270c7581a8ebf730b01c141a3 | sswan0629/udacity_intro_to_ml | /ud120-projects/datasets_questions/explore_enron_data.py | 1,362 | 3.59375 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
6ef2bd1b50b6f4de6e8d6ed036dc37bf07faed0e | mthomascomp/Python-Assignments- | /Grade Calculator.py | 2,394 | 4.5 | 4 | # Mervin Thomas
# Mr. Kyle Batterink
# ICS3U-b
# March 7, 2016
print("Enter your grade percentage:") #This print command allows the program to display the text which is in the string.
final_grade = float(input()) #This is the x variable which is registered as fht efloat of an input the user types in.
if final_grade... |
062e72558d3d3004d699334057563120a57f1c5d | hyunwookjleeucc/Year9DesignCS-PythonHJL | /LoginScreen.py | 1,259 | 4 | 4 | import tkinter as tk
#Classes: A blueprint to make objects.
#Object: An instance of the class.
#Three Parts
#Constructor: This is a special method only run once when we first instantiate "Make" the object.
#Attributes: These are variables that describe the state of the object.
#Behaviours: These are functions that ca... |
f387d046073e95e776b3513a8f02b0c3e02f6637 | carden-code/python | /stepik/star_frame.py | 528 | 4.625 | 5 | # The input to the program is a natural number nn. Write a program that prints an n * 19 star frame.
#
# Input data format
# The input to the program is a natural number n ∈ [3; 19] - the height of the star frame.
#
# Output data format
# The program should display a star frame with dimensions n * 19.
#
# Prompt. To pr... |
ff0c8f608338c3b1825afef4d26ee6e8215d886e | sferbrb/LaserSLAM | /新人培训/陈宏干/答案/习题46.py | 339 | 3.921875 | 4 | #题目:求输入数字的平方,如果平方运算后小于 50 则退出。
def sq(x):
return x*x
print('如果输入的数字小于 50,程序将停止运行。')
flag=1
while flag ==1:
num=int(input('请输入一个数字:'))
print('结果为:%d'%(sq(num))
if sq(sum) >=50:
flag=1
else:
flag=0 |
6fc4fde69a2172e22d090be56f126504f0e2cfb6 | Lucas-117/GameDesign2021 | /tuples.py | 774 | 4.0625 | 4 | # Lucas Williams
# lists and their functions
#indexing a list always start in 0
from typing import Counter
myNumber=[1,2,37,8,9]
myFruits=["apples","kiwis","mango", "banana"]
print(myFruits)
myFruits.append("strawberry")
for x in myFruits: # for each element in your array get the value
print (x, end=", ")
print()... |
2310401de62391d8a581d2b34f53b4fe91efd022 | bolmezz/denemePy | /Fonksiyonlar/asalSayi.py | 416 | 3.515625 | 4 | def asal_mi(sayi):
if sayi == 1:
return False
elif sayi == 2:
return True
for i in range(2, sayi):
if sayi % i == 0:
return False
return True
while True:
s = input("Bir sayı girin : ")
if s == "q":
print("Çıkış yapılıyor..")
break
if asal... |
ed1872ab243b4cda3dcd574db43c7c93ac00707c | python-practice-b02-927/kuleshov | /lab2/ex8.py | 376 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 10:08:56 2019
@author: student
"""
from turtle import *
a = 10
n = 10
def squarespy(a, j):
for i in range(3):
forward(j*a)
left(90)
right(90)
forward(a)
left(90)
forward((j+1)*a)
left(90)
shape('turtle'... |
37a262ec0c693cd919f63fc2cce3aa7afac638ca | VijayEluri/ads | /python/interviewquestions/collatz_conjecture.py | 1,059 | 4.40625 | 4 | """
Write a program to prove the Collatz conjecture:
- if a number is even, divide it by 2
- if a number is odd, multiply it by 3 and add 1
- repeat until you get to 1
"""
import unittest
def collatz_recursive(n):
if n == 1:
return n
if n % 2 == 0:
return collatz_recursive(n / 2)
return ... |
7b711677e5dad462974f4e62a2eedd1b0078b7b0 | naomimcmurchie/python-development | /p1.py | 964 | 3.90625 | 4 | import datetime
print('hello world')
# strings
message1 = 'Let us have a drink tonight.'
print(message1)
message2 = 'I/m looking for somesome to share in an advanture'
print(message2)
message3 = 'The phrase "Beam me up, Scotty" was never said on Star Trek.'
print(message3)
message4 = """One of my favorite lines f... |
ccdb6cbc02714c2f88328c6808672b849397ded1 | ICLau/randomStuff | /lambda test.py | 284 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 10 08:55:06 2017
@author:
"""
def make_inc (n):
return lambda x: x + n
"""
According to documentation, when make_inc is assigned to f with 5,
make_inc is, at that point, "closed"
"""
f = make_inc (5)
print (f(3))
print (f(6))
|
ea21b73533ab5466573ae8c739532063ae448782 | kennyp13669/python_files | /better_quadratic_solver.py | 3,691 | 3.796875 | 4 | import math
def quadratic_pos(a, b, c):
if d < 0:
return 0
else:
return (-b + (d ** (.5))) / (2 * a)
def quadratic_neg(a, b, c):
if d < 0:
return 0
else:
return (-b - (d ** (.5))) / (2 * a)
def vertex_x(a, b):
return -b/(2 * a)
def vertex_y(a, b, c):
return ((4 * a * ... |
50439ffac22a1a57280fdfe0744da969c148d2dd | wlsun-xiaole/python-lecture | /sample_codes/01-Python基本語法I/ZeroJudge/a004.py | 230 | 3.84375 | 4 | while True:
try:
# 主程式 開始
year = int(input())
if (year % 400 == 0) or (year%4 == 0 and year%100 != 0):
print('閏年')
else:
print('平年')
# 主程式 結束
except:
break
|
f2c1555fae45aa258ddfc96dfea52f70ee9ed239 | kyeonglinSong/algorithm_study | /python/k번째수.py | 299 | 3.515625 | 4 | #200203(월) 프로그래머스-k번째수
# .sort(), sorted()의 차이를 잘 알자
def solution(array, commands):
result = []
for command in commands:
temp = array[command[0]-1:command[1]]
temp = sorted(temp)
result.append(temp[command[2]-1])
return result
|
897d49c9bda71823536bec9295f28a3f588d5ede | rehoboth23/leetcode-base | /Duplicate Zeroes.py | 1,291 | 3.890625 | 4 | from typing import List
class Solution:
"""
funny solution that adds all new zeroes to the list then pops off the difference in list lenght
"""
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
size = len(arr)... |
6dde71b5c515fc207d0b8c41bb878c46fe9033e4 | dmkent/sensor-feed | /sensor_feed/sensor_multi.py | 6,678 | 3.828125 | 4 | """
A MultiSensorDevice represents a single device with multiple
sensors. This allows one interface to the device to be written
and that device to then expose multiple Sensor objects to
the feed.
This works by a MultiSensorDevice returning a collection
of ChildSensors, starting any of those sensors just passes
the com... |
26d4dcf8f17fe1914d9b0c0c1ba8588ff2fb8da7 | BrendanArthurRing/code | /katas/almost-increasing-sequence-fail-10-15-2019.py | 1,792 | 3.8125 | 4 | # This does not work - need to try test cases for all > pairs
# Dont assume the first one disqualifies.
# Also have to account for where the pair is found
# Just removing the element causes issues because of duplicates
def find_first_decreasing_pair(a):
for i, j in zip(a, a[1:]):
if i > j:
... |
ea96174391566e113a4d832e4096c9be8d0bcbef | arbonap/interview-practice | /fibby.py | 670 | 4.03125 | 4 | def recursive_fibbonacci(num):
if num in [0, 1]:
return num
else:
return recursive_fibbonacci(num - 1) + recursive_fibbonacci(num - 2)
print recursive_fibbonacci(3)
def iterative_fibonacci(n):
a = 0
b = 1
for i in range(n):
prev_a = a
a = b
b = prev_a + b
... |
3f4e7ba17a85a939f95162e21c92776630ba6c66 | idamadam/lpthw | /ex4.py | 899 | 4.0625 | 4 | # Add 100 cars to system
cars = 100
# Define car capacity
space_in_a_car = 4.0
# Add 30 Drivers
drivers = 30
# Add 90 passengers
passengers = 90
# Calculate cars not driven by removing cars with drivers
cars_not_driven = cars - drivers
# Equate cars driven to number of drivers available
cars_driven = drivers
# Find ava... |
00de49894b12ee33bc440e69351db20e7e075257 | inesa-lisnic/Kickstarter-project | /explore.py | 8,628 | 3.765625 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
def question_viz(kick):
print( """Q1. Which categories have the most successful number of projects and
which categories have the most failed number of projects based on c... |
67b61b4fbc27a4db0dc75a1461e55d48211db6cb | chinu1996/pythonPrac | /learning/inheritance.py | 694 | 4.125 | 4 | class A:
def feature1(self):
print("This is feature 1")
def feature2(self):
print("This is feature 2")
class B(A):
def feature3(self):
print("This is feature 3")
class C:
def feature4(self):
print("This is feature 4")
class D(B,C):
# This is an example of mul... |
0af8de1cd181034106c1c7337842e6ace2000aa0 | PhenixZhang/Python-Data-Structure-and-Algorithm | /Basic/Array&&LinkedList/LinkedList.py | 4,335 | 3.921875 | 4 | # -- coding:utf-8 --
class Node():
# data:数据域 next:指向下一个节点的指针
def __init__(self,data=None,next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
__repr__ = __str__
def getValue(self):
return self.data
def getNext(self):
... |
08862028c48ab94fa135a6128cd9b56c0d5217d3 | noahc66260/ProjectEuler | /problem42.py | 538 | 3.671875 | 4 | alphabet = " abcdefghijklmnopqrstuvwxyz"
def hash_word(s):
'''
Sums the indices the words in the letter starting at 1
'''
t = 0
for i in s:
t += alphabet.index(i.lower())
return t
fin = open('words.txt')
line = fin.readline()
line = line.split(',')
for i in range(len(line)):
line[i] = line[i][1:-1... |
b9f44b203c665a198b07202edaec310e73126d43 | hualazimi0425/squirrel | /238. Product of Array Except Self.py | 1,976 | 3.984375 | 4 | # solution 1
# time complexity O(n)
# space complexity O(n)
from typing import List
def productExceptSelf(nums:List[int]) -> List[int]:
length = len(nums)
# The left and right arrays as described in the algorithm
L, R, answer = [0] * length, [0] * length, [0] * length
# L[i] contains the product of ... |
23d75a6ae69a5fce5462dffb9015b3e7eaa558fd | dhruvinmehta/advent-of-code | /AoC_2019/day_6.py | 1,244 | 3.53125 | 4 | # Problem Statement
# https://adventofcode.com/2019/day/6
def read_input_file(file):
with open(file) as file:
return file.readlines()
def path(orbiter, graph):
return [graph.get(orbiter)] + path(graph.get(orbiter), graph) if graph.get(orbiter) else []
def create_graph(space_map):
return {orbit... |
1e114a422d766315dfd8fa511663da345ed9996a | cmjagtap/Algorithms_and_DS | /sorting/whoWinsElection.py | 474 | 3.984375 | 4 | #Array is given votes as a voter_no find who will win election
def winnerElection(array):
if not array:
return None
else:
votecount=maxVote=0
winner=array[0]
for x in xrange(0,len(array)):
votecount=0
for y in xrange(1,len(array)):
if array[x]==array[y]:
votecount+=1
if maxVote<votecount:
... |
603ec5b882b8a9fb77134acfbf5294de30edd9da | DraperHXY/PythonLearning | /com/draper/suanfa/yanghuisanjiao.py | 374 | 3.5625 | 4 | # 杨辉三角
n = input()
L = [1]
for i in range(int(n)):
for j in L: print(j, end=" ")
print("\n", end="")
L.append(0)
# 列表自动解析,且 第一项
L = [L[j] + L[j - 1] for j in range(len(L))]
"""
L = [1]
print(L)
L.append(0)
L = [L[0] + L[0 - 1], L[1] + L[0]]
print(L)
L.append(0)
L = [L[0] + L[0 - 1], L[1] + L[0], L[... |
aa3dd385ba918d42d8b68b7f1dad4fccc6a600d4 | makmakindia/PythonSelenium1 | /prog3gcdnolist.py | 214 | 3.875 | 4 | def gcd(m,n):
for i in range(1, min(m,n)+1):
if(m%i)==0 and (n%i)==0:
mrcf=i
return(mrcf)
m = int(input("Enter m value : "))
n = int(input("Enter n value : "))
print(gcd(m,n))
|
bef84c751da8d7ca3fdf03aa52edffae8b8673fc | rvaraprakash/Python | /ClassInh.py | 1,632 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 05:39:14 2019
@author: varaprakashreddy
"""
class A:
def feature1(self):
print ("Feature1 working..")
def feature2(self):
print ("Feature2 is working..")
class B:
def feature3(self):
... |
0fd01f6aada8df06fd19ba746eaa58b99799bc0c | Nikita-Silent/EX1 | /main.py | 12,390 | 4.25 | 4 | # Developer: Drachev N.
# "car" it's kind of car; stage it's type of car lvl up; ma it's methanol and nitrogen in a balloon.
print('''Выберите один из предложенных типов машины:
1. Drag car (250 л.с.; 0-100 за 9 сек.; 14 л на 100 км)
2. Drift car (200 л.с.; 0-100 за 11 сек.; 9 л на 100 км)
3. Veg car (150 л.с.; 0-100 ... |
984862f022b4b2848e784859f8a786e6f6838499 | mjvillacresesn/MyPython | /PyBank/mainbank.py | 2,846 | 3.703125 | 4 | import os
import csv
#Find path
pybank_file = os.path.join(".", "budget_data.csv")
pybank_outfile = os.path.join(".", "budget_data_output.txt")
#Store Varibles
totalm = 0
PLlist = 0
averagec = 0.0
monthpl = []
date = []
newV = []
moschangel = []
i = 0
totalchange = 0
meanaverage = 0.0
lists ={"" , 0}
#open file and ... |
bd008c88932db6676cdc6b27b52ec999c79e3f76 | Mygithub-projects/python_programs | /python_networking_batch_programs_20Mar_22Mar/prime_demo.py | 261 | 3.984375 | 4 | n=int(input("enter the number\n"))
l=n//2
f=0
for i in range(2,l+1):
if(n%i==0):
f=1
break
else:
continue
if(f==0):
print("{} is a prime number".format(n))
else:
print("{} is not a prime number".format(n))
|
279a82afe79402845ae2c33072a2ab7797d24580 | dode3/python-foundation-course | /mindstorms.py | 743 | 3.71875 | 4 | import turtle
def draw_shapes():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(2)
for _ in range(36):
for _ in range(4):
brad.forward(100)
brad.right(90)
brad.l... |
4de9f88b270cb53708783713d39e8ea6ce4961ca | MoochiPark/first-run | /DataStructure/Seminar/sort/insertion_sort.py | 278 | 4.15625 | 4 | def insertion_sort(list):
for index in range(1, len(list)):
while 0 < index and list[index] < list[index - 1]:
list[index], list[index - 1] = list[index - 1], list[index]
index -= 1
list = [8, 5, 6, 2, 4]
insertion_sort(list)
print(list)
|
c00c79a168cc66cd4ecff82f8d54a865b8aa50ab | Ameliarate16/python-programming | /unit-3/homework/dict_functions.py | 1,798 | 4.0625 | 4 | def dict_merge(first, second):
merged = first
for item in second:
if item in first:
#if the item is in both then make a list of the two
merged[item] = [first[item], second[item]]
else:
#otherwise just add the item
merged[item] = second[item]
re... |
6c670ced0990e714f13bc7ba292f23941601f118 | ymy96/Python-and-Application-to-Business-Analytics | /Assignment3_Mengyang Yao_Xin Shen.py | 7,578 | 3.703125 | 4 | # Connect 4
import random
# This function prints out the board that it was passed.
def drawBoard(board):
# "board" is a list of 10 strings representing the board (ignore index 0)
#print(len(board))
#print(len(board[0]))
for i in range(0,6):
for j in range(0,7):
print(' ' + board[i][j], end=' | ')
if(i != 6):... |
ec16792d22b86e9b73de48af2ea0dc18c63d3ff3 | Andrew-Coxall-0934/ICS3U-Unit2-01-Python | /ICS3U_Unit2_O1.py | 336 | 3.890625 | 4 | # !/usr/bin/env python3
# Created by: Andrew Coxall
# Created on: April 1, 2020
# Area and perimeter using pi
import math
def main():
print("If a circle has a radius of 15mm:")
print("")
print("Area is {} mm^2".format(math.pi*15**2))
print("Perimeter is {} mm".format(2*math.pi*15))
if __name__ == ... |
b0ba55225c8551db2d61f3ed3fbfd491923f8ba2 | MPTGits/HackBulgaria2019 | /week_06/test_decorators.py | 627 | 3.984375 | 4 | import unittest
import decorators
class DecoratorsTests(unittest.TestCase):
def test_when_given_name_and_integer_variables_and_correct_types_str_and_int_will_it_return_the_function_purpouse_(self):
#deposit is a function that returns the name of the person and the deposited amount of money
input_d... |
124bbf908e4c1ef6e1cc66b55120da8d6c2c457d | logasja/Unsupervised-Learning | /hill_climbing.py | 5,301 | 3.5625 | 4 | __author__ = "Jacob Logas"
# Some code templates courtesy of http://www.cleveralgorithms.com/nature-inspired/stochastic/hill_climbing_search.html
import math
import numpy as np
"""
Returns a random bitstring
"""
def random_bitstring(num_bits):
return np.random.randint(0,2,num_bits)
"""
Returns the... |
02b8f20c59d7dbf8e358e86789fc0c23ef9ce90f | kartikarora1/python | /startendwithsamecharacter.py | 261 | 3.703125 | 4 | import re
regex = r'^[a-z]$|^([a-z]).*\1$'
def check(string):
if(re.search(regex, string)):
print("Valid")
else:
print("Invalid")
if __name__ == '__main__' :
string=input()
check(string) |
4cece9515074573e5dd22cbce0f127a2415d22e6 | DanielleForrester/nlpATunb | /LC/random_generator.py | 325 | 3.5625 | 4 | '''
@date: Fri 7 Oct 2016
@author: claud29
starting from peter norvig's jupyter nb how to do things with words
'''
import random
from bag_of_words import get_text, tokenize
def write_random_sentence(bag, n = 10):
'''
random n word sentence with words in bag
'''
return ' '.join(random.choice(bag) for _ in range... |
deb665d2baf7bd559b8d4dcdbb7fc4e1fda5ecb8 | mishrakeshav/Competitive-Programming | /AlgoTalks/LinkedList/copy_random_list_pointer.py | 3,320 | 3.640625 | 4 |
# Definition for a Node.
class Node:
def __init__(self, x, next = None, random = None, ll = None):
self.val = int(x)
self.next = next
self.random = random
self.ll = ll
Approach 1
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None:
... |
ecc1953c633f3559fbffdd9eb64bbab36dcd4e0b | igorlauxen/TCC_Local_Search | /HelloWorld.py | 1,657 | 3.765625 | 4 | from simpleai.search import SearchProblem, astar
GOAL = 'HELLO WORLD'
class HelloProblem(SearchProblem):
# se tamanho do estado for menor que tamanho do goal
# retorna lista com alfabeto, senão, retorna lista vazia
def actions(self, state):
if len(state) < len(GOAL):
retur... |
1d7a3debfca60e8345d151316d2030b0f9a45d3c | eldadmwangi/sifu | /arrays/general/plus_one.py | 1,657 | 3.828125 | 4 | '''
Given a non-empty array of digits representing
a non-negative integer,plus one to the integer.
The digits are stored such that the most significant digit
is at the head of the list, and each element in the
array contain a single digit.
You may assume the integer does not contain any leading zero,
except the numb... |
19b21cc48d698e68831ffde3f93ea12a9730c7ae | zhoujun-star/Library | /sqlite_book.py | 5,707 | 3.984375 | 4 | import sqlite3
class sql_book():
def __init__(self):
self.con = sqlite3.connect("Book.db")
self.cur = self.con.cursor()
def CreateTable(self):
self.cur.execute("DROP TABLE IF EXISTS BOOKINFO")
sql = """CREATE TABLE BOOKINFO(
BOOKNAME CHAR(100) NOT NU... |
2a84c20c335748226e140e9503c1bc02523cb48c | simplynaive/LeetCode | /28. Implement strStr().py | 603 | 3.765625 | 4 |
def strStr(haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle) == 0:
return 0
if len(haystack) == 0 or len(needle) > len(haystack):
return -1
for i in range(len(haystack) - len(needle) + 1):
if haystack[i] == needle[0]:
... |
fb379dd3e9803aa9c8d7c4f76b4dddfae28bb704 | abhimita/algorithms | /edx/src/dynamic_programming_in_machine_learning_genomics/sequence_alignment_part_1/sequence_alignment_part_3/outcome_likelihood.py | 4,408 | 3.75 | 4 | #python3
import sys
import unittest
# Find the probability that an HMM emits a given string.
# Input:
# A string x emitted by an HMM (Σ, States, Transition, Emission).
# Output:
# The probability Pr(x) that the HMM emits x.
# Input Format.
# The first line of the input contains the outcome string x.
# The second line... |
c3df619d86db3e080da7cffeb00831b35cf38bed | sicou2-Archive/pcc | /python_work/part2/alien_invasion/alien_invasion/diy/alien_c13_5.py | 1,128 | 3.734375 | 4 | import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""This is the Alien class for the DIY Alien Invasion."""
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.image = pygame.image.load('images/a... |
cd6ab94a2b96a1669ca421a101ba25470687fcbf | tmarques82/Algorithms-course-exercises | /quicksort_comparisons.py | 2,679 | 4.34375 | 4 | """
Algorithm used for computing the number of comparisons needed when sorting an array number from a file with quicksort
algorithm. Pivots can be selected in different ways (default one is the first element of the array)
"""
def get_median_pivot(init_array):
if len(init_array) < 3:
return 0
middle_ind... |
f9dff1e7c5b58131350147e3e9160e9cb4ca02d4 | Akhtar-Zaman/OOP | /OOP/library.py | 739 | 3.71875 | 4 | class book:
def __init__(self):
self.name = ''
self.author = ''
self.available = 0
self.books = []
def get_book(self):
for i in self.available:
print('Book: ', self.books[i][0])
print('Author: ', self.books[i][1])
def add_books(s... |
d0c154d75f17fff285c8f1de24924ec32c7b539c | poponzu/atcoder1 | /atcoder/ABC/149/149c.py | 445 | 3.640625 | 4 | N=int(input())
#約数列挙
def make_divisors(n):
lower_divisors , upper_divisors = [], []
i = 1
while i*i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n//i)
i += 1
return lower_divisors + upper_divisors[::-1]
#出力部分... |
4f9ae91a05fbc7f910388dbf6c2391b31a3d5f5b | kitta123/Languages | /python/List/largestnuminarray.py | 280 | 3.984375 | 4 | lst = int(input("Enter the number :"))
a = []
for i in range(lst):
numbers = int(input("Enter the number" + str(1+i) + ":"))
a.append(numbers)
m = a[0]
for i in range(0,len(a)):
if(a[i] > m):
m = a[i]
print("Largest element present in given array: " + str(m))
|
dba3d714b8ffc5872ecd96c92761da0c08ceaaf3 | luismir20/Python-Programming | /423_HW8_Class (1).py | 2,178 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Q1. (5 Points)
# We want to creat a class Player with attributes name and age. Then we want to creat a subclass of Player called defender,
# at the end, we creat an object from each classes.
# In[6]:
class Player(): #create the class Player
def __init__(self,na... |
66da4651544925ad2067a17ab08629fe107ad296 | Sushant385/Programs | /Programs/Hackwithinfy1.py | 757 | 3.640625 | 4 | '''
def getTrip(String,n):
String.sort()
start = 0
trip = 0
for i in range(n-1,-1,-1):
if String[i]>1.99:
trip += 1
elif String[i]<=1.99:
if String[i]+String[start]<=3.00:
start += 1
trip += 1
if start >= i:
break
... |
9f42808b8bc10b05668240da344197adad7e1cee | esl4m/DSA_Python | /ch1/ch1_4_graphics/graphics_program.py | 3,014 | 4.3125 | 4 | #!/usr/bin/python3
#
# By Islam (esl4m)
# 3 Aug 2020
#
import turtle
# Command classes would be inserted here but are left out because they were defined earlier in the chapter.
# This is our PyList class. It holds a list of our graphics commands.
class PyList:
def __init__(self):
self.items = []
... |
ea881bb8f172b1ea3985e937e4384c31e99ab27f | a35205905/caesar_cipher | /main.py | 1,420 | 3.9375 | 4 | def main():
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
plain_text = get_plain_text()
offset = get_offset()
cipher_text = ''
for plain i... |
5b008166acf610f5aa905567f85185c095faa15f | gautam-ergo/Python-Assignments | /gautamgs@bu.edu_hw6/gautamgs@bu.edu_hw6_7_5.py | 1,397 | 3.953125 | 4 | """
CS 521 Information Structures with Python
#########################################
Module - HW 6
Creation Date - 10/28/2018
Student Name - Gautam Gowrishankar
"""
import math
class RegularPolygon:
def __init__(self, n=3, side=1, x=0, y=0):
self.__n = n
self.__side = side
... |
e1a377afbd9a574a5a36f8595cf2ce7e19ac5fd6 | Zebralt/autosnake | /shortest_path.py | 4,722 | 4.125 | 4 |
# Jocelyn Vernay, 2017
# This program implements a shortest-path algorithm.
from simple_grid import Grid
from random import randint
import sys
# Print something without EOL.
def printw(strs):
sys.stdout.write(str(strs))
sys.stdout.flush()
# Print an array, although this is useless, str() ... |
bdeb576072efa8c61a254c219349e6822266944c | Liltar/Hillel_homeworks_python | /lesson_17/test_lesson_6_task_1.py | 925 | 3.625 | 4 | from lesson_6 import task_1
import unittest
class TestNewDict(unittest.TestCase):
def test_keys(self):
keys = tuple([key for key, value in task_1.create_dict(task_1.coin, task_1.code).items()])
self.assertTupleEqual(task_1.coin, keys, 'keys are equal')
def test_values(self):
values = ... |
3c66dd00e38e3c4054679504ddb078ee84a0caf7 | KevinHorning/CS2302-IntermediatePython | /HW3/1.py | 846 | 3.984375 | 4 | #HW Assignment 3
#2302 Python 2
#Professor Bowler
#3-4-19
#8.35
class stack(object):
top = -1
data = []
def peek(self):
return self.data[self.top]
def isEmpty(self):
if self.top is -1:
return True
else:
return False
... |
8da024220d4050d3803bd7f765982ae0d558a7db | abhrakantidubey/text-to-speech | /speech.py | 992 | 3.71875 | 4 | import tkinter as tk
from tkinter import *
import pyttsx3
engine=pyttsx3.init("sapi5")
voices=engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
root=tk.Tk()
root.title("TEXT TO SPEECH")
root.geometry("600x200")
root.config(background="#67E6DC")
def speak(audio):
engine.say(audi... |
4206cda7e0cebcfa6b7e1f8f67dea30164694a13 | 14Praveen08/Python | /multiples.py | 109 | 3.953125 | 4 | number=int(input())
for j in range(1,6):
if j==5:
print(number*j,end="")
else:
print(number*j,end=" ")
|
df5610515e471f0049d0ba9696610eafdfa2d7e0 | jonathan-wells/operon-complexes | /operon_assembly/random_operons.py | 6,150 | 3.5625 | 4 | #!/usr/bin/env python3
import random
import itertools
import math
class RandomOperons(object):
"""Methods for shuffling genes in operons in different ways."""
def __init__(self, filename, data_indices, sep,
complevel=False, oplevel=False):
"""Initialize information about operons.
Arg... |
259570549df106ba9b876933b5764c8d9924cf00 | Banghyungjin/AI_Test | /rectangle.py | 95 | 3.796875 | 4 | width = 20
height = 40
width = 30
area = width * height
print ("size of rectangle is : ", area) |
95da97524b86a4ce6b1225f37d195cb5eb3704f7 | subhashdeshmukh/PandasLearning | /csvconcat/concat_csv.py | 595 | 3.921875 | 4 |
#this is the case
#concat two csv files provided they have similar data
#add another column with name of first file
#write this data to the third file
import pandas as pd
import math
# the list of csv sample files
csv_files = ['first.csv','second.csv']
# create an empty dataframe
final_df = pd.DataFrame()
# read ... |
fe214130c0b2961c364fc2e107c59ff8d33868b6 | ViktoriiaBila/basic-python | /PZ7/lab7_1.py | 1,225 | 4.21875 | 4 |
import math
class Sphere(object):
radius = 1.0
x = 0.0
y = 0.0
z = 0.0
def __init__(self, radius = 1.0, x = 0.0, y = 0.0, z = 0.0):
self.radius = radius
self.x = x
self.y = y
self.z = z
def get_volume(self):
return (4/float(3)*math.pi*math.pow(... |
9fa0f80646fcba2e31f4d42327304c335459cf81 | indefinitelee/Interview-Stuff | /numbers.py | 918 | 3.703125 | 4 | def main():
f("12365212354", 26)
def f(numbers, target):
for i in range(1, len(numbers)):
current = int(numbers[0:i])
to_end = numbers[i:-1]
evaluate(0, current, to_end, target, current)
def evaluate(sum, previous, numbers, target, out):
if len(numbers) == 0:
if sum + previ... |
51fb2a316a8445bab279943c28f3dce26a74c7e1 | diegofregolente/30-Days-Of-Python | /02_Day_Variables_builtin_functions/level 2.py | 1,736 | 3.90625 | 4 | print(type(first_name))
print(type(last_name))
print(type(full_name))
print(type(country))
print(type(city))
print(type(age))
print(type(year))
print(type(is_married))
print(type(is_true))
print(type(is_light_on))
print(type(name))
print(type(nickname))
print(type(main))
print()
print('First Name:', first_name, 'Lengh... |
0ea260914216d658d8e173a7f8f9bec75b124efa | gonzalob24/Learning_Central | /Python_Programming/PythonCoursera/Course1/EarningsNew.py | 440 | 3.96875 | 4 | # PRrogram to calculate overtime earnings
# and gross pay
hrs = input("Enter Hours:")
rate = input("Enter rate:")
while True:
try:
h = float(hrs)
r = float(rate)
except:
print("Error, please enter numeric input")
quit()
overTime = h - 40
if overTime > 0 :
payWithOverTime = overTime * 1.5 * r
pa... |
a21cb56d6d59115421d6531bbf648ad60156d75e | gregariouspanda/Julia-learns-python | /generate_story.py | 745 | 3.875 | 4 | import sys
import create_dictionary
import random
def main():
num_words = sys.argv[2]
word_dict = create_dictionary.create_dictionary(sys.argv[1])
print(generate_story(word_dict, int(num_words)))
def generate_story(word_dict, num_words):
story = ''
words = 0
last_word_added = word_dict['$'][... |
3d03712b8c94137f5b40640e3cb1b5ab00fa8963 | jimlawton/euler | /007.py | 370 | 3.625 | 4 | """
Project Euler Problem 7
=======================
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.
What is the 10001st prime number?
"""
from utils import isprime
INDEX = 10001
nprimes = 0
i = 1
while True:
if isprime(i):
nprimes += 1
if nprimes... |
e8db738931d85aec043bcf7d19135560d061e276 | YongyuG/pyTest | /Count_Words.py | 1,407 | 4.5625 | 5 | #This is a python practise for myself to review python coding
#The objective is to complete count_words function
#The function should count a string, rank the word in descending order occurance# and return a list where numbers of tuple inside the list, and the number n is #defined by how many words you want to diplay
... |
89dbb1b6797244dd29249ccf0643190c82642ca5 | LukaIgnjatovic/Udemy_-_Python_3_-_Deep_Dive_-_Part_1 | /18-python_optimizations_-_interning.py | 1,666 | 4.1875 | 4 | # The "interning" in Python means that some objects are reused on demand.
# At startup, Python (CPython), pre-loads (caches) a global list of integers in the range [-5, 256].
# Any time an integer is referenced in that range, Python will use the cached version of that object.
# These objects are called singletons and t... |
3575af5e174e6e6cb0c7f260e7ae7cdab7b8b2d8 | etainors/py-func | /print_color.py | 3,392 | 3.640625 | 4 | # -*- coding: utf-8 -*-
def print_color(*args, **kwargs):
'''
print_color(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=True)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
... |
c3b9da112443e539a38318da0303030eaa540d2d | frankShih/LeetCodePractice | /95-uniqueBinarySearchTreeII/solution.py | 1,370 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n ==... |
f2338ee9a1b33b7067103428062c571ccc3a52f8 | yfaway/openhab-rules | /legacy-jython-code/aaa_modules/time_utilities.py | 3,290 | 3.875 | 4 | '''
Utility class containing a set of time related functions.
'''
import time
def isInTimeRange(timeRangesString, epochSeconds = None):
'''
Determines if the current time is in the timeRange string.
:param str timeRangesString: one or multiple time range in 24-hour format.\
Example: '10-12', or '... |
1d84b872859458b63787d247c094328210e4ea8c | mohesh3/kids-basic-maths-question-giver-and-evaluator | /kids question giver bot.py | 2,956 | 3.90625 | 4 | #importing random function
import random
#taking name of the player
name=input("plese enter your name : ")
print(f"hi {name} choose your choice")
ans=0
tries=0
#addition function
def addition():
a=random.randint(1,1000)
b=random.randint(1000,900000)
global res,ans,tries,name
print(a,'+... |
f0e83a2e6641f109a1bf1bc66f067ca39cd3d002 | s1rGAY/IBA_course | /Python/Intermediate/Regular in ph/task E.py | 1,018 | 3.984375 | 4 | '''
Найти все вещественные десятичные числа, содержащиеся в строке. Числа, возможно, имеют знак.
Числа могут быть как с десятичной точкой, так и с экспонентой:
+/- целое . целое
+/- целое e/E +/- целое
+/- целое . целое e/E +/- целое
Какие-то "целые" могут отсутствовать, если это допускается синтаксисом Python
Формат в... |
8e22157369e24dadcaaae6c3404f70c25888da35 | verantius/python2019 | /cw2.py | 533 | 3.625 | 4 | #doda 4 imiona
#jezeli kara to wysfietli w ktorym rzedzie
#karo musi byc pierwsza
lista=[]
n = int(input("podaj lie imion chcesz podac: "))
for i in range (1,n+1):
x = input("pdaj imie:> ")
p=x.lower()
lista.append(p)
print("\n")
for y in lista:
print(y)
print("\n")
d = len(lista)
pr... |
f32761a2142fa4bbd2d1a2ed2bf58d3f9d54d1a9 | kzeidlere/patstavigie-darbi | /patstavigais_darbs_3/2.py | 260 | 4.09375 | 4 | start = int(input("Start: "))
end = int(input("End: "))
divider = int(input("Divider: "))
result = 0
for i in range(start, end + 1):
if i % divider == 0:
result += 1
print(f"{result} numbers between {start} and {end} can be divided by {divider}") |
f1edfc9eb9e04aefc9511264f4d184a82f1b3247 | TonySteven/Python | /maxProfit.py | 544 | 3.96875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 11/26/20 15:53
# @Author : StevenL
# @Email : stevenl365404@gmail.com
# @File : maxProfit.py
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
cost, profit = float("+inf"), 0
for price in prices:
... |
def3e7213a00a74dd0a38a4a44bf6e953b5dc4b5 | Samia1743/fibo | /fibo.py | 153 | 3.96875 | 4 | a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
break
i += 1
else: # loop not exited via break
print('prime')
|
195e40d41d9af0b778e6054f69a14b72bc76f114 | sshashan08/01-Basic-DS | /Hashing.py | 1,607 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 16 12:01:36 2016
@author: shashank
Hash Table Implementations
"""
class HashTables:
def __init__(self, Size):
self.size = Size
self.map = [None]*self.size
def get_hash(self, Key):
hash_value = 0
for i in Key:
... |
18784dae3bcdc9a392b10d23246cf50cd44b67de | bennettjs/Blockchain | /blockchain.py | 5,726 | 3.828125 | 4 | ### Understanding blockchains by building one.
# Core concept: chunks of data (blocks) chained together with unique hashes.
# Within each block is a hash backwards to the previous block. This gives the
# chain immutability: If a previous block was compromised, all subsequent
# blocks would have the incorrect hash.
# P... |
23d4cdca0d7c934982a5af0d6f508a2c55d2ec3a | loghmanb/daily-coding-problem | /problem033.py | 1,310 | 4.1875 | 4 | '''
This problem was asked by Microsoft.
Compute the running median of a sequence of numbers. That is, given a stream of
numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle
numbers.
For example, given the sequence [2, 1, ... |
6e186b92a61faaed8a0765ede883ea41674dc8f8 | huyngopt1994/BootCamp | /tic_tac_toe_game/main.py | 1,982 | 3.6875 | 4 | win_combine = [[1,2,3],[1,4,7],[3,6,9],[7,8,9],
[2,5,8],[4,5,6],[1,5,9],[7,5,3]]
total_move =[]
active_player = 1
def display():
print (player)
list=['[ ]']*9
for index, _ in enumerate(list):
for key in player.keys():
if (index+1) in player[key]["move"]:
... |
5ae216f0e9755644ff1070f36947410ca5d0122b | valerpok/hackbio | /abraham_python.py | 323 | 3.59375 | 4 | def humming(a, b):
distance = 0
for i in range(len(a)):
if a[i] != b[i]: distance += 1
return distance
name = "Abraham Adeyemo"
email = "Abrahamrocketmail2@gmail.com"
slack = "@Abraham4"
biostack = "genomics"
twitter = "@Abraham4"
humming_distance = humming(slack, twitter)
print(name, email, slack, biostack, twi... |
c658dc822797048944e7870260923a40b5596584 | gora050/Battleship | /modules/ship.py | 571 | 3.515625 | 4 | class Ship():
def __init__(self, bow, horizontal, length):
self.bow = bow
self.horizontal = horizontal
self.__length = length
self.alive = [1] * length
def __repr__(self):
return str(sum(self.alive))
def __add__(self, other):
return sum(self.alive) + other
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.