blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ac54a80869c640e1f07dbc364b7f000c2cb24b0d | pinobatch/little-things-nes | /rgb121/tools/bitbuilder.py | 6,272 | 3.890625 | 4 | #!/usr/bin/env python3
"""
"""
from __future__ import with_statement, print_function
def log2(i):
return int(i).bit_length() - 1
class BitBuilder(object):
def __init__(self):
self.data = bytearray()
self.nbits = 0 # number of bits left in the last byte
def append(self, value, length=1... |
5bc1f0ccb1d818d5350e1f986ab7ac973ae727cb | whirlkick/assignment8 | /jj1745/investment.py | 936 | 3.5625 | 4 | '''
Created on Nov 7, 2015
@author: jj1745
'''
import numpy as np
class instrument(object):
'''
Create the object of an investment instrument
the instrument is determined by how many shares the investor holds.
the value of each investment is then computed accordingly
'''
def __init__(sel... |
1d3e70307afeea8a02f453d066aaf6e2f61de560 | chaosWsF/Python-Practice | /leetcode/1022_sum_of_root_to_leaf_binary_numbers.py | 1,574 | 4.09375 | 4 | """
You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path
represents a binary number starting with the most significant bit. For example, if the path is
0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the... |
ceca8d13c0bd8d92960d375ac5f5f335f053e2bf | dengyings/biji | /NLP/双向最大匹配法.py | 1,799 | 3.640625 | 4 |
#正向最大匹配法
class MM(object):
def __init__(self):
self.max_size = 3
def cut(self, text):
result=[]
index=0
text_len = len(text)
dic = ['研究','研究生','生命','命','的','起源']
while text_len > index:
for size in range(self.max_size+index,index,-1):
... |
6380ddde36cf959db9188f3d029ef8b5b52dc4a5 | Fateeeeee/demo | /join函数合并字符串.py | 380 | 3.734375 | 4 | '''
1、join()函数
语法: 'sep'.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
'''
test = ["I", "Like", "Python"]
print(test)
print("".join(test)) # 表示分隔符为空合并字符串数组为一个字符串 |
458276d2efba99f4f4b051151d0b2a0682ae07e1 | mshekhar/random-algs | /epi_solutions/arrays/insert-delete-getrandom-o1.py | 2,058 | 3.84375 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.ele_as_list = []
self.ele_idx_map = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already conta... |
25175b36f6928f869f97a079e6d2ed1669c12174 | sanashahin2225/ProjectEuler | /projectEuler6.py | 695 | 3.765625 | 4 | # The sum of the squares of the first ten natural numbers is,
# (1^2 + 2^2 + 3^2 + ... 10^2) = 385
# The square of the sum of the first ten natural numbers is,
# (1+2+3+ ... 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers... |
e4bd91eaa4af430568e24bbaac488ab98e2dd503 | eselyavka/python | /reducer.py | 573 | 3.515625 | 4 | #!/usr/bin/env python
import sys
def reducer():
(iterator, max_duration) = (None, -sys.maxint)
for line in sys.stdin:
(year, duration) = line.strip().split(';')
if iterator and iterator != year:
print "%s\t%s" % (iterator, max_duration)
(iterator, max_duration) = ... |
08c2424b1e0a4d16d234ce30af4ca21cc877e626 | DevangSharma/D-Encryptor | /D-Encrypter main.py | 393 | 3.625 | 4 | from functions import *
print("Welcome! to D-Encryptor \nHere you can encode a message for someone else end at the other end one can decrypt "
"it as well")
n = input("Press Enter to continue \n")
test_input(n, "")
print(" 1 : Encryption \n 2 : Decryption")
task = int(input("Please select your task : "))
test... |
53ff13cf6c30c553b647374f69771cadf960cd7e | Damodharan5/Data_structures | /Huffman Tree/treee.py | 991 | 3.65625 | 4 | m = ""
d = {}
class _Tree_node():
def __init__(self):
self.left = None
self.right = None
self.ch = False
self.count = 0
def _traverse(root,value):
global m
global d
m+=value
if root.left == None or root.right == None:
d[root.ch] = m
else:
_traverse(root.left,'0')
m=m[:-1]
_traverse(root.right,'1'... |
d5ff0d704d84bd58ec2a07ec537a1639166bf6ee | bakliwalvaibhav1/python_basic_udemy | /3_Greatest_of_Three/greatest_of_three.py | 185 | 4.0625 | 4 | a= int(input('Enter First Number'))
b= int(input('Enter Second Number'))
c= int(input('Enter Third Number'))
if b<= a >=c:
print(a)
elif a<= b >=c:
print (b)
else:
print(c)
|
676ce06b56afda9d8860f681fa0108b8949ba89d | wujam/neu_cs_sdev | /Santorini/Design/observermanager.py | 831 | 3.984375 | 4 | from abc import ABC, abstractmethod
""" ObserverManager manages Observers """
class ObserverManager(ABC):
def __init__(self):
pass
@abstractmethod
def add_observer(self, observer):
""" Adds an observer.
:param Observer observer: an Observer to be added
"""
pass
... |
bad94eddd40c0b9b909706a83cb7fc1cb5d3cf89 | AceRodrigo/CodingDojoStuffs | /Python_Stack/_python/python_fundamentals/Rodriguez_Austin_VS_Functions_Intermediate_2.py | 3,254 | 4.0625 | 4 | #Challenge 1: Update Values in Dictionaries and Lists
x= [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Roone... |
312f1f97e1f569ba3f5fbad5dde881e497fe2aa4 | akcauser/Python | /education_07032020/015_if_else_elif.py | 285 | 3.890625 | 4 |
a = 10
b = 10
if a < b:
print("a küçüktür b")
elif a == b:
print("a eşittir b")
else:
print("a küçük değildir b")
print("bitti")
"""
> büyüktür
< küçüktür
>= büyük eşittir
<= küçük eşittir
== eşittir
!= eşit değildir
""" |
ab14b905c7221f16d1837859b8400c3282e7ebb3 | psmano/pythonworks | /pyworks/readTxtFile.py | 138 | 3.96875 | 4 | #Reading the Text File
filename = input('Enter File Name: ')
file = open(filename,mode='r')
text = file.read()
file.close()
print(text)
|
6c7cd043fb4915cab0c157e5d79028a4e42f2dca | hyybuaa/AlgorithmTutorial | /ReConstructBinaryTree.py | 1,400 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstruBinaryTree(self, pre, tin):
node = self.construBinaryTree(pre, 0, len(pre)-1, tin, 0, len(tin)-1)
return node... |
9771f08b07549eaae1ed47e400efad008fe10504 | Anupaul24/pythonclasses | /src/list.py | 890 | 3.9375 | 4 |
# l=("apple","mango","grapes","banana","kiwi")
# print(l)
# l.append("papaya")
# l.append("lichi")
# l1=[1,2,3,4]
# l.extend(l1)
# l.insert(0,"watermelon")
# print(l)
# l.remove(l[2])
# l.pop()
# print(l)
# print(l[2:5])
# print(len(l))
# l={"apple","mango","grapes","banana","kiwi"}
l={1,3,5,6,7,3,5}
print(l)
s={1,2,... |
75ecdd8457bd6c9df240912616db1ff3360520cf | afuyo/PREDICT400 | /Python/graphs.py | 1,298 | 4.4375 | 4 | import matplotlib.pyplot
from matplotlib.pyplot import *
import numpy
from numpy import linspace
# The example shows how to plot a system of consistent equations.
# This is Example 1 Section 2.1 of Lial. The function linspace divides the
# interval [-1,15] into 100 points. For each value in x, y1 and y2 will have
# ... |
2010d8904d749091e6a7866805a1d0f556b4d388 | Soujash-123/SAGNIK | /Sequence_Analyzer.py | 1,183 | 3.953125 | 4 | print("Enter the first 3 digits")
a=int(input("1"))
b=int(input("2"))
c=int(input("3"))
dr4=0
rr4=0
l=0
if 2*b==(a+c):
print("the series is in AP")
d=b-a
print(c+d,"is the next term")
dr4=c+d
elif b**2==(a*c):
print("The series is in GP")
d=b//a
print(c*d,"is the next term")
... |
d7526178e964cba7b1acada57d5ae6605d3b892f | krishnasairam/sairam | /cspp1-assignments/m14/2/poker.py | 2,389 | 3.890625 | 4 | ''' Write a program to evaluate poker hands and determine the winner
Read about poker hands here.
https://en.wikipedia.org/wiki/List_of_poker_hands'''
def is_straight(ranks):
''' straight '''
return len(set(ranks)) == 5 and (max(ranks) -min(ranks) == 4)
def is_flush(hand):
suit = hand[0]
for h_... |
f40e65df26eecce167f7b456b1c38d640f2ecbf8 | im-greysen/afs505_u1 | /project/game_of_life.py | 4,480 | 3.890625 | 4 | """Conway's Game of Life Python Script.
.. module:: AFS505_U1 Project_01
:platform: Windows
:synopsis: This is a Python3 script for Conway's Game of Life, a cellular automation program that implements
rules designed to mimic a cellular lifeform. Thi specific program achieves this goal by using a matrix wit... |
03c059fc12a78f89df01583aded1f4f34651faa4 | zhangchizju2012/LeetCode | /217.py | 425 | 3.71875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 24 11:13:19 2017
@author: zhangchi
"""
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic = {}
for item in nums:
if item in dic:
... |
6bfad8728604a59149501b535c522e0ce90c65e7 | H-Cong/LeetCode | /83_RemoveDuplicatesFromSortedList/83_RemoveDuplicatesFromSortedList.py | 645 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
curr = head
while curr and curr.next:
if curr.val == curr.next.va... |
cbf1a93f60f8e83b95115e3c428da2a3ce0d3a57 | Bighetto/EstudosCursoPython | /7-Operadores de Atribuição.py | 715 | 4.0625 | 4 | x = 20
# Atribuir mais quantidade a variavel "x"
# Maneira Basica: x = x + 10
x += 10
y = 10
y -= 5
#Sinal "+=" é o valor de x mais o valor colocado e ja da o resultado.
#Sinal "-=" é o valor de x menos o valor colocado e ja da o resultado.
z= 10
z *= 5
#Serve também para multiplicação."*=" é multiplicado por .... |
d5a0fd23a5bab282d65c3ac782ee297856d46fa8 | otavioacb/ProjetoMulticomandoMiniRobos | /Esp8266/Motor/motor.py | 1,058 | 3.84375 | 4 | from machine import Pin,PWM
class Motor:
"""
This class is an attempt to represent
a DC Motor for ESP8266 to controll
its movements.
Pwm Pin -> Controll the motor speed.
Dir Pin -> Controll the motor direction.
"""
def __init__(self, pin_pwm, pin_d... |
dd736d14583bf81ea55a5e95940b0db5fb1749a8 | FerCremonez/College-1st-semester- | /renata_a2_e1.py | 133 | 3.890625 | 4 | num1=int(input('Insira o primeiro número:'))
num2=int(input('Insira o segundo número:'))
calc=num1+num2
print('Resultado:',calc) |
476854314ccef8b6065284e2c092d39406b4b02b | AleksandraSzoldra/PpI | /cw3.py | 165 | 3.546875 | 4 | a=int(input("Podaj a: "))
b=int(input("Podaj b: "))
c=int(input("Podaj c: "))
p=(a+b+c)*0.5
P=(p*(p-a)*(p-b)*(p-c))**0.5
print ("Pole trójkąta wynosi: ",P) |
d1382a2301d7aba71c63e5b22e19550b256cd211 | egewarth/uri | /1005.py | 98 | 3.625 | 4 | a = float(input())
b = float(input())
m=((a*3.5)+(b*7.5))/11.0
print("MEDIA = {0:.5f}".format(m))
|
56feb0aaa6156317635579e561f7654c56028663 | chaitanyaPaikara/Py_Workspace | /Py_AI/Path_search.py | 2,726 | 3.875 | 4 | # ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'f... |
fda0c3328176210ca6baee89dd7005e6c2c52455 | sdjukic/GamazeD | /Geometry.py | 2,231 | 4.125 | 4 | from math import sqrt
class Point(object):
"""Class that defines Point structure in 2D Cartesian space."""
def __init__(self, *args):
self._x_coordinate = args[0]
self._y_coordinate = args[1]
def get_x(self):
return self._x_coordinate
def get_y(self):
return se... |
60787fa80a2f65113c0816b317ae77b2c6b6d4df | horeilly1101/countdown | /countdown/display_text.py | 1,802 | 4.21875 | 4 | """File that contains various responses to the player."""
RULES: str = f"""
WELCOME TO COUNTDOWN
You will be given 6 numbers and a goal number.
Your task: Use the 6 numbers to get as close to the
goal number as possible.
You may add, subtract, multiply, and divide the given numbers,
... |
db601f8a3e9f753385daccec2db0d3d4102b28ee | IronE-G-G/algorithm | /leetcode/101-200题/144preorderTraversal.py | 1,659 | 4.09375 | 4 | """
144 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
class TreeNode(object):
d... |
0cf8acb30cf69b4da998fc0ce8ca21678c5417b2 | henrryyanez/web_practicas | /Python_L1_Bucles.py | 181 | 3.953125 | 4 | # For Loops
seq = [1,2,3,4,5,6]
for henrry in seq:
# Code here
print(henrry)
# For Loops
seq = [1,2,3,4,5,6]
for henrry in seq:
# Code here
print('HOLA')
|
aa434379f4026a6fb42a643f3c50ebb3b7101ea0 | lelencho/Homeworks | /Examples from Slides/Lesson 7 Python Collections/DefaultDict.py | 154 | 3.625 | 4 | from collections import defaultdict
def some():
return [1, 2, 3]
d = defaultdict(some)
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d['ddd']) |
19e2ee55734d5e00e1990eb03b947a157e033e93 | asxzhy/Leetcode | /leetcode/question_824/solution_1.py | 819 | 3.90625 | 4 | """
I firstly separeted the sentence to a list of words. Then for every word, I checked if the first letter is a vowel. If it's a vowel, then do the correspongind conversion for the
word. If it is not a vowel, do the other conversion. Join the list back together and return the sentence
"""
class Solution:
def toG... |
2cf9359f79f58aca55b561f6b7ebade244fac5fc | chrisglencross/advent-of-code | /aoc2019/day6/day6.py | 1,728 | 3.546875 | 4 | #!/usr/bin/python3
# Advent of code 2019 day 6
import copy
with open("input.txt") as f:
lines = f.readlines()
# Build dictionary object -> set(orbiters)
direct_orbits = {}
for line in lines:
parts = line.strip().split(")")
if parts[0] in direct_orbits:
direct_orbits[parts[0]].add(parts[1])
els... |
ab56e30d81daa7f4accadfe6b74ab0bd04d1f67b | ryanswong/Python-git | /U3L1.1 Shopping List Lab.py | 2,240 | 3.953125 | 4 | shopping_list = [] # pylint: disable=locally-disabled, invalid-name
def invalid_input():
print "That\'s not a valid answer, try again. "
def print_list():
print '\n' + 'Grocery List: [' + ', ' .join(shopping_list) + ']' '\n'
def appender():
response = raw_input("What item do you want to ... |
bdada98295d49c879919accd40b4781b09c3ec29 | SchaeStewart/cis115 | /092916/tempCheck.py | 257 | 4.03125 | 4 | #Schaffer Stewart, Alan Skonieczny, Nathan Dabbs
#09/29/16
#Temperature Check
temp = float(input("Please enter the temperature: "))
if temp > 70:
print("Temperature is too hot")
elif temp < 40:
print("Temperature is too cold")
else:
print("Temperature is just right")
|
d7a6822736ad617146908f3f984c2d070451b32b | JeffHritz/practice | /wage_calculator.py | 820 | 4.15625 | 4 | # wage_calculator.py - Jeff Hritz
"""
This module gathers inputs and calculates your paycheck based on your hourly wage, how many hours you work,
tax rates, and pay-check deductions.
"""
pay_rate = int(input("Pay rate: "))
hours_worked = float(input("Hours worked: "))
tax_rate = float(.1981)
deductions = floa... |
1278b1f058a4cbf9d3b0d309530536c8fbb8a981 | brunoliberal/exercises | /stacks_and_queues/animal_shelter.py | 1,761 | 3.625 | 4 | from linked_list.likedlist2 import LinkedList
class AnimalShelter:
dogs = LinkedList()
cats = LinkedList()
# Time O(n). Space O(1)
def enqueue(self, name, type):
if name:
if type == 'dog':
self.dogs.add(name)
self.cats.add(None)
elif typ... |
a99e63ef261494e89df6d3107c739583ebe1c289 | selam-weldu/algorithms_data_structures | /leet_code/python/searching/find_max_in_inc_dec_array.py | 539 | 3.765625 | 4 | def find_max_element(arr):
if len(arr) == 0:
raise Error('No elements in the input array')
if len(arr) == 1:
return arr[0]
if len(arr) == 2:
return max(arr[0], arr[1])
low = 0
high = len(arr) - 1
while low < high:
mid = (low + high) / 2
# Compare mid's ne... |
3a332ffa33a722f4896abba811763f43148e7b3e | SuperEnderSlayerr/STV-algorism | /algorithm.py | 1,179 | 3.5 | 4 | '''
Ender (Michael Hanks)
STV algorithm implimentation.
'''
import random
class algorithm:
def __init__(self, candidates_with_parties, votes):
self.candidates_with_parties = candidates_with_parties
self.votes = votes
self.candidates = []
parties = list(candidates_with_parties.keys(... |
529a16d183525118688b752d6831f8ce51ce9750 | yingxingtianxia/python | /PycharmProjects/my_practice/untitled1/9.py | 345 | 3.546875 | 4 | #!/usr/bin/env python3
# -*-coding: utf8-*-
favorite_languages = {
'jen':'python',
'seach':'c',
'kenji':'ruby',
'chihiro':'html',
}
#print('Seach~s favorite language is '+ favorite_languages['seach'].title())
for name, language in favorite_languages.items():
print(name.title() + "'s favorite languag... |
c60fe6aba196f419b9bfaa7f840fc05ac002d84e | melanie197/PROGRAMACION-APLICADA-P57.py | /apenfileconwhile.py | 316 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 17:06:54 2021
@author: pc
"""
file=open("devices.txt","a")
while True:
newItem=input("Ingrese nuevo dispositivo: ")
if newItem=="exit":
print("LISTPO" +"\n")
break
else:
file.write(newItem+"\n")
file.close()
|
99f858d6dcfdeb60d3c19657ec7a5724dbff6fc0 | WilliamFWG/Warehouse | /python/PycharmProjects/py01/day04/stack.py | 890 | 4.0625 | 4 | #!/root/nsd1905/bin/python
''' stack
append stack
pop stack
show stack
'''
stack=[]
def show_menu():
menu='''
0) Push into Stack
1) Pull from Stack
2) Show Stack
3) Quit
Please Choose (0/1/2/3):'''
cmds={'0':push_stack,'1':pull_stack,'2':show_stack}
choice=''
while choice!='3':
choice=input(me... |
86e474e7d315fb575cea118b4e49a47496737fa5 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/scottebetts/lesson04/trigrams.py | 1,224 | 3.9375 | 4 | #!/usr/bin/env python3
# author: Scott Betts
import random
from collections import defaultdict
import pprint
import re
def words(file_in):
with open(file_in, 'r') as infile:
x = infile.read()
x = re.sub(r'[^\w\s]', ' ', x).lower()
x = x.split()
return x
def build_trigrams(words):
... |
7f4aa5ed70ba4ba82bdddb95a06ec19fb6cf6f31 | scaredginger/ieeextreme-2017 | /competition/bubbleChallenge.py | 1,506 | 3.515625 | 4 | #def printMatrix(m):
# for x in range(4):
# print("")
# for y in range(4):
# print(str(m[x][y]) + " ", end="")
# print("")
def checkForCycle(adjacencyMatrix, maxNum):
for x in range(0, maxNum+1):
for y in range(1, maxNum+1):
if adjacencyMatrix[x][y] == 1:
... |
92eb27c4f97e5b30b8edb5eedfc8d1e22b7fce88 | arnabs542/achked | /python3/sorting/insertion_sort.py | 412 | 3.734375 | 4 | #!/usr/bin/env python3
def insertion_sort(l):
for i in range(len(l)):
key = l[i]
j = i
while j > 0:
if l[j - 1] > key:
l[j] = l[j - 1]
j -= 1
else:
break
l[j] = key
def main():
l = [4, 3, 45, 2, 22, 15, 6,... |
16fa5bb8f9ec59fb24c0be485cb74c5f799136db | LuanaSchlei/HackerRank_Python | /python-mod-divmod/python-mod-divmod.py | 320 | 3.5625 | 4 | #!/bin/python3
#
# Url: https://www.hackerrank.com/challenges/python-mod-divmod/problem
#
# Title: Mod Divmod
#
input_a = int(input())
input_b = int(input())
division_a_b = input_a // input_b
print(division_a_b)
modul_a_b = input_a % input_b
print(modul_a_b)
divmod_a_b = divmod(input_a, input_b)
print(divmod_a_b) |
1cfec5b901e0adab367981541fc9771ad999a97e | dagute/Coding_Interview | /Python/Find pair that sums up to k/sumpair3.py | 277 | 3.53125 | 4 | # By using a dictionary:
# Time complexity: O(n)
# Space complexity: O(n)
# arr = [8, 2, 9, 5, 10, 1]
# k = 12
def findPair(arr, k):
visited = {}
for element in arr:
if visited.get(k-element):
return True
else:
visited[element] = True
return False
|
10e85a5adedaf0fb1543e02a12cd3e4a3372c36a | AnneNamuli/python-code-snippets | /rev.py | 169 | 4.125 | 4 | def reverse(s):
s = list(s)
for i in range (len(s)//2):
temp = s[i]
s[i] = s[len(s)- i -1]
s[len(s) - 1 - i] = temp
return "".join(s)
print reverse("hello")
|
ad5b4c82e65d05d7466809361d0d1bed7aa8508f | ngetachew/LinkedList | /linkedlists.py | 861 | 4.03125 | 4 |
class Node:
def __init__(self, v : int, p):
self.value = v
self.pointer = p
class LinkedList:
#Data values are ints
def __init__(self, h):
self.head = Node(h, None)
def create_node(self):
return Node(0, None)
def add_node(self, val):
temp = self.create_... |
0df208508c3ada41f3ff40943d9d7a0a65d00e4b | 981377660LMT/algorithm-study | /11_动态规划/dp分类/双字符dp/97. 交错字符串.py | 1,368 | 3.59375 | 4 | # 请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。
from functools import lru_cache
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
@lru_cache(None)
def dfs(i: int, j: int) -> bool:
if i == len(s1) and j == len(s2):
return True
res = False
... |
976d6c85555856c688a1ebac95a1048b0788766e | LeonNerd/PyTorch-Tutorial | /PythonScript/PythonScript/DeleteInBatches.py | 1,169 | 3.796875 | 4 | import os
#批量删除指定文件夹下的指定文件
#定义一个返回所有图片绝对路径的函数
def all_path(dirname):
result = []
for maindir, subdir, file_name_list in os.walk(dirname):
for filename in file_name_list:
apath = os.path.join(maindir, filename)
result.append(apath)
return result
def main():
... |
888a7c8dd6a8d005b52df8b8b3c651d28f83e09c | tarun-n/python_daily_tasks | /random_password.py | 1,172 | 3.609375 | 4 | import random
def check_username(username):
fr=open("randompassword.txt","r")
lines=fr.readlines()
names=[]
for i in lines:
names.append((i.split('-')[0]).rstrip())
if username in names:
return 1
else:
return 0
def gen_char(n):
opstr=''
letters_small=[chr(i) for i in range(ord("a"),(o... |
710b82a258e1a5c1d00d0807ca8fd6750f85f740 | poo5/Hacker_rank | /solving problem/plus-minus.py | 483 | 3.609375 | 4 | def plusMinus(arr):
pos = 0
neg = 0
zero_count = 0
for i in arr:
if i > 0:
pos = pos+ 1
elif i < 0:
neg = neg + 1
else:
zero_count = zero_count + 1
pos_cal = pos/n
neg_cal = neg/n
zero_cal = zero_count/n
return(pos_cal,neg_cal,... |
2cab0dbecc72bb2e22f112cc6926f95887c0eb0f | jjkr/code-jam | /archive/python/consonants/consonants.py | 1,222 | 3.65625 | 4 | import sys
def is_vowel(c):
vowels = ['a', 'e', 'i', 'o', 'u']
try:
vowels.index(c)
return True
except:
return False
def nvalue(s, n):
print('NVAL')
print(s + str(n))
substrs = []
i=0
while i<= len(s)-n:
# print( 'I LOOP' )
j = 0
while ... |
f223ea831a27ae77bbfa7c32781a13b659a6c55b | Pooja-svg801/15072021ML01 | /day 9 csv.py | 1,427 | 3.515625 | 4 | import tkinter as tk
import csv
app = tk.Tk(__name__)
app.title('Form')
app.geometry('300x200')
name = tk.Variable(app)
name.set('')
email = tk.Variable(app)
email.set('')
mobilenumber = tk.Variable(app)
mobilenumber.set('')
tk.Label(app, text = 'Name',\
font=('Arial',14),
bg='bla... |
528ce2f3121e33c8652c2faff4f473bc1d8b017b | greatabel/PythonRepository | /04Python workbook/ch3loop/78DecimaltoBinary.py | 315 | 3.71875 | 4 | line = input("Enter n:")
while line != "":
bN = ""
mylist = []
xN = int(line)
while xN >=1:
if xN % 2 == 0:
reminder = 0
else:
reminder = 1
print("reminder=",reminder)
xN =xN/2
mylist.append(reminder)
for item in reversed(mylist):
bN+=str(item)
print(str(bN))
line = input("Enter n:")
|
83dcc46e1ea325c8d2bbf1ee0b18eb75cffcaa47 | fary86/GeneralisedNeuralNetwork | /NeuralNetwork.py | 3,827 | 3.734375 | 4 | """
Title: OCR Neural Network from scratch
Author: Abhinav Thukral
Language: Python
Dataset: MNIST
Description: Implementing a simpler, more readable version of OCR Neural Network from scratch to teach beginners.
"""
import pandas as pd
import numpy as np
import time
#Reading the MNSIT dataset
def read_... |
e93a5a9bb9a2958ed9dd9fd0c607dd0092422795 | SeperinaJi/PythonExercise | /pizza.py | 1,461 | 4.28125 | 4 | # Exercise list in dictionary
pizza = {
'crust' : 'thick',
'toppings' : ['mushroom', 'extra cheese', 'pepperoni']
}
print("You ordered a " + pizza['crust'] + "-crist pizza " +
"With the fllowing toppings:")
for topping in pizza['toppings']:
print('\t' + topping)
#Exercise dictionary in dictionary
... |
c0620dc89173629e608233ff9688be6a73b5d605 | luodanping/learn-python-by-coding | /design_pattern/10_facade.py | 1,432 | 3.59375 | 4 | #facade
import time
SLEEP=0.5
#complex parts
class TC1:
def run(self):
print("#"*5+" In Text 1 "+"#"*5)
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(... |
eb62cc70c9812589bd8e7cdccb3b1dfae0698410 | benglish00/STP_CH3 | /ch3.py | 1,080 | 3.984375 | 4 | # basic for loop, i starts at 0
for i in range (10):
print(i+1)
import math
# length of a diagonal
l = 4
w = 10
d = math.sqrt(l**2 + w**2)
print(d)
#print long line
print("""Colooooooooooooooooooooooooooooooooooooooraddo
ooooo""")
#conditional
home = "Colorado"
if home == "Colorado":
print("Hello, Colorado!"... |
8e3a0aafeca9ca8868b3d5c353a745d5d4f658d5 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/2702.py | 544 | 3.578125 | 4 | def flip(char):
if char == '+':
return '-'
else:
return '+'
T = int(raw_input())
for t in range(T):
pattern, flipper = raw_input().split(' ')
flipper = int(flipper)
pattern = list(pattern)
flips = 0
fixed = 0
length = len(pattern)
while True:
while fixed<length and pattern[fixed]=='+':
fixed+=1
if ... |
1b95214b694b107a3e9cb8924db0c80b15f45971 | mccoderpy/alphabetic-to_json-Encoder | /converter_consolen-version.py | 2,928 | 3.625 | 4 | import json
import os
import time
class converter():
print('░▒▓███Welcome to the alphabetic-to_json-encoder of mccoderpy aka. mccuber04#2960██▓▒░ ©mccoderpy 2021')
loop= 0
while True:
inpu = input("Please enter the name of the file(with the ending) you want to convert in to an JSON>> ")
... |
f3eea484a492c274832789ca74d1ef9d94da778e | MikeCardona076/PythonDocuments | /python/Practica.py | 400 | 3.84375 | 4 | palabra=input("Escribe una palabra: ")
veces_palabra= int(input("Numero de veces: "))
for recorrido in range(0,veces_palabra):
if (veces_palabra > 120):
print("Pedro ", palabra)
else:
print(palabra)
if (veces_palabra==500):
print("Hola")
elif(veces_palabra < 100):
print("Hola Mo... |
794f9d7b3649d82a90420d646c16563bddc0c8ec | gerrycfchang/leetcode-python | /medium/subarray_product_less_than_k.py | 1,774 | 3.59375 | 4 | # 713. Subarray Product Less Than K
#
# Input: nums = [10, 5, 2, 6], k = 100
# Output: 8
# Explanation: The 8 subarrays that have product less than 100 are:
# [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
# Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
class Solutio... |
6aa082d2b14c8f9c356438ca8760d0711da9a2de | avinash-nonholonomy/hack_diversity_office_hours | /archive/2021/graphs_and_trees.py | 1,649 | 4 | 4 | #!/usr/bin/python
import networkx as nx
"""
Helpful resources:
NetworkX - Great python library for working with graphs
https://networkx.org/documentation/stable/tutorial.html
Summary of graph terms and alogorithms:
https://towardsdatascience.com/10-graph-algorithms-visually-explained-e57faa1336f3
"""
# Detect L... |
6333ce2053bbd67e3d1b825074f5c931dd1ac96b | Pjmcnally/algo | /strings/seven_segment_display/find_longest_word.py | 1,191 | 4.0625 | 4 | """Find the longest english word representable on a seven segment display.
This is based on the YouTube video by Tom Scott found here:
https://www.youtube.com/watch?v=zp4BMR88260&feature=youtu.be
"""
import os
import re
def find_longest_words(file_path):
"""Find longest word representable on a seven segment dis... |
803388179f449e7031f14def34ab7cd646ad1ff0 | mr-finnie-mac/mirror-meno | /display_main.py | 1,670 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# display_main.py
# Author: Fin Mead [Meadeor]
# Desc: Aggregate display for display mirror
# Last updated: 10/5/2020
#
# Imports
import RPi.GPIO as GPIO
import time
import tkinter
from tkinter import *
date = time.strftime('%b %d, %Y')
Time = time.strftime('%l:%... |
16977f124a3f31d5596f71b897fa056f78cad1fa | techadddict/Python-programmingRG | /Dictionaries/python dictionary 1.py | 567 | 4 | 4 | ##Write a program that counts how often each word occurs in a user specified text file
file = open('text.txt','r')
lines= file.readlines()
myDict={}
for line in lines:
#print(line)
wordList = line.strip().split()
for word in wordList:
word=word.strip(',!;.')
if(word in myDict):
... |
13cd6328ce809710b023f67a05108ea944a2fbbd | rayhan60611/Python-A-2-Z | /7.Chapter-7/test.py | 2,299 | 3.78125 | 4 | #Problem No 1:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
number =input("Enter Your Number: ")
for i in range(1,11):
print(f"{number}x{i} = {int(number)*i}")
#Problem No 2:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
l= ['Rayhan','Sumon','Sony','Tony','Sunny']
for name in l:
if n... |
7b2b2c1592e7ea7b921ecd29acb52626a4c014a2 | trevllew751/python3course | /selects.py | 325 | 3.9375 | 4 | import sqlite3
conn = sqlite3.connect("my_friends.db")
c = conn.cursor()
c.execute("SELECT * FROM friends WHERE closeness > 5 ORDER BY closeness")
# Iterate over a cursor
# for reslut in c:
# print result
# fetch one result
print(c.fetchone())
#fetch all results as a list
print(c.fetchall())
conn.commit()
conn.cl... |
3091c0406a70fd92c9084987a352c1643e21cfbc | Phomint/Udacity_DataScienceFoundations_BR | /Projects/Project_1/chicago_bikeshare_pt.py | 12,085 | 4 | 4 | # coding: utf-8
# Começando com os imports
import csv
import matplotlib.pyplot as plt
# Vamos ler os dados como uma lista
print("Lendo o documento...")
with open("chicago.csv", "r") as file_read:
reader = csv.reader(file_read)
data_list = list(reader)
print("Ok!")
# Vamos verificar quantas linhas nós temos
p... |
da02b179db282c8c287caff4808f478da505b8d6 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/distantBarcodes.py | 1,611 | 3.8125 | 4 | """
Distant Barcodes
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example 1:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: [1... |
48db4d76385cf690f5527168ba47f212c3f4b9bb | rpivo/leetcode-answers | /find-value-of-variable-after-performing-operations-2.py | 652 | 3.71875 | 4 | # define class Solution
class Solution:
# define function finalValueAfterOperations, which takes in the class
# instance (self), a list of strings called operations, and returns an
# integer
def finalValueAfterOperations(self, operations: List[str]) -> int:
# create variable x and set it equal... |
ab9804bcfa130d920b5b3f8159628c69855bf01f | RicardoVeronica/python-exercises | /fizz-buzz/fizz-buzz.py | 547 | 3.71875 | 4 | # fizz buzz problem with list comprehension
fizz = [value for value in range(1, 101) if value % 3 == 0]
buzz = [value for value in range(1, 101) if value % 5 == 0]
FizzBuzz = [value for value in range(1, 101)
if value % 3 == 0 and value % 5 == 0]
# fizz buzz problem with for
for number in range(1, 101):
... |
b738a81128b3c1ed09f11f1f5bdd7760cd292a92 | marykamau2/katas | /python kata/leap_year/leap.py | 332 | 4.21875 | 4 | year = int(input('Please put in your year?'))
def leap(year):
if (year % 4) == 0 and (year % 100) == 0 and (year % 400) == 0:
# year = True
return True
print(f'{year} entered is a leap year')
else:
# year = False
return False
print(f'{year} entered is not a leap year')
year2 = leap(year)
... |
4e552537703a056d48eb7291c7381e6ddc94dcdd | caveman0612/python_fundeamentals | /Practice/easy/Find CLosest Value in BST.py | 1,344 | 3.90625 | 4 | def findClosestValueInBst(tree, target):
return findClosestValueInBstHelper(tree, target, tree.value)
def findClosestValueInBstHelper(tree, target, closest):
# check current value
if tree is None:
print(type(tree))
return closest
# check the difference between target and current value c... |
a5d9cbf40e4ee06b12ba029bdacc9c9126804d57 | HkageProject/HKAGE_Project | /StudentSystem.py | 2,922 | 3.875 | 4 | students = ['demo']
scores = [60]
what_to_do = ''
from os import system
def antierror():
pass
def clear():
system('clear')
def add_student():
student_name = input('Enter the name of the student: ')
passed = 0
score = 0
while passed == 0:
try:
score = input('Enter score of student: ')
scor... |
b3637103f5afa718e350853a0d449d671fd97861 | AnushaSatram/guvi | /p11.py | 82 | 3.828125 | 4 | hk=input()
if(hk=="Saturday" or hk=="Sunday"):
print("yes")
else:
print("no")
|
311b0058e1c8186ea7348f2c3a0f06069cc18fd6 | beerfleet/udemy_tutorial | /Oefeningen/uDemy/bootcamp/033_oop_inheritance_exercise.py | 1,332 | 3.796875 | 4 | class Character:
def __init__(self, name, hp, level):
self.name = name
if not isinstance(hp, int):
raise ValueError("Hit points has to be an integer value.")
self.hp = hp
if not isinstance(level, int):
raise ValueError("Level has to be an integer value.")
... |
f2cd71189d8226e07bf707e75583af56ee3246f2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4173/codes/1716_2503.py | 131 | 3.5 | 4 |
n = int(input())
pi = 0
while(n>=1):
if(n%2 == 1):
pi = pi+(4/(2*n-1))
else:
pi = pi-(4/(2*n-1))
n = n-1
print(round(pi,8)) |
f1a0c18b6faa5783429639436b9462e92850677c | KKP127/pythonexample | /ex9.py | 244 | 3.6875 | 4 | days="Mon Tue Wed Thu Fri Sat Sun"
months="\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days:",days)
print("Here are the months:",months)
print(""" There's something going on here
the three double Quotes
No problem """)
|
63eec268d7bfae89111fa68693bab59f983fabcd | dldydrhkd/Problem-Solving | /프로그래머스/징검다리.py | 567 | 3.578125 | 4 | def check(mid, distance, rocks, n):
cur = 0
cut = 0
for i in rocks:
if(i-cur>=mid):
cur = i
else:
cut+=1
if(distance-cur<mid):
cur+=1
if(cut<=n):
return True
else:
return False
def solution(distance, rocks, n):
answer = 0
r... |
e3c9e0fe09909701f1a0b0d9812325215b2728bc | erichuang2015/python-examples | /threading/04Condition.py | 1,778 | 3.90625 | 4 | #!/usr/bin/env python3
# coding: utf-8
"""Condition类
使用Condition演示生产者/消费者问题.
"""
import threading
from random import randint
from time import sleep
# 自定义生产者线程类
class Producer(threading.Thread):
def __init__(self, threadname):
super().__init__(name=threadname)
def run(self):
global x
... |
30c2787690d1ffb2fa33bd34649a4a6181a59b80 | bigfairy-Jing/python-basis | /3.instance/26.二分查找.py | 421 | 3.765625 | 4 | def binarySearch(arr,l,r,x):
if r>=1:
mid = int(l + (r - 1)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr,l,mid-1,x)
else:
return binarySearch(arr,mid+1,r,x)
else:
return -1
arr = [2,3,4,10,40]
x = 10
result = binarySearch(arr,0,len(arr) - 1,x)
i... |
1c0091d6428a2eed0e9c2109e264fb571db7a316 | Tela96/cc_work | /week3/Excluder.py | 605 | 3.8125 | 4 | import random
import string
def excluder(orig_list):
exc_list = []
for item in orig_list:
if item not in exc_list:
exc_list.append(item)
print (exc_list)
def letter_gen():
letter_list = []
for letter in range(0, 10):
letter_list.append(random.choice(string.ascii_lower... |
750abb56747fe162cb6b6253ba2a202d311ee82d | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5166.py | 1,646 | 3.671875 | 4 | """
Written by blackk100 for Google Code Jam 2017 Qualifications
Problem
Tatiana likes to keep things tidy. Her toys are sorted from smallest to largest, her pencils are sorted from shortest
to longest and her computers from oldest to newest. One day, when practicing her counting skills, she noticed that some
... |
1cfa4c4bbee1c0e94082e2245872e4d3e0a0cbd6 | venkisagunner93/2048_AI | /src/logic.py | 741 | 3.8125 | 4 | #!/usr/bin/env python
import numpy as np
import random
class Game():
def __init__(self):
self.game_over = False
self.current_matrix = np.zeros((4,4), dtype = np.int)
for i in range(2):
self.create_population()
def create_population(self):
i = random.randint(0,3)
... |
5d5b668b7f25696aa51f10056f1484a7229186a4 | radomirbrkovic/algorithms | /hackerrank/other/the-grid-search.py | 425 | 3.734375 | 4 | # The Grid Search https://www.hackerrank.com/challenges/the-grid-search/problem
def gridSearch(G, P):
def check(x, y):
for i in range(r):
if P[i] != G[x+i][y:y+c]:
return False
return True
for i in range(R):
for j in range(C):
if G[i][j] == P[0]... |
a6c9ff4e0de7c105285965b499c4967fabae62e0 | phycog/guygit | /data_structure_lab/non-linear/binary_tree/creation_bi_tree_with_jon_snow.py | 1,005 | 3.65625 | 4 | '''
after i try to make tree (data structure) by my own
i have no idea what i am doing
'''
sibling_left_side = []
sibling_rifgt_side = []
class guy_tree:
def color_tree(self,color):
self.color = color
def main_tree(self,root,branch_l,branch_r):
self.root = root
self.branch_l = branch_l
... |
1ba3d786e3f603c7d4a8eee8da533952f278313a | ywl0911/leetcode | /80. Remove Duplicates from Sorted Array II.py | 848 | 3.53125 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
current = None
current_count = 0
length = 0
i = 0
while i < len(nums):
if nums[i] == current:
# prin... |
b433d5457bd51a50d8deb247e743fbf4aea53635 | DeepLearningHB/PythonMentoring | /Python_Mentoring_01/20183237 이시온 lab01/20183237 이시온 lab02_task03.py | 187 | 3.546875 | 4 | #3
A = [10, 4, 2, 7, 6, 1, 5, 8]
max = 0
for i in A :
if i > max :
max = i
print(max)
min = 100
for i in A :
if i < min :
min = i
print(min)
#
|
275a2c6e5d3151716e2595e6a93cd0773070f92c | manna422/pool_sim | /src/ball.py | 2,260 | 3.515625 | 4 | from math import sqrt, pow, sin, cos, pi
from physics import *
class Ball(object):
def __init__(self, table, x_pos, y_pos, score):
self.table = table
self.x_pos = x_pos
self.y_pos = y_pos
self.x_vel = 0
self.y_vel = 0
self.x_acc = 0
self.y_acc = ... |
a881e0ee6332d6e71150a0fb76b5c7eedd20fbc7 | StonecutterX/Python3 | /script/generators.py | 692 | 4.28125 | 4 | # /usr/bin/python
# usage of generators
# shawn 2018/1/12
def generator_function(n):
i = 0
while i < n:
print('before yield %d' %i)
yield i
i = i + 1
print('after yield %d' % i)
def fibon(n):
"""caculate Fibonacci
"""
a = b = 1
for i in range(n):
yi... |
7ae532ae20bd0fe06a2c66174bbebeb7e38690ac | kviiim/AdventOfCode2020 | /day5/day5-1.py | 705 | 3.6875 | 4 | import math
def findRow(currentRange, halfs):
if halfs[0] == 'F' or halfs[0] == 'L':
newRange = [currentRange[0], math.floor((currentRange[1]-currentRange[0])/2) + currentRange[0]]
else:
newRange = [math.ceil((currentRange[1]-currentRange[0])/2) + currentRange[0], currentRange[1]]
if len(ha... |
9a453174b960f3a23ee32860c1b696008ac267b0 | clongcurious1/py_turtle_graphics_exercises | /cecil_hexagon_nestedloop.py | 470 | 4.3125 | 4 | import turtle #import module
#add variable
cecil = turtle.Turtle() #name our turtle Cecil
cecil.shape('turtle') #make Cecil look like a turtle
#nested loop - create single shape (inner loop) first
#outer loop - repeat hexagon 36x, each time turning 10 degrees to the right
for n in range (36):
#inner loop - create one... |
fb89c80d091ce954936bd45cd951ebb91d006a39 | syeon-c/CodingTestArchive | /KAKAOBlindRecruitment/2021/ACombinedTaxiFare_Dijkstra.py | 1,199 | 3.59375 | 4 | import heapq
def printGraph(graph):
for i in range(len(graph)):
print(graph[i])
def solution(n, s, a, b, fares):
INF = int(1e9)
graph = [[] for _ in range(n+1)]
for x, y, z in fares:
graph[x].append((y, z))
graph[y].append((x, z))
# printGraph(graph)
def dijkstra(s... |
2e356dd3634cf07369e6cc9e61c38525b6c421c6 | IacovColisnicenco/100-Days-Of-Code | /DAYS_001-010/Day - 003/Exercises/day-3-5-exercise.py | 716 | 4.1875 | 4 | print("Welcome to Python Pizzas Deliveries !")
size = input("What size pizza do you want ? S, M or L ? ")
add_pepperoni = input("Do you want to add Pepperoni ? Y or N ? ")
extra_cheese = input("Do you want to add Extra Cheese ? Y or N ? ")
bill = 0
if size == "S" or size == "s":
bill += 15
if add_pepperon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.