blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
431e68d6ad74199ea6e389fb2202034086412520 | Rasketch-ai/00001 | /ring_of_integers_modulo_n/ring_of_integers_modulo_n.py | 4,218 | 3.96875 | 4 | import numbers
''' Функции, которые пригодятся '''
def gcd(n_1, n_2):# Алгоритм Евклида
'Алгоритм Евклида'
r_1 = n_1
r_2 = n_2
while r_1 != 0 and r_2 != 0:
if r_1 > r_2:
r_1 = r_1 % r_2
elif r_1 < r_2:
r_2 = r_2 % r_1
else:
brea... |
4838a3696f45d8fc28b49b93f5a58ea02ef5e4fb | hoangvupham2004/LHL_21_Day_Challenge | /Day13.py | 600 | 4.03125 | 4 | '''
Challenge 13
Use the pandas sort function and the pandas filter function from the previous challenge to answer these questions:
1. Which wines had a quality of 8 or higher and a residual sugar level above 5?
2. How many wines in total had a quality of 8 and 7 and a citric acid level below 0.4?
Note: Use the index ... |
8ca39a2f830c4dd3bd522748603feffd68815d53 | hoangvupham2004/LHL_21_Day_Challenge | /Day14.py | 2,406 | 3.84375 | 4 | '''
Challenge 14
Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley, and that the
sulfates can't be that high. The problem is, Dot can't really afford to spend tons of money on the wine.
Dot's conditions for searching for wine are:
Sulfates cannot be higher than 0.6.
... |
f6c023d8304e9e0fc9260236830220367e27e386 | hsclinical/leetcode | /Q00__/92_Reverse_Linked_List_II/Solution.py | 977 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
if left == right:
return head
else:
... |
23f6c0825d26b0923d0ebb09dc3b521dbd17146f | hsclinical/leetcode | /Q01__/29_Sum_Root_to_Leaf_Numbers/Solution.py | 1,049 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
if root == None:
return 0
else:
... |
eb60933ed09636bef8e23bb9085082c09f865145 | hsclinical/leetcode | /Q02__/11_Design_Add_and_Search_Words_Data_Structure/Solution.py | 1,312 | 3.765625 | 4 | import re
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.wordSet = []
self.searchResult = {}
self.wordSearched = {}
def addWord(self, word: str) -> None:
self.wordSet.append( word )
def search(self, word... |
9ed44e8405a992a194d64ef1dfe95b7da8b63d1b | hsclinical/leetcode | /Q02__/71_Encode_and_Decode_Strings/Solution.py | 1,253 | 3.71875 | 4 | from typing import List
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string.
"""
outString = ''
unitLen = 8
for singleStr in strs:
strLen = len(singleStr)
strLenLen = len(str(strLen))
outStrin... |
fade680b52fabd4035b53c353eaf7781bb3eb353 | hsclinical/leetcode | /Q01__/05_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/Solution.py | 2,522 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder) == 0:
... |
69e5661bd5fe59a28a46de35f26557fa2604de34 | hsclinical/leetcode | /Q03__/37_House_Robber_III/Solution.py | 1,284 | 3.71875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rob(self, root: TreeNode) -> int:
if root == None:
return 0
else:
val1, v... |
09179b3c7fec89ec1ea012e02280dbb9201ff8f1 | hsclinical/leetcode | /Q01__/50_Evaluate_Reverse_Polish_Notation/Solution.py | 938 | 3.53125 | 4 | from typing import List
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stackNum = []
for singleToken in tokens:
if singleToken == '+' or singleToken == '-' or singleToken == '*' or singleToken == '/':
num2 = stackNum.pop()
num1 = stackNum.po... |
b395e57364d47626cf2bec3d1331fdc5aefcac47 | Ashmit7Ayush/Registration_form | /Registration.py | 12,681 | 3.65625 | 4 | # first makae the course registration format and subjects
class Registration:
def FirstSem(self):
print('Select the Courses ')
sem_1_dict = {
'MA101':'Mathematics 1',
'CS101':'Computer Programming',
'CS110':'Computer Programming Lab',
'EC10... |
aee6d73a731b5069c23e3c8f4f7ba4ecf5e1eba0 | naveengovindasamy/basic-python-programs | /factorial using built in function.py | 113 | 3.953125 | 4 | import math
n = int(input("enter the number:"))
result = math.factorial(n)
print("factorial of",n,"is",result) |
4274d584263c40a8262dd78bd98b9bfc780ca18b | Phoom/pyBank | /main.py | 2,818 | 4.03125 | 4 | # Steven Pham
# Unit 3 | Assignment - Py Me Up, Charlie
# Option # 1 - pyBank
import os
import csv
# Setting path for data files
csvpath = os.path.join("budget_data_2.csv")
# Setting up dictionary for holding monthly changes
date_rev = {}
# Setting up variables to hold various counters
month_count = 0
total_reve... |
c3686278fb25e852cef3a4fca964492a9ccd31a0 | Parva1610/Multi-Programs | /Cryptography Codes/RSA.py | 1,908 | 3.859375 | 4 | import random
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def inverse_multiplication(e, phi):
d = 0
x1 = 0
x2 = 1
y1 = 1
temp_phi = phi
for i in range(temp_phi):
if((e*i)%temp_phi == 1):
return i
def prime_func(num):
if num =... |
c6400ec2a265d2f656495ccc4baa9cba389061ab | Parva1610/Multi-Programs | /Cryptography Codes/DSS_Verification.py | 1,044 | 3.5 | 4 | import hashlib as hsh
def modInverse(s, q):
for i in range(1, q):
if((s * i) % q == 1):
return i
return -1
print('\n Digital Signature Verification')
print('\n Global Public Key Parameters : ')
p = int(input('\n p : '))
q = int(input(' q : '))
g = int(input(' g : '))
y =... |
c92619eac619de6aff4aeaca4a4790ad7e4e475a | AtaiDobrynin/pythonmipt | /course1/filereader_class.py | 262 | 3.515625 | 4 | class FileReader():
def __init__(self, path):
self.path = path
def read(self):
try:
with open(self.path, 'r') as inf:
result = inf.read()
return result
except IOError:
return ""
'''
reader = FileReader("example.txt")
print(reader.read())
''' |
537127df185eaa3ce2930294f1004bd89e34bbe1 | toomasm/RNA-tools | /Toomas/trimmer.py | 8,072 | 3.625 | 4 | from Bio import SeqIO
import sys
import pysam
def read_trimmer(input_filename, output_file, trim_from_5p_end, Flag_3prime):
"""
Program that trims your specified amount of nucleotides from the 5 prime end of the fastq reads.
This code also allows a step for polyA tail trimming.
If Flag "Flag_3prime"... |
f932dbb68dc484386211a77c238b6b3e41a7ffe0 | KateKopteva/Lesson_12 | /task_12_1/ui_func.py | 792 | 4.03125 | 4 | """Реализовать пользовательский
интерфейс с бесконечным циклом"""
from exceptions import *
from func import *
def calculator():
while True:
x = input('a = ')
y = input('b = ')
if not is_number_invalid(x) or not is_number_invalid(y):
print('Введите числовое значение!')
... |
3698ac235aaaca7f7c79b3ad28293cb11d08b20e | balakumaran-sugumar/python | /assignmentproj/Deck.py | 612 | 3.671875 | 4 | # add all the cards to the deck, the deck should have 52 cards in all
import random
from assignmentproj.Card import Card, suites, ranks
class Deck:
card_deck = []
# create combination of 52 cards and add it to the deck
def __init__(self):
for suite in suites:
for rank in ranks:
... |
b5cbfaa460bd60bc92bd0418477ed3b836077423 | balakumaran-sugumar/python | /filterMapReduce/simpleLambda.py | 778 | 4.25 | 4 | def square(num):
return pow(num, 2)
need_squared = [1, 2, 3, 4, 5, 6]
# this is function as argument
mapped_func = map(square, need_squared)
# this prints the address and nothing else
print(mapped_func)
# printing the contents of the map in for loop
for numbers in mapped_func:
print(numbers)
# filter func... |
b16ac06faf2097883d44e1549ad3a394f1268962 | balakumaran-sugumar/python | /DataStructuresAndAlgorithms/IOs/io_file.py | 1,032 | 4.1875 | 4 | # modes
# 'r' open for reading (default)
# 'w' open for writing, truncating the file first
# 'x' create a new file and open it for writing
# 'a' open for writing, appending to the end of the file if it exists
# 'b' binary mode
# 't' text mode (default)
# '+' ope... |
6af52a8b6d45cac64a5e78cbe21d4655dccced70 | balakumaran-sugumar/python | /advanced_modules/Collections.py | 466 | 3.953125 | 4 | from collections import Counter
list_counter = [1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7]
# this is a dict where the key is the actual value and the value is the key
print(Counter(list_counter))
# this is another way of getting the count of the words in the sentence
words = "This is for ... |
e48b0508c327e8e7b80b83f3557b198d74bdce48 | katosadchuk/ML-Practice | /Sinkhole Kaggle Comp/hw4.py | 2,742 | 3.890625 | 4 | # Kateryna Osadchuk
# hw 4
import numpy as np
from sklearn.neural_network import MLPClassifier
import pandas as pd
def main():
filename1 = "train.csv"
filename2 = "test.csv"
# make matrix of training data from csv file
train_data = np.genfromtxt(filename1, delimiter=",", dtype='float32', autostrip=Tr... |
596b634a8986c3a8e20865a6662556361284acdf | MathiasDarr/TwitterDatathon | /sparkNLP/generate_sentiment_aggregation.py | 1,000 | 3.546875 | 4 | """
This file contains functions for creating a dictionary where the keys are state names and the values are the average sentiment
for each candidate.
"""
from sparkNLP.utils.construct_spark_dataframe import create_dataframe_from_parquet
def generate_average_sentiment_dictionary(dataframe):
"""
Generates a d... |
4551a19b4247b5a78231da84ca19d0a83342c2a4 | vijayalakshmimekala/dsp-programmes | /mul.py | 680 | 4.03125 | 4 | r1=int(input("enter the rows of matrix1"))
c1=int(input("enter the columns of matrix1"))
r2=int(input("enter the rows of matrix 2"))
c2=int(input("enter the columns of matrix 2"))
if(c1==r2):
a=[ ]
print("enter the elements of matrix1")
for i in range (0,r1):
for j in range(0,c1):
a[i,j]=int(input( ))
b={ }
print... |
36f5001776a0789825726762e958440553abb01a | elsaabs/hackinscience | /exercises/080/solution.py | 221 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 14:15:37 2015
@author: elsa
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for i in range(0, 26):
for j in range(i+1, 26):
print(alphabet[i] + alphabet[j])
|
05e1170a9bab029cff2faa4904fa07c0c6d842d0 | elsaabs/hackinscience | /exercises/019/solution.py | 248 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 19:57:58 2015
@author: elsa
"""
import sys
import operator
if len(sys.argv) == 3:
print(operator.add(int(sys.argv[1]), int(sys.argv[2])))
else:
print('usage: python3 solution.py OP1 OP2')
|
c311380c29181e3a797f438c6281d01c5f7dd28e | elsaabs/hackinscience | /exercises/329/mul.py | 564 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 11:54:57 2015
@author: elsa
"""
def mul(list):
if len(list) == 0:
return 0
else:
a = 1
for number in list:
a = number * a
return a
'''
def mul(list):
if len(list) == 0:
return 0 #if I put a==0 instead of... |
bdc97e862ddab22e927fccbe5c9fbc6e0e0a4dc3 | FayStatha/atds-project-NTUA-2021 | /code/generate-parquet.py | 680 | 3.53125 | 4 | # This script is used to generate and save .parquet files
# from .csv files, to use them as an input to SparkSQL query scripts
from pyspark.sql import SparkSession
from io import StringIO
import csv, sys
spark = SparkSession.builder.appName("generate-parquet").getOrCreate()
# The user must give the path of the csv f... |
182136600a873cbbc31db606c48176f4be241948 | Cameron-Carter/ICS3U-Assignment-02-Python-sphere_volume | /sphere_volume.py | 533 | 4.375 | 4 | #!/usr/bin/env python3
# Created by: Cameron Carter
# Created on April 2021
# This program calculates the volume of a sphere based on inputted radius
import math
def main():
# This function calculates volume
print("This program calculates the volume of a sphere.")
# Input
radius = float(input("Ente... |
b63af7208c08291659ee9d9369a36f5162201f73 | zhensolid/princess | /用户登录窗口.py | 1,085 | 3.609375 | 4 | import tkinter
#定义类
class Weblog(object):
#定义函数
def login():
print("登陆成功")
def cancel():
print("取消登陆")
def loginwin():
win = tkinter.Tk()
win.title("登陆窗口")
win.geometry("400x200")
tkinter.Label(win, text="用户名:").place(x=50, y=50)
tkinter.Label(win,... |
6938c7996baf86d451ce6b99bdaf9aa3ebd5a221 | kaelwebdev/holbertonschool-interview | /0x09-utf8_validation/0-validate_utf8.py | 408 | 3.609375 | 4 | #!/usr/bin/python3
"""
0x09 UTF-8 Validation
"""
def validUTF8(data):
"""
check valid UTF-8
"""
c = 0
for n in data:
m = 1 << 7
if not c:
while n & m:
c = c + 1
m >>= 1
if c > 4:
return False
elif n >>... |
58e6490fb146823eb634b813f4ad0d0ed730a700 | kaelwebdev/holbertonschool-interview | /0x1F-pascal_triangle/0-pascal_triangle.py | 598 | 4.03125 | 4 | #!/usr/bin/python3
"""
Pascal triangle
Commented section uses binomnal theorem (Newton's binaminal theorem)
to calculate Pascals' triangle
"""
# from math import factorial as fc
def pascal_triangle(n):
"""Pascal Triangle"""
a = []
if n <= 0:
return a
# for i in range(n):
# ... |
3dd88bb27113072724cf9306c186b701564bd7c0 | cech-matej/python-basics | /03-types/tuple.py | 2,242 | 4.375 | 4 | '''
Tuples - neměnitelné n-tice hodnot (seřazený seznam prvků)
In Python tuples are written with round brackets.
Tuples v Pythonu se píše pomocí kulatých závorek
'''
# Vytvoření tuples
numbers = (1, 2, 3)
print('numbers: ', numbers)
print('Type(numbers): ',type(numbers))
chars = tuple('Hello world')
print('chars:... |
cccba3041295462d570b19bae2b11aa6c10a8814 | tholmberg/Python-101 | /Alpabetical_sort_strings.py | 381 | 4.4375 | 4 | # Parse a string and then apply an alphabetical sort to the words
#Apply a string to the code
# my_str = "Hello world Lets parse some strings!"
#User input a string
my_str = input ("Enter a string: ")
#Break the string into a list
words = my_str.split()
#sort the list
words.sort()
#dsplay the sorted words
print (... |
0f983f318b51736ceb9d8f2ef365f1c8eea7e2c1 | JustinZhanay/Unit-4-Lesson5 | /Lesson5/Problem5.py | 542 | 3.875 | 4 | from turtle import *
Squirtle = Turtle()
screen = Screen()
Squirtle.color("blue")
Squirtle.pensize(5)
Squirtle.speed(6)
Squirtle.turtlesize(1,1,1)
Squirtle.shape("turtle")
screen.bgcolor("red")
def row():
def drawStar():
for x in range(5):
Squirtle.forward(75)
Squirtle.left(144)
Squirtle.penup()
Squirtle... |
f8f7686f1c4d7c9888c90adbfc80adc9d2607980 | bakeryproducts/concepts | /code_basics/classes.py | 911 | 3.84375 | 4 | class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self):
raise NotImplementedError('im an Abstract class you dummy!')
class Dog(Pet):
def talk(self):
print('imma doggo called ' + str(self.name))
jack = Dog('Jack', 3)
# jack.talk()
pet = ... |
e909d55ecc638f6094fb31a212e58d252ddd7444 | bakeryproducts/concepts | /threadsnqueue.py | 1,517 | 4.15625 | 4 | # basics of threading with queues
import threading
from queue import Queue
import time
print_lock = threading.Lock() #lock for continues printing
def job(worker): #main job to be done with multiple threads
time.sleep(.5) #sim it
with print_lock:
print(threadi... |
d21ab95441782a6d9db123618f94f971e59167a2 | bakeryproducts/concepts | /code_basics/mapping.py | 271 | 3.59375 | 4 | import random
li = [1,2,3]
def dbl(amm):
return amm*2
new = list(map(dbl,li))
print(new)
#---------------------------------------
import heapq
ran=[random.randint(1,100) for _ in range(10)]
print(heapq.nlargest(3,ran),ran)
# 2/12/2013 9/2/2017
month=3
year=3
|
fc77c05d1c375b284c4f69da2986f4039741ae97 | ClintonOliera/password | /credentials.py | 1,253 | 3.859375 | 4 | class Credentials:
"""
Class that generates new instances of users.
"""
credentials_list = []
def __init__(self,credentials_name,name,password,email):
self.credentials_name = credentials_name
self.name = name
self.password = password
self.email = email
... |
b07a33019225dac6ab3e7f5b13fd0c2f98f13bbb | savaged/PyFun | /HomeworkSent.py | 217 | 3.859375 | 4 | userInput = input("sent? (True/False): ")
print(userInput)
StudentRecord = ["Joe", "Homework Forgotten", "-2", str(userInput)]
msg = "Letter"
if StudentRecord[3] == "False":
msg = msg + " not"
msg = msg + " sent."
print(msg)
|
230fd993c381d42ce474cb2b6af31102a259614c | wellingtongb/www.codeChef.com | /TotalExpenses.py | 407 | 3.546875 | 4 | lineAmount = int(raw_input())
result = 0
i = 0
while i < lineAmount:
userData = raw_input()
splitUserData = userData.split(" ")
productsAmount = int(splitUserData[0])
#print "products " + str(productsAmount)
price = int(splitUserData[1])
#print "price " + str(price)
result = productsAmount * price
if products... |
600b3b0aceb2fc529c20500ff38ba3e139f20520 | Mario096/Python-Pandas | /python/RunTimings.py | 1,782 | 4.125 | 4 | #Define main
def main():
message = "Athlete Min Max Avg\n"
#get user input on number of athletes
number = input("Enter the number of athletes practicing:")
#validate user input
while not (number.isdigit()):
print("Number of athletes must be an integer")
number = input("Enter the n... |
2e253472f852dc777d3bee414a9e135585662b4a | FelipeBalam/U3---Actividad-No.-2---Bit-cora-de-Pr-cticas | /U3 - Actividad No. 2 - Bitácora de Prácticas.py | 4,168 | 3.796875 | 4 | #local
import time
print (" Ejemplo local")
print (" Vamos a realizar una suma")
print ("Ingresa un primer valor:")
N1 = int (input(""))
print ("************************")
print ("Ingresa un segundo valor:")
N2 = int (input(""))
print ("*************************")
SUMA=N1+N2
print ("Suma de Valores ingresado... |
f8a3608a7c49acaf2bd28739cbb5528a2da73060 | zubairwazir/code_problems | /leetcode/python/arrays/product_array_except_self.py | 684 | 3.90625 | 4 | class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n= len(nums)
prodSoFar= 1 #running product
output = [nums[n-1]]*n
#preprocessing the array
for i in range(n-2,-1,-1):
... |
e72c8921d1f1f0791c7283ae21cbc75296ab6b32 | zubairwazir/code_problems | /leetcode/python/search_insert_position.py | 1,209 | 4.09375 | 4 | # Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
# You may assume no duplicates in the array.
# Example 1:
# Input: [1,3,5,6], 5
# Output: 2
# Example 2:
# Input: [1,3,5,6], 2
# Output: 1
# Example 3:
# Inpu... |
38022eb76d713dcb8f5be3e8602d37d425d4cf39 | zubairwazir/code_problems | /classical_algorithms/python/Bubble Sort.py | 421 | 4.21875 | 4 | def bubblesort(array):
n = len(array)
for i in range(0,n-1):
for j in range(0,n-i-1):
if (array[j] > array[j+1]):
array[j] , array[j+1] = array[j+1] , array[j]
print(array)
m = int(input('Enter the number of elements in the array '))
mylist = []
for... |
125f9b4446d4547dc84f6d257d9a6acdc6148b69 | zubairwazir/code_problems | /cracking_the_code/chapter3/Q3.3-stack-of-plates.py | 2,602 | 3.734375 | 4 | from stack import Stack
class SetOfStacks:
lst_stacks = []
def __init__(self, capacity):
self.capacity = capacity
self.lst_stacks.append(Stack())
self.last_stack_size = 0
def push(self, value):
last_stack = self.lst_stacks[-1]
if self.last_stack_size < self.capaci... |
59aafd1672dd4b25faef41af9b574c433c5bff24 | zubairwazir/code_problems | /cracking_the_code/chapter4/minimal_tree_v2.py | 786 | 3.75 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class MinimalTree:
def __init__(self, array):
self.root = self.createMinimalBST(array)
def createMinimalBST(self, array):
if len(array) <= 0:
return None
... |
9ea027f7a0ff74b472bf9b46379e690e6b9c4874 | zubairwazir/code_problems | /cracking_the_code/chapter1/Q1.2_check_permutation.py | 1,332 | 3.953125 | 4 | import unittest
"""
The first approach would be sort the strings and compare it. But sorting takes O(nlogn) (time), so we have to find a better approach.
The second approach (the one implemented here) uses the fact that if a string is a permutation of the other, it has to have
the same number of the exact same characte... |
a05c69f1b641cd5be9c657be6c60b959a04bc033 | zubairwazir/code_problems | /leetcode/python/Dynamic Programming/746.min_cost_climbing_stairs.py | 1,885 | 4.03125 | 4 | # On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
#
# Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
#
# Example 1:
# Input: c... |
40537617d9b0f8f92e2e4c3d69f4bd45c445d63d | zubairwazir/code_problems | /cracking_the_code/chapter1/Q1.5_one_away.py | 1,501 | 3.5 | 4 | import unittest
import logging
# O(n) time
def one_edit_away(str1, str2):
if abs(len(str1) - len(str2)) > 1:
return False
else: # make str1 be always the longest
if len(str2) > len(str1):
tmp = str2
str2 = str1
str1 = tmp
i = j = 0
diff = Fa... |
bbbf80428330e907c97a96dafe5ebcfa1eaec8a2 | zubairwazir/code_problems | /cracking_the_code/chapter4/Q4.2_minimal_tree.py | 1,863 | 4.03125 | 4 | ################################################(Way 1)#############################################################
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insertTree(self, data):
if self.data:
if data < self.data:
if self.left:
self.lef... |
221e445f41ab002ccbcdb493d64faa1b9260b28f | insisthzr/leetcode | /leetcode77/main.py | 676 | 3.640625 | 4 | #!/usr/bin/env python3
class Solution:
def __init__(self):
self.k = 0
self.n = 0
self.array = []
self.result = []
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
self.n = n
self.k = k
... |
a815561ed2fe2b34e12ac94207f29fb463e5c438 | insisthzr/leetcode | /leetcode56/main.py | 971 | 3.84375 | 4 | #!/usr/bin/env python3
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort(key=lambda interval: interval.st... |
4df8cad9449f022ae0c34f42515b12d837cbeaae | lampton14/week1 | /day1/binarytooctal.py | 1,920 | 3.78125 | 4 | def BinaryToOctal(number):
unit = input("does you number have a decimal? ")
if unit == "yes":
[num_bef_dec, num_aft_dec] = number.split(".")
if unit == "no":
num_bef_dec = number
num_aft_dec = ""
output = ""
if len(num_bef_dec) % 3 == 1:
num_bef_dec = "00" + num_bef_... |
9847063266a68725cb37eac073e0473053b2ea21 | mluceroc/WHacks | /models/location.py | 422 | 3.75 | 4 | class Location:
def __init__(self, latitude, longitude):
self.longitude = longitude
self.latitude = latitude
def __str__(self):
return self.latitude + " " + self.longitude
def __hash__(self):
return hash((self.latitude, self.longitude))
def __eq__(self, other)... |
fce559a22952919e68092a04910c0c8aea3128ac | shinglyu/leetcode-solution | /326-power-of-three.py | 1,075 | 3.875 | 4 | # brute force O(log_3 n)
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
rem = n
while rem >= 3:
if rem % 3 != 0:
return False
rem = rem/3
if rem == 1:
return True
... |
a9bc25ded93912ab1d3c567a615fa98932aef428 | impacevanend/unalPython | /algoritmosOrdenamiento/ordenamientoInser.py | 636 | 3.890625 | 4 | #ordenamiento por burbuja
#poco efciente -> hace en este caso
#64 iteraciones 8*8
#Se cambia multiples veces.
#Se llevan a cabo muchos cambios, muchas comparaciones.
lista =[5,7,3,1,8,4,9,2,6]
for i in range(len(lista)-1):
for j in range(len(lista)-1):
print("Comparando:", lista[j],"con",li... |
ca17e89a2a1e245deeec291de07ad348b8ea3761 | impacevanend/unalPython | /funcioRecursiva.py | 2,155 | 3.75 | 4 | """
suma(5) = 5+4+3+2+1+0
suma(4) = 4+3+2+1+0
suma(n) = n + suma(n-1)
"""
# def suma(n):
# if n == 0:
# return 0
# else:
# a = suma(n-1)
# print(a)
# return n + a
# print(suma(5))
# def suma_parcial(l,n):
# if n == 0:
# return 0
# else:
# ret... |
b014557fa828f7b765db114b76c94597cb77a210 | impacevanend/unalPython | /algoritmosOrdenamiento/pruebaAlgoritmosOrdenamiento.py | 2,697 | 3.75 | 4 | ##Ordenamiento por selección, burbuja, burbuja mejorado
import random
lista1 = [random.randint(1, 100) for i in range(100)]
lista2 = list(lista1)
lista3 = list(lista1)
lista4 = list(lista1)
lista5 = list(lista1)
print("----------------------------------")
comparaciones = 0
cambios = 0
#Burbuja básico
for i in rang... |
b6ac47dec6139b9aebf86b7116b30bca2099516d | impacevanend/unalPython | /clase/funciones.py | 859 | 3.9375 | 4 | #*Función cuadrado
def f(x):
return x ** 2
#print(f(2))
#*área circulo
def area(radio):
pi = 3.14159265
return pi * radio ** 2
#print(f'El area del circulo es: {area(10)}')
#*área rectangulo
def area_rectangulo(largo, ancho):
return largo * ancho
#print(f'El area del rectangulo es: {area_rectang... |
49ab06f02abf50bf145205fd1c5bf9c23ed4ea2f | impacevanend/unalPython | /tuplas.py | 3,409 | 4.375 | 4 | """
Se delimita por medio de una coma y paréntesis redondos
(,)
No se pueden modificar después de definidas
("Texto",) Una tupla con elemento que e una cadena. Para el caso de una tuplas de un sólo elemento
Python requiere una coma final para considerarla una tupla.
*Formas de crear tuplas:
x = ()
tup =(1,2,3,4,5,'... |
a3dc82a2ee33ea6691f13c155834e4fe880c2992 | impacevanend/unalPython | /clase6-7deJunio.py | 543 | 4.0625 | 4 | """
Librerias:
Numpy(arreglos en varias dimensiones),
pandas,
"""
import numpy as np
# a = np.zeros((2,3,4))
# print(a.shape)
# print(a)
# print("--------")
# def log_entero(num, base=2):
# cont = 0
# while num >= base:
# cont+=1
# num /= base
# return cont
# print(log_entero(1024))
#... |
4d832066ee5e40ff13b4f8d2bed12945d9b325c4 | bloy/adventofcode | /2015/dec20.py | 1,162 | 3.578125 | 4 | #!/usr/bin/env python
import math
def factors(number):
divisors = [x for x in range(1, int(math.sqrt(number)) + 1)
if number % x == 0]
large = [number // divisor for divisor in divisors
if number != divisor * divisor]
return divisors + large
def present_count(house_number):
... |
e6ea79a25e0b4535c4bfd0c60109553f282bfce0 | SimoHsieh/PythonCrashCourseExercises | /5.1.hw.py | 1,024 | 4.09375 | 4 | #1
name = "Simo"
print('Is name == simo? I predict False.')
print(name == "simo")
#2
name = "Simo"
print('Is name == Simo? I predict True.')
print(name == "Simo")
#3
name = "Simo"
print('Is name.lower() == simo? I predict True.')
print(name.lower() == "simo")
#4
name = "Simo"
print('Is name != Simo? I predict False.')
... |
c9e8a7375b8ee7f91a2bd6d204d6e747e29021f5 | SimoHsieh/PythonCrashCourseExercises | /5.3hw.py | 172 | 3.703125 | 4 | alien_color = ['green','yellow','red']
#1
if alien_color[0] == "green":
print("You just earned 5 point!")
if alien_color[1] == "green":
print("You just earned 5 point!") |
7630e3916a31a56186765e2ece3dedbe8f6c6668 | SimoHsieh/PythonCrashCourseExercises | /5.7.hw.py | 225 | 3.890625 | 4 | favorite_fruit = ['apple','molo','pupu']
if "apple" in favorite_fruit:
print('You really love apple!')
if "molo" in favorite_fruit:
print('You really love molo!')
if "pupu" in favorite_fruit:
print('You really love pupu!') |
8c95426c6fadb8e9ada1ce281b2c71e7b3799004 | PragmaticBeaver/code-dump | /python/fibonacci.py | 885 | 4.09375 | 4 |
# fibonacci_cache= {}
# def fibonacci(n):
# if n in fibonacci_cache:
# return fibonacci_cache[n]
# if n == 1:
# value = 1
# elif n == 2:
# value = 1
# elif n > 2:
# value = fibonacci(n-1) + fibonacci(n-2)
# fibonacci_cache[n] = value
# return value
from functoo... |
9b64f61226d4839b5f3700e0bcff104f4fb35c75 | komal-sharan/New-Eleusis | /scientistI.py | 10,847 | 3.53125 | 4 | #alternate
#AND_OR
from new_eleusis import *
#from card_generator import *
import CurrentBestHypothesis
#import alternate_card_generator
correct = []
wrong=[]
l=['5S','6D','8C']
#global prevres
prevres=None
def correct_wrong(card):
print "?????",prevres
#print "hbh",CurrentBestHypothesis.co... |
bbc2638a7243637933753207647d05d8baa8374d | roshid2500/kg_roshid2500_2021 | /main.py | 1,090 | 3.9375 | 4 | import sys
#Input arguments are global constants in this case
#Must check whether arguments are given
INPUT1 = sys.argv[1] if(len(sys.argv) == 3) else "";
INPUT2 = sys.argv[2] if(len(sys.argv) == 3) else "";
'''
Determines whether string x has a one-to-one mapping with
string y
O(n) time where n = len(x)
... |
b0449fe7fddb4a8210ac536fc06b4da39c0ae52a | Boldie/PartKeeprPrintingService | /src/DeviceRawPrinter.py | 783 | 3.671875 | 4 | import Printer
class DeviceRawPrinter (Printer.Printer):
"""
This is a printer implementation, which accesses a device
over the filesystem. Everything passed to printData will be
directly written to the device.
"""
def __init__(self, config):
self.config = config;
# Check a... |
9d1de513262600d6169212b43e5b0a3ecebf064e | verydecent/Data-Structures | /linked_list/linked_list.py | 1,602 | 3.71875 | 4 | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
retu... |
c56dc3796648176c96990cfb9220b63b3dc881ec | Wrexan/GB_Python_Algo | /wrex_hw_lesson_3/wrex_algo3_hw1.py | 765 | 3.5 | 4 | # 1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
operand_range = (2, 9)
field_range = (2, 99)
result = []
for o in range(operand_range[0], operand_range[1]+1):
result += o, 0
for f in range(field_range[0], field_range[1]+1):
if f % ... |
435231c2da19f8cc6399fa281c9c42fd5035b57a | Wrexan/GB_Python_Algo | /wrex_hw_lesson_2/wrex_algo2_hw1.py | 2,947 | 4.0625 | 4 | # 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
# Числа и знак операции вводятся пользователем.
# После выполнения вычисления программа не должна завершаться,
# а должна запрашивать новые данные для вычислений.
# Завершение программы должно выполняться при вводе символа '0' в... |
2a0eb98cedae51e519e6f49978bad53d4aea55a7 | SPRINGING/e296MA_hw2 | /python/Driver.py | 1,081 | 3.703125 | 4 | from abc import ABCMeta, abstractmethod
class Driver:
__metaclass__ = ABCMeta
def __init__(self, name, weight):
self.name = name
self.weight = weight
@abstractmethod
def throttle_action( car, env):
pass
@abstractmethod
def stop_for_refueling( car, env):
pas... |
b6a27a1d16af5b37acbe8eb64e54d1ab1635660c | swp2-5class/shinmyeongcheol | /소프 로마자 과제(9) 20181635신명철/calcFunctions.py | 2,566 | 3.609375 | 4 | from math import factorial as fact
def factorial(numStr):
try:
n = int(numStr)
r = str(fact(n))
except:
r = 'Error!'
return r
def decToBin(numStr):
try:
n = int(numStr)
r = bin(n)[2:]
except:
r = 'Error!'
return r
def binToDec(... |
8764cc45fb552557f56fb027fd553738f79595ce | jiyeonCoder/YamPizza | /yamPizza.py | 2,764 | 3.84375 | 4 | #Yam Pizza Ver.1.0
#Written by Jiyeon Choi
#Jun.17.2021.
import turtle as t
import random
from playsound import playsound
#Set score as 0
score = 0
# Check if the game is currently playing
playing = False
#Background music
playsound('yamPizza_music.wav', block=False)
#Turn turtle right
def turn_rig... |
a2152f425cb21d0f6675d990f9130a9338191a41 | jaredg-ai/module-4-assessment | /process.py | 724 | 3.53125 | 4 | log_file = open("um-server-01.txt")
# this opening the file 'um-server.01.txt' and assigning it to log_file in order to get the necessary data from the file.
def sales_reports(log_file):
for line in log_file:
line = line.rstrip()
day = line[0:3]
if day == "Tue":
print(line)
#thi... |
4e11621e27ac01135f7182aefbf57a4cf06fb65f | KristinaPlazonic/slurm_data_parallelization | /single_task_script.py | 1,311 | 3.59375 | 4 | #!/home/kp807/anaconda3/bin/python
from functools import reduce
import sys
import os.path
def computeOneFile(filename):
""" This is an example of a computation to parallelize. In this case, we count the number of words in the given file.
"""
with open(filename, 'r') as f:
#### implement your own ... |
4d3a63491c08371395a1ae713903f47336f8d37b | GuilhermeFariasn7/infosatc-lp-avaliativo-02 | /questao5.py | 330 | 4.09375 | 4 | #Escreva um programa para verificar se um elemento x está presente em uma lista.
FRUTAS = []
FRUTAS = ["banana","morango",'laranja','abacate','jecaa']
verificar = input("Digite algo para saber se está na lista: ")
if verificar in FRUTAS:
print(verificar," está na lista!")
else:
print(verificar," nao está na li... |
e1c4c2b8c46e991088672c46dc9378dcaf991a96 | marcosfeelipee/MediaDoALuno | /Python/2 - numeros positivos.py | 127 | 3.859375 | 4 | n = int(input("Digite um número"))
soma = (n + 1)*n / 2
print("a Soma dos primeiros números de {} é {:.0f}".format(n,soma))
|
762865148341fb020670eae9488d0ea067527861 | saadsaifse/flight-analysis | /movement_analysis/postprocessing/scatterPlotWithFitting.py | 1,553 | 3.6875 | 4 | import os
import sys
import pylab as plt
import numpy as np
from matplotlib.lines import Line2D
def scatterPlot(data, shouldReturn = False):
"""Takes formatted data and plots a scatterplot
Parameters:
data: Two dimensional list, index 0 contains lists of temperatures while index 1 contains list of di... |
a5bda4dce0eaf1b70ee08fb71ea8fbd2fe658167 | ulyssefred/leetcode-and-niuke | /sorttwosortedlist.py | 385 | 3.671875 | 4 | class Solution:
def merge(self, A, m, B, n):
while m and n:
if A[m - 1] >= B[n - 1]:
A[m + n - 1] = A[m - 1]
m = m - 1
else:
A[m + n - 1] = B[n - 1]
n = n - 1
if n:
A[:n] = B[:n]
return A
list... |
9ccb8d98d8e6f9e3accda3b28db5389fbf939a34 | ulyssefred/leetcode-and-niuke | /回文链表.py | 1,526 | 3.625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 双指针法
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
cur = head
res = []
while cur:
res.append(cur.val)
cur = cur.next
i, j = 0,len(res)-1
while ... |
f924290641db0c9cdc4be06837001f2b28d2106c | DmitrijRal/new_python_practical_works | /lesson4/Tasks/Task2.py | 370 | 3.96875 | 4 | # Представлен список чисел. Необходимо вывести элементы исходного списка, значения
# которых больше предыдущего элемента.
first_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
print([el for key, el in enumerate(first_list) if key and el > first_list[key - 1]]) |
d8c2acd2341b81a3831c18bce984806a0cee6b41 | DmitrijRal/new_python_practical_works | /lesson3/Tasks/Task 4.py | 750 | 4.21875 | 4 | # Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде
# функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции
# возведения числа в степень.
x = int(input("Ente... |
abd79f94da312557c367d466cab5c1b9e1cd6e0c | DmitrijRal/new_python_practical_works | /lesson6/task1.py | 1,748 | 3.5625 | 4 | # Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет)
# и метод running (запуск). Атрибут реализовать как приватный. В рамках метода
# реализовать переключение светофора в режимы: красный, желтый, зеленый. Продолжительность
# первого состояния (красный) составляет 7 секунд, второго (желт... |
b0dea317f318aac3f8b0670c4564e7a1709c1d30 | DmitrijRal/new_python_practical_works | /lesson4/Tasks/Task1.py | 678 | 3.890625 | 4 | # Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной
# платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах * ставка в час)
# + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с
# параметрами.
from sys import argv
def wage(out... |
35a5859e1756606b144439dab2b74f6a1707d6bd | shortnick/Python-Work | /AutomateBoringStuff/numberGuess.py | 618 | 4 | 4 | #This is a guess the number game
import random
print("Hi! What's your name?")
name = input()
print("Ok,"+name+", I'm thinking of a number between 1 and 20. What is it?")
sekritNum = random.randint(1,20)
for guesses in range(1, 7):
print("Take a guess.")
attempt = int(input())
if attempt < sekritNum:
print("T... |
85b79fd27fbb54be01e28d156227cbaf2edba670 | shortnick/Python-Work | /AutomateBoringStuff/regExExample.py | 442 | 3.5625 | 4 | #! python3
import re
message = "Hello my name is bob. You've got my machine. My cell is 222-896-5555 if you need me urgently."
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo =phoneNumRegex.search(message)
#can also use phoneNumRegex.findall(message)
print("Found number "+mo.group())
batRegex= re.compile(r'... |
48797cae8590e4cdfcc4ec81c5d4506324c2fa1d | priyanka884/Python_assignment | /Task_5.py | 4,807 | 4.3125 | 4 | #1)Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. Make sure to use only higher order function.Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. Make sure to use only higher order function.Write a program to Python f... |
d297b87420fbc2445761edd8844c3c75c5e3cd9e | jihwan89/gitTest | /Practice02.py | 2,237 | 3.828125 | 4 | # 빙고게임
# 1,2. 사용자에게 입력받은 값으로 가로세로 빙고판 만들기, 랜덤 숫자 체우기
# import random
# r_num, c_num = input("가로, 세로의 값을 입력하세요 : ").split()
# b_num = int(input("빙고판의 숫자범위를 입력하세요 : "))
# row = int(r_num)
# col = int(c_num)
#
# com_list = [0 for i in range(row) for j in range(col)]
# num_list = []
# for i in range(row):
# for j in r... |
7717fc0505e46207cf0d6bd62569ba4e2fb9b6e3 | RafayelGardishyan/CLGE | /clge/Behaviour/Vector2.py | 1,666 | 3.703125 | 4 | class Vector2:
def __init__(self, *args):
if len(args) == 1:
self.x = float(args[0].x)
self.y = float(args[0].y)
else:
self.x = float(args[0])
self.y = float(args[1])
def __add__(self, other):
totalx = self.x + float(other.x)
total... |
bb5c320d018f352c10e2a0fc222ee95dcc625e91 | SpencerKasper/BoizDoin-SomeMath | /Riley/Python/ErrorProp/MethodTesting.py | 163 | 3.59375 | 4 | #Testing how methods work
x = 3
def adding(variable):
answer = variable + 1
return answer
finalAnswer = adding(4)
print finalAnswer
|
8bff00c8e3288f965e8cbb20bb6b0c21f69aa5b4 | SpencerKasper/BoizDoin-SomeMath | /Riley/Python/ErrorProp/functionTest.py | 863 | 3.796875 | 4 | #Dice Game
import random
class Dice(object):
def rollDice(self, roll):
dice = [1,2,3,4,5,6]
rolledNumber = random.sample(dice, 1)
return rolledNumber
class Game(object):
def __init__(self):
self.computerRoll = Dice.rollDice()
print("The computer roll... |
57659ed6acd851c1a91b09a548ba59eaf3275a84 | DGovi/HangMan | /Hangman.py | 3,393 | 3.84375 | 4 | import pygame
import math
import random
# setting up the screen
pygame.init()
WIDTH = 900
HEIGHT = 500
disp = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hangman")
# game "settings"
isRunning = True
MAXFPS = 60
clock = pygame.time.Clock()
# colors
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK ... |
aa4e9d8a6c7f883c9e5c146f182bb5465d67c3ee | BrandenEsses/elastic-pendulum | /pendulum.py | 2,493 | 3.640625 | 4 | from matplotlib import pyplot as plt
from scipy.integrate import odeint
import numpy as np
import matplotlib.animation as animation
g = 9.81 # m/s^2
def m1_ode(y,t,m1,m2,k1,l01):
"""
Input:
- y: Initial conditions, tuple (l1, z1, theta1, z2)
- t: Time values, array
- m1,m2,k1,l01: Phys... |
ac3f47f6a4a32e5393d5a1a64cc1dcd088ccbe6b | mhouse1/pi_zero_osd | /test.py | 877 | 3.75 | 4 | '''
overlay a cross on the center of the display
'''
import time
import picamera
import numpy as np
# Create an array representing a 1280x720 image of
# a cross through the center of the display. The shape of
# the array must be of the form (height, width, color)
a = np.zeros((720, 1280, 3), dtype=np.uint8)
a[360, :,... |
a56efaef9f941d902e9e178b83917dc36ddfb1eb | codehakase/python-sandbox-commits | /oop/AndelaHomeStudy/ShoppingCartTest.py | 1,556 | 3.734375 | 4 | import unittest
class ShoppingCartTestCases(unittest.TestCase):
def setUp(self):
self.cart = ShoppingCart()
self.shop = Shop()
def test_cart_property_initialization(self):
self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct')
self.assertIsInstance(self.cart.items, dict, ms... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.