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 |
|---|---|---|---|---|---|---|
c637389ec6e8586669c69b7897551c01efee63a7 | mitya52/sandbox | /ratio.py | 3,623 | 3.8125 | 4 | class Ratio():
'''
Rational numbers implementation
'''
def __init__(self, p=0, q=1):
if type(p) != int or type(q) != int:
raise TypeError('p and q must be integer')
if q <= 0:
raise ValueError('q must be > 0')
self.p = p
self.q = q
self._normalize()
# Arithmetic operators
def __mul__(self, other... |
b0f3078c52ba3322ce6068fc8b3e42fb93909d58 | groovesweeper/groovesweeper.github.io | /groovesweepersite/groovesweeperapp/src/model/Playlist.py | 3,241 | 3.78125 | 4 | from Filter import *
from Song import *
import copy
class Playlist:
"""
A class used to represent playlists holding multiple songs
...
Attributes
----------
__songList: List
List of all songs in a playlist
__name: String
Name of the playlist
__numOfExplicit
Number of explicit songs in the playlist
Me... |
5590128a082adaaffd68bb830363a4a3afe5707d | darcdqn/darcDQN | /darcDQN/envs/berry.py | 2,717 | 3.65625 | 4 |
import gym
import numpy as np
from gym import spaces
from gym.utils import seeding
from .berry_helper import Berries
class BerryEnv(gym.Env):
"""
Description:
An agent is presented with a berry and the option to eat or not
to eat the berry. The goal is to differentiate between berries
... |
2d229db2f7ab2db6ea5efca9f3327491bc51f0d0 | Ro7nak/python | /basics/Word_Order/app.py | 275 | 3.59375 | 4 | from collections import Counter
test = open("test.txt", "r")
z = []
for i in test:
z.append(i)
# print(z)
n = int(z[0])
a = []
for i in range(1, n+1):
a.append(z[i].rstrip())
a = Counter(a)
print(len(a))
for i in range(n-1):
print(a.most_common()[i][1], end=" ")
|
29df0290888e7598834022b71ab73b43549e4516 | Ro7nak/python | /basics/Numbers_sample.py | 743 | 4.0625 | 4 | from math import *
print(50)
print(2.56)
print(-5.63)
print(3+4.5) # all basic operations are supported
print(10 % 3) # mod function, here 10/3 remender will be printed
age = 50
price = 50.625
print(age)
print(str(age)) # number to string
# print("my age is " + age) # will not work
print("my age is " + str(ag... |
478657666cb8373727bc6219e706c6d77a67087a | Ro7nak/python | /basics/guessing_game.py | 444 | 3.90625 | 4 | secret_word = "draft"
guess = ""
# while guess != secret_word:
# guess = input("enter secret word: ")
# print("correct")
count = 0
limit = 5
out_of_guesses = False
while guess != secret_word and not out_of_guesses:
if count < limit:
guess = input("enter secret word: ")
count += 1
else:
... |
181d6b61957005addfe14c3020731a23b5372da0 | Ro7nak/python | /basics/higher_order/app3.py | 377 | 3.953125 | 4 | def add(data):
return data+2
def prod(data):
return data*2
def main_fun(function1,function2, number_list):
result_sum=0
for num in number_list:
if(num%3==0):
result_sum=result_sum+function1(num)
else:
result_sum=result_sum+function2(num)
return result_sum
numb... |
4c9b7bc8bbc0d7c62f2441f24dc9f0d9c4b95e7f | Ro7nak/python | /basics/while_loop.py | 95 | 3.859375 | 4 |
num = 1
while num <= 10:
print("value = " + str(num))
num += 1
print("out of loop")
|
762121b1d623ce8b5fc62b6234b333c67187131e | Ro7nak/python | /basics/Encryption_Decryption/module.py | 621 | 4.625 | 5 | # encrypt
user_input = input("Enter string: ")
cipher_text = '' # add all values to string
for char in user_input: # for every character in input
cipher_num = (ord(char)) + 3 % 26 # using ordinal to find the number
# cipher = ''
cipher = chr(cipher_num) # using chr to convert back to a letter
cipher... |
4c22fdef635c6dde5a0bb8bdb7fb081be8bc9a4a | Ro7nak/python | /basics/exponent_function.py | 172 | 4.09375 | 4 | print(2 ** 3)
def square(base_num, power_num):
result = 1
for int in range(power_num):
result = result * base_num
return result
print(square(2, 3))
|
ed20989907ee4df0db7384a9f8213cb8c25f9b75 | Ro7nak/python | /basics/ice_cream_parlor/app.py | 600 | 3.796875 | 4 | import math
import os
import random_app_demo
import re
import sys
# Complete the whatFlavors function below.
def whatFlavors(cost, money):
for i in range(len(cost)):
for j in range(1 + i, len(cost)):
if cost[i] + cost[j] == money:
print(str(i + 1) + " " + str(j + 1))
... |
6ab3f5122dfca30facae08ef9a51a47bbc275e45 | maxmii/myapp | /scripts/number_range.py | 229 | 3.59375 | 4 | import sys
def number_range(number):
if int(number) >= 50 and int(number) <= 200:
return "Number is valid"
else:
return "Number is invalid"
#print(number_range(50))
print(number_range(sys.argv[1]))
|
62ee7c0074316a912c72d14906c50b747611cced | xyG67/FabFlix | /cal_avg.py | 1,657 | 3.75 | 4 | def main():
total = 0.0
length = 0.0
average = 0.0
try:
TS = raw_input('Enter the TS file name and path, if you do not know, type ts.txt: ')
TJ = raw_input('Enter the TJ file name and path, if you do not know, type tj.txt: ')
totalTS = 0.0
lengthTS = 0.0
averageTS =... |
d85a139d910c67059507c6c73d49be723f3faa56 | bugmark-trial/funder1 | /Python/sum_of_digits_25001039.py | 349 | 4.25 | 4 | # Question:
# Write a Python program that computes the value of a+aa+aaa+aaaa with a given
# digit as the value of a.
#
# Suppose the following input is supplied to the program:
# 9
# Then, the output should be:
# 11106
#
# Hints:
# In case of input data being supplied to the question, it should be
#
# assumed to be a ... |
d3a32cd816f83245e03cf0e17a45f91c66c4b0bf | dichen001/CodeOn | /HWs/Week 7/Recursive_FIb.py | 145 | 3.734375 | 4 |
def solveFib(val):
if val == 0 or val == 1:
return val
else:
return solveFib(val-1) + solveFib(val-2)
print solveFib(0) |
e10eae47d7a19efb93d76caeb2f6a2752cdd6666 | dichen001/CodeOn | /HWs/Week 5/S5_valid_anagram.py | 1,626 | 4.125 | 4 | """
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
"""
def isAnagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
### Please start your code here###
le... |
d71fe3bbadffb4084d4da928971b623fe3627100 | dichen001/CodeOn | /HWs/Week 6/Single_Queue.py | 485 | 3.90625 | 4 | # Queue class
class Queue(object):
def __init__(self):
# Start the queue
self.queue = []
def enQueue(self, val):
# Append a new value to the queue
self.queue.append(val)
def deQueue(self):
# Take out the first value in the list
return self.queue.pop(0)
def... |
723763fca2b01dc53fb81f627b3b7bb0accbc891 | dichen001/CodeOn | /HWs/Week 3/LinkedList.py | 993 | 3.8125 | 4 | class Node(object):
def __init__(self, val=None):
self.val = val
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
def ins(self, node=None):
if node:
node.next = self.head
self.head = node
def getLen(self):
... |
680aaf12f0c4c61a3304a91559aaee6ed1a57ae2 | dichen001/CodeOn | /HWs/Week 5/S5_two_sum_sorted.py | 2,176 | 4 | 4 | """
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Please note that your returned answers... |
bd90689da08ce04c428fdf4781e06e935bce3243 | vinaypathak07/codezilla | /Sorting/Merge Sort/Python/merge_sort.py | 1,107 | 4.25 | 4 | def merge_sort(array_list, start, end):
'''Sorts the list from indexe start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(array_list, start, mid)
merge_sort(array_list, mid, end)
merge_list(array_list, start, mid, end)
'''Merges each sorted l... |
3e73ef211d9d20808bad316e3d1f8493a386abd7 | joeyyu10/leetcode | /Array/56. Merge Intervals.py | 731 | 4.21875 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are ... |
935379c6960d70bac803fe4fd0dd8600351b80e5 | Artyom-rgb/infa_2020_artyom | /lab3/ex2.py | 1,828 | 3.84375 | 4 | import pygame
import math as mt
from pygame.draw import *
pygame.init()
FPS = 30
screen = pygame.display.set_mode((800, 800))
screen.fill((255, 255, 255))
orange = (255, 106, 10)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 55)
syr = (225, 0, 255)
colorx = (180, 141, 141)
blue = (141, 202, 204)
def three(x, y... |
886bcb3990f524a5495b4254f71d6f6d03986a9f | reemanaqvi/HW06 | /HW06_ex09_06.py | 939 | 4.34375 | 4 | #!/usr/bin/env python
# HW06_ex09_05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write function(s) to assist you
# - number of abeced... |
0ad30fc8730fc6c16b4acb00c8774df35b987271 | mitchl2/CodeEvalSolutions | /src/wifi_search.py | 10,268 | 3.921875 | 4 | '''
Functions that determine which buildings have Wi-Fi hotspots.
The corresponding CodeEval challenge for this module is called "Where is Wi-Fi"
(https://www.codeeval.com/open_challenges/159/).
Created on Oct 19, 2015
@author: Mitchell Lee
'''
import sys
from itertools import izip
from math import cos, sin, radi... |
a922550fd95b01543a9bf7fcc1b596c6ddb09f80 | AdrianPratama/AdrianSuharto_ITP2017_Exercise2 | /Palindrome.py | 196 | 4.25 | 4 | word = input("Please input the word here:")
word_list = list(word)
if word_list == list(reversed(word_list)):
print("The word is a palindrome")
else:
print("The word is not a palindrome")
|
3750c27703921a1f2eac98b8507b406489d6ae62 | giosullutrone/DeBlur_dataset_generator | /src/AugmentedImage.py | 2,855 | 3.53125 | 4 | class AugmentedImage:
"""Class that lets you manipulate an image"""
@staticmethod
def get_image_width(image):
return image.shape[1]
@staticmethod
def get_image_height(image):
return image.shape[0]
@staticmethod
def image_from_file(image_path, grayscale=False):
"""Ge... |
8d3c52d71990361ba4c8b5ef1ce6da85d881e214 | snowu/various | /fibonacci.py | 194 | 3.828125 | 4 | class Fibonacci():
val1= 1
val2= 1
val3= 0
while 1 > 0:
val2= val1 + val2
val1 = val2 - val1
print '%s' % (val2) + '\n'
#import pdb
#pdb.set_trace()
Fibonacci()
|
8981d1e20e26a2def75105b34768a289ba6de3f1 | Splashbeats/EnglishGrammarBattle | /py/testScript.py | 1,197 | 3.640625 | 4 |
# I'm expecting 2 breaks
sentenceToTest = "Jack went to bed late last night because he studied _____ 1:00 a.m."
print("---------------------------------------------------")
print("------------------Test Script----------------------")
print("---------------------------------------------------")
print("Testing: " + se... |
3b4ac26a260e4a0118d90637899ee3755c975a97 | aburmd/leetcode | /Regular_Practice/easy/17_371_Sum_of_Two_Integers.py | 1,883 | 4.125 | 4 | """
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
"""
class Solution:
def getPositivesum(self,a,b):
while b!=0:
bitcommon=a&b #Example: 4(100),5(101) bit commo... |
771bead3170f430741cd5303038f507f5153e4ed | aburmd/leetcode | /Regular_Practice/easy/19_350_Intersection_of_Two_Arrays_II.py | 1,463 | 4.09375 | 4 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in an... |
0a300b6aacc8325c5441b5152f3d2885f4377e1b | aburmd/leetcode | /Regular_Practice/easy/16_387_First_Unique_Character_in_a_String.py | 946 | 3.890625 | 4 | """
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
"""
import collections
class Solution:
def firstUniqChar(self,... |
9eba98a92942adeb3cffc9bab950d03c384e56c0 | MarthaSamuel/simplecodes | /OOPexpt.py | 1,142 | 4.46875 | 4 | #experimenting with Object Orienting Programming
#defining our first class called apple
class Apple:
pass
#we define 2 attributes of the class and initialize as strings
class Apple:
color = ''
flavor = ''
# we define an instance of the apple class(object)
jonagold = Apple()
# attributes of the object
jonago... |
e1ed0266607d521df5085b3b4fa919b689acb0fb | mctr/pro-lang | /Python/Veri_yapilari/fibonacci.py | 218 | 3.671875 | 4 | #! usr/bin/python
# -*- coding :utf-8 -*-
def fib(a):
if a < 2:
return 1
else:
return fib(a-1) + fib(a-2)
#~ print fib(6)
def fak(a):
if a < 2:
return 1
else:
return a * fak(a -1)
#~ print fak(15)
|
2a0cc28451850f29f1d0f9240ebdeef2bd4dd535 | mctr/pro-lang | /Python/Veri_yapilari/gcd-obeb.py | 203 | 3.78125 | 4 | def gcd(a, b):
if b == 0:
return a
else:
return gcd(b,a%b)
#~ print gcd(8,6)
def obeb(a ,b):
while a % b != 0:
olda = a
oldb = b
a = oldb
b = olda % oldb
return b
#~ print obeb(2, 5)
|
a9ff3ede005cd6e8bda3061d24b45909919f7086 | Shreyanshu333/Volve-Machine-Learning | /dca.py | 7,857 | 3.578125 | 4 | def hyperbolic(t, qi, di, b):
"""
Hyperbolic decline function
"""
import numpy as np
return qi / (np.abs((1 + b * di * t))**(1/b))
def arps_fit(t, q, plot=None):
"""
Arps Decline Curve Analysis using Non-Linear Curve-Fitting
Input:
t = time array (in numpy datetime64)
q = production rate array (... |
5a96386d565c64f041abcd761be2a45325e813b4 | Jivaldo-Cruz/calendar | /calendario.py | 600 | 3.921875 | 4 | import time
from datetime import date, datetime
import calendar
#show calendar
date_complete = time.localtime()#get date of computer
Calendar = calendar.calendar(date_complete[0])#Show calendar for cause of years
print(Calendar)
#division
print(f"{'='*70}")
#calendar complete
today = date.today()
print(f"The date t... |
4ac5b4a4d773a73aa6768d57afd9e44a3482cb86 | AllenWang314/python-test-scaffolding | /interview.py | 275 | 4.3125 | 4 |
""" returns square of a number x
raises exception if x is not of type int or float """
def square(x):
if type(x) != int and type(x) != float:
raise Exception("Invalid input type: type must be int or float")
print(f"the square is {x**2}")
return x**2
|
b2657312ad32f9829d36945c97322cf0333fe11a | ZachLynch123/python-projects | /matplotlib/barGraph.py | 757 | 4.0625 | 4 | import matplotlib.pyplot as plt
""" Bar chart
# dataset 1
x = [2,4,6,8,10]
y = [6,7,8,2,4]
# dataset 2
x2 = [1,3,5,8]
y2 = [8,5,6,7]
# plotting as bar graph
plt.bar(x, y, label="Bars1", color='r')
plt.bar(x2,y2, label="Bars2", color='c') """
# histograms, which are used to show distribution
# dataset 1
populatio... |
84ed875a37f483f8acfa592c24bd6c9dd5b4cbf7 | RuchirChawdhry/Python | /all_capital.py | 1,163 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
"""
Write a program that accept a sequence of lines* and prints the lines
as input and prints the lines after making all the ... |
656ae9779498767407dfbec47689c6aaf15907d3 | RuchirChawdhry/Python | /circle_class.py | 984 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
"""
Define a class 'Circle' which can be constructed by either radius or diameter.
The 'Circle' class has a method which can ... |
ee72fca759b6f86d90e344bd93e23050db601d34 | piro15/KimJimin | /python_problem/python_problem_1.py | 968 | 3.84375 | 4 | import random
num=0
def brGame(self,opponent):
a=0
while a==0:
try:
n=int(input("부를 숫자의 개수를 입력하세요(1,2,3만 입력 가능):"))
if n!=1 and n!=2 and n!=3 :
print('1,2,3 중 하나를 입력하세요')
else:
for i in range(n) :
global num
... |
071f64909e548392e286f24516a6af9ef5c2d7a7 | devansh-18-punj/Snake-Water-and-Gun-game | /Snake_Water-Gun.py | 3,570 | 3.859375 | 4 | import random
import playsound
print("\n *** Welcome to snake water and gun game ***\n")
print("You have to choose number of chances, how many you want to play")
print("Scoring will be done accordingly and lastly all the best for your game \n")
your_points = 0
Computer_points = 0
n = int(input("Enter number of... |
1f86f8a400284bf10354a24cce7f3bd0d4467c9b | ruizheng0521/Everyday_HWs | /Everyday HWs/sorting algorithem hw2.py | 2,731 | 4 | 4 | from random import *
def which_algor(select, size, lst,start = None, end = None):
if len(lst) != size:
return "list size do not match"
if select == 0:
return bubble_sort(lst)
elif select == 1:
return insertion_sort(lst)
elif select == 2:
return selection_sort(lst)
elif select == 3:
return... |
a52555080501916879d674e032f192358403f8cb | krishnatejaperannagari/Project_Euler | /HackerRank_Project_Euler_001_001_Test.py | 328 | 3.671875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(raw_input())
for i in range(T):
Sum = 0
N = int(raw_input())
Temp = (N - 1) // 3
Sum += (Temp * (3 + Temp * 3)) // 2
Temp = (N - 1) // 5
Sum += (Temp * (5 + Temp * 5)) // 2
Temp = (N - 1) // 15
Sum -= (Temp * (15 + Temp * 15)) // 2
p... |
8e0906b40277f7921faf5e1380dc34249e83a9a7 | shosseini811/Hackerrank-Solutions | /Drawing Book.py | 557 | 3.78125 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/drawing-book/problem
import os
import sys
#
# Complete the pageCount function below.
#
def pageCount(n, p):
if p%2 ==0:
c1 = p /2
c2 = (n-p)/2
else:
c1 = (p-1)/2
c2 = (n - p -1)/2
if c1<=c2:
return(int(c1))
... |
0b234e329e30321c38ba803dacd62792007ec593 | ykim5470-Lewis/westagram | /Info1110/week02/Sum.py | 147 | 3.671875 | 4 | parameter1= 4
parameter2= 5.5
sum= parameter1+ parameter2
print("The sum of " +str(parameter1)+ " and "+str(float(parameter2)) +" is " + str(sum))
|
bf124ae72ad7509858c10319adcf3c6d78ef4dae | timok90/towa | /database.py | 3,022 | 3.625 | 4 | import sqlite3
class MySqliteDb(object):
def __init__(self):
self.test_var = 1
self.connection = None
self.cursor = None
self.logging_table = False
self.tablename = None
self._create_connection(
"C:\\Users\\timok\\Desktop\\TOWA\\Python\\sqlite\\pysqlite... |
0c92e87ae3755a7e147c17f384ac761f105d822e | LobbyBoy-Dray/Leetcode-Problem-Set | /code/2020-11-06-中等-分隔链表.py | 1,591 | 3.671875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def partition(head, x):
# 用哑结点初始化两个链表
before_head = ListNode(-999)
after_head = ListNode(-999)
# 指针初始化
before = before_head
after = after_head
# 遍历原链表
while head:
if head.val < x... |
c1a549522015d059f993b2f5613f649df910c1d4 | LobbyBoy-Dray/Leetcode-Problem-Set | /code/0621-中等-任务调度器.py | 769 | 3.578125 | 4 | def leastInterval(tasks, n):
# Step 1
max_count = 0
my_dict = dict()
for i in tasks:
if i in my_dict:
my_dict[i] += 1
else:
my_dict[i] = 1
if my_dict[i] > max_count:
max_count = my_dict[i]
# Step 2
max_nums = []
for i in my_dict:... |
eba74eed72394a3e790e6a966464c6e28c110778 | LobbyBoy-Dray/Leetcode-Problem-Set | /code/2020-11-06-中等-两两交换链表中的节点.py | 1,228 | 3.75 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def swapPairs(head):
# 先固定真实开头
before = head
# 添加哑结点
tmp = ListNode(-999)
tmp.next = head
head = tmp
# 前驱设置
previous = head
while before and before.next:
after ... |
61b1092108d34b1b0a75f59f49bb9648a307a68f | LobbyBoy-Dray/Leetcode-Problem-Set | /code/2020-11-07-中等-两数相加.py | 959 | 3.515625 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1, l2):
curr_l1 = l1
curr_l2 = l2
ans_head = ListNode(-999)
ans_curr = ans_head
# 进位计数器
carry = 0
while curr_l1 or curr_l2:
tmp = carry
if curr_l1:... |
a8123bfa8f1c164aba08e9068ed29da72166e806 | Sanchi02/Dojo | /BackToRoots/Heap.py | 1,564 | 3.859375 | 4 |
class Heap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def heapify(self,index):
while(index//2 > 0):
if (self.heapList[index] > self.heapList[index//2]):
self.heapList[index], self.heapList[index//2] = self.heapList[index//2]... |
047a51a0facbbb358b719da0db50e64e3c72e688 | Sanchi02/Dojo | /BackToRoots/BinSearch.py | 461 | 3.90625 | 4 | numList = [1,2,3,4,5,6,7,8,9,20]
def binSearch(lower,upper,numList,num):
if(upper>=lower):
mid = int(lower+(upper-lower)/2)
if(numList[mid]==num):
return mid
elif(numList[mid]>num):
return binSearch(lower,mid-1,numList,num)
else:
return binSearch(... |
af882ed610e2b3ea1ca54d175439b59b22fc81fe | Sanchi02/Dojo | /LeetCode/DP/CoinsChange.py | 1,216 | 3.96875 | 4 | # You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
# Example 1:
# Input: coins = [1, 2, 5], amount = 11
#... |
b14ebe99e35d74973076154fc537ca71cb78ff30 | Sanchi02/Dojo | /BackToRoots/SinglyLL.py | 2,250 | 3.875 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SinglyLL:
def __init__(self):
self.head = None
def printList(self):
currNode = self.head
val = currNode.data
while currNode is not None:
print(val)
... |
f7aff74db8e567029bd1b2f3f1b20a6abcf78c62 | Sanchi02/Dojo | /PracticeComp/AMSGAME1.py | 247 | 3.546875 | 4 | def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
for _ in range(int(input())):
num = int(input())
arr = list(map(int, input().split(' ')))
res = arr[0]
for i in arr[1:]:
res = gcd(res,i)
print(res)
|
932b0f7f067f3f92d2f551ffa2f9354cf351b0e2 | Sanchi02/Dojo | /LeetCode/ClimbingStairs.py | 1,039 | 3.984375 | 4 | # https://leetcode.com/problems/climbing-stairs/
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
# Example 1:
# Input: 2
# Output: 2
# Explanation: There are two ways to climb to the top.
# 1. 1 ... |
6e71571b65ba743786399f3c84da4ba5e826d389 | Sanchi02/Dojo | /LeetCode/LinkedList/RevereseLL.py | 887 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# class Solution:
# def reverseList(self, head: ListNode) -> ListNode:
# prev = None
# nextPtr = head
# while(nextPtr):
# tmp = nextPtr.n... |
92a2ce9363a823e57202519cce2daf55eb9f7cb7 | Sanchi02/Dojo | /RecurrentModules/SieveOfErosthensis.py | 343 | 3.640625 | 4 | rangeOfNum = int(input())
primes = []
sieve = [True]*(rangeOfNum+1)
sieve[0] = False
sieve[1] = False
p = 2
while (p*p <= rangeOfNum):
if(sieve[p] == True):
for i in range(p+p, rangeOfNum+1, p):
sieve[i] = False
p += 1
for i in range(rangeOfNum+1):
if(sieve[i] == True):
primes.a... |
22c0f7dcb62a981c154b6582f3eecb504126f000 | Sanchi02/Dojo | /LeetCode/Strings/ReverseWordsII.py | 1,286 | 3.984375 | 4 | # Given an input string , reverse the string word by word.
# Example:
# Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
# Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
# Note:
# A word is defined as a sequence of non-space characters.
# The input string does not contai... |
15f18d0bbfc641ce6a8f98fe48d7404523e050ad | Sanchi02/Dojo | /BackToRoots/DoublyLL.py | 1,159 | 3.921875 | 4 | class Node:
def __init__(self, data=None):
self.prev = None
self.data = data
self.next = None
class DoublyLL:
def __init__(self):
self.head = None
def printList(self):
currNode = self.head
val = currNode.data
while currNode is not Non... |
b586ee5e0157c98c691f4b48d362233ef91f0e54 | Sanchi02/Dojo | /LeetCode/DP/UniquePaths.py | 1,623 | 4.09375 | 4 | # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
# How many possible unique paths are there?
... |
433677cbd6b0179703ce63f20d33b5191a830887 | Sanchi02/Dojo | /LeetCode/CourseSchedule.py | 2,185 | 4.0625 | 4 | # There are a total of n courses you have to take, labeled from 0 to n-1.
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
# Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you sh... |
7480729ee5a08e2466ec71ad6f0c4493a2c6d45a | Sanchi02/Dojo | /LeetCode/DecodeString.py | 2,084 | 3.828125 | 4 | # https://leetcode.com/problems/decode-string/
# Given an encoded string, return its decoded string.
# The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
# You may assume that the input str... |
f3c2abbab1697397006113c42c1fc03568d17719 | Sanchi02/Dojo | /LeetCode/Strings/ValidPalindrome.py | 742 | 4.125 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Example 1:
# Input: "A man, a plan, a canal: Panama"
# Output: true
# Example 2:
# Input: "race a car"
# Output: fals... |
7690ccd7dea37f64af44cdd0ea84a7bf439cb264 | Sanchi02/Dojo | /LeetCode/RotateList.py | 1,405 | 3.9375 | 4 | # Given a linked list, rotate the list to the right by k places, where k is non-negative.
# Example 1:
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
# Example 2:
# Input: 0->1->2->... |
61168129a2a63174699324ddabb394d94160fda1 | Sanchi02/Dojo | /PracticeComp/LAPIN.py | 647 | 3.796875 | 4 |
for i in range(int(input())):
stringy = list(input())
isLapin = True
half1, half2 = [],[]
if(len(stringy)%2==0):
mid = int(len(stringy)/2)
half1 = stringy[0:mid]
half2 = stringy[mid:len(stringy)]
else:
mid = int(len(stringy)/2)
half1 = stringy[0:mid]
... |
768e42c29a97bcf3c2d6ec5992d33b9458fb56e8 | ujjwalshiva/pythonprograms | /Check whether Alphabet is a Vowel.py | 256 | 4.40625 | 4 | # Check if the alphabet is vowel/consonant
letter=input("Enter any letter from a-z (small-caps): ")
if letter == 'a' or letter =='e' or letter =='i' or letter =='o' or letter =='u':
print(letter, "is a Vowel")
else:
print(letter, "is a Consonant")
|
16e2b332cc9022d3a25d0d64e7fdd97a664d6cc5 | ujjwalshiva/pythonprograms | /Number of Characters in an Email.py | 610 | 3.6875 | 4 | mail = input("Enter Your Email-Id: ")
mail=mail.lower()
vowels = consonants = num = whitespaces = spcharacters = 0
for i in mail:
if i in ['a', 'e', 'i', 'o', 'u']:
vowels += 1 # vowel = vowel + 1
elif i in ['1','2','3','4','5','6','7','8','9','0']:
num += 1
elif i == " ":
whitespac... |
f2f04679c0f9f0f64000d4c27c940d153d044d10 | Volfee/graph_traversal | /graph.py | 2,198 | 4.03125 | 4 | import collections
class Graph:
"""
Directed and weighted graph using adjacency list
"""
def __init__(self):
self.adjacency_list = dict()
def add_node(self, value):
self.adjacency_list[value] = self.GraphNode(value)
def add_edge(self, val1, val2, weight, directional=False):
"""
Creates edge from node ... |
ccdd055ba5366cba70eeba991c7a3230e9543f72 | rath/me2terminal | /utils.py | 360 | 3.53125 | 4 | # -*- coding: utf-8 -*-
#
# Author: Jang-Ho Hwang <rath@xrath.com>
# Version: 1.0, since 2009/09/12
#
def length(str): return len(str.decode('utf-8').encode('euc-kr'))
def expand_to(str, len, pad_char=' '):
remain = len - length(str)
pad = remain / 2
ret = "%s%s%s" % (pad_char*pad, str, pad_char*pad)
... |
b914eb951b9e1bec9282fc9caa8a060fc8178a8c | mayanksh/datastructure | /ds_array_heros.py | 260 | 3.828125 | 4 | heros=["spider man", "thor", "hulk", "iron man", "captain america"]
print(len(heros))
heros.append("black panther")
print(heros)
heros.remove("black panther")
heros.insert(3,"black panther")
print(heros)
heros[1:3]= ["doctor strange"]
heros.sort()
print(heros) |
e2fc183c66e10a9b10bf5bf5c42255338068723b | josecolella/PLD | /src/levels.py | 16,291 | 3.796875 | 4 | #!/usr/bin/env python3
import pygame
class Level:
"""
This class represents the different levels of the game and
allows for scalability of the game
"""
@staticmethod
def cycle_check(toggle_objects):
"""
Check if toggle chains in toggle_objects do not contain cycles
A ... |
0499bc68514da5150191be0a0433f3a27b2cc4c3 | iamakhilverma/codingBat-python | /List-1/sum3.py | 81 | 3.609375 | 4 | def sum3(nums):
result = 0
for num in nums:
result += num
return result |
9f255c7148485589c93570e3b7cc5e7f9f186274 | haowu74/DailyCoding | /Day394/Program.py | 1,110 | 3.875 | 4 | import argparse
class node:
def __init__(self, value, left=None, right=None) -> None:
self.value = value
self.left = left
self.right = right
def build_node(index, numbers):
size = len(numbers)
value = numbers[index]
right = None if index * 2 + 2 >= size else build_node(index * ... |
335651174e61037a113b6b98d1a4c234e242f247 | haowu74/DailyCoding | /Day396/program.py | 757 | 3.765625 | 4 | import argparse
def palindromic(word):
size = len(word)
if size <= 1:
return True, size
if size == 2:
return (True, 2) if word[0] == word[1] else (False, 1)
l = 0
if word[0] == word[size - 1]:
r, l = palindromic(word[1:size-1])
# Only used when the substring has to b... |
137572ce21e3d19177094664e1cbf64a8d241317 | frsilent/random | /python_book/more.py | 445 | 3.765625 | 4 | __author__ = 'frsilent'
def more(text, numlines = 15):
"""
breaks up a text file into sections so users can scroll through it with y/Y
"""
lines = text.split('\n')
while lines:
chunk = lines[:numlines]
lines = lines[numlines:]
for line in chunk: print(line)
if lines ... |
c649f6449fce38e22bec8258d8621c32f18dc6a6 | MultiRRomero/lightwall-pong | /server/game.py | 1,730 | 3.625 | 4 | #!/usr/bin/python
import time
""" This represents a ball object in pong """
class Ball:
def __init__(self, position_x, position_y, direction, speed):
self.px = position_x # x coordinate (in pixels)
self.py = position_y # y coordinate (in pixels)
self.dir = direction # ball direction (in... |
5177ce59da595ad925ebeab60093fb37b600674f | wunoah5/Guess | /GuessWhile.py | 775 | 4.0625 | 4 | #終極密碼 while 的寫法
# 1.產生1~1000的隨機整數
# 2.讓使用者猜
# 3.每次猜錯時會告知範圍
import random
maxr = 100
mixr = 1
r = random.randint(mixr+1, maxr-1)
while True:
print('終極密碼', mixr, '到', maxr, ': ')
ans = int(input())
#如果回答等於隨機數
if r == ans:
print('~~你~最~雖~小~~')
break
#如果回答大於最小值且小於隨機數,取代最小值
elif ans ... |
1b27851e71bb8a6b2f76ecdb98bad7f7716873b1 | A01376572/Mision_06 | /listas.py | 2,557 | 4.0625 | 4 | # Autor: Daniel Rojas, A01376572
# Misión 6. Listas en Python
def recortarLista(enteros): #Elimina el primer y último valor de una lista
enteros2 = []
for indice in range(len(enteros)):
n = enteros[indice]
if indice != 0 and indice != len(enteros)-1:
enteros2.append(n)
... |
3b9e27604e1ad3f221f223d61c278188dc790e65 | leandromoreirati/Explorando-Marte | /explorando-marte.py | 2,520 | 3.640625 | 4 | import sys
from itertools import islice
class Direcoes(object):
w = {'x': -1, 'y': 0}
n = {'x': 0, 'y': 1}
e = {'x': 1, 'y': 0}
s = {'x': 0, 'y': -1}
posicao = {'W': w, 'N': n, 'E': e, 'S': s}
@staticmethod
def proxima_direcao(comando, posicao_atual):
c_referencia =... |
74bd72dc3f5daf31e59c4d0ee24d32a016a56b23 | Sudhansh6/HDR-IL | /Peg In Hole HDR-IL/NNModel.py | 1,153 | 3.53125 | 4 | #Neural Network
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
import torch
class Net(nn.Module):
def __init__(self, input_size, output_size, hidden_size):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidde... |
9c8c2d07f6bd60fbcadebf7d533a6e3124fef4ae | davidwang0829/Python | /小甲鱼课后习题/43/习题2.py | 705 | 4.125 | 4 | # 定义一个单词(Word)类继承自字符串,重写比较操作符,当两个Word类对象进行比较时
# 根据单词的长度来进行比较大小(若字符串带空格,则取第一个空格前的单词作为参数)
class Word(str):
def __new__(cls, args):
if ' ' in args:
args = args[:args.index(' ')]
return str.__new__(cls, args) # 将去掉括号的字符串作为新的参数初始化
def __lt__(self, other):
return len(self) < le... |
26223d6c2bed2e56a4f01cbb932b3d4d67ff3266 | davidwang0829/Python | /小甲鱼课后习题/47/习题1.py | 1,479 | 3.703125 | 4 | # 定制一个列表,要求实现以下要求:
# (1)实现获取,设置和删除一个元素的行为(删除元素的时候对应的计数器也会被删除)
# (2)增加counter(index)方法,返回index函数所指定的元素记录的访问次数
# (3)实现append(),pop(),remove(),insert(),clear()和reverse()方法
class CountList(list):
def __init__(self, *args):
super().__init__(args)
self.count = []
for i in range(len(args)):
... |
2464ef162d7e78abc5ae47fd319ad5d73ad9e7f9 | davidwang0829/Python | /小甲鱼课后习题/16/习题2.py | 316 | 3.890625 | 4 | # 编程实现sum()
def sum1(obj):
result = 0
for i in obj:
if i.isnumeric() is True: # 在isdigit,isdecimal和isnumeric中isnumeric判定范围最广
i = int(i)
result += i
else:
continue
return result
temp = input('Test sum():')
print(sum1(temp))
|
293b42218daa67efd25faf950a7f77d8a7e280eb | davidwang0829/Python | /小甲鱼课后习题/32/习题1.py | 294 | 3.71875 | 4 | # 请问以下代码是否会产生异常,如果会的话,请写出异常的名称:
my_list = [3, 1, 5, 4, 2]
my_list.sorted()
p = open('C:\\test.txt', wb)
f.write('I love Python!\n')
f.close()
def my_fun1():
x = 5
def my_fun2():
x *= x
return x
return my_fun2()
|
09b4f6f111c59763c7b7438c5a6f534e5450600e | davidwang0829/Python | /闰年.py | 465 | 3.890625 | 4 | #编写一个程序,判断是否是闰年
print("欢迎使用") #欢迎使用
year = int(input("请输入一个年份:"))
while year <= 0:
print("年份需要大于0,请重新输入") #如果小于等于0 告知重新输入
year = int(input("请输入一个年份:"))
if year % 4 == 0:
print("您输入的年份", year, "是一个闰年")
else:
print("您输入的年份", year, "不是一个闰年")
print("谢谢使用")
|
16e13a2f6042e3deae198df89a2956f6648edfb4 | davidwang0829/Python | /小甲鱼课后习题/34/习题2.py | 1,464 | 4.15625 | 4 | # 使用try…except语句改写第25课习题3
print('''--- Welcome to the address book program ---
--- 1:Query contact information ---
--- 2:Insert a new contact ---
--- 3:Delete existing contacts ---
--- 4:Exit the address book program ---''')
dic = dict()
while 1:
IC = input('\nPlease enter the relevant instruction code:')
if I... |
6bb8689b169b93e53e361329c03ef609d33799f3 | davidwang0829/Python | /小甲鱼课后习题/35/习题1.py | 1,640 | 3.71875 | 4 | # 为04课的猜数小程序加上界面
# 使用try…except语句
import easygui as g
import random
g.msgbox("--------------Let's play a game--------------", '习题1')
answer = random.randint(1, 10) # 答案为1~10内的某一随机数字
times = 3 # 初始化计数器
guess = 0
while times >= 0: # 你甚至可以写成while times + 1:
title = 'Guess the number'
if times > 0:
msg... |
e2ff4a0f6df1717d29370cb9ce43fb6741aa9632 | davidwang0829/Python | /小甲鱼课后习题/45/属性访问.py | 775 | 4.1875 | 4 | # 写一个矩形类,默认有宽和高两个属性
# 如果为一个叫square的属性赋值,那么说明这是一个正方形
# 值就是正方形的边长,此时宽和高都应该等于边长
class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def __setattr__(self, name, value):
if name == 'square':
self.width = self.height = value
el... |
d2fc97783679c543c89fc174a7772b3fbda0f495 | davidwang0829/Python | /小甲鱼课后习题/46/习题1.py | 1,537 | 3.765625 | 4 | # 编写描述符Record:记录指定变量的读取和写入操作
# 并将记录以及触发时间保存到文件:record.txt
import time as t
class Record:
def __init__(self, value, record):
self.value = value
self.record = record
def __get__(self, instance, owner):
try:
with open('record.txt', 'a') as f: # 记录读取操作
time = ... |
ab57709d2a0df789897229e8ab9a7415afcf1a84 | MinCheng123/Python | /leetcode/299. Bulls and Cows.py | 827 | 3.6875 | 4 | class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
bull,cow=0,0
p,q=0,0
temp=0
count=0
secret,guess=list(secret),list(guess)
while p<len(guess):
if se... |
f0b51cd72a6cd1b0eb78165ce8b1efedd2aa5b71 | MinCheng123/Python | /leetcode/20. Valid Parentheses.py | 872 | 3.53125 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
abcd = []
hashmap1 = {'(': ')', '{': '}', '[': ']'}
hashmap2 = {')': '(', '}': '{', ']': '['}
for eleme... |
81224612ad6cfe0daf76773cdad7a15925d58924 | MinCheng123/Python | /leetcode/48. Rotate Image.py | 1,690 | 3.765625 | 4 | class Solution:
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
size = len(matrix[0])
for row, element in enumerate(matrix):
for column, value in enumerate(element):... |
85eacaf5b08b922f9327e58912c44e680c6fd7d7 | kovalgek/algorithms | /algorithms/sort/merge_sort.py | 697 | 3.71875 | 4 |
def merge(A, p, q, r):
n1 = q - p + 1
n2 = r - q
L = []
R = []
for i in range(n1):
L.append(A[p + i])
for j in range(n2):
R.append(A[q + 1 + j])
L.append(float('inf'))
R.append(float('inf'))
i = 0
j = 0
for k in range(p,r+1):
if L[i] <= R[j]:
... |
f9c06d0aa2a7f4543793378a1c2ce49a863a3508 | AnanyaBanerjee/Machine-Learning | /assignment_6/6_3_1.py | 4,421 | 3.71875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 23:06:35 2018
@author: Ananya Banerjee
Neural Network
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score
#from sklearn.neural_network import MLPCLassifier
from sklearn.line... |
9f3b1bd849a6c28edca1b6252fe3b92734eda184 | ahsia3/SecureSay | /ServerPlus.py | 11,814 | 3.578125 | 4 | #A server that can contain multiple clients
from socket import *
from random import *
from _thread import *
import DatabasePlus
def encryption1(string):
encrypted_string = ''
for i in range(len(string)):
encrypted_string += (chr(ord(string[i]) + 1))
return encrypted_string
# Method to determine L... |
b628105fa291c3c70f0e883451b9762d13e696c5 | JRigelo/python_the_hard_way | /hard_way5.py | 645 | 3.671875 | 4 | # exercise 5
# more variables and printing
my_name = 'joyce'
my_age = 33 # perhaps a lie
my_height = 178 # cm
my_weight = 129 # lbs
my_eyes = 'brown'
my_teeth = 'white'
my_hair = 'brown'
print "Let's talk about %s." % my_name
print "She's %d centimeters tall." % my_height
print "She's %d pounds heavy." % my_weight
pr... |
dbbd8b9824860d9daf5303006cf7f737b0140609 | kamleshbiloniya/demo | /cpsir/part6.py | 236 | 3.5 | 4 | from scipy.integrate import quad
import numpy as np
def integrand(x,t):
return (t**x) / (1+2*t+3*t**2+4*t**3+3*t**4+2*t**5+t**6)
def expint(x):
return quad(integrand, 0, np.inf, args=(x))[0]
for i in range(0,6):
print(i,expint(i))
|
be23213891eb1945990bd61cec32c986a29fba49 | matvelius/Selection-Sort | /selection_sort.py | 1,825 | 4.3125 | 4 | # The algorithm divides the input list into two parts:
# the sublist of items already sorted, which is built up from left
# to right at the front (left) of the list, and the sublist of items
# remaining to be sorted that occupy the rest of the list.
# Initially, the sorted sublist is empty and the unsorted sublist ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.