blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1821203583f295e84288655690a363a4ec03ab32 | PengZhao-GitHub/PythonStudy | /PythonPrograms/squareRoot.py | 383 | 4.125 | 4 |
c = input('please enter a number')
x = float(c)
epsilon = 0.01
step = epsilon**3
numGuesses = 0
ans = 0.0
while abs(x- ans**2) >= epsilon and ans**2 <= x:
ans += step
"""print(ans)"""
numGuesses += 1
print('numGuesses =', numGuesses)
if abs(ans**2 - x) >= epsilon:
print('Failed on square root of', ... |
b4b879888ecda1957430a1734d96c3b15a179c1c | shahidul2k9/problem-solution | /leetcode/_735_AsteroidCollision.py | 642 | 3.578125 | 4 | from typing import List
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for ast in asteroids:
while stack and ast != 0:
t = stack[-1]
if (ast > 0 and t > 0) or (ast < 0 and t < 0) or (t < 0 and ast > 0):
... |
2e862dde1d6a7a98c0d83e4392e9dbd2ecf507f5 | Nanared1/Python-Codes | /Python programs/strings and loops quiz.py | 839 | 3.78125 | 4 | #Nana Abekah
#Strings and Loops Quiz
#February 15, 2017
#Mr. Veera
#ICS 4U0
user_input = input("Enter words to be translated: ");
#function to translate from American to Canadian
def Translate(string):
#find = "or";
replace = "our";
#last_letters = string[len(string)-2:len(string)];
return(string[0:le... |
69ef42542d5bd6c96f1a082de5080bc53fb172a2 | dsnowb/data-structures-and-algorithms | /challenges/fizzbuzztree/fizzbuzztree.py | 512 | 3.625 | 4 | from bst import BST
def fizz_buzz_tree(bst):
'''Applies FizzBuzz to binary search tree'''
if not isinstance(bst,BST):
raise TypeError('argument must be of type <BST>')
def fb(node):
print(node.val)
if not abs(node.val + 15) % 15:
node.val = 'FizzBuzz'
return... |
2150b231e49fae9a63f99a49e13812abb588be32 | UCUBezB/BzBCodec | /src/convert.py | 6,048 | 3.53125 | 4 | '''
Module for converting files into custom codec using compression algos
'''
import sys
import numpy as np
from PIL import Image
from moviepy.editor import VideoFileClip
from pydub import AudioSegment
import os
from lzw import lzw_compress, lzw_decompress
from Huffman_algo import HuffmanCode
from lz77 import compress... |
361706354067219b35da4d33aab1148fde4052fc | pw-eiti-anro-21l/piktel_stepanienko | /turtle_manipulation/turtle_manipulation/GetSpeed.py | 1,372 | 3.59375 | 4 | # Sets speed of the turtle according to user input.
# Python imports
import curses
# ROS2 imports
from geometry_msgs.msg import Twist
# Project imports
from turtle_manipulation.Constants import Constants
class GetSpeed:
def __init__(self):
self.speed = Twist()
self.constants = Constants()
... |
1bca3b186a21318256f11204b318c11dd7f46b06 | kevinard/labs_1ads | /exo2_1_4.py | 741 | 3.96875 | 4 | # 2.1.4
#
# Signe d’un produit
#
# Ecrire un programme qui calcule le signe du produit de deux nombres réels sans calculer la valeur de ce produit.
# Par signe, on entend positif, négatif ou nul.
x, y = eval(input("Entrez le premier nombre : ")), eval(input("Entrez le second nombre : "))
# on pose 1 pour un signe pos... |
2d301eb1bc23f599bf997aa208835342b5bdbd21 | LeoGraciano/python | /WHILE condição de parada inteiros.py | 157 | 3.734375 | 4 | r = 0
n = 0
qt = 0
while n != 999:
n = int(input("Digite um valor: "))
if n !=999:
qt += 1
print (n)
print (qt)
print ("FIM")
|
28f95dec261957e9ea00ae650b9ef4ba5517f2dd | whokilleddb/Miscellaneous | /Python/PhoneNumberScan.py | 574 | 3.65625 | 4 | #!/usr/bin/python3
import phonenumbers
from phonenumbers import geocoder, carrier
from tabulate import tabulate
def scanNum(num):
number=phonenumbers.parse(num)
if phonenumbers.is_valid_number(number):
des=geocoder.description_for_number(number,'en')
supplier=carrier.name_for_number(number,'en')
info=[["Number... |
14e1309c1b780111bda6277aeeab8eaf87aedc32 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#187 Exclamation marks series #2 Remove all exclamation marks from the end of sentence.py | 288 | 3.90625 | 4 | # Description:
# Remove all exclamation marks from the end of sentence.
#
# Examples
# remove("Hi!") === "Hi"
# remove("Hi!!!") === "Hi"
# remove("!Hi") === "!Hi"
# remove("!Hi!") === "!Hi"
# remove("Hi! Hi!") === "Hi! Hi"
# remove("Hi") === "Hi"
def remove(s):
return s.rstrip('!')
|
d277cd89f384fa9340411bd4639e0d6d8d71a5a4 | zzy1120716/my-nine-chapter | /ch10/0076-longest-increasing-subsequence.py | 2,751 | 3.65625 | 4 | """
76. 最长上升子序列
给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。
样例
给出 [5,4,1,2,3],LIS 是 [1,2,3],返回 3
给出 [4,2,4,5,3,7],LIS 是 [2,4,5,7],返回 4
挑战
要求时间复杂度为O(n^2) 或者 O(nlogn)
说明
最长上升子序列的定义:
最长上升子序列问题是在一个无序的给定序列中找到一个尽可能长的由低
到高排列的子序列,这种子序列不一定是连续的或者唯一的。
https://en.wikipedia.org/wiki/Longest_increasing_subsequence
https://segmentfault.co... |
f6b57c2b68c585c42b41141768009cb9bd7d8398 | belaboe97/Python | /Week 3/PartD.py | 94 | 3.84375 | 4 | def factor(x,y):
return (y%x==0)
x=5
y=10
if factor(x,y):
print(x,"is a factor of",y) |
4473d1e58eb3c73a887d7bda9a37501dc959818a | manehharutyunyan/python-homeworks | /L3/Problem3.py | 966 | 3.5 | 4 | import cv2 as cv
import numpy as np
img = cv.imread("C:\\Users\\maneh_onrsjft\\Downloads\\Python\\L3\\L3\\practical_homework3\\pic2.jpg")
cv.imshow('pic2', img)
average = cv.blur(img, (7,7)) #more blur
cv.imshow('average blur', average)
cv.imshow('bilateral blur', average)
#img, diameter, sigmacolor (larger value m... |
1a2f59e3127e3a77e44dcd66ac1b814f57746cfb | Jack-Stoneman/CS235FlixSkeleton | /domainmodel/review.py | 1,396 | 3.71875 | 4 | from datetime import datetime
from .movie import Movie
class Review:
def __init__(self, movie: Movie, review_text: str, rating: int, timestamp = None):
if type(movie) is not Movie:
self.__movie = None
else:
self.__movie = movie
if review_text == "" or type(review_t... |
e6940c45f59b27a30aa5ca0e4baff4e81b4edc67 | awasekhirni/pythonecosystem | /3DesignPatterns/3_1_Creational/singleton/SpEight.py | 803 | 3.5625 | 4 | #thread safe implementation of singleton
import threading
class MySingletonClass(object):
__lockObj=threading.Lock() #thread locking
__instance=None #the unique instance
def __new__(cls,*args,**kwargs):
return cls.getInstance(cls,*args,**kwargs)
def __init__(self):
... |
7bd81bcc6faf5207054e621a5e0270b19e75b7d9 | actionpotato/python | /36_dragon.py | 1,637 | 3.796875 | 4 | #!/usr/bin/env python
from random import randint
from sys import exit
import time
# while True
# need a while loop here to cycle through the battle
while True:
fight_dragon()
def fight_dragon():
# This is how I will calculate the D20 values:
dice_roll = (randint(1,20))
d20 = int(dice_roll)
pri... |
66a147cf0ea5cd50b6c5f0f41b55c4b0cba1c65f | onkarj-98/Data_structures_and_Algorithms | /Tree/Tree_from_level_inorder.py | 905 | 3.8125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def buildTree(levelorder, inorder):
if inorder:
for i in range(0, len(levelorder)):
if levelorder[i] in inorder:
node = Node(levelorder[i])
io_... |
4111941268ba3adb376dceb978ec087b601734e9 | akshaymkhare/python | /classwork/20180916/tables.py | 486 | 4.09375 | 4 | #/usr/bin/python
"""
Program : Write a program to accept a lower bound and upper bound form user and display tables
"""
def tables(n):
print (n,"'s Table :\n")
for y in range (1,11):
print(n,"*",y,"=",n*y)
print ("===============")
def main():
lb,ub = eval(input("Enter a lower and upper bound to display the... |
e631ff32ee227668d22816c70ac2bc752493477b | sofiassr97/Problems-Miguel | /problem_2Mike.py | 477 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 16:31:18 2020
@author: Lenovo
"""
#Crea un programa que dada una lista de numeros, regrese la misma lista pero
#sin los duplicados, ejemplo [1, 2, 3,3,3, 4, 4, 1] deberia regresar [1,2,3,4]
def elimina_duplicados(numeros):
lista=[]
for i in listaN:
... |
d3c94bb3c2adc5b8706f0711c5bb6b8cd1414801 | katur/connectfour | /connectfour/util.py | 2,332 | 4.40625 | 4 | def get_int(num, name='Number'):
"""Convert a string to an int.
Raises and error if num is not convertible to an int.
Args:
num (str): The value to cast to an int.
name (Optional[str]): Description of the number (e.g. 'Days'),
to include in error messages.
Returns:
... |
417ae0d1d91e18995b149e009de0bf7a4bf3e85c | axd8911/Leetcode | /wei_ruan_gao_pin/0146_LRU_Cache.py | 1,403 | 3.59375 | 4 | class ListNode:
def __init__(self,key,value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.dic = {}
self.head = ListNode(0,0)
self.tail = ListN... |
77172ad21f1fff627da1caf23ce8b4793f3e6a34 | DavidtheDJ/DSW-10-27 | /Finishing-CoffeeShop.py | 2,866 | 4.125 | 4 | #David Justice
#11-2-16
#Completing the Coffee Shop
import sqlite3
def create_table(db_name,table_name,sql):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",(table_name,))
result = cursor.fetchall()
keep_table ... |
9560f930942820086e6e9a20b908a96fa4ed3bab | San1357/Leetcode_Problem | /Scramble_String.py | 875 | 3.71875 | 4 | '''Problem :Scramble String '''
#CODE :
class Solution:
def __init__(self):
self.map = {} # key: (s1, s2), value: bool
def isScramble(self, s1, s2):
if (s1, s2) in self.map:
return self.map[(s1, s2)]
if len(s1) != len(s2):
self.map[(s1, s2)] = False
... |
291ad6da5a335a247736b83444b7eb41d6599e60 | Aasthaengg/IBMdataset | /Python_codes/p03200/s975632592.py | 341 | 3.5 | 4 | s =list(str(input()))
s_replace = [1 if i == "B" else 0 for i in s]
count = 0
ans = 0
for i in range(len(s_replace)):
if s_replace[i] == 1: #もし黒だったらカウントしてください
count += 1
continue
else: #もし白だったら黒の数を足してください
ans = ans + count
continue
print(ans) |
10a490deecc6c3a58c647aa9c9708d76ca4989da | AryaEver/Machine-No-Learning | /Misc/Bhanu_img.py | 764 | 3.5625 | 4 | # Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from model import modelToBeImported
from Image_Data_Loader import Data_Loader
# Importing the dataset
data = Data_Loader({'fname': 'abc', 'shape': (120, 120)})
X,y = data.read()
# Splitting the dataset into the Training s... |
c8a5323f04c774476282135979cb0c04ce9944d1 | skrishna1978/CodingChallenge-January-2019- | /1.17.2019 | pangramCheck.py | 829 | 4.09375 | 4 | #1.17.2019 - Shashi
import string #import the string module
def is_pangram(sentence): #function starts here
if not sentence: #if blank string
return "N/A"
sentence = sentence.lower() #convert string to lower case
alphabet = "abcdefghijklmnopqrstuvwxyz" #load up all letters in the alphabet
... |
7f7bd8b68fb4de96026570036491dfc6dc5cf0b2 | FlawlessFalcon/Pythonista | /InteractivePy/DataTypes/AtomicDataTypes.py | 616 | 3.703125 | 4 | '''
The standard arithmetic operations, +, -, *, /, and ** (exponentiation), can be used with parentheses forcing the order of operations away
from normal operator precedence. Other very useful operations are the remainder (modulo) operator, %, and integer division, //. Note that when
two integers are divided, the resu... |
089d0045c57c65ae1a034c9939e9c1c13b0aaaaa | project-renard-survey/semanticscience | /tools/MolSurfGenService/MolSurfaceGen32/chimera/share/CGLtk/Citation.py | 619 | 3.984375 | 4 | """ Citation: show citation for literature reference"""
import Tkinter
class Citation(Tkinter.Frame):
"""Citation is treated as a Frame
'cite' is the citation text
'prefix'/'suffix' is text to precede/follow the citation
"""
def __init__(self, master, cite, prefix=None, suffix=None):
Tkinter.Frame.__init__(... |
ec85f1c76e2c87aa1377c61c2927c70d8190b94e | dlfkid/AssertRenameAndPackScripts | /Music_name.py | 1,158 | 3.75 | 4 | import os
import os.path
import sys
rootdir = sys.path[0]
print("脚本所在位置:" + rootdir)
dirName = input("输入需要进行资源包整理的文件夹名字:")
firstDir = input("输入音乐包起始ID:")
def walkMusicFile(dirname,firstid):
startID = int(firstid)
for parent, dirnames, filenames in os.walk(os.path.join(rootdir, dirName)):
for dir in ... |
d9db88fcb91e1b5a27d4d012a0eed05db29acdab | Sahilpreet-2213/Common_files | /Project/first.py | 7,529 | 3.953125 | 4 | import pandas as pd
import numpy as np
import os , sys
from main import *
# use reset index after edit
# basic input in other(main) file
# command just display or change database
def info(data): # basic info_ #display
print(data.info())
def first_n(data, x=4): #to get first n records of a DataFra... |
963fcdd0e62445230a5b0182f00d35d6f7ed2766 | MarinaPasternak/amis_python71 | /km71/Pasternak_Marina/2/task10.py | 275 | 3.703125 | 4 | i1=int(input("Line number of the first cell "))
j1=int(input("Column number of the first cell "))
i2=int(input("Line number of the second cell "))
j2=int(input("Column number of the second cell "))
if i1-j1==i2-j2 or i1==i2 or j1==j2:
print("YES")
else:
print("NO")
input() |
3ed923b953e45b1db60e0e5d5efee286533d381c | paulmcaruana/Learn_to_Code_in_Python_3-_Programming_beginner_to_advanced_Files | /ex_6_dictionaries.py | 241 | 4.09375 | 4 | person = {"name": "Paul", "gender": "male", "age": 46, "address": "9 Ashmore Road", "phone": "07437010710"}
key = input("What information would you like to know? ").lower()
result = person.get(key, "key not found")
print(result)
|
db587c8189e90e7d4a8e60e8124f4d0ab56118d4 | SanyaRudik/checkio | /checkioTVvoiceOOP.py | 1,632 | 3.609375 | 4 | class VoiceCommand:
def __init__(self, chanel):
self.chanel = chanel
self.number_chanel = 0
def first_channel(self):
self.number_chanel = 0
return self.current_channel()
def last_channel(self):
self.number_chanel = len(self.chanel)-1
return self.current_chan... |
7f6d75b1ba0be03beff69df094247844604d6ac8 | MAhaitao999/advanced_python | /chapter11/thread_condition.py | 3,183 | 3.609375 | 4 | from threading import Condition
import threading
# 条件变量, 用于复杂的线程间同步
# class XiaoAi(threading.Thread):
# def __init__(self, lock):
# super().__init__(name='小爱')
# self.lock = lock
#
# def run(self):
# self.lock.acquire()
# print("{}: 在".format(self.name))
# self.lock.rel... |
d1f40328f1780fabeef7d5394fa5f64f3735fba6 | chanvi1/hba_coursework | /homework/hw03/accounting.py | 2,309 | 3.953125 | 4 | #Someone counted up the differerent types of melons that were sold.
def count_melon(filename):
f = open(filename)
melon_tallies = {"Musk": 0, "Hybrid": 0, "Watermelon": 0, "Winter": 0}
for line in f:
data = line.split(",")
melon_type = data[1]
melon_count = int(data[2])
... |
00ee139f17066fd5afdfa1c89171a41524da7f6e | Shiv2157k/leet_code | /revisited_2021/arrays/pascal_triangle_ii.py | 521 | 4.03125 | 4 | from typing import List
class Pascal:
def get_row(self, num_row: int) -> List[int]:
"""
Approach: DP
Time Complexity: O(N^2)
Space Complexity: O(N)
:param num_row:
:return:
"""
row = [1] * (num_row + 1)
for i in range(1, num_row + 1):
... |
f226190182b1525eb41a9fbca0ed5d9792d220c6 | kevincui5/logistic-regression | /ex2.py | 3,640 | 3.75 | 4 | ## Logistic Regression
## Load Data
# The first two columns contains the exam scores and the third column
# contains the label.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('ex2data1.txt', header=None)
X = data.iloc[:, 0:2].values
y = data.iloc[:, 2].v... |
feeb5168071fb1b0f8c6f9d4a8d5a762f5a417b7 | fplucas/exercicios-python | /estrutura-de-decisao/8.py | 280 | 3.828125 | 4 | produtos = []
for numero in range(1, 4):
produtos.append(float(input('Informe o preço do %so. produto: ' % numero)))
menor = produtos[0]
for produto in produtos:
if produto < menor:
menor = produto
print('O produto que você deve comprar é o de R$ %s' % menor) |
f3ed9f664dba297767b55fe5cdf0ad4ea2168b5f | Masstran/pong_game | /scoreboard.py | 476 | 3.578125 | 4 | from turtle import Turtle
from config import ALIGNMENT, FONT
class Scoreboard(Turtle):
def __init__(self, position):
super().__init__()
self.color("white")
self.penup()
self.score = 0
self.goto(position)
self.hideturtle()
self.refresh()
def refresh(self... |
2b14bfe95328da80efaaf6d81f937806fffa55d4 | MrMallet/Python | /exercise4++.py | 1,842 | 3.875 | 4 | num = int(input("Enter a number to find its divisors: "))
top= num+1
bot= 1
a=[]
b=[]
ans =0
def createRange(bot, top):
a = range(bot,top)
return (a)
#createRange()
def modulo(div):
ans=(num % div)
return ans
for x in a:
if (modulo(x) ==0):
b.append(x)
print(b)
print(cre... |
a60a6d27fafca7bf7309d73b83ac9b5410913ab4 | chazingtheinfinite/project_euler | /code/large-sum.py | 474 | 3.5 | 4 | #!/usr/bin/python
""" Large Sum
Author: Kevin Dick
Date: 2018-09-25
---
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
"""
num_file = '../data/large-sum.txt'
nums = []
f = open(num_file, 'r')
for line in f: nums.append(line.strip())
f.close()
def brute_force():
total = 0
for... |
bb1ce5d6a43044fa26b16c0827de406fe0ccb607 | Remi67/Python_crash_course | /Chapter_10_RP/10-4_guest_book.py | 465 | 3.53125 | 4 | # Author: Rémi PAUL
# Date: 26-May-2020
# Chapter 10: try it yourself, page 193 of the book 'Python crash course' second edition written by Eric MATTHES
filename = 'guest_book.txt'
with open(filename, "a") as file_object:
while True:
guest_input = input("Please enter your name: ")
if guest_input !... |
8620e74a2b5b7428b99a29cd1270a5735ea3c17b | aambrioso1/Pygame | /ZombieChase.py | 4,440 | 3.703125 | 4 | """
Program to demonstrate event handling in with the Pygame module.
"""
import pygame, sys
import random
import math
from pygame.locals import *
pygame.init()
FPS = 200 # frames per second setting
fpsClock = pygame.time.Clock()
# Set up the animation window
screen = pygame.display.set_mode((800, 600),... |
e4abab786d7de01765ac6fa4051356e75f3d6fcc | MeghnaPrabhu/Autoencoders | /code/network.py | 11,093 | 3.84375 | 4 | '''
Python 3.x
This file implements a multi layer neural network for a multiclass classifier
Hemanth Venkateswara
hkdv1@asu.edu
Oct 2018
'''
import numpy as np
from activations import Activations
def initialize_weights(net_dims, network_type):
'''
Initializes the weights of the multilayer network
Inputs:... |
b04a7d6c6e6719fed4eb1a19fcccaa1cf3f23003 | krishdb38/Python_Free_Coding | /test.py | 603 | 3.953125 | 4 | import tkinter as tk
from tkinter import messagebox
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
def ExitApplication():
MsgBox = tk.messagebox.askquestion ('Exit Application','Are you sure you want to exit the application',icon = 'warning')
if MsgBox == 'yes':
root... |
6c9463e3b9206febfa9bcc42a5d802e94cc0c60d | rhydian98/YoutubeDownloader | /YouTubeDownloader.py | 694 | 3.859375 | 4 | """
Author: Rhydian Edwards
Date: 24/10/2020
Description: The Idea of this script is that the user should be able to grab take the link to the youtube video they want to download and this script will grab the 720p version of
that video, or if there is not one which is 720p it will grab the highest resolution verison.
... |
341430a5e83940a5d4e2797d480e63c756449238 | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/331/75928/submittedfiles/testes.py | 279 | 3.84375 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
a = 10
b = 15
c = 20
if a>b:
print ('a eh maior que b')
elif a>c:
print ('a eh maior que c')
elif b>c:
print ('b eh maior que c')
elif c<b:
print ('c eh maior que b')
else:
print ('nao eh porra nenhuma')
rint('fim') |
439b44425ce5ea51db856cbe4bfe1b208eb08b84 | lienordni/Erdos | /198.py | 106 | 3.625 | 4 | n=5
s=0
for n in range(3,16):
s=0
for i in range(0,n+1):
for j in range(0,n+1):
s+=i^j
print(n,s) |
7f3f46d2e519b1170eafdec8483179ec6493c531 | remotephone/pythoncrashcourse | /ch01-05/05_01-cars.py | 594 | 4.03125 | 4 | # Simplemente!
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Conditional tests
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# ignoring case
print("Check if Au... |
5405db17dd6ed6652dabb05282798e9240c26f6c | GuillermoDeAnda/Mision_03 | /Auto.py | 877 | 4 | 4 | # Guillermo De Anda Casas , A01375892
# Programa que calcula el rendimiento de un auto y los litros que se necesitan para ciertos km.
def calculaK(K,L):
res1 = K / L
return res1
def calculaM(K,L):
mi = K / 1.6093
gal = L * 0.264
res2 = mi / gal
return res2
def calculaKilom(kilo,K,L):
lit... |
fbf93ea728f31105922416b42f4a28c97e10ae2e | sanjayk1801/algoexpert | /easy/twoNumberSum.py | 621 | 3.734375 | 4 | def twoNumberSum1(array, targetSum):
n = len(array)
for i in range(n - 1):
j = i + 1
for k in range(j, n):
sum = array[i] + array[k]
if sum == targetSum:
return [array[i], array[j]]
return []
def twoNumberSum2(array, targetSum):
nums = []
for i in array:
potential_match = targetSum ... |
45f457d17cdc8dfffc70bfd10ca3db22ff275605 | sunset375/CodingDojo-1 | /Python/Python_Knowledge/algos/w4d1/Group 1.py | 1,465 | 4.15625 | 4 |
# Binary Search
# Search to find if the value exists, do not loop over every element.
# Approach:
# Take the middle item and compare it to the given value.
# Based on that comparison, narrow your search to a particular section of the array
# Input: [1, 2, 3, 4, 5], 4
# Output: True
# Input: [1, 3, 6, 9, 13], 1
# O... |
d57099f11cbf14cc242a76a943b1170b7473864c | Alexeiabianna/python-beginner | /pressureDiastolic.py | 416 | 4.09375 | 4 | sist = int(input("Sistólica: "))
diast = int(input("Diastolic: "))
if sist >= 180 or diast >= 120:
print("Crise hipert.")
elif (sist >= 140 and sist < 180) or (diast >= 90 and diast < 120):
print("Hipertensão est. 2")
elif (sist >= 130 and sist <= 139) or (diast >= 80 and diast <= 89):
print("Hipertensão e... |
59b209d85e5b7893cfc6be2d95712108abe8f813 | QtTao/daily_leetcode | /876.链表的中间结点/solution.py | 1,219 | 3.78125 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# author : Tao Qitian
# email : taoqt@mail2.sysu.edu.cn
# datetime : 2021/5/10 23:14
# filename : solution.py
# description : LC 876 链表的中间结点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# ... |
91d085b18ade2dcd0c2314fd8c9cb6e741209cee | urbaneriver426/STACK | /postfix.py | 578 | 3.75 | 4 | def postfix(self, string):
new_stack = Stack()
x = ""
for i in range(len(string)-1,-1,-1):
if string[i] == " ":
self.push(x)
x = ""
elif i == 0:
x = string[i] + x
self.push(x)
elif string[i] != " ":
x = string[i] + x
for i in range(self.size()):
z = self.pop()
if z == "+":
... |
762637df9889de5ec7d7d1ed66d8aac1d351310f | dli85/tic-tac-toe-ai | /play.py | 3,981 | 3.5 | 4 | from randomAi import RandomAI
from game import Game
from minimaxAi import minimaxAI
from NNS import NeuralNetworkSupervised
from NNR import NeuralNetworkReinforcement
def playerTurn():
pos = int(input('Where would you like to play? '))
return pos
def play():
aiNum = int(input('What ai would you like to pl... |
e9be94487d36fba538d0cc56f58c5a910f30ec03 | peterhogan/python | /probability/gamma_dist_test.py | 215 | 3.53125 | 4 | from functools import reduce
def factorial(x):
try:
result = reduce(lambda i, j: i*j, range(1,x+1))
return result
except (RuntimeError, TypeError, NameError):
return 0
def gamma(x):
return factorial(x-1)
|
3916bbd6d4b06d4372f266c60a1df7f07152b064 | werewolf-65/NewAlgoEveryday | /DynamicProgramming/count_construct.py | 1,045 | 3.96875 | 4 | def count_construct(target, word_bank=[], memo={}):
# base case
if (target == ""):
return 1
# memoization check
if target in memo:
return memo[target]
# no of ways the target string can be formed from the words in the word bank
no_of_ways = 0
for word in word_bank:
... |
df84320058f005117295b155da033cc58cc70044 | neoden/euler | /python/problem1.py | 372 | 4.34375 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def is_multiple_of_3_or_5(x):
if x % 3 == 0 or x % 5 == 0:
return True
else:
return False
s = 0
for i in range(1, 100... |
91ccdfa5fe3197328d6409bd2780e5f419c70ed0 | ykannan/SysEng | /python/DSA/leetcode/improve.py | 26,676 | 3.9375 | 4 | # sample = 'abefhefcdefhab'
#
# match_string = ['e', 'f', 'h']
#
# word_length_map = []
# word_length = 0
# match_pattern = ''
#
# for i, character in enumerate(sample):
# if character in match_string:
# word_length += 1
# match_pattern += character
#
# else:
# if word_length >=3:
# ... |
74fe6216403b71b142be5b0691f1c3e8755249ad | VimanyuAgg/dsand | /active_directory.py | 1,763 | 3.515625 | 4 | # Problem 4: Active Directory
# Modified the self.group & self.users variables as the order
# in which there added isn't important and searching in a set is O(1)
# while searching in a list is O(n) where n is the length of the list
# Used recursion to avoid code duplicacy
# Time Complexity: O(n) where n is the total nu... |
f2b602a591659f8e5ca776119494b0f0512622be | debaratidas1994/Python-Lab | /1/socket_tcp/client.py | 1,032 | 4.15625 | 4 | """
Write a client-server program using sockets. Client sends a tuple
containing two strings. One is the input string and other is a string which
denotes operation to be performed on the input string. Once the server
receives the tuple, it performs the operation on the string and sends the
result back to the clien... |
0c7ce2f91d8285a7453398eea666ee7a8e99d3bb | rajatsachdeva/Data_Analysis_with_Pandas | /1_pandas_introduction/1_pandas_introduction.py | 578 | 3.53125 | 4 | import pandas as pd
import datetime
import pandas_datareader as web
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
# Specify the start and end date for which the data will be fetched
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2017, 1, 1)
# Fetch data from yahoo ... |
8bce776c08dd9332c7bb5a5680ddfde35f1be159 | Sizif13/RandomCode | /Dots.py | 295 | 3.65625 | 4 | from itertools import product
def dots(str):
lst = []
for prod in product(("", "."), repeat=len(str) - 1):
mixed = [char for tpl in zip(str, prod + ("",)) for char in tpl]
new_word = "".join(mixed)
lst.append(new_word)
return lst
x = dots('abc')
print(x)
|
3741a32aa56a3cba5e3503984570cee515a21356 | Abdelhamid-bouzid/problem-Sovling- | /Medium/searchMatrix.py | 804 | 3.984375 | 4 | '''
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,3... |
d855dd79c2ca5ee476e370c139a27e2276cf320b | daniel-reich/ubiquitous-fiesta | /dcdy9QMBbryyWENcm_14.py | 103 | 3.546875 | 4 |
def total_cups(n):
if n < 6:
return n
elif n >= 6:
total = n + (n // 6)
return total
|
e040c69b7a0879596d218e0dc0af7984075283f4 | FelypeNasc/PythonCursoEmVideo | /Exercicios/061-080/desafio080.py | 492 | 3.921875 | 4 | lista = list()
for pos in range(5):
num = int(input('Digite um valor: '))
if pos == 0 or num > lista[-1]:
lista.append(num)
print('Adicionado ao final da lista.')
else:
index = 0
while index < len(lista):
if num <= lista[index]:
lista.insert(index... |
86b4f186c72e7dd3c8641a4be4273cc1ae750369 | Eeman1113/rat_bonk | /rat_game.py | 948 | 3.828125 | 4 | import random
import threading
import time
import keyboard as key
#prints rat at a random time and starts a one second timer for the user to react
def rat():
rat.a=0
rat.c=0
for i in range(1,100):
rat.a=random.randint(1,100)
if int(rat.a)%2==0:
rat.b=time.sleep(random.randint(1,... |
29f8e4b7b583a9f0182da06effbf55952fae6591 | immohsin/DS-ALGO | /prob_1.py | 553 | 4.09375 | 4 | # Implement stack using Linked List
from linkedlist import SinglyLinkedList
ll = SinglyLinkedList()
# Assingment to have Stack push & pop operation to reflect Naming convention
push = ll.addFront
pop = ll.deleteFront
# stack operation
print("push 10: ", end="")
push(10)
ll.print()
print("push 9: ", end="")
push(9)
... |
c0126cfedcb31832004e65b2b1e343d9978c4275 | zjsdcae/LeetCode | /qiafan/OFFER/20.py | 908 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def theSameTree(T1, T2):
if T2 == None:
r... |
0adf3f16dc61b1efaa25ed71ea6c72e47fc7817c | Esukhia/bospell-old | /bospell/b_tokenizers/helpers.py | 1,563 | 3.6875 | 4 | def is_tagged_sequence(tokens, token, s_tag, e_tag):
return token and tokens and tokens[-1]\
and tokens[-1][-1].strip() == e_tag \
and token[0].strip() == s_tag
def segment_with_tags(string, start_tag, end_tag, sep, in_tag_max=3):
"""segment a string on sep,
yet keep everything betwe... |
df29cb4575c299b3a6efb1bc4245ccb77b568998 | MarcosRigal/Master-en-Python-Udemy | /15-manejo-errores/main.py | 1,258 | 4.53125 | 5 | """
# Capturar excepciones y manejar errores en código
# susceptible a fallos/errores
try:#Comprueba el funcionamiento
nombre = input("¿Cual es tu nombre?")
if len(nombre) > 1:
nombre_usuario = "El nombre es: " + nombre
print(nombre_usuario)
except:#Si va mal
print("Ha ocurrido un error, introduzca un nom... |
908f7d2a0a86fec6cfe8ab4c8a07501610cd8c94 | Bladedrinks/Python_Learning | /equilateral_triangle_different_units.py | 1,048 | 4.4375 | 4 | # Program to display a triangle made up of a certain shape (like *, #, etc) where the shapes on each side is different
# than the shapes in the interior.
# Below is the expected triangle example with 9 rows (side length):
# * Row 1: 1 * and 0 o
# * * Row 2: 2 * and 0 o
# * o * ... |
c69a3a626bbe64cc1fe3d6f0b25203781e459de5 | Sofiene-Saguem/Machine-learning-first-step | /multiple linear regression/multiple linear regression (1).py | 1,606 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[13]:
#import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
#importing datasets
dataset = pd.read_csv('Fish.csv')
#Extracting Independ... |
aea49c90fc05f4f71ef73660dc055ea89403c9d7 | xiaoxiaopingzi/LeetCode | /Algorithm Diagram/6.5-BFS.py | 896 | 3.625 | 4 | # -*- coding: UTF-8 -*-
"""
@author: WanZhiWen
@file: 6.5-BFS.py
@time: 2018-11-13 10:03
通过BFS来遍历图,以找到指定的对象
"""
# 通过字典建立图
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
graph['anuj'] = []
graph['peggy'] = []
graph[... |
960db588d41e799c5e0fbb8b89eae7e190ede416 | Cprocc/Week_test | /2018-08-03/3.py | 855 | 3.609375 | 4 | def longestOnes1(A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
longest = 0
for i in range(len(A)):
long_one = 0
re_times = K
for cur in range(i, len(A)):
if A[cur] == 1:
long_one += 1
elif A[cur] == 0 and re_times >... |
3ccee3af4c2f1575833d0257bb2e8534850b6f7b | ehtlfk/baekjoon_algo | /codeforces/codeforcess_71A.py | 542 | 3.53125 | 4 | n = int(input())
for _ in range(n):
word = input()
ret = ''
if len(word) > 10:
ret += word[0]
ret += str(len(word)-2)
ret += word[-1]
else:
ret = word
print(ret)
# 메모리를 더 효율적으로 활용할 수 없을까?
# +=은 매우 느린 연산임, ret를 복사하고 다시 합치기 때문
# python 내부에서 어떻게 처리하는지는 모르겠음 ... |
552bcadcb5d15d5be966bffca10f0981b09e07f7 | jeyziel/python-studies | /python-zumbies/Lista1/10.py | 601 | 3.796875 | 4 | '''
Escreva um programa para calcular a redução do tempo de vida de um fumante. Pergunte a
quantidade de cigarros fumados por dia e quantos anos ele já fumou. Considere que um fumante
perde 10 minutos de vida a cada cigarro, calcule quantos dias de vida um fumante perderá. Exiba o
total de dias.
'''
qnt_cigarros_por_d... |
4e2d94f24b9ddcc3291dd47801f3a3587ca3746a | vigneshpalanivelr/python-pattern-programs | /Pattern Program Hollow diamond.py | 598 | 3.921875 | 4 | def pattern_hollow_diamond():
ch = input("press a to begin: ")
while(ch!= "s"):
n= int(input("# rows: "))
a=((n-1)/2)
if not (n%2==1):
print ("please enter an odd value: ")
continue
for row in range(n):
for col in range(n):
if (row+col==a) or (col-row==... |
9bd599fab3a2ef866bb02e1257418a6186f2af1d | felixzhao/questions | /Array_and_Strings/2Sum.py | 535 | 3.609375 | 4 | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""
Dictionary
logic:
- keep a dictionary save 'target - nums[i]' as key, and i as value
- if num in nums already existed in dictonary,
which means we found the pair
time O(N)
... |
65d33fe4aa17739d503756689ef4dffb1a985882 | borin98/Projetos-De-Programa-o-No-Atom | /Projetos Em Phyton/SeparaNumeros1.py | 539 | 3.8125 | 4 | n = int ( input ( "Digite um número inteiro entre 0 à 9999 : " ) )
i = 0
while ( n > 9999 ) :
print ( "\nValor inválido !!!!" )
n = int ( input ( "\nDigite um número inteiro entre 0 à 9999 : " ) )
while ( i < 3) :
resto = n%10
n = int (n/10)
if ( i == 0 ) :
print ( "\nUnidade : {}".fo... |
bd206f1a729c759fb4f38d6ac2fcfe9e77263c14 | touhiduzzaman-tuhin/python-code-university-life | /Practice_P_T_A_B_M/9.py | 254 | 3.5625 | 4 | # Binary Search
li = [1, 5, 7, 3, 2, 9]
li.sort()
n = 5
s = 0
e = len(li) - 1
while s <= e:
mid = (s+e) // 2
if li[mid] == n:
print("Found")
break
if li[mid] < n:
s = mid + 1
else:
e = mid - 1 |
ffe664abf896bd9b15dd3c2c0a2df21bf8fea658 | hunterfro7/Projects-During-Senior-Year | /ngram model/ngram.py | 8,900 | 3.875 | 4 | # ngram.py
#
# Ibrahim Rahman
# Due Date: 2/19/2019
# CMSC 416
#
# The problem to be solved in this assignment was to design and implement a program that
# would be able to learn an N-gram language model. It would base this language model off
# of plain text files that would be stated in the command line argument. Th... |
c17601f7db770a04810eb1a55e02260cde9c3d00 | jeancrus/Projeto_jogo_da_velha | /projetofinal.py | 8,432 | 3.515625 | 4 | contagem1, contagem2 = 0, 0
def VerificaJogo():
global tabuleiro2, tabuleiro, jogador1, jogador2, contagem1, contagem2, ganhou1, ganhou2
#verificação reta = = =
verifica1, verifica2 = 0, 0
if verifica1 != 3 and verifica2 != 3:
for i in range(3):
verifica1 = 0
verifica2 =... |
b4a8849d6ff13e66b575f6685e24d1a988d46883 | DevStarSJ/algorithmExercise | /euler/19.py | 839 | 4.15625 | 4 | # 0 : Sunday ~ 6: Saturday
def getDay(current, days):
return (current + days) % 7
def isLeafYear(year):
if year % 100 == 0:
return True if year % 400 == 0 else False
return year % 4 == 0
DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def moveNextMonth(currentYear, currentMonth, currentDa... |
b8c3ebe63516852c8a6225a437f5104adeebc98c | lixuanhong/LeetCode | /commonPrefix.py | 1,411 | 4.15625 | 4 | """
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input st... |
deb6471354b5007b9592c0c400df02bae2d931c2 | LandWhale2/Algorithm-training | /그리디/문서검색.py | 189 | 3.515625 | 4 | a = input()
b = input()
node = 0
cnt = 0
while node+len(b) <= len(a):
if a[node:node+len(b)] == b:
cnt += 1
node += len(b)
else:
node += 1
print(cnt) |
f50e10a78e168166f3e0331abbfc3911a1ff5385 | strange/colorcount | /colorcount | 3,338 | 3.640625 | 4 | #!/usr/bin/env python
import collections
import colorsys
import errno
import fileinput
import math
import os
import re
import sys
def rgb_to_hsv(rgb):
"""Convert RGB-triplet to HSV-triplet."""
rgbd = tuple([round(b, / 255., 4) for b in rgb])
return colorsys.rgb_to_hsv(*rgbd)
def rgb_to_hex(rgb):
"""Re... |
87b7b74d149b8cddccd58eb80405bb5e43143ec5 | dlaststark/machine-learning-projects | /Programming Language Detection/Experiment-2/Dataset/Train/Python/runtime-evaluation-in-an-environment-2.py | 248 | 3.59375 | 4 | >>> def eval_with_args(code, **kwordargs):
return eval(code, kwordargs)
>>> code = '2 ** x'
>>> eval_with_args(code, x=5) - eval_with_args(code, x=3)
24
>>> code = '3 * x + y'
>>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1)
7
|
d61ddd2e8faecc5e5f6976e7c81870ec32dd6b49 | Lee-hsien-sen/python-excel-unittest | /venv1/main.py | 2,275 | 3.53125 | 4 | 1、a、UI校验
b、功能测试:
(发送视频)
本地相册选择还是直接拍摄
视频秒数验证:1 - 10s,超出10s
视频个数验证1个
视频格式验证
支持的视频格式
不支持的视频格式
最后发送视频,是否可以正常观看(包括自己、朋友)
(朋友圈点赞)
点赞成功
点赞后取消点赞
弱网情况下点赞
没网情况下点赞
点赞后评论
点赞后消息列表的显示(是按时间还是昵称... |
e6a5516ebdb2709eba28a552cd6fe1ba690f1096 | rahulatrkm/Algorithms | /sentence_reverse.py | 1,337 | 4 | 4 | '''
You are given an array of characters arr that consists of sequences of characters separated by space characters. Each space-delimited sequence of characters defines a word.
Implement a function reverseWords that reverses the order of the words in the array in the most efficient manner.
Explain your solution and a... |
4c9637a1a5695d3fc4114124cf2dca7bfdca33df | crazykuma/leetcode | /python3/0019.py | 925 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 双指针法
# 设置快慢两个指针,快指针比慢指针快n步,那么当快指针指向末尾none的时候,慢指针正好指向要删除的节点
pfast = head
st... |
aa40931eae454a1de5beef6427d759efae3a922c | YaoChenchen/gittest1 | /test.py | 1,959 | 3.65625 | 4 | # coding=utf-8
import threading, time
class MyObject:
def __init__(self,oName):
self.oName = oName
class People(MyObject):
def __init__(self, name, age):
self.name = name
self.age = age
super(People, self).__init__() #非多继承的可以不用放在第一行
print "Init people: %s" % self.name... |
04ed4edc661fb7a466435248e612fdbe8bdcc5ec | gabriellaec/desoft-analise-exercicios | /backup/user_176/ch25_2019_03_29_02_34_57_649748.py | 130 | 3.578125 | 4 | d= int(input('qual a distancia que deseja percorrer?'))
if d <= 200:
print (d*0.50)
else:
print (100 + (d-200)*0.45)
|
7cf44502651ec9c5c4284a1354e67eb07312d138 | vncloudsco/ksng-hosting | /GmoPanel/plogical/system_os.py | 835 | 3.53125 | 4 | import os
def find_sub(dirs=None, name=None):
"""
find subfolder
:param dirs:
:param name:
:return:
"""
folders = os.walk(dirs)
list_folder = []
for folder in folders:
if name == '*' or name is None:
list_folder.append(folder[0])
elif name == folder[0].sp... |
e542b3860f07cd77e21eedf686bade2e5b9c566d | Poppy22/coding-practice | /CrackingTheCodingInterview/Chapter 1 - Arrays and Strings/1.8.py | 929 | 3.734375 | 4 | def zero_lines(matrix, lines, N, M):
for i in range(N):
if lines[i]:
for j in range(M):
matrix[i][j] = 0
def zero_columns(matrix, columns, N, M):
for j in range(M):
if columns[j]:
for i in range(N):
matrix[i][j] = 0
def search_for_zeroes(matrix, N, M):
lines = [False] * N
columns = [False] * M
... |
a02952c2fe50ca536bbbf6e7e4f1864e95f3b1af | Shyngyskhan/BFDjango | /Week 1/informatics/functions/B.py | 146 | 3.84375 | 4 | def double_power(nubmer, power):
return number ** power
number = float(input())
power = int(input())
print (double_power(number, power)) |
2b6e0808fe837358d6acac803dfb32a2ee75311d | bhawna94110/100-days-of-DSA-coding-in-python | /Linkedlist/insertAtTail.py | 534 | 3.875 | 4 | class Node:
def __init__(self,key):
self.key = key
self.next = None
def printList(head):
curr = head
while(curr!=None):
print(curr.key,end=" ")
curr =curr.next
def insertAtTail(head,data):
if(head==None):
return Node(data)
curr = head
while(curr.next!=None... |
570d99eaf50df56074dc2892597dee1d9bf6c415 | SMurphyTech/Learn-Python-the-Hard-Way | /ex13.py | 365 | 3.78125 | 4 | # imports the needed module so that python knows what
# to do with 'argv'
from sys import argv
# read the WYSS section fro how to run this
# asigns the arguments typed in the bash console to variables
script, first = argv
second = input("You entered " + first + ". Would you like to enter something else? ")
print("Yo... |
3e0b69a8e463f9fd3db8d3b7994271dd1ae40908 | Shraddhat5191/Python_File | /if else/A D S.py | 183 | 4.125 | 4 | # user=input("enter the character :-")
# if user>='a' and user<='z':
# print("alpha")
# elif user>='0' and user<='9':
# print("digit")
# else:
# print("it is special") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.