blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9201174ec5ac6d814d7e832796a6c2cc2a71619c | SenseiCain/python_crash_course | /syntax/functions.py | 1,387 | 4.0625 | 4 | # -- FUNCTIONS --
# Same indention notation as for loops
# Define a Fn with def
# Snake case
def greet(name):
print(f'Hello, {name.title()}!')
# greet('Christian')
# Positional arguments
def greet_with_sirname(name, sirname='Mr/Mrs'):
print(f'Greetings {sirname}. {name}')
# greet_with_sirname('Christian', 'Mr')
# ... |
a0f3ce93b1b31b4832d13c8121ccd3a30d2ed717 | vparjunmohan/Python | /Basics-Part-I/program79.py | 189 | 4.125 | 4 | 'Write a Python program to get the size of an object in bytes.'
import sys
val = input('Enter a string object ')
print("Memory size of '"+val+"' = "+str(sys.getsizeof(val))+ " bytes")
|
1ee93d08f113ef38a6fd6a016cc19195c5ecbe32 | jsimfors/the_cash_register | /puppgift.py | 10,685 | 4.34375 | 4 | class Item:
"""
Attributes:
item: what kind of item, ex banana
price: the price of the item
amount: the amount left in stock
"""
def __init__(self, item, price, amount):
"""
:param item: what kind of item, ex. banana
:param price: The price of the item
:param... |
fe9279a9cf98f8691ab0c37e276453c299487318 | alandmoore/tkinter-basics-code-examples | /Video2/diary.py | 1,611 | 3.59375 | 4 | """My Diary Application in Tkinter"""
import tkinter as tk
# First line
root = tk.Tk()
# configure root
root.title('My Diary')
root.geometry('800x600')
root.columnconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
# subject
subject_label = tk.Label(root, text='Subject: ')
subject_label.grid(sticky='we', padx=5, ... |
63bbad4eba82181361a3a1273c5bf8847e71fbe7 | hungd25/projects | /CS6390/HW4_P1.py | 3,718 | 3.953125 | 4 | """
"""
def get_world_series_wins(file_location):
"""
This function reads the World Series Data and return a list type per line
:param file_location:
:return: list of wins
"""
series_file = open(file_location, 'r') # open file with read only
series_wins = series_file.read().splitlines() ... |
6eb5114bcff34b32d3bc764773dc76e812c092e5 | saikumarpochireddygari/Interview_Prep | /int_to_roman.py | 4,291 | 4.03125 | 4 | """
Question : Given a integer value convert it into it's equivalent roman representation and return the same.
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman n... |
4fdefc5403a6fa5b8d05f1b6c9556b03903b87b9 | chrisjdavie/hackerrank_algos | /compare_the_triplets/src/test.py | 834 | 3.5 | 4 | import unittest
from .solution import competition, compare_scores
class testComplete(unittest.TestCase):
def test_example(self):
a_i = ( 5, 6, 7 )
b_i = ( 3, 6, 10 )
a_score, b_score = compare_scores( a_i, b_i )
self.assertEqual(a_score, 1)
self.assertEqual(b_score, 1)... |
f67c54e276519f3262c4de78033c72e900f5d988 | ashu20031994/HackerRank-Python | /Day-1-Python Introduction/3.Division.py | 629 | 4.375 | 4 | """Task
The provided code stub reads two integers, and , from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, // . The second line should contain the result of float division, / .
No rounding or formatting is necessary.
Example
The result of the integer divisio... |
820439d74ac637d9c9cdf34d9b75369db5ec04e8 | chensheng1/gitskills | /python 实例/cstest.py | 580 | 3.71875 | 4 | #!usr/bin/env python
#coding:cp936
k=5 #Ӳҵıֵ
n=100 #֧Ǯ
mon=[] #ʼıֵ
backmon=[] #ѰıֵĿʹСʼ
for i in range(k+1): #Ŀеıֵб
mon.append(2**i)
mon.reverse()
for m in mon: #ѡıֵnȥõֵǴ˱ֵĿʣµҪжϵġ
backmon.append(n/m)
n=n%m
for j in range(k+1):
if backmon[j]!=0: #жϴӡ
print str(mon[j])+... |
1b17f63d3c562e74e3d22c15dcb5f134476ba6eb | masterprueba/Prueba-Big-Data | /primero/spark.py | 1,786 | 3.5625 | 4 |
##- 1.Cargar el archivo csv por medio de comandos dentro de Databricks Community.
## Primero, cargo el archivo CSV y muestro los datos.
import numpy as np
import pandas as pd
import collections
file_location = "/FileStore/tables/Tweets.csv"
file_type = "csv"
# Opciones
infer_schema = "false"
first_row_is_header =... |
6a6717d45c5cd3b387279cec4a73e4ce86f1f1e3 | breynaUC/py-clase04 | /ejercicios02.py | 175 | 4 | 4 | estudiantes= {"Raul":21,"Jairo":18,"Keyla":19}
nombre = input("Nombre: ")
if nombre.title() in estudiantes:
print(estudiantes[nombre.title()])
else:
print("No existe") |
34d245a28e407c72e235ca3cb860380e0bc3c606 | nazarov-yuriy/contests | /yrrgpbqr/p0347/__init__.py | 606 | 3.53125 | 4 | import unittest
from typing import List
import collections
# ToDo: use uniquiness of answer and implement bucket sort
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counts = collections.Counter(nums)
return sorted(counts, key=lambda x: -counts[x])[:k]
class Test(un... |
4db6f9178e623ddcffded9307e1f27ecc9c424fa | SoSopog-dev/All | /kryptering.py | 454 | 3.5625 | 4 | import random
from random import randint
alphabet = "abcdefghijklmnopqrstuvwxyzæøå "
p_al = ""
pairs = {}
p_al = list(p_al)
if int(input("Generate? 1 = Yes 2 = No")) == 1:
seed = randint(1,100)
random.seed(seed)
for letter in alphabet:
newletter = alphabet[randint(0,29)]
while new... |
3e205f2cae2c99e36f307feab693797808b577e8 | piercepurselley/Python_Web_Dev_Practice | /Python Web Dev Practice/find_characters.py | 480 | 3.75 | 4 | word_list = ['hello', 'world', 'my', 'name', 'is', 'Anna']
char = 'o'
new_list = []
#WE ARE GOING FOR...
# new_list = ['hello', 'world']
# print [s for s in list if sub in s]
# for x in range(0,len(word_list)):
# if let in len(word_list) == char:
# print "I did it!"
for x in word_list:
if x.find('o'... |
ce64623746347a2eaf78a58cd551346b1c7468d2 | kavyaachu47/luminarpython | /luminar/Classroomassignments/fibnopgm.py | 161 | 4.15625 | 4 | #Program to produce fibonacci series
num=int(input("enter value"))
a=0
b=1
sum=0
c=1
while(c<=num):
print(sum,end="")
c+=1
a=b
b=sum
sum=a+b |
1c8f7223bd09bde85e8aac7bef38d6960dfdd5d8 | rustt71749/01_Lucky_Unicorn_V2 | /04_Lucky_Unicorn_payment_mechanics.py | 812 | 3.953125 | 4 | # Lucky Unicorn Decomposition Step 4
# Set up payment mechanics
# To do
# Adjust total correctly for a given token
# - if it's a unicorn add $5
# - if it's a zebra / horse, subtract 0.5
# - if it's a donkey,subtract 1
# Give user feedback based on winnings
# State new total
# Assume starting amount is $10
total... |
85ff122284f8c29288f2032e8f94dce154b1a516 | Aasthaengg/IBMdataset | /Python_codes/p02393/s646088337.py | 363 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 30 16:38:31 2015
@author: hirose
"""
#Branch on Condition - Sorting Three Numbers
n = map(int, raw_input().split())
a = n[0]
b = n[1]
c = n[2]
for i in range(3):
for i in range(2):
if(n[i] > n[i+1]):
temp = n[i]
n[i] = n[i+1]
... |
e45fda96ee2cc0c772fc40fcdbfc40caaa64dafe | typemegan/Python | /CorePythonProgramming_2nd/ch14_excution/udm_method.py | 1,474 | 3.78125 | 4 | #!/usr/bin/python
#coding:utf-8
'''
比较类中的三种方法:
类方法,实例方法,静态方法
'''
class A(object):
def func(self): pass # self用来接收python自动传入的实例,无论绑定还是未绑定调用
@classmethod
def bar(cls):pass # cls用来接收由python自动传入的类对象
@staticmethod
def foo(*args):pass
print 'A:'
print 'A.func:'.ljust(12), A.func
print 'A.bar:'.ljust(12), A.bar
... |
b489e48634ed1bdd7286e8b46978c7fccbd556b0 | tuouo/selfstudy | /learnfromBook/PythonCookbook/DataStructure/about_priority_queue | 919 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return... |
efcdd0fce7bffdb788497ab7e787f41db40f8c48 | fmurray1/obs_overlay | /life_overlay_gen.py | 1,251 | 3.5 | 4 | """
Script generates a square image with a number in the middle
to use as an OBS overlay for playing magic over webcam.
"""
import click
from PIL import Image, ImageDraw, ImageFont
SNOW_WHITE = (255, 250, 250)
def text_on_img(text="NULL", filename='output.png', text_size=120, image_w=200, image_h=200):
"Draw a ... |
65161b034f0738a7ecb1b15354604a5f5c66ee76 | Johnelvis/ECG-NN-Classifier | /ecg-nn-classifier/preprocessing/filters.py | 1,788 | 3.5 | 4 | from scipy.signal import medfilt, butter, lfilter
"""
Low pass filters the ecg signal to remove high frequency noise like electromagnetic interference.
"""
def low_pass_filter(data, cutoff, order, sample_rate=360):
# Nyquist frequency
ny = sample_rate >> 1
cut = cutoff / ny
# Calculate filter coeffici... |
4ab2db331b42f517acce0877681669d791c37919 | shocklink/ShellScriptRepository | /shell-script/plot-memory-space/hex_to_binary.py | 197 | 3.53125 | 4 | #!/bin/python
count = 0;
with open('d','r') as f:
for line in f:
for word in line.split():
#print(word),
print(bin(int(word, 16))[2:].zfill(64)),
print
|
81111419f9b7f234b651b54444d1de6f093171f6 | vijaymaddukuri/python_repo | /training/sdArray.py | 169 | 3.84375 | 4 | color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
newList=[]
for (i,x) in enumerate(color):
if i not in (0,4,5):
newList.append(x)
print(newList) |
2fc1aca509b73e5b46cbd9c747a03c1689969d16 | Mike-Xie/cs-module-project-hash-tables | /hashtable/code_test.py | 1,349 | 3.984375 | 4 | all_ints = [85, 46, 27, 81, 94, 9, 27, 38, 43, 99, 37, 63, 31, 42, 14]
names = ["Bob", "Jane", "Bill"]
divisible_by_three = list(filter(lambda x: x % 3 == 0, all_ints))
names_that_are_4_chars = list(filter(lambda x: len(x) == 4, names))
for item in divisible_by_three:
print(item)
# Print out all of the strings in t... |
acf5892120dcb3c6204ddede75604f3279801bc4 | chenjiahui1991/LeetCode | /P0014.py | 735 | 3.734375 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
result = strs[0]
for i in range(1, len(strs)):
result = self.getLongest(result, strs[i])
return result
... |
4e1f9bcbb5d1bc368136051e50bfa1a4f9b675ba | radhikaca/puzzles | /Largesum.py | 304 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 07:36:42 2020
@author: rad
"""
def fibonacci():
"""Fibonacci numbers generator, first n"""
a, b, i = 0, 1, 0
while i<10:
yield i
#yield a
#a, b = b, a + b
i += 1
f = fibonacci()
for i in f:
print(i)
|
b6a9835ce89cdd2ff0961c29f0d007d52cdc2713 | xyzhangaa/ltsolution | /CountandSay.py | 703 | 4 | 4 | ###The count-and-say sequence is the sequence of integers beginning as follows:
###1, 11, 21, 1211, 111221, ...
###1 is read off as "one 1" or 11.
###11 is read off as "two 1s" or 21.
###21 is read off as "one 2, then one 1" or 1211.
###Given an integer n, generate the nth sequence.
#time O(n*2^n)
#space O(2^n)
def co... |
3c0abbab55674cae73b79d15de0f38e1aaaeba50 | maryyang1234/hello-world | /string/10.计算字符串中的数字和.py | 343 | 3.984375 | 4 | import re
def findSum(str1):
p = re.compile("[0-9]+")
list = p.findall(str1)
sum =0
for i in list:
sum= sum+int(i)
return sum
str1 = "12abc20yz68"
print(findSum(str1))
"""def find_sum(str1):
# Regular Expression that matches digits in between a string
return sum(map(int,re.fi... |
44cfca596adbb9b0d993b1d597c31e707c200180 | simonom/outreach | /tephiplt/tephiplt.py | 10,361 | 3.59375 | 4 | '''script to demonstrate the equations underlying the tephigram'''
# based on EART23001: Atmospheric Physics and Weather (University of Manchester)
# Simon O'Meara 2020: simon.omeara@manchester.ac.uk
# other helpful resource(s): http://homepages.see.leeds.ac.uk/~chmjbm/arran/radiosondes.pdf
# -------------------------... |
4be572ee85b35d30e9aba7a0d7c09a698ee83e35 | rv404674/Algo-Implementations | /graph/dfs.py | 1,145 | 3.828125 | 4 | # NOTE
# TIme complexity of In
# for list - Average(O(n)) ( Implemented as sequences)
# for dict - Average O(1), Worst O(n) ( as dict is hashing data type)
# edpresso.com for dfs implementation
# for a directed graph, the sum of size of adjaceny list of all nodes is E. 2+2+1+1 = 6
# hence O(V) + O(E) = O(V+E)
# OV) b... |
daab04c1d1026165d2a385d0f75b7b6e741bd914 | Vputri/Python | /tugas.py | 276 | 3.78125 | 4 | print "Ketikkan Control C atau -1 untuk keluar"
number = 1
while number != -1:
print ''
try:
number = int(raw_input("Masukan angka : "))
print "Anda memasukan :",number
except ValueError:
print "Bukan angka bilangan integer atau float!"
|
fb15cf38c01c041585dab3b53621e5020e157446 | nirnicole/Artificial-Intelligence-Python-Repositories | /Evolutionary Computation/Genetic Algorithm/Maze.py | 11,164 | 3.765625 | 4 | import Problem
import random
from PIL import Image
import numpy as np
import math
class MazeProblem(Problem.EvolutionProblem):
"""
in this problem we get different attempts to find a solution to a distance problem and we try to utilize them.
its actually a local searching problem.
dna str... |
0585b33867eaaa8a59059a63b4cc670f1bd4b615 | michaelRobinson84/CP1404_semester2 | /cp1404practicals/prac_09/sort_files_2.py | 1,503 | 4.125 | 4 | import shutil
import os
def main():
os.chdir("FilesToSort")
lst_file_extensions = []
for directory_name, subdirectories, filenames in os.walk('.'):
for filename in filenames:
str_file_extension = get_file_extension(filename)
if str_file_extension not in lst_file_extens... |
e8b75cdc4e175ac09576106e68aaebe00cfd8a81 | lucianojunnior17/Python | /Curso_Guanabara/aula72.py | 507 | 3.875 | 4 | cont = ('zero','um','dois','três','quatro','cinco','seis','sete','oito',
'nove','10','onze','doze','treze','quatorze','quize', 'dezeseis',
'dezessete','dezoito','dezenove','vinte','vinte um ','vinte dois',
'vinte três','vinte Quatro','vinte Cinco')
while True:
num = int(input('Digite um... |
1c13ac630b8d73c06c0fa14adb0c08669a7ef2d2 | helsonxiao/exercises | /dictionary.py | 413 | 4.25 | 4 | dictionary = {}
while True:
user_action = input("Add or look up a word (a/l)?")
if user_action == "a":
type_word = input("Type the word:")
type_definition = input("Type the definition:")
dictionary[type_word] = type_definition
elif user_action == "l":
type_word = input("Type ... |
f9a21b792c1bc1a46163196eb52ce918fe3722c8 | Juanjo-M/Primero | /Lab3219-1.py | 309 | 4.21875 | 4 | #print ("¿Que palabra desea escribir?"):
#P=str(input(""))
P = input("¿Que palabra desea escribir? ")
while (P !="chupacabra"):
#print("Puede seguir escribiendo palabras")
if (P == "chupacabra"):
break
P = input("¿Que palabra desea escribir? ")
print("Aqui se detiene el bucle") |
6012313385274520a4dadff02ff1fbbeb5037f9a | KrisR15/Knots_and_Crosses | /Knots_&_Crosses.py | 6,157 | 3.953125 | 4 | import random
def display_board(board): #Create a game board
print("\n"*100)
print(" "+board[1]+" | "+board[2]+" | "+""+board[3]+" ")
print("-----------")
print(" "+board[4]+" | "+board[5]+" | "+""+board[6]+" ")
print("-----------")
print(" "+board[7]+" | "+board[8]+" | "+""+board[9]+" "... |
0e70290950aabafe8b9e6c5a0f2f44863186062c | RaskoANML/maths | /Python/LeoExoPoly1d.py | 424 | 3.5625 | 4 | """
First trial with data plotting
"""
import numpy as np
import matplotlib.pyplot as plt
p = np.poly1d([666,0,1,2])
x = np.arange(-20,60,1)
print "Voici les antecedants :", x
print "Voici le polynome", p
# calcul des ordonnees
y = p(x)
print "Voici les ordonnees correspondant a l'interval -20 a 59: ", y
plt.plo... |
f23398f7af6a1d7625dcab2dab3103b6fc93cd8b | Harry-Ramadhan/Basic-Phthon-5 | /casting.py | 377 | 3.78125 | 4 | # float to integer
# x = 1.99999
# print (x)
# print (type(x))
# y = int (x)
# print (y)
# print(type(y))
# int to float
# a = 100
# print(a)
# print(type(b))
# b = float(a)
# print(b)
# print(type(b))
# string to float
# x = "4.5"
# print(x)
# print(type(x))
# y = float (x)
# print(y)
# print(type(y))
# # float ... |
530e7ee280aa40fb04cad40771b0e5549372cd5c | AChen24562/Python-QCC | /Exam2-Review/Review3d-if-loops.py | 311 | 4.3125 | 4 | #3d Loops and Input
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
if num1 < num2:
while num1 <= num2:
print(num1, end="|")
num1 += 1
elif num1 > num2:
for x in range(num1):
print(num1, end="|")
num1 -= 1
else:
print(f"{num1} = {num2}")
|
9a6e7affeb833bbea4288dc31bca0acf3e6042ec | ed-kiryukhin/MITx_6.00.1x | /ProblemSet01/PS01-1.py | 276 | 3.96875 | 4 | ## https://courses.edx.org/courses/course-v1:MITx+6.00.1x_8+1T2016/courseware/Week_2/Basic_Problem_Set_1/
## COUNTING VOWELS
## Assume s is a string of lower case characters
count=0
for letter in s:
if letter in "aeiou":
count += 1
print "Number of vowels: %d" % (count)
|
d70f05b74205bbbcb95b03f09e9dc76e6a71ed16 | mayurikpawar/pythonbasic | /data.py | 660 | 4.1875 | 4 | #python program demonstrating list
my_data = ["MY SELF MAYURI KAILAS PAWAR"]
l1 = ["I AM PERSUING BE E&TC FROM SANDIP FOUNDATION","nashik"]
print my_data
print l1
l1.reverse()
print l1
list = ['i am from jalgaon','but i am studying in nashik']
print('index of i am from jalgaon',list.index('i am from jalgaon'))
print(li... |
cd86db56f077762c121b7b85288385e5ef76039c | skuld1020/PY4E | /PY4E/triangle_area.py | 1,045 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 14 22:37:06 2020
@author: Happy sunday
"""
"""給三點求三角形邊長和面績"""
def area(a,b,c):
s = (a+b+c)/2
A = (s*(s-a)*(s-b)*(s-c))**(1/2)
return A
def length(x1,y1,x2,y2):
L = ((x1-x2)**2+(y1-y2)**2)**(1/2)
return L
A_x1 = input('Please input... |
3a02b435c8dfc37ca835cfd443618bce0fa0b180 | KingJMS1/EEInformation | /Add.py | 221 | 3.546875 | 4 | from time import time
b = 5
c = 3
d = 2
initime = time()
for x in range(100000):
b = (c + d)%100
c= (b + d)%1000
d= (c + b + d)%500
b= (d - c)%150
fintime = time()
print("TIME: " + str(fintime - initime)) |
91d5f2188d3b1fd32e2df4ef54452ddf654a069e | Noksis/Python | /Sara/Task 5.py | 1,120 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame()
file = open('Input.csv','r')
df = pd.read_csv(file)
Answer = []
# First task (Index: 0,1,2)
Answer.append("Size:")
Answer.append(df.size)
Answer.append("10:")
Answer.append(df[:10])
Answer.append("Random 10:")
Answer.append(df.sa... |
0b504117f2537045f1ed76550798c36e5965e0b1 | NikolasMatias/urionlinejudge-exercises | /Iniciante/Python/exercises from 2001 to 2600/exercise_2493.py | 1,481 | 3.734375 | 4 | def is_calculo_possible(valor_a, valor_b, resultado_calculo):
return valor_a+valor_b == resultado_calculo or valor_a-valor_b == resultado_calculo or valor_a*valor_b == resultado_calculo
def test_calculo(calculo, expressao_escolhida):
valor_a,valor_b, resultado_calculo = [int(x) for x in calculo.replace('=', ' '... |
ee78ab4299708bdaa37f2acbf193a01ec7e91dbc | C-Powers/AutomateTheBoringStuff | /truthy_and_fasly.py | 595 | 4.5625 | 5 | #this code looks at truthy and falsey values.
#no boolean operators are used, but if we enter a name, it's "truthy" because
#we did input something
#if we dont input a name, it's falsey, because we did not input a name
name=raw_input("Please enter a name: ")
if name:
print "Thank you so much for entering a name. ... |
b9d405a29353245bc80d8c9b9b15bf48f38d9c3b | gefranco/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 207 | 3.5625 | 4 | #!/usr/bin/python3
import json
def save_to_json_file(my_obj, filename):
with open(filename, mode="w", encoding="utf-8") as myFile:
json_obj = json.dumps(my_obj)
myFile.write(json_obj)
|
9be94a2011df44d9c00859fe28784a90589ea48b | wellingtongoncalves/Python | /desafio010.py | 143 | 3.796875 | 4 | carteira = float(input('Quanto você tem na carteira: '))
dolares = carteira / 3.27
print('Você pode comprar {:.2f} dolares'.format(dolares)) |
95a7f62ab6a223fae447c33adfd5cff3b31b8af4 | artneuronmusic/Blog_AcceptanceTesting | /app.py | 1,667 | 3.765625 | 4 | from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
posts = []
@app.route('/') #its show the homepage after url
def homepage():
return render_template('home.html') #will return the page: home.html
@app.route('/blog') #now in blog page
def blog_page():
return render_... |
0d1c2ac6bf562fbf71615a82ac83d1cff86ea1d9 | CppChan/Leetcode | /medium/mediumCode/BinaryTree/DistanceOfTwoNodes.py | 1,393 | 3.6875 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def distance(self, root, k1, k2):
if root == k1:return self.findnode(root, k2,0)
if root == k2: return self.findnode(root, k1,0)
return self.findcommon(root, k1, ... |
18400af13b65f17c94f4e27c2a25319ded04df08 | WD2016GitBuild/iPython | /itchat/timer.py | 507 | 3.53125 | 4 | #coding=utf8
import datetime
import time
def doSth():
print("acb")
# 一般网站都是1:00点更新数据,所以每天凌晨一点启动
def main(h=1,m=0):
while True:
now = datetime.datetime.now()
print(now.hour)
print(now.minute)
# print(now.hour, now.minute)
if now.hour == h and n... |
531ac21c7675a1541892a43afa816412db3cdabc | venanciomitidieri/Exercicios_Python | /081 - Extraindo dados de uma Lista.py | 841 | 4.1875 | 4 | # Exercício Python 081 - Extraindo dados de uma Lista
# Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
# A) Quantos números foram digitados.
# B) A lista de valores, ordenada de forma decrescente.
# C) Se o valor 5 foi digitado e está ou não na lista.... |
d834259aff6b772dd4de91b08ffd036ca61e882a | dushabella/Introduction_to_Bioinformatics | /03_genome_reconstruction/project3.py | 5,537 | 3.640625 | 4 | """
Mini project #3:
---------------
A project is focused on finding the minimum length k of k-mers for which it is possible to obtain unique cyclic genome.
It bases on constructing de Bruijn graph with k-mers on a nodes, which indeed is a solution of Eulerian path problem.
Good source of knowledge:
http://www.bioinfo... |
f7887648f9e418c6406ff72f9b90938a22d54131 | raunakpalit/myPythonLearning | /venv/setChallenge.py | 429 | 4.40625 | 4 | # Create a program that takes some text and returns a list of
# all the characters in the text that are not vowels, sorted in
# alphabetical order.
#
# You can either enter the text from the keyboard or
# initialise a string variable with the string.
vowels = frozenset("aeiou")
random_text = input("Enter a text: ")
f... |
afb83515e78ac7f14d0b967d49e332c9d1bf5cea | 89Mansions/AI_STUDY | /keras/keras54_conv1d_09_cifar10.py | 2,952 | 3.796875 | 4 | # Dnn, LSTM, Conv2d 중 가장 좋은 결과와 비교
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
#1. DATA
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print(x_train.shape, y_train.shape) # (50000, 32, 32, 3) (50000, 1)
print(x_test.shape, y_test.shape) # (10000, 32,... |
2e991dce3e99d8bd078e0d06d3f8de2a90e7cec2 | cp4011/Algorithms | /New_Interview/排序算法/10_桶排序.py | 2,838 | 4.3125 | 4 | """ 桶排序(Bucket Sort)
1. 设置一个定量的数组当作空桶;
2. 遍历输入数据,并且把数据一个一个放到对应的桶里去;
3. 对每个不是空的桶进行排序;
4. 从不是空的桶里把排好序的数据拼接起来。
桶排序实际上是计数排序的推广,但实现上要复杂许多。
桶排序先用一定的函数关系将数据划分到不同有序的区域(桶)内,然后子数据分别在桶内排序,之后顺次输出。
当每一个不同数据分配一个桶时,也就相当于计数排序。
假设n个数据,划分为k个桶,桶内采用快速排序,时间复杂度为O(n)+O(k * n/k*log(n/k))=O(n)+O(n*(log(n)-log(k))),
显然,k越大,时间复杂度越接近O(n),当然空间复杂度... |
bfa2301b4152e8ba54f19eb8afe20514ecb6813e | 2KNG/old_freshman | /python_source/수업/210401.py | 2,798 | 3.5 | 4 | # # # # g = [30,10,20]
# # # # print(g)
# # # # print(g[2])
# # # # import turtle as t
# # # # t. shape ('turtle')
# # # # t. speed (0)
# # # # a=['red','orange','yellow','green','blue','black' ]
# # # # t. begin_fill()
# # # # for i in range(300):
# # # # t. fd(i)
# # # # t. rt(i)
# # # # if i < len(a):
#... |
e42f13fa50de819f49b2a09086aee196a71e1b52 | 31more/Homework_python_1 | /hometask2_ready.py | 7,040 | 4.21875 | 4 | """
For и range, которые мы изучили
в предыдущем файле, можно использовать
для обращения к элементам списка
по индексам.
Немного про списки и индексы
l = [6,2,5,6,2,1,9] такие индексы
0 1 2 3 4 5 6
Если мы хотим получить доступ к элементам
списка, нам необходимо обращаться
по индексам. """
print("""Нап... |
acace5e89b8c239d29084761f8075c429f73c18d | z627797668/PAT-B.py | /1001.py | 117 | 3.734375 | 4 | n=input()
ans=0
n=int(n)
while n!=1:
ans+=1
if n%2==0:
n/=2
else:
n=(3*n+1)/2
print(ans)
|
1c8e7c54e3e4071a478ba158a0af43e59102579e | PeterL64/UCDDataAnalytics | /5_Data_Manipulation_With_Pandas/2_Aggregating_Data/6_One_Method_Of_Calculating_Proportion_By_Subsetting_And_Summing.py | 931 | 3.859375 | 4 | # What percentage of sales occurred at each store type
# Calculating grouped summary statistics without using the .groupby() method
# From the sales DataFrame, Walmart has three different store types, A, B and C
import pandas as pd
# Calculate the total weekly_sales over the whole dataset.
sales_all = sales["weekly_... |
232feb2fa72867a5ce9c6ae0c3e4f95332383aa2 | hysz/leetcode | /longest_substring.py | 1,885 | 3.640625 | 4 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
'''
We construct a lookup table that allows you to query for next occurence of a character.
We use len(s) to denote a non-existent index.
Ex for string "abab"
{
"a:
{
... |
f9fa69f4d89dae8293c108caacbb123fa4f2244c | quake0day/oj | /sortColors2.py | 1,191 | 3.609375 | 4 | import sys
class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
# write your code here
count = 0
start = 0
end = len(colors) - 1
while count < k:
minium = sys.maxint
... |
d2ee85b8419cce79cfaeadfc47dab7797ade8948 | mjefris16/Muhammad-Jefri-Saputra_I0320066_M-Abyan-Naufal_Tugas7 | /I0320066_soal1_tugas7.py | 996 | 3.765625 | 4 | print("="*40)
judul = "Program Kalimat Sapaan"
center = judul.center(40,"*")
print(center)
print("="*40)
Nama = input("Siapa nama anda: ")
kapital = Nama.capitalize()
print("Nama anda adalah: ", kapital)
sapaan = input("Masukkan kalimat sapaan anda: ")
print("Kalimat sapaan anda: ", sapaan)
print("Jumlah ... |
6b937beba87cf764239e14aa690e81771e6ac0dd | Eric-Wonbin-Sang/CS110Manager | /2020F_final_project_submissions/madireddysaumit/7395236_main-1.py | 1,914 | 3.5625 | 4 | import csv
import matplotlib.pyplot as plt
import yfinance as yf
date_list = []
price_list = []
with open("NFLX.csv") as csv_file:
for row in list(csv.reader(csv_file))[2:]:
print()
print(row[0])
date_list.append(row[0])
price_list.append(float(row[4]))
with open("AAPL.csv") as csv... |
ae359eab5722da60127ec70c3fe15ce3df7c4567 | Dolantinlist/DolantinLeetcode | /1-50/4*_median_of_arrays.py | 1,047 | 3.59375 | 4 | #There are two sorted arrays nums1 and nums2 of size m and n respectively.
#Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
l = len(nums1) + len(nums2)
if l%2:
return self.fi... |
98028f9379448d78e7c7fe5a0109d8c6947bdcc4 | paolofrd/PROBLEM-5 | /PROBLEM5.py | 1,836 | 3.59375 | 4 | import math #for user-inputs with lib-dependent characteristics
import matplotlib.pyplot as plt
import matplotlib.patches as mpatch
user = input('Input function x(n): ')
reses = [] #storage
xn = [] #storage of x(n) variables
gibx = list(range(0,200))
#y(n)
for n in range (0,200):
#y(n) = -1.5x(n) + 2x(n ... |
0192eaedd7405159c4b68c5501b620ee6f0588a9 | occ010/aoc2019 | /day3/part1.py | 3,269 | 4 | 4 |
def main():
wire1 = []
wire2 = []
with open("input", 'r') as fp:
wire1 = parse_coordinates(fp.readline())
wire2 = parse_coordinates(fp.readline())
# Loop through all the line segments in wire1 and wire2 to see where they intersect
intersections = []
for i in range(len(wire... |
55bdeabb0b264434185d0b96b67df82699a315ca | swairshah/ml | /sampling/error_estimate.py | 1,960 | 3.546875 | 4 | # Sampling uniformly to calculate error wrt optimal model
# vs sampling with Importance sampling to calculate error wrt
# optimal model. Does one give a 'better' estimate than the other?
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn import datasets... |
4f09bc904bbd8c7b7ba00bddbb5efc38ace9d707 | gsy/leetcode | /employee_importance.py | 1,180 | 3.640625 | 4 |
# Employee info
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
... |
5186fc54db1173b8c5a1db6731fba7ccbbe117ad | jbro321/Python_Basic_Enthusiastic | /Python_Basic_Enthusiastic/Chapter_07/P_07_1_5.py | 457 | 3.78125 | 4 | # Enthusiastic_Python_Basic #P_07_1_5
def main():
num = int(input("값을 입력하세요: "))
if num < 0:
print("입력한 값은 0보다 작습니다.")
elif 0 <= num < 10: #파이썬만 가능한 수식
print("입력한 값은 0 이상 10 미만입니다.")
elif 10 <= num < 20:
print("입력한 값은 10 이상 20 미만입니다.")
else:
print("입력한 값은 20 이상입니다.")... |
4443e279d14f83abdf021cd0c0362d40184a259c | Hellofafar/Leetcode | /Medium/681.py | 3,468 | 3.765625 | 4 | # ------------------------------
# 681. Next Closest Time
#
# Description:
# Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits.
# There is no limit on how many times a digit can be reused.
#
# You may assume the given input string is always valid. For example, "... |
f45ec95b7b2e24120bb6ca3bdb7196c2c13fb0c1 | thiago-allue/portfolio | /02_ai/1_ml/3_data_preparation/code/chapter_16/05_cart_regression.py | 637 | 3.84375 | 4 | # decision tree for feature importance on a regression problem
from sklearn.datasets import make_regression
from sklearn.tree import DecisionTreeRegressor
from matplotlib import pyplot
# define dataset
X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)
# define the model
model = Deci... |
c0ec19829fe70224b31690c061a7cec76a64238c | CatPhD/JSC_Python | /Day 1/W3/Sols/p4.py | 169 | 3.953125 | 4 | a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
R =((a+b>c) and (b+c>a) and (c+a>b))
print('Is this a triangle?:', R)
|
5ddea5ba935f16553b8466628f392a36f8debfba | Shobhit-hub/infomation-security-assignment-1 | /additive cypher.py | 1,832 | 4.03125 | 4 |
#Program for Additive Cypher
#function to encode
def encode(text,shift):
result=""
for i in range(0,len(text)):
if text[i]>='a' and text[i]<='z':
result+=chr(((ord(text[i])-ord('a')+shift)%26)+ord('a'))
elif text[i]>='A' and text[i]<='Z':
result+=chr(((ord(te... |
f324c7c89a0153d73b1c2f6041a5ed728c9228f5 | Ebyy/python_projects | /Files/Refactoring.py | 480 | 3.6875 | 4 | import json
filename = 'username.json'
def greet_user():
"""Initiate code to greet user."""
try:
with open(filename) as f_object:
username = json.load(f_object)
except FileNotFoundError:
username = input("What is your username? ")
with open(filename,'w') as f_object:
... |
ca770131f4604f4355ac9e429073c69ef300cc5c | phlalx/algorithms | /leetcode/523.continuous-subarray-sum.py | 1,697 | 3.671875 | 4 | #
# @lc app=leetcode id=523 lang=python3
#
# [523] Continuous Subarray Sum
#
# https://leetcode.com/problems/continuous-subarray-sum/description/
#
# algorithms
# Medium (24.24%)
# Likes: 1107
# Dislikes: 1559
# Total Accepted: 110K
# Total Submissions: 449.6K
# Testcase Example: '[23,2,4,6,7]\n6'
#
# Given a li... |
435d913d035c7b65722ed1e4a780ed74d54a0fcf | mrinmayig/Python-data-structures-and-algorithms | /findminele.py | 509 | 3.84375 | 4 | #Given an array of length N find the minimum element in the array
def minElem(arr):
curr_num=0
min_num=arr[0]
for i in range(1,len(arr)):
curr_num=arr[i]
if curr_num < min_num:
min_num=curr_num
return min_num
#Given an array of length N find the maximum element in the arra... |
0fed8ae7a5af8de3b4341cc637f33a309482effc | allyshoww/python-examples | /exemplos/ex6.py | 712 | 3.6875 | 4 | #!/usr/bin/python
carrinho = []
produto1 = {"nome": "Tenis", "valor": 21.70}
produto2 = {"nome": "Meia", "valor": 10}
produto3 = {"nome": "Camiseta", "valor": 17.30}
produto4 = {"nome": "Calca", "valor": 100.00}
carrinho.append(produto1)
carrinho.append(produto2)
carrinho.append(produto3)
carrinho.append(produto4)
de... |
a8a1432aced1f46d13b3f3988bad93f5dd49ac72 | ZhouZiXuan-imb/pythonCourse | /python_Day09-字符串/03-字符串的模拟用户注册案例.py | 344 | 3.75 | 4 | count = 0
while (True):
username = input('请输入用户名:')
password = input('请输入密码:')
result = username.find(password)
if (count >= 5):
print('今日不能再次注册')
break
if (result != -1):
print('请重新输入')
count += 1
else:
print('登陆成功')
|
715262b2ba6193bcd68fb4b73b73c2dabb1fa3ba | koshikka/assingment1 | /a1_t1_4.py | 134 | 3.5625 | 4 | def c_to_k(c):
k = c + 273.15
return k
c = 27.0
k = c_to_k(c)
print ("celsius of" + str(c) + "is" + str(k) + "in kelvin")
|
d2cc82ee4b5eb82e4ad11c407d66dd12527c35ec | qumc8642/data_science_questionaire | /q2.py | 701 | 3.75 | 4 | import pandas as pd
import numpy as np
# The most important part of this dataset seems to be the salary,
data = pd.read_csv('data.csv')
imputed_data = data
#Impute the salary with the mean on the data (there are some 0s check for nan too)
salary = data['Salary']
mean = np.mean(salary)
index = 0
bad_indexes = []
for n... |
c9990236f7693bd7be5cfbd206be54fd97f43fe5 | mikeykh/prg105 | /12.3 Recursive Power Method.py | 612 | 4.3125 | 4 | # Design a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a positive integer.
def main():
# Get the product of the base raised to the exponent
x = get_power(3, 4)
# Displays the pro... |
ba78696042f255ea658e195f8413dd2780678280 | loki-ppl/caesar-cipher | /caesar.py | 1,868 | 3.9375 | 4 | cifra = 3
alfabeto = "abcdefghijklmnopqrstuvwxyz"
letras = 26
new_texto = []
new_texto2 = []
texto = ""
resultado = ""
menu = True
while menu == True:
opcao = input("\nDigite 1 para Cifrar\nDigite 2 para Decifrar\nDigite 3 para mudar a Cifra\nDigite 0 para Sair\n")
# ============================= Ci... |
275d7652eb50cdd4d8148d9d3c465022ecf14013 | niralpokal/amazon_orders | /csvparser.py | 271 | 3.53125 | 4 | import csv
def parsecsv(filename):
with open(filename, newline='') as csvfile:
parsedcsv = []
ordersreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in ordersreader:
parsedcsv.append(row)
return parsedcsv |
80e7a9468b0b4b86dfb4cdc08131d60eb46c43eb | brianhuynh2021/Python-Crash-Course | /apostrophe.py | 651 | 3.53125 | 4 | # Avoiding Syntax Errors with Strings
# One kind of error that you might see with some regularity is a syntax error.
# A syntax error occurs when Python doesn’t recognize a section of your pro-
# gram as valid Python code. For example, if you use an apostrophe within
# single quotes, you’ll produce an error. This happe... |
bd8c35eaf5bd3cfacef28ba4dfd57789dc457824 | nishantchaudhary12/Starting-with-Python | /Chapter 5/StringRepeater.py | 270 | 4.15625 | 4 | #string repeater
string = input('Enter the string: ')
number = int(input('Enter the number of times you want to print the string: '))
def string_print(x, y):
for num in range(y):
print(x,end='')
if __name__ == '__main__':
string_print(string,number)
|
2860e405f1620859125218b7dc77e4df93dae195 | kimmorsha/MarawiSiegeTweetsEmotionAnalysis | /marawi_tweets_with_location/marawi_tweets_august/official/initial_preprocessed/rename.py | 660 | 3.65625 | 4 | import os
"""
Renames the filenames within the same directory to be Unix friendly
(1) Changes spaces to hyphens
(2) Makes lowercase (not a Unix requirement, just looks better ;)
Usage:
python rename.py
"""
path = os.getcwd()
filenames = os.listdir(path)
print(path)
num = 8
for filename in filenames:
print(filena... |
7d16a609305084006db9bfd1e0313998a2e02d7d | jjdshrimpton/PythonJunk | /Sorting Visualiser2.py | 8,472 | 3.609375 | 4 | import math
from tkinter import *
from random import randint, shuffle, sample
from time import sleep
root = Tk()
root.title("Sorting Algorithms Visualiser")
sortType = StringVar()
menuText = StringVar()
colourOptions = ["Red", "Green", "Blue", "Monochrome", "Random"]
#Initialises the necessary functions based on ente... |
34846e9ee05b0f08ccdcc8a6127dc7d74f80ec00 | manji-0/atcoder | /tenkai/2015/a.py | 157 | 3.5 | 4 | def main():
A = [100,100,200]
for i in range(3,20):
A.append(A[i-1]+A[i-2]+A[i-3])
print(A[-1])
if __name__ == '__main__':
main()
|
d01d04383b79db71acc820de63d8278259ae4d80 | jacquerie/leetcode | /leetcode/0012_integer_to_roman.py | 784 | 3.609375 | 4 | # -*- coding: utf-8 -*-
NUMERAL_ROMAN_MAP = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
class Solution:
def intToRoman(self, num):
result = []... |
41c176104cdcc2ff420a0a47a3319ddbfb8236a4 | ptkang/python-advanced | /chapter04/duck_4_1.py | 1,984 | 4.53125 | 5 | # 鸭子类型:当看到一只鸟走起来像鸭子,游泳起来像鸭子,叫起来也像鸭子,那么这只鸟就可以被称为鸭子
# 一个对象实现什么样的方法,则它就拥有什么样的类型和操作
# 一个对象只要实现了相关类型的魔法函数,那么就可以使用这个类型对应的方法操作这个对象
# 一个对象拥有一个已实现的魔法函数,那么这个对象就可以被这个魔法函数对应的操作正确使用
# 鸭子类型的本质:面向协议编程,一个类实现了对应协议的魔法函数,则可以使用这个类实现的协议操作来操作这个类.
# 即python本质是面向协议编程
# 多态:实现相同函数的不同对象,都可以使用相同的函数或操作去访问,将... |
6333cdb7c1c8c009233cbe2f1eb9e3c0a790e02f | Nishinomiya0foa/Old-Boys | /2_Threading_MySql_html/day39_Pool/07_CallBack.py | 457 | 3.53125 | 4 | """回调函数
---- 把一个函数的返回值作为参数,执行另一个函数(在主进程执行)"""
import os
from multiprocessing import Pool
def func1(n):
print('In func1 ', os.getpid())
return n**2
def func2(n):
print('In func2 ', os.getpid())
print(n)
if __name__ == '__main__':
print('主进程:', os.getpid())
p = Pool(5)
p.apply_asy... |
132381ce00557f229f7291fe5ff4fec741edd751 | DenysLins/code-interview | /leetcode/70-climbing-stairs/solution.py | 340 | 3.8125 | 4 | # https://leetcode.com/problems/climbing-stairs/
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 1, 2
if n < 2:
return n
else:
for i in range(3, n + 1):
a, b = b, a + b
return b
if __name__ == "__main__":
print(Solution... |
a698479abe43cba6b063e565a07d7b69806f32f0 | hammerdrucken65/t1 | /dice.py | 1,894 | 4.15625 | 4 | import random
# getnum print "prompt" to screen", takes input from user, and converts that input
# to an integer. If the user input cannot be converted to integer, the program
# informs the user and tells them to start again.
def getnum(prompt, min, max): # prompt = question statement to print to screen, min is the ... |
8076ca925bdf1a4951cc4d8d89dd05f74b91e703 | rubykumar1/python-creations | /palindrome_check.py | 477 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 2 08:24:28 2017
@author: Ruby Kumar
EXERCISE:Ask the user for a string and
print out whether this string is a
palindrome or not. (A palindrome is a
string that reads the same forwards and
backwards.)
"""
number = input("Enter a number: ")
num_list = [int(digit) for... |
78d182a6a372d1f795b3c2eeb9d42951597bb7b7 | brotchie/brotchie-euler | /py/p30.py | 164 | 3.640625 | 4 | def isdigpow(x, p):
return x == sum(int(k)**p for k in str(x))
pows = []
for i in range(2, 2e5):
if isdigpow(i, 5):
pows.append(i)
print sum(pows)
|
aba6a94254c8a8b42d4646b5c7ba94b833bcd5b9 | vip7265/ProgrammingStudy | /leetcode/problems/sjw_sqrtx.py | 669 | 3.625 | 4 | """
Problem URL: https://leetcode.com/problems/sqrtx/
"""
class Solution:
def mySqrt(self, x: int) -> int:
# return self.naiveSolution(x) # 2020ms, O(sqrt(n))
return self.binarySearchSolution(x) # 40ms, O(logn)
def naiveSolution(self, x):
base = 0
while base*base <= x:
... |
802fcdfa9702f243421523081a3d0c1df4ad3ccb | jennifer-ryan/pands-problem-set | /7_square_root.py | 861 | 4.28125 | 4 | # Problem: Write a program that that takes a positive floating point number as input and outputs an approximation of its square root.
# Import square root function from math module.
from math import sqrt
# Import getFloat function from pcinput.py to ensure input is a positive floating point number.
from pcinput impo... |
897ed86105ae5b026b98a1fdb7c93cf7df15f3cd | Scottycags/csc201_fp_s2016_Scott_Cagnard | /election_Scott_Cagnard.py | 17,652 | 4 | 4 | # Name: Scott Cagnard
# Homework 5: Election prediction
import csv
import os
import time
def read_csv(path):
"""Reads the CSV file at path, and returns a list of rows from the file.
Parameters:
path: path to a CSV file.
Returns:
list of dictionaries: Each dictionary maps t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.