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 |
|---|---|---|---|---|---|---|
1dfd1b6ceeaaa4e18804ebdf96697fff2e494a25 | mimichen226/GirlsWhoCode_SIP2018 | /Python/Libraries/DONE_rock_paper_scissors.py | 562 | 4.1875 | 4 | ########### Code for Rock Paper Scissors ############
import random
gestures = ["scissors", "rock", "paper"]
computer = random.choice(gestures)
human = input("Rock, paper, scissors, SHOOT: ")
human = human.lower().lstrip().rstrip()
print("Computer chooses {}".format(computer.upper()))
if computer == human:
prin... |
61ec2165581279f45a6fef750861a56b37a59142 | mimichen226/GirlsWhoCode_SIP2018 | /DataScience/Polarity Word Cloud/sky_words.py | 1,775 | 3.703125 | 4 | '''
In this project, you will visualize the feelings and language used in a set of
Tweets. This starter code loads the appropriate libraries and the Twitter data you'll
need!
'''
import json
from textblob import TextBlob
from wordcloud import WordCloud
import matplotlib.pyplot as plt
#Get the JSON data
tweetFile = op... |
ea774afee1f4834f28579f6bdf11a15865f95822 | Kobebryant2408/Deep-learning-task | /2-3/7.py | 6,779 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 10:03:25 2018
@author: kobe24
任务:利用tensorflow写神经网络
特别注意:第二部分为多类分类问题,一开始要加载数据集并进行数据预处理;
所采用的算法为Adam应用于mini_batch梯度下降(tensorflow实现)
"""
#TensorFlow Tutorial
#1 - Exploring the Tensorflow Library
import numpy as np
import math
import h5py
import matplotlib.pyplo... |
10c56707b774b22f38ca1932bcd28199ee9d42a3 | carlosgeos/protalign | /score.py | 1,445 | 3.53125 | 4 | import re
class Score:
bases = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M',
'F', 'P', 'S', 'T', 'W', 'Y', 'V', 'B', 'Z', 'X', '*'] # Aminoacids
def __init__(self, substitution_mat):
"""Gets the clean sub matrix in a data structure. See parser in
util.sub_mat_... |
30b9c712c5179862c53dae36f7e0a55e3ac858e8 | h1gfun4/algorithms | /python/sorting/merger_sort.py | 962 | 3.75 | 4 | from datetime import datetime
# time complexity 0(n log(n))
# space complexity 0(n)
def sort(data):
result = []
if len(data) < 2:
return data
l_left = len(data) // 2
l_right = len(data) - l_left
left = sort(data[:l_left])
right = sort(data[l_left:])
i = j = 0
while i < l_left ... |
fbd47bbf59d2c0f4c73346da3f909052cd61ba20 | cestmaviela/python_pycharm | /oop/05.py | 310 | 3.6875 | 4 | #构造函数例子
class Person():
#对Persion类进行实例化的时候
#姓名要确定
#年龄要确定
#地址要确定
def __init__(self):
self.name = "NoName"
self.age = 18
self.address ="home"
print("In init func")
#实例化一个人
P = Person(e,c)
|
2d50ea95d3d2037347874b47d51ab394f665240e | mastermndio/pipelines-Q1-2021 | /coding-crash-course/07-arithmetic-operators.py | 203 | 3.875 | 4 | # Addition
print(5 + 5)
# Subtration
print(10 - 4)
#Multiply
print(5 * 2)
#Division
print(20 / 4)
# Modulo/Modulus(Division, but the remainder is returned instead of the division value)
print(20 % 6) |
bff09661d3f94c924370978ec58eba596f184bcc | penelopy/interview_prep | /Basic_Algorithms/reverse_string.py | 389 | 4.3125 | 4 | """ Reverse a string"""
def reverse_string(stringy):
reversed_list = [] #strings are immutable, must convert to list and reverse
reversed_list.extend(stringy)
for i in range(len(reversed_list)/2):
reversed_list[i], reversed_list[-1 - i] = reversed_list[-1 -i], reversed_list[i]
print "".join(... |
c8cce1acee3c59a0b0ad4ff5dc1eb1da7e16f9f2 | penelopy/interview_prep | /Basic_Algorithms/build_matrix.py | 400 | 3.828125 | 4 |
def build_matrix(width, height):
count = 0
matrix = []
for i in range(height): #7 (0, 1, 2, ...6)
row = []
for x in range(width): #5 (0, 1, 2, 3, 4)
count += 1
row.append(count)
matrix.append(row)
return matrix
matrix = build_matrix(5, 7)
def print_... |
b94060751d6869bcc33294ca42c341341e1cb31c | penelopy/interview_prep | /Linked_Lists/linked_lists_2.py | 2,828 | 3.75 | 4 | # from data structure book
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
... |
cfbc7dde425dc29830796447a4472720555c3338 | penelopy/interview_prep | /Recursion/recursion.1.1.py | 5,637 | 4.34375 | 4 | """
Recursion
The Evil Wizard Malloc has attacked you and taken away your ability
to use loops! The only way you can defeat him is by fighting back
using the power of recursion!
Below are function stubs for a variety of functions that are able
to be solved recursively. For this exercise, you are not allowed
to use:
... |
6507cb3071727a87c6c7309f92e7530b74fcc5a2 | penelopy/interview_prep | /Trees_and_Graphs/tree_practice_file.py | 1,262 | 4.25 | 4 | """NOTES AND PRACTICE FILE
Ex. Binary Tree
1
/ \
2 3
Ex. Binary Search Tree
2
/ \
1 3
A binary search is performed on sorted data. With binary trees you use them to quickly look up numbers and compare them. They have quick insertion and lookup.
"""
class BinarySearchTree:
def __init__... |
81eee3e3435e122f2f8019ad8389408d6c1843c2 | aneesha-das/personal-home-assistant | /nanpy/calender.py | 2,612 | 3.546875 | 4 | import datetime
from datetime import timedelta
import texttospeech
def find_date(string):
now=datetime.datetime.now()
dayArray=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
if("today" in string.lower()):
texttospeech.convert("Today is "+str(now.date()))
elif("tomorrow" in string.lower()... |
a6cfcadcba5fb1aba6dc49e653b2ac9625f18de2 | chieinviolet/oop_project2 | /user_name.py | 929 | 4.15625 | 4 | """
※雰囲気コード
データ型宣言: UserName <<python ではクラス型と呼ばれる。
属性:
実際のユーザー名
ルール:
・ユーザー名は4文字以上20文字以下である
できること
・ユーザー名を大文字に変換する
"""
class UserName:
def __init__(self, name):
if not (4 <= len(name) <= 20):
raise ValueError(f'{name}は文字数違反やで!')
self.name = name
def s... |
90c11279b9ba78863d93f84e68b725d86b8cbba0 | ashwinSALGAOCAR/DataStructures | /SinglyLinkedList/SinglyLinkedList.py | 3,960 | 4.03125 | 4 |
#!/usr/bin/python
class Node:
def __init__(self, data):
self.item = data
self.ref = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
n = self.head
while n.ref is not None:
n ... |
b1a60ba40ecb8f18e25d7d08e8f5f818cdf23484 | bavipanda/Bavithra | /linkedlist.py | 457 | 4.03125 | 4 | class linkedListNode:
def __init__(self,value,nextNode=None):
self.value = value
self.nextNode = nextNode
node1 = linkedListNode("3")
node2 = linkedListNode("7")
node3 = linkedListNode("10")
node4 = linkedListNode("15")
node1.nextNode=node2
node2.nextNode=node3
node3.nextNode=node4
currentNode = node1
while Tru... |
29b81abb43d6167f5ead8d625e705a9675831b8d | bavipanda/Bavithra | /check the given is alphabets or digits.py | 207 | 4.25 | 4 | ch = input()
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print("is an Alphabet")
elif(ch >= '0' and ch <= '9'):
print("is a Digit")
else:
print("is Not an Alphabet or a Digit")
|
3d5a69edb1d8f512f19e1d3085f6ac93d62211b9 | bavipanda/Bavithra | /calculate ci.py | 303 | 3.765625 | 4 | def compound_interest(principle, rate, time):
result = principle * (pow((1 + rate / 100), time))
return result
p,r,t =map(float,input().split())
amount = compound_interest(p, r, t)
interest = amount - p
print("Compound amount is %.2f" % amount)
print("Compound interest is %.2f" % interest)
|
9c98306ef0e9e475f6aa30be784b419a43ebcc5f | bavipanda/Bavithra | /max num between two nums.py | 96 | 3.734375 | 4 | num1 = 10
num2 = 14
if (num1 >= num2):
largest = num1
else:
largest = num2
print(largest)
|
48d24b0d4b03f7e4d733833ddb214cf8ba8c85f1 | bavipanda/Bavithra | /sumN.py | 61 | 3.515625 | 4 |
b=int(input())
t=0
while b>0:
t=t+b
b=b-1;
print(t)
|
88346ac4d3d3a16a3c05aba3b4d9723fab2cb88d | rosedurians/Lesson10 | /Problem1.py | 312 | 3.640625 | 4 | import time
print('-'*65)
print('Life Decision Bot:')
print()
answer = input('Are you having a good morning? ')
if answer == 'Yes':
print('Well...')
time.sleep(1)
print('It is gonna get a LOT worse...' )
time.sleep(1)
else:
print('Sorry to hear that, chap')
print('Go see a movie later.' )
print('-'*65)
|
0ae7ac322f0a1f9deaffe3c438a568d1844deaef | ageller/UniviewIceCube | /testing/code/odf_tarball/python/event_time.py | 2,526 | 4.09375 | 4 | from datetime import timedelta, datetime
import sys
class EventTime:
"""
The EventTime class. The purpose of this class is to translate IceCube time,
which constist of the year and tenths of nanoseconds since the beginning of the
year, to a format that is more user-friendly. This class uses python's
... |
bca3068971767f5404728e68a86d8fae065463a9 | Ghelpagunsan/python_exercise | /7.py | 130 | 3.5625 | 4 | def arr_to_dict(key, val):
a = dict(zip(key,val))
return str(a)
print(arr_to_dict(['moe', 'larry', 'curly'], [30,40,50])) |
1cdffd615c15e79f2f2cf89a81e6aceddff3eed6 | Ghelpagunsan/python_exercise | /8.py | 127 | 3.921875 | 4 | def duplicate(x):
y = []
for i in x:
if i not in y:
y.append(i)
y.sort()
return y
print(duplicate([1,3,2,3,2,6,2])) |
2bec8e896b556bc8077e14e4ee64cec5957a6ef8 | ak14249/Python | /dictionary.py | 578 | 4.25 | 4 | myDict={"Class" : "Engineer", "Name" : "Ayush", "Age" : "25"}
print(myDict)
print(myDict["Class"])
print(myDict.get("Name"))
print(myDict.values())
for val in myDict:
print(myDict[val])
for x,y in myDict.items():
print(x,y)
myDict["Name"]="Prateek"
print(myDict)
myDict["Designation"]="Linux Admin"
print(myDict)
... |
98129a80b37c6798dc3af6129e4abf7a8bfd875c | ak14249/Python | /while_loop.py | 1,711 | 3.984375 | 4 | print("Que: Write a while loop that adds all the numbers up to 10 (inclusive).")
counter=0
total=0
while counter <= 10:
total= total+counter
counter= counter+1
print(total)
print("\n=========================================================\n")
print("Que: Using while loop, if statement and str() function; i... |
2ee39e37dec9a9c5df1f70683a5a01d2a6935f09 | ak14249/Python | /map_function.py | 2,336 | 4.40625 | 4 | print("Que: Write a map function that adds plus 5 to each item in the list.\n")
lst1=[10, 20, 30, 40, 50, 60]
lst2=list(map(lambda x:x+5,lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Write a map function that returns the squares of the items in the list.\n")
l... |
bcb600fbf2ea852a613717687f51785a41b35c72 | edgarleonardo/FibonacciFn | /fibonacci.py | 969 | 3.90625 | 4 | import unittest
def FibonacciFn(val):
if val <= 0:
return 0
elif val == 1:
return 1
else:
return FibonacciFn(val - 1) + FibonacciFn(val - 2)
class Tests(unittest.TestCase):
def test_right_result(self):
rightValue = 55
testValue = 10
testResult = Fibonac... |
64e7a8ee6f3f3b44d05271552a10f61e76572109 | tranc99/python-metaprogramming | /backupfinal.py | 1,029 | 4 | 4 | # final.py
class Final(type):
def __new__(cls, name, bases, attr):
# Final cannot be subclassed
# check that a Final class has not been passed as a base
# if so, raise error, else, create the new class with Final attributes
type_arr = [type(x) for x in bases]
for i in type_a... |
1a68fbc863666ffaae39c89691371b1bc349cdeb | hanxuwu/Learning-Python | /Principles of Programming/Assignment/Assignment1/ASS question4.files/poker_dice.py | 7,855 | 3.609375 | 4 | #from random import seed
from random import randint
from collections import Counter
def play():
def generate_poker_dice(nb_dice):
dice_card=['Ace','King','Queen','Jack','10','9']
poker_dice_dict={i:dice_card[i] for i in range(6)}
poker_dice_reverse_dict={dice_card[i]:i for i in range(... |
397b1184d928a865df44e214ac14fe0fb46662e2 | hanxuwu/Learning-Python | /Principles of Programming/Assignment/Assignment1/ASS question1.files/pivoting_die.py | 2,322 | 3.765625 | 4 | # Insert your code here
while True:
try:
N = int(input('Enter the desired goal cell number: '))
if N <= 0 :
raise ValueError('Incorrect value, try again')
break
except ValueError:
print('Incorrect value, try again')
def Direction_generator():
sum1=2
temp=5
... |
6098028a07d94854e273ca763d3ff1f566ea6c4d | karthikrk1/python_utils | /primeSieve.py | 1,330 | 4.34375 | 4 | #!/bin/python3
'''
This is an implementation of the sieve of eratosthenes. It is created for n=10^6 (Default Value).
To use this in the program, please import this program as import primeSieve and call the default buildSieve method
Author: Karthik Ramakrishnan
'''
def buildSieve(N=1000000):
'''
This function... |
52eeb2501477aaef012fc450a3e444a7382cee90 | pokotsun/chaos-theory | /IFS_atractor.py | 1,528 | 3.59375 | 4 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import randint
def W(point, func):
x, y = point
return func(x, y)
def W1(point):
return W(point, (lambda x, y: (0.836*x + 0.044*y, -0.044*x + 0.836*y + 0.169)))
def W2(point):
return W(point, (lambda x, y: (-0.141*x... |
df576aef12698e9422e0f199c1d7f7f901f4e6c5 | imm0nkey/Udacity_SelfDrivingCarTerm1 | /04_MiniFlow/04_5_ForwardPropagation_KahnsAlgorithm.py | 2,491 | 3.796875 | 4 | """
This script builds and runs a graph with miniflow.
There is no need to change anything to solve this quiz!
However, feel free to play with the network! Can you also
build a network that solves the equation below?
(x + y) + y
"""
"""
Test your network here!
No need to change this code, but feel free to tweak it
... |
eb347c93656487bfd5bcee469a46b63f528dbf22 | AzidicArcturus/PythonProjects | /Binary tree maker 08 01 2017 v5 DJM.py | 3,522 | 3.765625 | 4 | class Node:
def __init__(self, value):
self.l = None
self.r = None
self.v = value
self.isSubtree = True
def info(self):
writeFormat = ("""==== NODE {0} INFO ====\n
Left value: {1}\n
Right value: {2}\n
Is it a subtree?: {3}\n
============================
"""
... |
af8e0ab5c3cabbda9b75721c81492e285345c9d3 | brianhoang7/6a | /find_median.py | 940 | 4.28125 | 4 | # Author: Brian Hoang
# Date: 11/06/2019
# Description: function that takes list as parameter and finds the median of that list
#function takes list as parameter
def find_median(my_list):
#sorts list from least to greatest
my_list.sort()
#distinguishes even number of items in list
if len(my_list) % 2 ... |
d4035c9951a071df58fc65774292077ed0c9351d | mokhan778/Cryptography | /CrackCeasar.py | 665 | 3.546875 | 4 | import sys
f = open(sys.argv[1], "r")
contents = f.read().lower()
f.close()
# print contents
contents.lower()
fin = open(sys.argv[2], "r")
d = fin.readlines()
fin.close()
letters = 'abcdefghijklmnopqrstuvwxyz'
for key in range(len(letters)):
translated = ''
for symbol in contents:
if symbol in lett... |
6fd8a8081b74902c3b9ef0e1843e13449f774e7d | gtgrover/pi_sense_sendpic | /sender_remote.py | 1,305 | 3.546875 | 4 | #!/usr/bin/env python
#Socket client example in python
import socket #for sockets
import sys
import importlib
# GET THE PICTURE MODULE TO LOAD, FROM THE COMMAND LINE
if len(sys.argv) > 1:
module="."+sys.argv[1]
else:
module=".arraise"
# GET THE IMAGE, USE IMPORT MODULES TO LOAD A PICTURE AS A PY MODULE
svar... |
7cae3655a3f9df12dc2e36ad002f69058d18d69d | ShaoxiongYuan/PycharmProjects | /4. Python 爬虫工程师/2. 数据结构/Day12/merge_sort.py | 711 | 4.03125 | 4 | """
归并排序
"""
def merge_sort(li):
if len(li) == 1:
return li
# 第1步:先分
mid = len(li) // 2
left = li[:mid]
right = li[mid:]
left_li = merge_sort(left)
right_li = merge_sort(right)
# 第2步:再合
print(left_li, right_li)
return merge(left_li, right_li)
def merge(left_li, rig... |
7230d4dbc311d52d6dadc2bab59363ca3ba25d99 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day07/exercise04.py | 230 | 3.96875 | 4 | list1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
list2 = []
for c in range(len(list1[0])):
list3 = []
for r in range(len(list1)):
list3.append(list1[r][c])
list2.append(list3)
print(list2)
|
1a9632fbbea84d21c56b09f557b898c7f8abb1bf | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day07/exercise02.py | 153 | 3.859375 | 4 | for r in range(4):
for c in range(5):
if r % 2 == 1:
print("*", end="")
else:
print("#", end="")
print()
|
2272040aad3b017f3170e7c8b06b93b65381920d | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/3. Python 高级/Day16/exercise05.py | 950 | 3.5 | 4 | class Skill:
def __init__(self, name="", duration=0, atk=0, cost_sp=0):
self.name = name
self.duration = duration
self.atk = atk
self.cost_sp = cost_sp
def __str__(self):
return "技能名称:%s,时间:%d,攻击力:%d,消耗法力:%d" % (self.name, self.duration, self.atk, self.cost_sp)
list_sk... |
e542b483144b13c5a9eb03f6d7a5b408508a3e3c | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day04/exercise02.py | 190 | 4.15625 | 4 | for i in range(3):
print(i)
for i in range(6, 11):
print(i)
for i in range(2, 9, 2):
print(i)
for i in range(9, 2, -1):
print(i)
for i in range(-1, -7, -1):
print(i)
|
2af381a24ca8dba1665482160abbe39ee5a88ae5 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day05/exercise01.py | 293 | 3.8125 | 4 | list_score = []
while True:
score = input("请输入成绩:")
if score == "":
break
else:
list_score.append(int(score))
print("最高分是%d分,最低分是%d分,平均分是%f分。" % (max(list_score), min(list_score), sum(list_score) / len(list_score)))
|
4d96c1e2e70ba6350dd2024ed87cedf1592a9f0f | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/3. Python 高级/Day16/exercise02.py | 134 | 3.578125 | 4 | list1 = ["唐僧", "猪八戒", "悟空"]
for i, item in enumerate(list1):
if len(item) > 2:
list1[i] = ""
print(list1)
|
38b64f3dc626ea64d8910aed8b7c61db8d171437 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day08/demo04.py | 937 | 4 | 4 | """
形式参数
"""
# 1.位置形参:必选
def func01(p1, p2, p3):
print(p1)
print(p2)
print(p3)
# 2.默认形参:可选
def func02(p1=True, p2="", p3=0):
print(p1)
print(p2)
print(p3)
func02()
func02(False, "a", 10)
func02(p2="A")
func02(False, p3="C")
# 3.星号元组形参:合(位置)
# 以args命名
def func03(*p1):
print(p1)
func... |
46d61b5a79836698710c3a4f58810eab61f89314 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day08/exercise06.py | 354 | 3.859375 | 4 | def is_prime(i):
"""
:param i:
:return:
"""
for a in range(2, i):
if i % a == 0:
return False
return True
def all_prime_number(start, end):
"""
:param start:
:param end:
:return:
"""
return [item for item in range(start, end + 1) if is_prime(item)]... |
e523c745957b1e64950dd245254982470b3a7876 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day05/exercise03.py | 247 | 3.71875 | 4 | list1 = []
i = 0
while True:
num = input("请输入整数:")
if num == "":
break
else:
list1.append(int(num))
while i < len(list1):
if list1[i] % 2 == 0:
i += 1
else:
del list1[i]
print(list1)
|
aa8a0bbf146ab7f680daa2d31cc8409c067c6d0d | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/2. 面向对象/Day10/exercise01.py | 1,442 | 3.59375 | 4 | class Enemy:
def __init__(self, name, blood, defense, attack):
self.name = name
self.blood = blood
self.defense = defense
self.attack = attack
def injure(self):
self.blood -= 100
def print_self(self):
# print(self.__dict__)
print(self.name, self.bloo... |
49db0b19d53d5c62abb8c6a71cc8f55e7d4fb291 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day06/exercise03.py | 426 | 3.828125 | 4 | dict1 = {}
while True:
name = input("请输入学生姓名:")
if name == "":
break
age = input("请输入学生年龄:")
sex = input("请输入学生性别:")
score = input("请输入学生成绩:")
dict1[name] = [age, sex, score]
for k, v in dict1.items():
print(f"{k}的年龄是{v[0]},性别是{v[1]},成绩是{v[2]}。")
if "唐僧" in dict1:
print(dict1["唐... |
6dfe42ee3764645d0505e904ae57282e51999227 | mrsyafapri/algorithms-in-python | /searching/sequential_search.py | 1,239 | 3.875 | 4 | def sequential_search(data, key):
# Lakukan perulangan array (for) sebanyak data yang ada
for i in range(len(data)):
# Jika angka yang dicari (key) ditemukan (sama dengan) pada data index ke i (data[i])
if data[i] == key:
# Kembalikan nilai index-nya
return i
# Jika a... |
dc356fbc3cd5a6aa6a36ed26588e5908e9ddb513 | BohanHsu/leetcode | /binaryTreeLevelOrderTraversalII.py | 1,050 | 3.5625 | 4 | import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.level = []
# @param root, a tree node
# @return a list of lists of integers
#def levelOrder(self, root):
def levelOrderBottom(sel... |
1802574c458bfdb3769fae2da731079f7151e4bc | davidabelman/rhyme | /wordnet/create_collocations.py | 3,124 | 3.578125 | 4 | """
This file creates the collocation dictionary pickle
TODO: create proper collocation score based on P(x+y)/P(x)P(y)
Would need to record number of occurances of each word individually, as well as how many collocations per word
When calculating MI, look up number of collocations between words, and number of each word... |
38976e6c3eff66e21a6c289279481ed6adb0596c | volchey/Python | /N-puzzle/State.py | 3,080 | 3.59375 | 4 | #/usr/bin/python
import math
from Functions import *
from Puzzle import *
class State():
def __init__(self, func: Functions, puzzle: Puzzle, parent, is_debug = False):
self.func = func
self.puzzle = puzzle
self.parent = parent
self.is_debug ... |
cf5cd180448cc2cad4fb1bd4f4d2a308578e18b4 | Mauricio-KND/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 228 | 3.609375 | 4 | #!/usr/bin/python3
""" Initializes island_perimeter function. """
def island_perimeter(grid):
""" Returns the perimeter of the island described in grid."""
width = 3
height = 3
return (2 * height + 2 * width)
|
2a1089b37e358e1cdc431b046479087c4b3bec9b | yuanhaozuogenius/CS325 | /HW1/Problem4/insertsort.py | 509 | 3.828125 | 4 | def insertionSort(array):
for j in xrange(1,len(array)):
key = array[j]
i = j - 1
while (i > -1) and (array[i] > key):
array[i + 1] = array[i]
i = i - 1
array[i + 1] = key
dataFile = open("data.txt", "r");
outFile = open("insert.out", "w");
for line in dataFile:
lineArray = list(map(int,line.spli... |
10d3317baab6a3eb669e6c7583033065bb40fbda | wovo/micro-python | /generic/blink.py | 838 | 3.703125 | 4 | # blink the blue pin
import time
from machine import Pin
print( "servo demo" )
def pulse( pin, delay1, delay2 ):
pin.value( 1 )
time.sleep( delay1 )
pin.value( 0 )
time.sleep( delay2 )
def servo_pulse( pin_nr, position ):
"""
Send a servo pulse on the specified gpio pin
that causes the servo t... |
aba7e14b2b5e8f909e45606803f503ab71247377 | pwnfooj716/cube-timer | /cube_data.py | 1,012 | 3.671875 | 4 | import random
import time
moves = ("U", "D", "L", "R", "F", "B")
modifiers = ("", "'", "2")
def generate_scramble(length):
scramble = ""
prev_move = ""
for i in range(length):
new_move = random.choice(moves)
while new_move == prev_move:
new_move = random.choice(moves)
s... |
a42c2b0403bb89166149ac82f518389a3eff497c | LarryGeorges-Muala/Virtual-ATM-Complete | /Virtual_ATM.py | 10,246 | 3.609375 | 4 | #App Name: Virtual ATM Login and Menu
#Login Password: 12345
#Python Version 3.5
#Developper: Larry Georges Muala
import tkinter
from tkinter import messagebox
import time
#atm menu instantiation
window = tkinter.Tk()
#hide menu window until login confirmed
window.withdraw()
#window title
window.tit... |
bbacdc29ca3d75eeaee34e1d9800e57b390bd83c | pastcyber/Tuplesweek4 | /main.py | 917 | 4.1875 | 4 | value = (5, 4, 2000, 2.51, 8, 9, 151)
def menu():
global value
option = ''
while(option != 6):
print('*** Tuple example ***')
print('1. Print Tuple ***')
print('2. Loop over tuple')
print('3. Copy Tuple')
print('4. Convert to list')
print('5. Sort Tuple')
print('6. Exit ***')
op... |
05352ffe93095cf14fa47fb6cd1b4ab0f381d1b0 | duikboot/snippets | /closure.py | 320 | 3.546875 | 4 | import functools
def outer(outer_arg):
def inner(inner_arg):
return outer_arg + inner_arg
return inner
def func(a, b, c):
return a, b, c
p_func = functools.partial(func, 10)
print(p_func(3, 4))
l = ["a", "bb", "f", "sdf"]
print(sorted(l, key=len))
print(sorted(l, key=functools.partial(len)))
|
4007c7a100ebd1386e0966bfd8524c7ff5f52ff1 | MarineGEO/template-utilities | /csv-class-converter.py | 1,285 | 3.9375 | 4 | # converts a csv file of vocab or field items into a python class format
import csv
import chardet
# user inputs - path to csv file and the desired class type
csv_file = "/Users/ambell/Documents/MarineGEO-template-workbooks/fish-seines/fields_v0.0.1.csv"
classType = "Field" # "Field or "Vocab"
# grab the encoding of... |
68f3ceca69fde44166b76173c7177fcdd40a825f | jose-dev/teaching_python | /src/test/game/hangman/test_hangman_game.py | 2,740 | 3.546875 | 4 | from game.hangman import hangman_utils
import unittest
class HangmanUtilsTest(unittest.TestCase):
def test_read_file_with_words(self):
filename = 'resources/hello_world.txt'
expected = ['hello', 'world']
self.assertEqual(hangman_utils.read_file_with_words(filename), expected)
def test... |
5269721b75e778a4666e512b4b6b9593138ce495 | quocdat32461997/Inverted_Index | /inverted_index.py | 1,283 | 3.890625 | 4 |
#word_index:
'''
word_name: name of word
word_pos: a dictionary containing key - text_name word in and value - pos of each word frequency in
'''
class word_index():
#__inint__()
def __init__(self, w_name, file_name, index):
self.word_name = w_name
self.list_file = {file_name:[... |
deebe2698e3613a642c35cb4b4224ebf110d8b62 | psnagra13/Autify-Assignment | /utilities/webpage_downloader.py | 1,058 | 3.515625 | 4 | from urllib.request import urlopen
import bs4
class WebpageDownloader:
'''
downloadWebPageFromUrl(weburl)
downloads the html for the url provided and return result as a string
weburl : string
url of the webpage to be downloaded
return string
... |
4b34b354cca966eb3465259a70de793d3051ad92 | ZHUDEJUN1985/reinforcement_learning | /MonteCarlo.py | 4,029 | 3.609375 | 4 | #coding=utf-8
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
ACTION = ['hit','stick']
TERMINAL = (-1,-1)
class Blackjack(object):
def __init__(self):
self.card_num = 0
self.sum = 0
self.has_ace = False
... |
b860f7e3cd10c3efe9f523f997649bc90c8adbcf | codeAligned/DataStructures-1 | /LinkedList.py | 1,356 | 3.953125 | 4 | class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_next(self, n):
self.next = n
def __str__(self):
return str(self.data)
class LinkedList(object):
def __init__(self, hea... |
0aa52b70e6dbb83a5813aab14ac43fff09c89c30 | codeAligned/DataStructures-1 | /Tree.py | 350 | 3.53125 | 4 | class node(object):
def __init__(self, name, parent=-1):
self.name = name
self.parent = parent
self.children = []
def getName(self):
return self.name
def getParent(self):
return self.parent
def getChildren(self):
return self.children
def setParent(self, p):
self.parent = p
def addChild(self, c)... |
c6dd4388defe4acd6b40b6e500198f10c4cae884 | dovilemureikaite/python_unit_2 | /MODULE_2/module_2.py | 14,715 | 3.78125 | 4 | # Mod2_2-2.1_Intro_Python.ipynb
# _____________________________________________________
#
# TASK 1
#
# [ ] create team_names list and populate with 3-5 team name strings
team_names = ["John", "Steve", "Paul", "Roger"]
# [ ] print the list
print(team_names)
# _________________
# [ ] Create a list mix_list with numbers... |
d6d8475b71e0a55514fc8e36d5735a9fd6954a29 | LukazDane/SPD-2.31-Testing-and-Architecture | /lab/refactoring/decompose_conditional2.py | 1,639 | 3.875 | 4 | # By Kami Bigdely
# Decompose conditional
# Reference: https://www.healthline.com/health/high-cholesterol/levels-by-age
# Blood test analysis program
total_cholesterol = 70
low_cholesterol = total_cholesterol < 200
medium_cholesterol = 200 < total_cholesterol < 240
high_cholesterol = 200 < total_cholesterol > 240
ldl... |
3f22bc4d92722c071fea421aa266909f92e07e1e | wcafricanus/digitrecog | /datasourcetest.py | 434 | 3.625 | 4 | from tensorflow.examples.tutorials.mnist import input_data as mnist_data
# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)
mnist = mnist_data.read_data_sets("data", one_hot=True, reshape=False, validation_size=0)
def training_step(i, update_test_data, update_train_da... |
34723a3a18561e3083c4c416f40e00fdff04aecc | janniss91/SudokuSolver | /solver.py | 16,688 | 3.75 | 4 | import argparse
import csv
from collections import Counter
from copy import deepcopy
from typing import List
from typing import Tuple
from typing import Union
NUMBERS = [str(number) for number in range(10)]
class SudokuTable:
def __init__(self, file_name: str):
self.rows = []
self.columns = [[] ... |
1fd29fd8d121e75e605be7ac7023cd2d736c86e7 | YOOY/leetcode_notes | /problem/maximum_distance_between_a_pair_of_values.py | 462 | 3.84375 | 4 | # no need to loop nums2 from the beginning for every i
# nums1, nums2 are both decreasing
# so for i we found the max j and for i+1, we can start from j
def maxDistance(nums1, nums2):
maximum = 0
j = -1
for i, num in enumerate(nums1):
while j+1 < len(nums2) and nums2[j+1] >= num:
j += 1
... |
456cee03a3ab77e658e35bac46d22aa2a0bf3a17 | YOOY/leetcode_notes | /problem/find_first_and_last_position_of_element_in_sorted_array.py | 412 | 3.59375 | 4 | def searchRange(nums, target):
l = 0
r = len(nums) - 1
first = last = None
while (l <= r) and (not first or not last):
if nums[l] == target and not first:
first = l
if nums[r] == target and not last:
last = r
if not first:
l += 1
if not... |
70f84fb61188d4a12f42bc5ab4e90f190dde764b | YOOY/leetcode_notes | /problem/check_if_number_is_a_sum_of_powers_of_three.py | 292 | 4.15625 | 4 | # check if n can be formed by 3**0 + 3**1 + ... + 3**n
# if any r equals to 2 it means we need 2 * (3 ** n) which should be false
def checkPowersOfThree(n):
while n > 1:
n, r = divmod(n, 3)
if r == 2:
return False
return True
print(checkPowersOfThree(21)) |
2b4f8a9b261130a0675d205f48e1e3369c53adfe | sexyjoon/fluent-python | /14-iterable_iterator_generator/sentence_iter.py | 1,209 | 3.625 | 4 | import re
import reprlib
import collections
RE_WORD = re.compile('\w+')
class Sentence:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __iter__(self):
return SentenceIterator(self.words)
def __repr__(self):
return 'Sentence(%s)' % repr... |
bea9eea2add31255dcae3567470261bce512c084 | siddhu15798/git_intro | /file01.py | 459 | 3.734375 | 4 | from itertools import permutations
def Permutations(str):
PL = []
for i in range(1, len(str)+1):
n = permutations(str, i)
for j in list(n):
PL.append(''.join(j))
return PL
def isPalindrome(n):
x = []
for i in n:
str1 = i
str2 = str1[::-1]
if st... |
07815b759c627172f59ac80c7bc403f6b9b48a90 | Aditi-Billore/leetcode_may_challenge | /Week2/trie.py | 2,258 | 4.1875 | 4 | # Implementation of trie, prefix tree that stores string keys in tree. It is used for information retrieval.
#
class TrieNode:
def __init__(self):
self.children = [None] *26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
... |
0c57c1bef0749c0aabb4b45c52919ff043c7123f | Aditi-Billore/leetcode_may_challenge | /Week3/kadaneAlgorithm.py | 646 | 3.84375 | 4 | #maximum sum subarray using kedane's algorithm
def maximumSubArray(list1):
currentSum = 0
currentStart = currentEnd = 0
maxStart = maxEnd = 0
maxSum = 0
for currentEnd, value in enumerate(list1):
if currentSum <= 0:
currentStart = currentEnd
currentSum += value
... |
df16fceb937c02f96a65eeb1089b93a39f068bfb | RobertLarsen/rlib | /rlib/netstring.py | 1,129 | 3.84375 | 4 | def create(s):
r"""
Creates and returns a netstring from the specified data which may be binary.
>>> create('Hello, World!')
'13:Hello, World!,'
>>> create('\x00\x01')
'2:\x00\x01,'
>>> create(create("Hello") + create("World"))
'16:5:Hello,5:World,,'
"""
return "%d:%s," % (len(s)... |
253cde8fb2bbd82354f594b724cdd8617d537b3a | myyan92/topology_learning | /attention_layer.py | 2,993 | 3.515625 | 4 | # modified from the official model repo
import tensorflow as tf
def split_heads(x, num_heads):
"""Split x into different heads, and transpose the resulting value.
The tensor is transposed to insure the inner dimensions hold the correct
values during the matrix multiplication.
Args:
x: A tensor w... |
7b9424dc3a0cf43e35df9557d8739d48587ad0a1 | jcarlosbatista/pacote-desafios-pythonicos | /07_front_back.py | 2,802 | 4.125 | 4 | """
07. front_back
Considere dividir uma string em duas metades.
Caso o comprimento seja par, a metade da frente e de trás tem o mesmo tamanho.
Caso o comprimento seja impar, o caracter extra fica na metade da frente.
Exemplo: 'abcde', a metade da frente é 'abc' e a de trás é 'de'.
Finalmente, dadas duas strings a e... |
38e3fb5f1b3bf74483e4c1ab06ff4b9b322689f2 | yogeshchandra12345/DataStructurePython | /dijkstra.py | 2,329 | 3.78125 | 4 | import sys
import time
class vertex:
def __init__(self,node):
self.id=node
self.adjacent={}
self.visited=False
self.previous=None
self.distance=sys.maxsize
def __lt__(self, other):
if isinstance(other,self.__class__):
return self.distance < other.dista... |
7b0df7e21d32c7077d97329908cf3258a54fe473 | yogeshchandra12345/DataStructurePython | /dynamic_programming/factorial.py | 381 | 3.84375 | 4 | def factorial(n):
if n < 0:
return -1
if n==0 or n==1:
return 1
else:
return n*factorial(n-1)
print(factorial(-1))
def factorial_dp(n):
result = [0 for _ in range(n+1)]
if n > 0:
result[0] = 1
for i in range(1, n+1):
result[i] = i*result[i-1]
... |
cd5bf438bfb38ab76628db215b89e7f4662a6a79 | SoumitraAgarwal/Scilab-gsoc | /Community bonding /FacialLandmark.py | 1,262 | 3.5625 | 4 | // Importing necessary python libraries
pyImport numpy
np = numpy;
py = pyBuiltin();
pyImport pandas
pd = pandas;
//pyImport matplotlib
//plt = matplotlib.pyplot;
// Importing the data set
data_X_train = pd.read_csv('data_X_train.csv');
data_X_test = pd.read_csv('data_X_test.csv');
data_y_train = pd.read_csv('data_y... |
56eb91b4bacad0e60adbd837af2c56297542b7b4 | SoumitraAgarwal/Scilab-gsoc | /Machine_cloud/macros/loader/Scripts/custom.py | 1,230 | 3.671875 | 4 | # Simple Linear Regression
# Importing the libraries
import numpy as np
import pandas as pd
import pickle
# Importing the dataset
dataset = pd.read_csv('/home/soumitra/Working/Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and T... |
b066c946378798e05642ae244c2d8dbc80680108 | pranayfating/EBP | /SLP.py | 1,137 | 3.546875 | 4 | from perceptron import Perceptron
BLUE = 1
RED = 0
LMSE = 0.001
def normalise(data):
temp_list = []
for entry in data:
entry_list = []
for value in entry[0]:
entry_list.append(float(value*0.003921568))
temp_list.append([entry_list, entry[1]])
return temp_li... |
1e40aae1aa99bc4b515900b2badf2236545bb34c | alaguillog/python-misc | /python-scripts/password_manager.py | 1,432 | 4 | 4 | #author: kaywinnet
#A very very basic imitation of a password manager program
class Password_manager:
def __init__(self, username):
self.username = username
self.old_passwords = ["password", "1234", "asdfghjkl"] #if there's an issue set this as a class attribute
def get_password(self... |
b591729dcfbbb565158ad7a7541b8bfaa0378cda | Tu7ex/Python_Programming | /Clase1.py | 2,565 | 4.21875 | 4 | '''Comentario'''
#adsasd
var = 1
print(type(var)) #Muestra el tipo de variable que es.
print("")
# Cadena de caracteres
cadena1="Clase n° 1"
cadena2='Curzo de Python'
print(type(cadena1))
# Boolean (True -> V, False -> F)
encendido= True
print(type(encendido))
print("")
# Operadores aritméticos
# Suma
x=20
y=5
res = x... |
d92124e419f0c59cbe4f0e421fdcbdaf9a2133a7 | thatchloe/MIT_problem_sets | /pset3_MIT_6.001x/hangman.py | 2,713 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 18:30:22 2018
@author: luong hoang anh
"""
#problemset3_hangman.py
#Player will have to guess a secret word which is randomly chosen by computer
#Player is allowed 8 guesses and only able to submit one letter at a time
#One guess will be only lost when you guess incorr... |
239d29e78ee6f68d72bcda0a08f25d62ee223b7d | ellezv/data_structures | /src/trie_tree.py | 2,588 | 4.1875 | 4 | """Implementation of a Trie tree."""
class TrieTree(object):
"""."""
def __init__(self):
"""Instantiate a Trie tree."""
self._root = {}
self._size = 0
def insert(self, iter):
"""Insert a string in the trie tree."""
if type(iter) is str:
if not self.con... |
839d263f7eda93ca3e214cc763d12a2abc6c4208 | ellezv/data_structures | /src/tests/test_insertion_sort.py | 608 | 3.796875 | 4 | """Test file for insertion sort."""
import math
def test_simple_list():
"""Test sort on a small, simple list."""
from insertion_sort import insertion_sort
arr = [1, 2, 3, 4]
sort = insertion_sort(arr)
assert sort == [4, 3, 2, 1]
def test_far_more_complex_list():
"""Test sort on a much larg... |
1be3b1d12f8c1e47892dcf00b68be6912dbe20b9 | ellezv/data_structures | /src/tests/test_linked_list.py | 3,007 | 3.625 | 4 | """Tests for our linked_list module."""
import pytest
def test_linked_list():
"""Test the instantiation of our Linked List."""
from linked_list import LinkedList
lst = LinkedList()
if lst.head is None:
pass
def test_node():
"""Test the instantiation of a node."""
from linked_list im... |
7f8a2b90387776eeeea1aa75e6ef9e57fc111de6 | techiesourav/Python_For_Informatics_execrcise | /Chapter02/exercise_2.4.py | 956 | 4.09375 | 4 | # Exercise 2.4
# Exercise 2.4 Assume that we execute the following assignment statements:
#
# width = 17
# height = 12.0
#
# For each of the following expressions, write the value of the expression and the
# type (of the value of the expression).
#
# 1. width/2
# 2. width/2.0
# 3. height/3
# 4. 1 ... |
3341eb0c172a0f32390d51dbbc82b31b13578572 | pglen/pgpygtk | /neural/neural-009/neuutil.py | 720 | 3.78125 | 4 | #!/usr/bin/env python
import random, exceptions
# ------------------------------------------------------------------------
# Deliver a random member of an array
def randmemb(var):
if type(var) != type( () ) and type(var) != type([]) :
raise exceptions.ValueError("Must be a list / array")
rnd = rando... |
db796902ced60e67d4deeb45cc72f0cac5ff1ee1 | ParkYewon95/Git | /Python/Basic/06_loop.py | 267 | 3.90625 | 4 | menus = [1,2,3,4]
for menu in menus :
print(menu)
print("===================")
for i in range(1,10,2):
print(i)
print("===================")
for i in range(4):
print(menus[i])
print("===================")
test = range(4)
for i in test:
print(i) |
eb086aba05cfd1b5afdfc064b10c996d658ffec8 | piehld/590PZ-Project | /dict_sources/preprocess_wordnet_dict.py | 1,648 | 3.703125 | 4 | import os
"""
Script to pre-process/clean up words from WordNet data, filtering out only those that are of a relevant length, no numbers, no underscores, etc.
Will create a new smaller text file in the same readable format as other dictionary source files used.
Idea for efficient removal of special characters from h... |
d11c722ff8f47a4f42340284190e357dadc45bbf | rydens/halfbday | /dayssince | 721 | 3.84375 | 4 | #!/usr/bin/env python3
import skilstak.colors as c
import datetime as dt
import time as t
import sys
print(c.green + "How many days since your birth? Let's find out!")
print()
print('Birthday, in integers, put a zero if needed:')
birthyear = input(c.red + 'Year: ' + c.cyan)
birthmonth = input(c.red + 'Month: ' + c.cy... |
efd4e42ddf6602acbb3da91fba07ecdc2485a6a2 | sanchit-bhalla/pyhton-programs | /simple_game.py | 1,072 | 4.09375 | 4 | import random
def Computer_code():
"""
it generates a list of 3 digits
"""
digits=[str(num) for num in range(10)]
random.shuffle(digits)
return digits[:3]
def generate_clues(comp_code,userguess):
'''
Close: You've guessed a correct digit but in the wrong position
M... |
64f36d53d21666be487100bd9d919afd18ece35c | ginchando/SimplePython | /CheckLeapYear/check.py | 731 | 4.1875 | 4 | year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
isLeapYear = False
if year % 400 == 0:
isLeapYear = True
elif year % 4 == 0 and year % 100 != 0:
isLeapYear = True
result = "is" if isLeapYear else "is not"
print(f"{year} {result} a leap year")
month_name = {
1: "January",
2: "F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.