blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
546d87df26c7c3358cd6a80d7de1f63a7dff7508 | rajilaxmi/python | /conditional loops/37.seasons.py | 584 | 4.21875 | 4 | # print the season according to the day and month
month=input("Enter a month: ")
day=int(input("Enter a day: "))
season=""
if month in "Nov, Dec, Jan, Feb" :
season="winter"
elif month in "Mar, Apr":
season="spring"
elif month in "May, Jun, July":
season="summer"
elif month in "Aug, Sep, Oct":
season="autum"
else:... |
cd6a50d28e40efed4b01711a5fb1fcc74c680db2 | ezralalonde/cloaked-octo-sansa | /02/hw/04.py | 801 | 4.34375 | 4 | # Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return stat... |
eba3b4f300f81e2ceb8e6f8a408d928daa98dbe8 | DanielMalheiros/geekuniversity_logica_de_programacao | /Python/secao08/exercicio05.py | 708 | 3.859375 | 4 | """Seção 08 - Exercício 05
Faça um programa que carregue um vetor de dez números inteiros. Calcule e mostre os números superiores a
50 e suas respectivas posições. Mostrar mensagem se não existir nenhum número nesta condição."""
# variáveis
vetor = []
tem_maior_50 = False
# entrada
for n in range(0,10):
... |
20c9b5cc6330ec6ca8e9cec020e2c77bda0c3413 | qtds6592/qtds | /hello.py | 19,366 | 3.671875 | 4 |
def getList(ll):
re=[]
aa=0;
for m in ll:
re.append(aa+m)
aa=m
re.append(1)
return re
def fib():
l=[]
while True:
l = getList(l)
yield l
g = fib()
def get():
return next(g)
for b in fib():
n = n + 1
print(b)
if n == 10:
... |
be901c81baba759461496a0d79e12f61202a7c27 | lianghp2018/PycharmDemo | /公共操作/02_乘号运算符(复制).py | 136 | 3.6875 | 4 | # 字典不支持乘号运算符
str1 = 'qwe'
l1 = [1, 2]
t1 = (10, 20)
str1 *= 10
print(str1)
l1 *= 10
print(l1)
t1 *= 10
print(t1)
|
c2b7485a92a022d58160267f837fb3aa4e9394db | GNakayama/codility | /src/python/lesson3/exercise4.py | 1,155 | 3.59375 | 4 | # Name: MinAvgTwoSlice
# Link: https://codility.com/demo/take-sample-test/min_avg_two_slice/
def solution(A):
N = len(A)
result = 0
# If N == 2 the only possible result is 0
if N == 2:
return 0
# calc prefix sum
pref = prefix_sum(A)
start = 0
min_average = floa... |
6fe67bdc57a59485349dd49a4fc48bc7d9b8c278 | Benji377/OpenCode | /Utils/password_generator.py | 340 | 3.890625 | 4 | import random
import string
def generate_password(length=8):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
# Usage example:
# Generates a random password of length 12
password = generate_password(... |
364981ac37902f85758ef15b2c270521aaf94c19 | eeue56/PyChat.js | /database/updates.py | 674 | 3.5 | 4 | import sqlite3
class Conn(object):
def __init__(self):
self.connection = sqlite3.connect()
def insert_new_user(self, username):
c = self.connection.cursor()
c.execute("INSERT INTO Users VALUES(?)", (username,))
connection.commit()
def insert_new_message(self, username, roo... |
512cc2a3d99edeab4d89698c3a0c14254c61bc89 | gouskova/oecalc | /code/CVcounter.py | 2,486 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import regex as re
'''
a module for counting various CV patterns in a .txt file. The file should have one word per line, with segments separated by spaces--like this:
p̩ʲ u t i
r i n t u
f a ʃ o
To use:
$ CVcounter LearningData.txt
This will print:
sequence count
V... |
9475a12bbdd1202661b896ca96e33d7eb816cc30 | HawkinYap/Leetcode | /leetcode872.py | 1,097 | 3.953125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# def leafSimilar(self, root1, root2):
# """
# :type root1: TreeNode
# :type root2: TreeNode
# :rty... |
a7e8ef3d0fcd914639ac5b40e0a7905c7076ea94 | starry001/Python3Lesson | /GUI/__init__.py | 1,319 | 3.890625 | 4 | from tkinter import *
from tkinter import messagebox
'''
第一步是导入Tkinter包的所有内容
第二步是从Frame派生一个Application类,这是所有Widget的父容器
在GUI中,每个Button、Label、输入框等,都是一个Widget。Frame则是可以容纳其他Widget的Widget,
所有的Widget组合起来就是一棵树。
pack()方法把Widget加入到父容器中,并实现布局。pack()是最简单的布局,grid()可以实现更复杂的布局。
在createWidgets()方法中,我们创建一个Label和一个Button,当Button被点击时,触... |
745d0ee39490b7c001b74d95b133987e954b75b9 | mahshana/python-co1 | /11.py | 214 | 4.09375 | 4 | a=int(input("enter a number"))
b=int(input("enter a number"))
c=int(input("enter a number"))
if a>b and a>c :
print(a," is bigger")
elif b>c and b>a :
print(b,"is greater")
else :
print(c,"is greater") |
af372c03876e8ebeda5d6f12b9c7bca99c2ed3ac | jack-crawford/code-Nova | /1051 code/sum.py | 229 | 3.96875 | 4 | sum = 0.0
iterate = 0
add = 1.0
goal = input("What number do you want? ")
while sum != goal and sum < goal :
sum = sum + 1/add
add = add + 1
iterate = iterate + 1
print iterate
print sum
print "Total is " + str(iterate)
|
e8d2460f0f574104aa3a97602640036a80e186bb | bingzhong-project/leetcode | /algorithms/word-ladder/src/Solution.py | 1,228 | 3.578125 | 4 | class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
def get_next_words(word, wordList):
words = []
for i in range(len(word)):
... |
d95358d2ce9e5b77e99d7fae35186d74fd6fcdc9 | louis-25/TIL | /python_source/lotto.py | 1,030 | 3.6875 | 4 | import random
#lottoset에 1-45번호 (random.randint(1,45))6개 생성 저장
#while반복문 set변수.add
lottoset =set();
count = 0
while count < 6 :
lottoset.add(random.randint(1,45))
count+=1
print(lottoset)
a = {1, 2, 3, 4, 5}
a.add(6)
a.pop()
print(a)
#데이터 없는 SET 생성함수
#중복데이터 허용X ADD 무시
lottoset = set();
cnt = 0;
while True:... |
449b4d26b90ad62ff4ea84fb9584cd8bde89e77d | algebra-det/Python | /OOPs/MultiThreading.py | 5,696 | 4.625 | 5 | class hello:
def run(self):
for i in range(5):
print("hello - Hello")
class hi:
def run(self):
for i in range(5):
print("hi - Hi")
t1 = hello()
t2 = hi()
# Here this execution is being done by main-thread
t1.run()
t2.run()
print("__________for hello hi______________... |
3f9deef9c9cea7417f40660ef8c24d5aabe69fbe | JieD/Data_Mining_Term_Project | /test/test_db.py | 1,112 | 4.34375 | 4 | import sqlite3
# if the database is already created, connect to it instead of making a new one
conn = sqlite3.connect('db/test.db')
print "Opened database successfully";
with conn:
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE books (title text, author text)""")
# insert som... |
56cfdb4ddbb87f678df6224fd0aab8cbd431ed10 | Mohit54/AMS | /ch.py | 441 | 3.78125 | 4 | from tkinter import *
def change_color():
current_color = text.cget("background")
next_color = "green" if current_color == "red" else "red"
text.config(background=next_color)
root.after(1000, change_color)
root = Tk()
L1=Label(root, text = "Admin",bg="pink").grid(row=0,column = 0,padx=20, pad... |
cadfdf621f62d248ccfbdb2eec104c5fb3043b1c | HanaAuana/PyWorld | /Food.py | 1,283 | 4.15625 | 4 | #Michael Lim CS431 Fall 2013
import pygame
import random
#Define some color constants
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
#Define size constant
SIZE = 10
#A class to define the food objects. Inherits from the pygame.Sprite class to facilitate drawing
class Food(pygame.sprite.Sprite):
# Constructor. Takes... |
f0557fbb7832f9bf98462ddd6f8494d1ba52a959 | Jiteshchoudhary/Basic_interview_program_python | /prime_no_upto_n.py | 222 | 3.546875 | 4 | def prime_no_upto_n(no):
count=0
for i in range(2,no//2+1):
if no%i==0:
count+=1
break
if count==0 and no!=1:
print(no)
for i in range(1,1000):
r=prime_no_upto_n(i) |
6ace4fe13b69daeac00d61c163c96d9551b9248d | Keimoshi/Practise | /Dict/userDict.py | 2,195 | 3.765625 | 4 | #!/usr/bin/env python
#coding:utf8
import getpass
import sys
import os
def load_file_from_dict(filepath):
with open(filepath,'r') as dict_file:
for line in dict_file:
(key,value) = line.strip().split(',')
db[key] = value
return db
def save_file_as_dict():
try:
wit... |
112cb0da24277b6255611db9028c6a14b76aab4a | tomfa/flashcard-json-maker | /simplequiz_interpreter.py | 3,968 | 3.6875 | 4 | #coding: utf-8
'''
This script reads a Q-A txt-file and generates JSON output.
USAGE:
Save your Q-A file
FORMAT:
Chapter 1 - cakes. The whole line is a part of the chapter title.
Q: Question that we wonder about?
A: Answer telling us what we want to know?
Q: Empty ... |
0d3748940f5932136333f470efe4ad56ca3ec868 | EduardoBautista9916/Metodos-Numericos | /Dife_Inte/control.py | 1,667 | 3.890625 | 4 | from os import system
def val_num():
try:
digit= float(input(">"))
except(ValueError):
print("VALOR NO VALIDO")
digit=val_num()
return digit
def llenarTabla(h, cant):
puntos = []
aux=[]
print("Ingrese el valor inicial de x")
valx=val_num()
aux.append(valx)
p... |
2d1831532f6cdf9591d3cace857af008c90254b4 | brianchiang-tw/CodingInterviews | /04_Search element in 2D Array/by_adaptive_search.py | 1,859 | 3.75 | 4 | class Solution(object):
def findNumberIn2DArray(self, matrix, target):
if matrix in ([], [ [] ]):
# Quick rejection for empty matrix
return False
h, w = len(matrix), len(matrix[0])
# start search from top-right corner
y, x = 0, w-1
# keep searching... |
4ad1e0af45ae56a5e458513c7da97e3af81af561 | ebinej97/Luminarpython | /language_fundamentals/swapping.py | 200 | 4 | 4 | num1=10
num2=20
print("num1 before swapping ",num1)
print("num2 before swapping",num2)
num1= num1+num2
num2=num1-num2
num1=num1-num2
print("num1 is",num1)
print("num2 is",num2)
(num1,num2)=(num2,num1) |
c2491b6dc03df81e90b752f3751f6d53a5cde40e | ijoshi90/Python | /Python/class_trial.py | 1,227 | 4.125 | 4 | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 18-12-2019 at 14:14
"""
"""
class myClass:
x = 5
mc1 = myClass()
print("Object value : ",format(mc1.x))
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
p1 = Person("John",29)
print(p1.name)
p... |
2c1c578a66352fa8e55331eecf662260fe627fa0 | takabei/eclipse-workspace | /firstPython/3/ifPython.py | 455 | 3.796875 | 4 | '''
Created on 2019年7月2日
@author: liuyi
'''
import math
#eval()用于将字符串转换为字面量(直接出现在程序中的常量值)
radius = eval(input("现在立马给老子输入数字,记住是数字!:"))
if radius >= 0:
area = radius ** 2 * math.pi
print("the area for thr circle of radius", radius, "is", area, end = "\t")
#end = "\t" 用于不换行输出print()内容
print("test")
else... |
eab35ac161eecab999c659fd5bb0d4810e02de11 | PapaKIRA/PythonExamples | /PythonExamples/blabla/src/ex3pag69.py | 373 | 3.5 | 4 | '''
Created on Nov 13, 2012
@author: Andrei
'''
# if(x != y) like in C++
MyList = ["apple","orange","lemon", "Juice"]
if("apple" == MyList[0]) : # == -searches for the exact element in the list
print("true")
elif("orange" in MyList[1]) :
print("Orange is the 2nd element in the list")
else... |
4a33d713b0b69d79248fca4c94c047de02e4d063 | weiyue0307/Classification-Recognition | /(HW1.2)Bayes.py | 4,807 | 3.671875 | 4 | import csv
import random
import math
def loadCsv(filename): # Read the data
lines = csv.reader(open(filename, "rb"))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset
def splitDataset(dataset, splitRatio): # Split the ... |
a74af51ce618257ecf0d3cfcd928d925f38b2a24 | lancelote/advent_of_code | /src/year2017/day07a.py | 1,660 | 3.515625 | 4 | r"""2017 - Day 7 Part 1: Recursive Circus."""
import re
PATTERN = r"(?P<parent>\w+) \((?P<weight>\d+)\)( -> (?P<children>[\w, ]+))?"
def process_line(line: str) -> tuple[str, int, list[str]]:
"""Convert raw line to a manageable view.
Returns a tuple of:
- Command name itself.
- Its integer w... |
e23f0bb630287972a6c62c691b0ce4b6cbd32b60 | zhengfuli/leetcode-in-python | /n056_merge_intervals.py | 712 | 3.734375 | 4 | # Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort(key = lambda ... |
3d64485f0b52ee11be244fe28120586b4f0b194d | KLPitts/pg2014_pitts | /HW1/hw1q1.py | 678 | 4.125 | 4 | # Katie Pitts
# KLPitts@tamu.edu
# 10-16-2014
# HW1, Problem 1, Fibonacci numbers
def fib(N):
"""Function to return a list of N Fibonacci numbers
http://en.wikipedia.org/wiki/Fibonacci_number
Inputs
___________
N = number of Fibonacci numbers to be returned,
starting with beginning of Fibonacci sequence.
... |
e7d92b15bd925dbeb470a045922c2134810cd214 | MFTI-winter-20-21/DIVINA_2020 | /СТРОКИ.py | 308 | 3.734375 | 4 | boom = "Moscow is the capital of Russia\n"
bam = "bonya"
print(boom+bam)
print(boom*10)
print(bam*10)
print(boom[0:6])
print(boom[6:15])
print(boom[::-1])
print(boom[:21])
print(bam[0])
if "mOsCoW".lower() in boom.lower():
print("YES")
print(bam.title())
print(bam)
bam = bam.title()
print(bam)
|
31c926e14ed6cc71ec66901b0f40d4569b1590d3 | GersonFeDutra/Python-exercises | /CursoemVideo/2020/world_3/ex112/utils/data.py | 254 | 3.59375 | 4 | def input_coin(message: str) -> float:
entry: str
while True:
entry = input(message).strip().replace(',', '.', 1)
if entry.replace(',', '.', 1).replace('.', '', 1).isdigit():
break
return float(entry)
|
a1519ec71a182844f744e59389d3c907ad5da5bd | kh4r00n/Aprendizado-de-Python | /ex004.py | 345 | 3.84375 | 4 | a = input('Digite algo')
print('O tipo primitivo desse valor é', type(a))
print('Esse valor é númerico', a.isnumeric())
print('É alfabetico', a.isalpha())
print('É alpha numerico', a.isalnum())
print('Está em maiusculo?', a.isupper())
print('Está em minusculo?', a.islower())
print('Está capitalizado?', a.istitle... |
036a03e85f1e7ec140266802a61fb5e56bd86f70 | Adem54/Python-Tutorials | /3.hafta eksik kalanlar/python4.py | 966 | 4.34375 | 4 | # Kontrol kodu olarak 123 kullanın:
#
# Kullanıcıya while döngüsü 3 kere doğru pin girme şansı verin. Hatalı girişler için ekrana "Hatalı Giriş.
# Tekrar PIN girin" yazdırın
# 3 girişten birinde doğru pin girilirse "PIN Kabul Edildi. Hesabınıza Erişebilirsiniz." yazdırın.
# 3 girişte de yanlış girilirse "3'den Fazla Gi... |
0becc2cd0289fbc801c0c15198b82645440a261f | PythonOleg/python2020 | /DZ5_8.py | 125 | 3.546875 | 4 | def func8(x):
print(x ** 2 - x -1)
print((x ** 3) - 4*(x**2) - (4*x) +1)
x = int(input('Input x: '))
func8(x)
|
d2cbd911525d2bc106ff3a2180d1fce4db518f5e | nitya-govind/LearningPython | /venv/mypasswords.py | 901 | 4.25 | 4 | #! python3
# CLI tool for retreiving passwords to accounts
import sys, pyperclip, getpass
#getpass lets user enter a password with no echo(can't count the strings in pass while entering it)
PASSWORDS = {'email1': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'email2': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
... |
8925ab26ca77f20d76125d87fdef7319e5264457 | almehj/project-euler | /old/problem0047/brute_factor_test.py | 798 | 3.78125 | 4 | #!/usr/bin/env python3
import sys
import prime_numbers
def main():
goal_factors = int(sys.argv[1])
max_val = int(sys.argv[2])
in_seq = False
seq_len = 0
for n in range(2,max_val+1):
n_fact = len(prime_numbers.factorization(n))
if n_fact == goal_factors:
in_seq = True
... |
40427c1bc982285f132c6a7acef72560a43449d2 | de-lachende-cavalier/DEEPVAULT | /utils/misc_utils.py | 617 | 3.59375 | 4 | import secrets
"""
Miscellaneous utils used in other files, put here to avoid WET code.
"""
def get_random_line(file):
with open(file, 'r') as f:
lines = f.read().splitlines()
return secrets.choice(lines)
def get_user_token_initials(user_token):
"""
Splits up the token and isolates the init... |
8efefe44c234dad147f03a7a753c051cd3fecbc5 | TaylorTheDeveloper/bipartite | /bipartite.py | 2,098 | 3.890625 | 4 | from collections import deque
def checkBipartite(graph,root=0):
#Returns true if a graph is bipartite
#Defaults to start on root 0, but can be started on any node
#The Color Array will store the colors of each vertex
#True = Purple
#False = Green
#None = Unpainted
colors = [-1 for i in range(0,len(graph))]
... |
760a8e538a06517da67de4c7448e497129d070eb | dabaker6/Udacity_Statistics | /Correlation.py | 708 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 09:36:32 2017
@author: bakerda
"""
import numpy as np
import math
def xbar(data):
return sum(data)/len(data)
def r(x,y):
numer = sum(np.multiply([i-xbar(x) for i in x],[i-xbar(y) for i in y]))
sumsqrdiff_x = sum([(i-xbar(x))*... |
f1becbee6d217879d98b9ba3d029c12933c28d4d | qianlongzju/project_euler | /python/PE032.py | 451 | 3.703125 | 4 | #!/usr/bin/env python
S = set(str(i) for i in range(1, 10))
def isPandigital(a, b):
global S
s = str(a) + str(b) + str(a/b)
if len(s) == 9 and set(s) == S:
return True
return False
def main():
r = set()
for a in range(1000, 10000):
b = 2
while b*b <= a:
if a%... |
7f41c423ea61d975579cc74579016173e91787f6 | SabirKhanAkash/RUET-Lab-Works | /3-2/CSE 3210 (Artificial Intelligence)/Lab Final/Python Question 3.py | 132 | 4.1875 | 4 | str1 = input("Enter your String of words with spaces: ")
words = str1.split()
words = list(reversed(words))
print(" ".join(words)) |
cf2720aceab1f4cf8c8dbdbde719b7733c26b5a6 | IDTitanium/Data-Structures-and-Algorithms | /searching/binary_search_recursive.py | 498 | 4.0625 | 4 | from typing import Iterable
def binary_search_recursive(arr: Iterable[int], target: int, low: int, high: int) -> int:
"""Recursive binary search
"""
if len(arr) == 0:
return -1
midpoint = (low + high) // 2
if arr[midpoint] == target:
return midpoint
if arr[midpoint] > targe... |
eecec92e39a9fa5f182bf1387916f8294d35f44c | navya144/PythonDataVisualisation | /unit6distributions/histogram.py | 433 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
#Optional:
#Setting the state of the pseudo-random number generator
#to a fixed value for reproducibility - will give random, different results each time if disabled
np.random.seed(10)
column_data = np.random.normal(42, 3, 1000) # generate some random x v... |
99a0eb3222f6d9994f0e9295c5d1f3a5a7e8e6a0 | maleeham/Leetcode | /ValidPalindrome.py | 406 | 3.90625 | 4 | /*Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.*/
class Solution:
def isPalindrome(self, s):
translator = str.maketrans('', '', string.punctuation + ' ')
s = s.translate(translator)
s = s.lower()
return s == s[::-1]
... |
7c8438b2ce11d3f4a76808c04086f6fe6f610f79 | lkilcommons/GDCmagnetic | /polar_plot.py | 1,711 | 3.90625 | 4 | import numpy as np
from matplotlib import pyplot as plt
def latlt2polar(lat,lt,hemisphere):
"""
Converts an array of latitude and lt points to polar for a top-down dialplot (latitude in degrees, LT in hours)
i.e. makes latitude the radial quantity and MLT the azimuthal
get the radial displacement (re... |
2be037e67f62e9bde181894ccdc73a727ce2afb8 | Neogarsky/phyton | /dz_number.py | 552 | 3.53125 | 4 | # 4 задача
my_list = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА', 'токарь высшего разряда нИКОЛАй', 'директор аэлита']
list_1 = ', '.join(my_list)
# print(list_1.title()) все слова с заглавной буквы
print(f'available list{my_list}')
print(f'Hello,{list_1.title()[19:25]}\n',
f'Hel... |
4d42c6cad3dbf7967ddeefd88332d47b065003af | AlexanderKhalikov/playWithTitanic | /Part2.py | 2,213 | 3.609375 | 4 | import pandas as pd
import numpy as np
def pprint(smth):
print(smth)
print()
# 1) Загрузите выборку из файла titanic.csv с помощью пакета Pandas.
df = pd.read_csv('titanic/train.csv', index_col='PassengerId')
# 2) Оставьте в выборке четыре признака: класс пассажира (Pclass),
# цену билета (Fare), возраст ... |
844025eae2ccd8d2a047b6778addb3c4f70cacb8 | SpenceGuo/my_leetcode | /problem_algorithms/python3/142-II_CircleList.py | 1,180 | 3.796875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return None
nodeSet = set()
while head:
if ... |
2cb4b883d37c774d48bfa02dbde2457126fa27f0 | mattpmartin/DataStructuresSeries | /Merge Sort/Final.py | 977 | 4 | 4 | import random
# creating array of random ints
numbers = [int(random.random() * 20) for _ in range(100)]
# printing array so we know what were looking at
print(numbers)
# Shell sort
def mergeSort(numbers):
if len(numbers) > 1:
mid = len(numbers) // 2
leftHalf = numbers[:mid]
rightHalf = n... |
472d88f452951130bfe72dd6a37c0dcdfdd6ac46 | gbattra/StreetviewHouseNumberDetector | /models/object_detection_model.py | 3,837 | 3.6875 | 4 | # the CNN model to detect objects in an image
import numpy as np
import matplotlib.pyplot as plt
class ObjectDetectionModel:
x_train = []
def __init__(self,
data: dict,
epochs: int,
layers: list
):
self.data = data
self.epoc... |
fad8a9a7f1becad81710cd9201de16943894a676 | watchdogold/stuff | /demo.py | 118 | 3.828125 | 4 | a = input("enter number")
b = input("enter number")
c=a+b;
c=a-b;
print("addition is",c)
print("substraction is",c)
|
8b790304e8cc320cb09724b1fdf1bd2589dbe7fd | harshil002/hellopython | /HWpart1.py | 143 | 3.796875 | 4 | A = input("Enter Tweet: ")
print(len(A))
if len(A)>140:
print("Characters Limit Exceeded")
else:
print("Sentence fits in Tweet")
|
55cda140377c1151ce96049cc17959306d352cd6 | melissapott/codefights | /evenDigitsOnly.py | 172 | 3.765625 | 4 | def evenDigitsOnly(n):
while n > 0:
if n % 2 != 0:
return False
n = int(n/10)
return True
n = 248622
print(evenDigitsOnly(n))
n = 642386
print(evenDigitsOnly(n)) |
5e31899cbb7ec897278bfdfe589d0d9e5470114d | jshaffstall/PyPhysicsSandbox | /examples/motors.py | 652 | 3.640625 | 4 | """
An example of using motors on shapes. The screencast developing this code can be found
here: http://youtu.be/VtyRKKQBjfI?hd=1
"""
from pyphysicssandbox import *
window('Motors', 300, 300)
gravity(0, 0)
#gravity(0, 200)
wheel = ball((100, 100), 25)
wheel.color = Color('blue')
wheel.draw_radius_line = True
motor(... |
a20d7bec084cbe3414ade7a0023803f12f5bfe94 | CesarVeras/algoritmos_senai | /problema5.py | 272 | 3.8125 | 4 | def main():
nome = input("Informe seu primeiro nome: ")
sobrenome = input("Informe seu sobrenoem: ")
idade = int(input("Informe sua idade: "))
print("Olá %s %s, sua idade é de %i anos." % (nome, sobrenome, idade))
if __name__ == "__main__":
main()
|
558187608f83ddfeffacafc8b5e657df59942c46 | animeshramesh/interview-prep | /Python/DP/EASY_CLIMBING_STAIRS.py | 340 | 3.703125 | 4 | https://leetcode.com/problems/climbing-stairs/
class Solution(object):
def climbStairs(self, n):
if n == 1: return 1
dp = [0] * (n+1)
dp[1]=1
dp[2]=2
for i in range(3, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[-1]
# Read that Solution
# There are so many... |
5ff46c563620cb5ef35af42207856435d4aca165 | manastole03/Programming-practice | /python/Array/Common_from_3.py | 754 | 4.3125 | 4 | array1=[]
array2=[]
array3=[]
n=int(input('How many elements u want in array1: '))
for i in range(n):
f= int(input('Enter no: '))
array1.append(f)
array2=[]
n=int(input('How many elements u want in array: '))
for i in range(n):
f= int(input('Enter no: '))
array2.append(f)
array3=[]
n=int(input('How many... |
2819a966f35f0f921cb51a4ca43dad681eff4d41 | GenryEden/kpolyakovName | /452.py | 172 | 4.0625 | 4 | def f(x):
if x < 3:
return 0
elif x == 3:
return 1
elif x == 18:
return 0
else:
ans = f(x-1)
if not(x-3 < 12 < x):
ans += f(x-3)
return ans
print(f(21)) |
621044dbfeb3e22a3cfbf3f7bb12c2972b5362ab | ZimpleX/neural-net-bp | /cost.py | 1,309 | 3.515625 | 4 | from abc import ABCMeta, abstractmethod
import numpy as np
tiny = 1e-30
class Cost:
__metaclass__ = ABCMeta
@classmethod
@abstractmethod
def act_forward(cls):
"""
NOTE: overwrite this with classmethod
"""
pass
@classmethod
@abstractmethod
def c_d_y(cls):
... |
94095a9864174451768e52442deb50cb5af441c0 | hkmamike/leetcode | /P885-SpiralMatrix3.py | 1,228 | 3.578125 | 4 | class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
visitOrder = []
directions = {(0, 1):(-1, 0), (-1, 0):(0, -1), (0, -1):(1, 0), (1, 0):(0, 1)}
self.posAt = (r0, c0)
visited = set()
def findNext(r, c):
... |
319308fc41e634908af53fa8c1712811e677fbca | theChiChen/TwitchChatBot | /commands/random.py | 293 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import random as randomlib
def random(args):
usage = 'random usage : !random <min> <max> (use full integers)'
if len(args) == 3:
min = int(float(args[1]))
max = int(float(args[2]))
return args[0] + " " +str(randomlib.randint(min, max))
else:
return usage |
8402157eb2c7d5a15456c3d503a0a3876850469c | Ri-Hong/CCC-Solutions | /CCC '03/CCC '03 S3 - Floor Plan.py | 3,783 | 3.828125 | 4 | '''
Author: Ri Hong
Date AC'd: May 2, 2020
Problem: https://dmoj.ca/problem/ccc03s3
'''
#Explanation
'''
First we construct a 2D array with 'I' representing walls and '.' representing empty room spaces. We then loop through every cell of the 2D array and check if it is an empty room space.
If it is, we start a DFS on... |
8ba4a7a4666a0550616b7f65f7b06c686eb12d1d | amnk/forth | /forth.py | 2,717 | 4.125 | 4 | #!/usr/bin/env python
"""
Very basic and robust Forth interpreter.
See def_commands for full list of available commands
"""
import sys
import fileinput
f_error = "Operation error for {f} command. Exiting."
s_error = "Not enough elements in stack. Exiting"
def _value(value):
"""
Function is used as a helper,... |
a92a4edc105864a44dc1dbd87cb061715b47a1c4 | DevendraKumarL/leetcode-probs | /Easy-Level/RemoveElement.py | 850 | 3.953125 | 4 | '''
Problem:
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter w... |
efeef00f6e41f399bc9b2251a1cce6df2fed3515 | Qinode/leet_q_python | /sort_color.py | 459 | 3.625 | 4 | class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
colors = [0, 0, 0]
for i in nums:
colors[i] += 1
index = 0
for i, n in enumerate(colors):
... |
2a3bc47ee2755196838e1763c665b43e7d377fdf | QianYC/algorithms | /select_kth.py | 1,774 | 3.5625 | 4 | import sys
import numpy as np
#=====================================
# find min or max
def min(arr):
res=sys.maxsize
for i in arr:
if i<res:
res=i
return res
#=====================================
# find min and max at the same time
# O(3*n/2)
def min_max(arr):
min=sys.maxsize
... |
8a503caee170f0b825094fc00289c8def983b95d | dhruvikmevada/PythonPrograms | /What is my name.py | 379 | 4.15625 | 4 | """
Date : 11-07-2019
"""
def whatismyname():
fname = input("What is your firstname? - ")
lname = input("What is your lastname? - ")
if len(fname) >=10 or len(lname) >= 10:
print("Firstname or lastname should not exceed length of 10 char ")
else:
print("Hello " + fname + l... |
3d34f64d741678bce9e30be8e760df3ff8dcb950 | princesaoud/PythonLab | /Prime_number.py | 473 | 4.21875 | 4 | print("Prime number ")
y = "yes"
def prime_number():
number = input("Enter a number ")
temp = 1
prime = True
while temp < number / 2:
temp += 1
# print(number, temp, number/temp)
if number % temp == 0:
prime = False
break
if not prime:
prin... |
b696447dd92647e21d320c7cf195910b147bbe18 | samsaket7/codes | /deep_lstm.py | 21,014 | 3.65625 | 4 | import numpy as np
class Deep_lstm_Network:
"""
A deep lstm network without peephole connection. The network consists of an
input layer, multiple hidden layers(also called recurrent layers) and an
output layer. The dimension of each layer is passed as an input(num_nodes).
For loss computation th... |
184d55a104d4a22529ff8513e61e345d487d0e76 | sidtandon2014/Algorithms | /Algos/Arrays/Heaps/ImplementHeapWithPriorityQueue.py | 2,434 | 3.765625 | 4 | from math import floor
class Heap:
def __init__(self, arr, typeMulFactor):
self.arr = arr
self.typeMulFactor = typeMulFactor
def shiftUp(self, index):
parentIndex = (index - 1) // 2
if parentIndex < 0:
return
if self.typeMulFactor * self.arr[parentIndex] >... |
4fc5c077f94af06dc507145b266763502d69fc56 | prakharaditya/Genuary_2021 | /Jan10_Tree/tree_bk1.py | 1,759 | 3.796875 | 4 | """
GENUARY 2021 - Tree
Draw 3 trees
Jan10 2021
"""
w, h = 840, 840
margin = 20
NUM_LEAVES = 140 # also, points in the spiral
THETA_INC = 0.15
RADIUS_INC = 0.6
MIN_RADIUS = 10
def render_foliage(spiral_center):
""" Draw the Spiral in reverse, from out to in """
noStroke()
scx, scy = spiral_center
... |
a06ed3659e7dfa9b2320023f179ed7d57be1b0f0 | koyo922/leetcode | /p106_construct_bin_tree_from_in_post_traversal.py | 1,899 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 expandtab number
"""
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/constru... |
163f99205b42c3bc2201185e76bb0f7acdc226c0 | HongyingLee/leetcode | /listL/removeDuplicates.py | 402 | 3.671875 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Author: Hongying_Lee
# @Time: 2020/4/4
# @Name: removeDuplicates
# 抄的算法
def removeDuplicates(nums):
low = 0
length = len(nums)
if length <= 1:
return length
else:
for high in range(length):
if nums[low] < nums[high]:
... |
e3abde849283b8f7b090f7dc2fef9532a7d7f124 | astilleman/Informatica5 | /Toets/Processie van Eternach.py | 207 | 3.546875 | 4 | #invoer
t = int(input('Geef een tijdstip: '))
stappen = 0
#berekening
for i in range(1, (t + 1)):
if i % 2 != 0:
stappen += i + 1
else:
stappen -= (i // 2)
#uitvoer
print(stappen)
|
e55cc1a29f1419414d3b074e437a105bca06821e | kobeomseok95/codingTest | /boj/silver/9372.py | 776 | 3.703125 | 4 | from sys import stdin
READ = lambda : stdin.readline().strip()
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a > b:
parent[a] = b
... |
34df8feb87e64525a60f09443dd683c8ecef7a42 | mHernandes/codewars | /6kyu_stop_gninnips_my_sdrow!.py | 859 | 4.3125 | 4 | """
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed
(Just like the name of this Kata).Strings passed in will consist of only letters and spaces.Spaces will be included only when more than one word is present.
Examples: spinWord... |
f53aa6a885f2a09ae8ae5fc521b5840b8d938459 | luoyubie/Learning | /LeetCode/roman_Int.py | 810 | 3.53125 | 4 | # _*_ coding:utf-8 _*_
# @Author: Bie
# @Time: 2018年10月29日
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
romanDict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
result = 0
re... |
8cb892e229410fd579bc074197a82ce5432b1c08 | SDA-workshops/algorithms | /binarysearch.py | 550 | 3.96875 | 4 | from typing import List, Optional
def search(items: List[int], target: int) -> Optional[int]:
left, right = 0, len(items) - 1
while left <= right:
middle = left + (right - left) // 2
if items[middle] == target:
return middle
if items[middle] < target:
left = mid... |
335cd0574d4be56654424c7ed90180f3c7ac0cfd | owenkickass/password_retry | /password_retry.py | 253 | 3.90625 | 4 | password = 'a123456'
i = 3
while i > 0 :
pwd = input('請輸入密碼')
if pwd == password:
print('密碼正確')
break
else :
i = i-1
if i > 0:
print('密碼錯誤 還剩', i ,'次機會')
else:
print('沒機會了')
|
f19744409399cbbcb51d50c21c55172103e5fe55 | PARAMESH8220986581/programming | /count numbers.py | 125 | 3.515625 | 4 | k=["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
a=int(input())
if a>=1 and a<=10:
print(k[a-1])
|
516dd997e55a4cf5b78f0a346d0d37198117f946 | yangyuebfsu/ds_study | /leetcode_practice/1200.py | 1,207 | 4.125 | 4 | ***
1200. Minimum Absolute Difference
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr
a < b
b - a equals to the minimum ... |
52e8af546a1e90b53e77e7e1f9f2a576e74ff573 | RuimengWang/KNN-R-and-Python | /KNN-classifier python.py | 1,410 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 18:28:05 2017
@author: wrm
"""
from sklearn.neighbors import NearestNeighbors
from sklearn.neighbors import KDTree
from sklearn.neighbors import BallTree
import numpy as np
###Here is the calculation process for the nearest distances###
X1 = np.array([[-... |
ca6a25b90c7490a6e720c64bc85b113eb5bebe9e | santoshparmarindia/algoexpert | /cycleInGraph.py | 1,075 | 3.796875 | 4 | def cycleInGraph(edges):
for vertex, edge in enumerate(edges):
visited = {}
queue = [vertex]
while queue:
currentVertex = queue.pop(0)
if currentVertex in visited:
return True
visited[currentVertex] = True
if len(edges[currentVe... |
2eb8a7f5ae4bb3d9aa107ef0776a0659533a5cfb | jon-bassi/crypto-tools | /tools/Vignere.py | 1,212 | 3.671875 | 4 | __author__ = 'jon-bassi'
import sys
# Vignere Cipher encrypt and decrypt tools
def encrypt(text, key):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
# alphabet is first letter in vignere alphabet
# difference between letter and alphabet is the new letter
encrypted = ''
for letter in range(len(text)):
... |
e79917b9bc153de794822cf8c1df8fc92d2cb3e3 | Vaishnavmatte/Project2.O | /project2.O.py | 1,367 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
a=6
if(a==6):
print("correct")
# In[11]:
a=15
b=20
if (a>=25):
print("a is greater")
else:
print("a is lesser")
# In[28]:
player1 = str(input("Enter either stone,paper,scissor"))
player2 = str(input("Enter either stone,paper,scissor"))
if (player1=="... |
a2fe3e17a43eb2772ad7506acda1a675c587b0c3 | ChrisUKGIS/GiNTro | /Documentation_Practicals/test1.py | 1,071 | 3.90625 | 4 | # Program to remove emoticons.
string_with_emoticons = "Oh, hai! Can I haz cheezeberger? :D :D"
emoticons = (":D", ":)", ":/", ":p", ";)")
#for i in range(len(emoticons)):
# print("Fish tickle")
# j = 0
# while j<len(emoticons):
# emoticon_start = string_with_emoticons.find(emoticons[i])
# ... |
4650bc491e5e1af1531f61be6208be9886e52831 | Matheus900/Curso-de-Python3 | /Mundo 02/exe012.py | 474 | 3.921875 | 4 | l1 = float(input('Primeiro lado: '))
l2 = float(input('Segundo lado: '))
l3 = float(input('Terceiro lado: '))
if l1 < l2 + l3 or l2 < l1 + l3 or l3 < l1 + l2:
print('Esses valores admitem um triângulo.')
if l1 == l2 == l3:
print('Trângulo equilátero.')
elif l1 == l2 or l1 == l3 or l2 == l3:
... |
2cc5274064be5551734f31fcf3285cab971072aa | ryanwilkinss/Python-Crash-Course | /Do it Yourself/Chapter 8/8-14.py | 1,069 | 4.3125 | 4 | # Write a function that stores information about a car in a dictionary. the
# function should always receive a manufacturer and a model name. It should
# then accept an arbitrary number of keyword arguments. Call the function
# with the required information and two other name-value pairs, such as a
# color or an op... |
9f9ff664891f089838f46a300647a4693411ccab | bigfairy-Jing/python-basis | /3.instance/8.输出指定范围内的质数.py | 264 | 3.78125 | 4 | lower = int(input('输入区间最小值'))
upper = int(input('输入区间最大值'))
lis = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if(num%i)==0:
break
else:
lis.append(num)
pass
print(lis)
|
9fedbaecb36d5df4c39cec90a17712d5a8ea217e | drewdoescode/python-projects | /computers r not smart.py | 4,909 | 3.578125 | 4 | Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 122122122122122122122122122/12231223122312231223
9984457.065405553
>>> print("hello world")
hello world
>>> print ("apple pie")
apple pie
>>> input ("do you... |
b4c4887c857694fad70248f85405e833342692f7 | DaveFerBear/miscellaneous | /genetic_algorithms/genetic_test_2.py | 415 | 3.6875 | 4 | import random, string
def fitness(final_word, word):
fitness = 0
for i in range(0, len(final_word)):
if (final_word[i] != word[i]):
fitness+=1
return fitness
POP_SIZE = 10
NUM_MUTATIONS =
target = "popcorn"
# Initialize Population
pop = []
for i in range(0,POP_SIZE):
s = ""
for j in range(0, len(target)):... |
303fc345383de0a5dffedfdb6b512fc7dc5b5c29 | MicaelSousa15/PTS | /31.py | 136 | 3.703125 | 4 | lista = [1,2,3,4,5]
for x in lista:
print('Numero',x)
# Ele vai imprimir a lista mostrando a string 'Numero' antes de qualquer valor |
49d1cb8f7bc96df3714d989cee9ed738e1cc94ed | rowing391988/Python_learn | /Lesson_1.py | 2,535 | 4.125 | 4 |
print("Задача 1")
name = 'Андрей '
print("Привет пользователь " + name)
last_name = input('Введите вашу фамилию: ')
print(name + last_name)
age = int(input("Введите ваш возраст: "))
current_year = int(input("Введите текущий год: "))
year_of_birth = current_year - age
print('Поздравляю! Вы родились в ' + str(year_of_bi... |
199d97fc556f287bed7c19df201d2b7b540fb88d | ftn8205/python-course | /40-3.py | 720 | 3.578125 | 4 | from threading import Thread
import time
# 產生線程的方式
# 方法一
def task(name):
print('%s is running' %name)
time.sleep(1)
print('%s is over' %name)
# 開啟線程不需要在main下面執行代碼,但還是習慣在main下面寫
t = Thread(target=task,args=('egon',))
t.start()
print("Main")
# #方法二
# class MyThread(Thread):
# def __init__(self, name):
# ... |
de0bcba06d4a950d8bdcc532f9e314f51f3816c2 | khelm/DOSA | /create_model.py | 1,953 | 3.859375 | 4 | '''
create_model is a program that allows users to select either a model file
or an annotated dataset and find similar data on the Blackfynn
SPARC portal
Author: Karl G. Helmer
Institution: Massachusetts General Hospital
Date: 2018-12-06
'''
import json, sys
from blackfynn import Blackfynn
from blackfynn import Coll... |
0023bfd1aab15e780002f586d6a7ccbc94b998da | platipy/platipy | /pong/10/pong.py | 4,034 | 3.625 | 4 | import spyral
import random
import math
WIDTH = 1200
HEIGHT = 900
SIZE = (WIDTH, HEIGHT)
class Ball(spyral.Sprite):
def __init__(self, scene):
super(Ball, self).__init__(scene)
self.image = spyral.Image(size=(20, 20))
self.image.draw_circle((255, 255, 255), (10, 10), 10)
s... |
0044d9669dc072f542ca611400ad63b24db6635f | sotojcr/100DaysOfCode | /PythonLearningStep1/21closure.py | 1,358 | 4.5 | 4 | #closure
#nested function
def outerFun(text):
t = text;
def innerFun():
print(t)
innerFun()
outerFun('Hey!')
"""here, innerFunction() is treated as nested Function
which uses text as non-local variable. """
"""in clousre it is a fun object that remebers values in enclosing
even if they are not present in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.