blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d35819db69a7309997458e33c4a2037057bb28f4
lennox-davidlevy/flask_api_course
/02_string_formatting/code.py
320
3.75
4
# f string name = "Bob" greeting = f"hello, {name}" print(greeting) # with .format() name = "David" greeting = "Hello, {}" with_name = greeting.format(name) print(with_name) #with .format() longer template longer_phrase = "Hello, {}. Today is {}" formatted = longer_phrase.format("David", "Friday") print(formatted)
0dcef73336dd40adf1847a6c2a2c0ab247ae58d3
AFatWolf/cs_exercise
/Mid-term preparation/Q7.py
178
3.65625
4
def summer_percentage(temp): cnt = [x for x in temp if x >= 30] return len(cnt)/len(temp) * 100 temp = [29,28,27,27,31,32,33,28,27,33] print(summer_percentage(temp), "%")
81d6efffca743fb97d865749bf3cdebedafb63ce
matinJ/PycharmProjects
/test_1/classpython.py
824
3.765625
4
__author__ = 'Jian' class school: def __init__(self,name,age): self.name = name self.age = age print '(initialized schoolmember:%s)' %self.name def tell(self): print 'Name:"%s" Age:"%s"' %(self.name,self.age), class teacher(school): def __init__(self,name,age,salary): ...
a4a5b31862c7c169c8d50dbdd996e908ebee310b
dzhang32/codino
/codino/data/CodonDesign.py
1,339
3.65625
4
from codino.data import FreqTable class CodonDesign: def __init__(self) -> None: """CodonDesign class for storing codon designs. Stores the frequency of each nucleotide (A/T/C/G) at each position (1/2/3) of a codon. Frequencies are stored in FreqTables. """ self.first = Fr...
559c69a6ec44ab8201ceffe371177b2b9822d08a
andreinaoliveira/Exercicios-Python
/Exercicios/004 - Dissecando uma Variável.py
689
4.25
4
# Exercício Python 004 - Dissecando uma Variável # Faça um programa que leia algo pelo teclado # e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele. frase = str(input("Digite algo: ")) print("O tipo primitivo desse valor é {}".format(type(frase))) print("Só tem espaços? {}"....
627faa3b72b035674d1dd88f937ee7338b84e848
alan199912/Pyhton
/Ejercicios 1/02-longitud.py
251
3.75
4
# Definir una función que calcule la longitud de cadena dada. def longitud(cadena): i = 0 for string in cadena: i += 1 print("la longitud es de: ",i) frase = input("ingrese algo ") longitud(frase)
a6bbf0bd1720255d67a607cb9a4d33968b03a302
mayanbhadage/LeetCode
/79.WordSearch/word_search.py
1,427
3.609375
4
class TrieNode: def __init__(self): self.isWord = False self.childrens= {} class Solution: def exist(self, board: List[List[str]], word: str) -> bool: directions = [(-1,0), (1,0), (0,-1), (0,1)] rows, cols = len(board), len(board[0]) result = [] self.found...
34d3a959c1b4fd7de09a27802da44e9f445c827e
vasiliana/patrec-labs
/lab1/lib.py
4,189
3.640625
4
from sklearn.base import BaseEstimator, ClassifierMixin def show_sample(X, index): '''Takes a dataset (e.g. X_train) and imshows the digit at the corresponding index Args: X (np.ndarray): Digits data (nsamples x nfeatures) index (int): index of digit to show ''' raise NotImplementedError def plot_digits_s...
8192924725c3bb164b4d40317c628f7ce77a266f
baolinliu/Programming
/code practice/sorting_names.py
568
4.375
4
# Write a function that takes in a list of names, and returns a list # # where the names are # sorted in alphabetical order of last name # Example: # Input: ['Baolin Liu', 'Barack Obama', 'Ada Lovelace', 'Alan Turing'] # Output: ['Baolin Liu', 'Ada Lovelace', 'Barack Obama', 'Alan Turing'] def sort_by_last_name(lst)...
5395f20b125efe21ad8c5c7d322577f9696fd3f0
ckFeatHers/CIS-HW-Platform
/CharlotteLab5.py
3,110
4.15625
4
#Program 5 PYTHON Charlotte Feathers #due 17 April 18 def main(): choice = 1 words1 = open_words_one() words2 = open_words_two() #open with title and menu print('*********** Python Program 5 *******************') while choice != 6: menu() choice = int(input(...
7f31d80f256cf10482f80230c7f00898f8b4ea9a
jiaoqiyuan/Tests
/Python/gui/gui.py
519
3.5625
4
from tkinter import * window = Tk() window.title("Welcome to LikeGeeks app") #lbl = Label(window, text="Hello", font=("Arial Bold", 50)) lbl = Label(window, text="Hello") lbl.grid(column=0, row=0) window.geometry('350x200') txt = Entry(window, width=10, state='disabled') txt.grid(column=2, row=0) txt.focus() def cl...
302e9e980fd18b9b65623abcb9178a1cbd5f962f
taeheechoi/data-structure-algorithms-python
/20-80-questions/primes.py
274
3.796875
4
def primes(number): primes = [] for num in range(number+1): if num > 1: for i in range(2, num): if num % i == 0: break else: primes.append(num) return primes print(primes(1000))
bb6acfc2a6b276a310b8c11423ca9c4a46c005c6
supermitch/Advent-of-Code
/2017/09/nine.py
1,075
3.828125
4
def main(): with open('input.txt', 'r') as f: data = f.read().strip() garbage_stack = 0 group_stack = 0 ignore = False group_count = 0 garbage_count = 0 for c in data: if ignore: ignore = False continue # Skip this char if garbage_stack: ...
256d8fa520189600f06377d00d23120f154f6fdc
thibault883/5WWIPython
/06-condities/risk.py
1,391
3.703125
4
#invoer aanv_1 = int(input('geef het aantal ogen van de dobbelsteen: ')) aanv_2 = int(input('geef het aantal ogen van de dobbelsteen: ')) aanv_3 = int(input('geef het aantal ogen van de dobbelsteen: ')) verd_1 = int(input('geef het aantal ogen van de dobbelsteen: ')) verd_2 = int(input('geef het aantal ogen van de dobb...
b1486df657826c94c9db3dbf3635e21939026d3a
DavidWild02/Nand2Tetris
/07/VirtualMachine_OnlyStackArithmetic.py
6,839
3.546875
4
import sys C_ARITHMETIC = "C_ARITHMETIC" C_PUSH = "C_PUSH" C_POP = "C_POP" C_LABEL = "C_LABEL" C_GOTO = "C_GOTO" C_IF = "C_IF" C_FUNCTION = "C_FUNCTION" C_RETURN = "C_RETURN" C_CALL = "C_CALL" class Parser: def __init__(self, inputFile): ...
7f3be1a741ae5df7c3a2e169f43382e96a40430c
claiton582/telaCadastro
/Cliente.py
2,637
3.5625
4
from Banco import Banco class Cliente(object): def __init__(self, idusuario=0, nome="", telefone="", email="", endereco="", numero=""): self.info = {} self.idusuario = idusuario self.nome = nome self.telefone = telefone self.email = email ...
8006db68b66a9c33df28f10ae9f654a14e0e7090
jyothi1jyo/python_programs
/Equi_energy.py
546
4.03125
4
SPEED_OF_LIGHT = 299792458 print("One of the exciting human discoveries is that mass and energy are interchangable and are related by the equation E = m × C^2. \n" "This relationship was uncovered by Albert Einstein almost 100 years ago.\n" "We now know that the sun produces its heat by transforming smal...
556229a486cbcd6b06966402b906229978efdb83
bazoon/algo
/puzzles/red.py
749
3.625
4
import math def encode(s): chars = filter(lambda e: e != " ", list(s)) l = len(chars) sq = math.sqrt(l) n_columns = int(math.ceil(sq)) parts = [chars[i:i+n_columns] for i in range(0, l, n_columns)] result = "" for x in xrange(len(parts[0])): for z in xrange(len(parts)): pl = len(parts[z]) if x < p...
fd4ae849403d4ea343af820b0a7f20ccc14c778d
Lordzyblaze/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/model_state.py
465
3.5625
4
#!/usr/bin/python3 """Write a python file that contains the class definition of a State and an instance Base = declarative_base()""" from sqlalchemy import Integer, String, Column from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class State(Base): """class State""" __tabl...
10115240419c0bd98b7143297da9a7e5ffce4d71
emeps/university-repos
/programming-one/eleicao-condominio/mEP7.py
2,756
3.53125
4
def quantidadeCandidatos(candidatos = []): # Quantidade de Candidatos qtdCandidatos = int(input()) candidatos += [qtdCandidatos] return qtdCandidatos, candidatos def cadastroCandidato(qtdCandidatos, candidatos): if qtdCandidatos < 1 : return candidatos else: #Nomes do Candidatos...
8e4f53a8988b36551a39303ef72496e256492cde
zonezoen/leetcode
/leetcode/lc102.py
756
3.859375
4
# Definition for a binary tree node. from typing import List # https://leetcode-cn.com/problems/binary-tree-level-order-traversal/ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrder(self, ...
8b10a40c146247d2f9686eefed6e9b9d87557fc8
leonardo221097/alvarezleonardo_ejercicio32
/ejercicio32.py
657
3.515625
4
import numpy as np import matplotlib.pyplot as plt datos = np.loadtxt("ejercicio32.dat") s=np.shape(datos) print(s) plt.figure(figsize=(20,8)) plt.subplot(2,3,1) plt.imshow(datos, aspect=0.1) #para realizar las otras dos graficas me guié de la solucion del ejercicio 29 dada por el profesor. plt.subplot(2,3,2) numx=1...
291aa3680fc3f3a07b6ffbf132b0dcab6b71aaeb
RaspiKidd/PythonByExample
/Challenge35.py
192
4.40625
4
# Python By Example Book # Challenge 035 - Ask the user to enter their name and then display their name three times. name = input("What is your name? ") for i in range (0,3): print(name)
dd5b0d64a97cf270679d14492cca81ad68f3e34b
darthkenobi5319/Python-Lab-15
/3.RockPaperScissors.py
1,153
3.671875
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 9 11:10:42 2017 @author: ZHENGHAN ZHANG """ import random #the RPS function from Lab 11 def rps(h1,h2): choices = ['Rock','Paper','Scissors'] assert(h1 in choices) assert(h2 in choices) assignment = {} for i in range(len(choices)): c = choices...
91b69296ae6d8da5efff3bf1bf2bcd8f3008d490
lakivisi-zz/lolo_bootcamp
/binarysearch.py
924
3.765625
4
def binarySearch(alist, item): first = 0 last = len(alist)-1 found = False while first<=last and not found: midpoint = (first + last)//2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: last = midpoint-1 else: first = midpoint+1 return f...
ac79dee2be7b148ac62cf4ad0777f0cb4a36475d
banditelol/PyTestforDataScience_PyDataLA
/05_Test_Adder_Activity/solved/test_add.py
201
3.65625
4
import adder def test_adder_case_1(): """ Test adding 2 and 3""" number = adder.add(2,3) assert number == 5 def test_adder_case_2(): number = adder.add(2,-3) assert number == -1
7c646d66a571fd7d46db178b70bc67122ac5fa41
Lancher/coding-challenge
/algorithms-well-known/_selection_sort.py
347
3.890625
4
# 1. select minimum and swap with 0 and so on # # 2. time complexity is O(n^2), swapping is O(n) # # # --END -- def selection_sort(nums): for i in range(len(nums)): min_i = i for j in range(i + 1, len(nums)): if nums[j] < nums[min_i]: min_i = j nums[i], nums[min...
550b552e13c850ffa1757f78071a03658513b698
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/beer-song/88d245f46251476a81dad747b55a67b8.py
1,089
3.609375
4
FIRST = ' bottles of beer on the wall, ' SECOND = ' bottles of beer.\n' THIRD = 'Take one down and pass it around, ' FOURTH = 'Go to the store and buy some more, ' def song(big,small=0): str = '' for i in range(big,small-1,-1): str += verse(i)+'\n' return str def verse(amount): if amount...
6ca004eac54e70ad0ffdd8ed5f3dac80b5169478
kenhuang630104/function
/is_leap.py
331
3.984375
4
def is_leap(year): if year % 4 != 0: return False elif year % 4 == 0 and year % 100 != 0: return True elif year % 100 == 0 and year % 400 != 0: return False elif year % 400 == 0 and year % 3200 != 0: return True print(is_leap(2008)) print(is_leap(2018)) print(is_...
61ee21439317b8ce9cb05e15a85ee8e12b1c8735
Kcheung42/Hacker_Rank
/Data_Structures/Linked_List/Reverse_LinkedList.py
551
4.28125
4
""" Reverse a linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def ReverseUtil(head, cur, prev): i...
ece77760e9082382b699438f04a25d0d114d8645
archimedessena/classes
/clsstrm.py
689
4.1875
4
def what_day_is_today(day): if day.weekday() == 5 or day.weekday() == 6: return "is true" return "is not true" import datetime today = datetime.date(2020, 1, 6) print(what_day_is_today(today)) class Product: budget = 1.02 discount = 0.01 def __init__(self, order, time, locatio...
54465a328e83ff8ae4b3f8c552691222145268f3
SeaEagleI/Python
/Web/CrawlMasPic/CrawlPic.py
1,759
3.59375
4
#[Standard Tool] #The programme is to Crawl Pics from a designated website with a url of \ #"url" and save them to a certain existed local dir with the path of \ #"dir_path" #coding:utf-8 import requests import re import os.path as op url = 'http://www.ixiumei.com/a/20180702/296918.shtml' dir_path = '/home/andrew/D...
2a0ec389fed24f8f22cb48567a11113a13bc5184
AdamZhouSE/pythonHomework
/Code/CodeRecords/2718/60793/293176.py
521
3.796875
4
""" s = input() ls = eval(input()) swap_pairs = [ls[0]] ls = ls[1:] for x in ls: a = x[0] b = x[1] for y in swap_pairs: if a in y: if b not in y: y.append(b) elif b in y: if a not in y: y.append(a) else: swap_pairs.a...
8aaee33a5507326cfeda9f6b8700fb2c52d07bb5
rrixon/fizzbuzz
/Original.py
371
3.953125
4
string = "" number = int(input("Choose a number: ")) for x in range(1, (number + 1)): if x % 3 == 0: string = string + "Fizz " if x % 5 == 0: string = string + "Buzz " if x % 7 == 0: string = string + "Quack " if x % 3 != 0 and x % 5 != 0 and x % 7 != 0: string = string ...
a44bccced3e711f1e5e0fd62661b2fc00dfce837
sonicfigo/tt-sklearn
/sk4-example/e1/s1_cross_validated_pred.py
953
3.59375
4
# coding=utf-8 """ scatter 画出 target 和 cross_val_predict 做出的predict 的对应关系 有没有趋向那条 plot出来的 线性函数? """ from sklearn import datasets from sklearn.model_selection import cross_val_predict from sklearn import linear_model import matplotlib.pyplot as plt boston = datasets.load_boston() X = boston.data y = boston.target # ...
859d8ca31f2dd59e5f86addfe625a0fe059c7d26
Shea6031/python_daily
/function_timer.py
602
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 9 11:12:50 2018 @author: xj2sgh """ import time from functools import wraps def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = time.time() result = function(*args, **kwargs) t1 = tim...
59f3c5bdab4738ce078077244505e00f3b2bcaa6
ArturButkiewicz/Course-Exercises-Class-
/pythonExercisesClass/rocket.py
1,214
4.09375
4
from random import randint from math import sqrt class Rocket: def __init__(self, speed: float = 1, altitude: float = 0, x: float = 0): self.altitude = altitude self.speed = speed self.x = 0 def move_up(self): self.altitude += self.speed def __str__(self): retur...
9b55c2c5bbc8f431e3c3d2f534b14a8c056b4dd0
noecaserez/Ejercicio-Python
/ejercicios3/ejercicio1_solucion.py
377
3.78125
4
""" Ejercicio 1: Crear una función que, a partir de un dato de entrada que sea en horas, nos informe cuántos minutos y cuántos segundos serían esas horas. Imprimir por pantalla dichos valores. """ # Solución def min_seg(horas): minutos = horas * 60 seg = horas * 3600 print(f"{horas} horas son {minutos} mi...
c9305dfa6b53964b3e4fbc5f5add53a141baf161
adrian-gell24/CS151
/Project1/Project1 Extensions/RepeatImageExtension3.py
1,032
3.765625
4
# imports from turtle import * # set up code # shape definitions def diamond(start , distance): left(start) forward(distance) left(60) forward(distance) left(120) forward(distance) left(60) forward(distance) def trapezoid(start1 , distance1 , distance2): left(start1) forward(distance1) left(120) forward...
259e02bfc8bc78fd8c1acca6f49326cad289914a
RakaPKS/StructuresAlgorithmsAndConcepts
/exercises/Arrays and Strings/rotateMatrix.py
136
3.921875
4
# Rotate a matrix 90 degrees def rotate(matrix): return list(zip(*matrix[::-1])) matrix = [[1, 2], [3, 4]] print(rotate(matrix))
e4495c16f7e2c2aa621fbb774bef45154b4c2f4d
tasos5819/Machine-Learning-Regression-Algorithms
/simplelinearregression.py
1,279
4.03125
4
from sklearn.model_selection import train_test_split import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression #datapreprocessing dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1] y = dataset.iloc[:,-1] #train test split X_train, X_test, y_tr...
1345a55a79a3c655f98786f58ee490a95f15db27
BigDataRoad/Algorithm
/src/main/com/libin/yfl/35.py
1,113
4.03125
4
# coding:utf-8 ''' 1221. 分割平衡字符串 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。 返回可以通过分割得到的平衡字符串的最大数量。 示例 1: 输入:s = "RLRRLLRLRL" 输出:4 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。 示例 2: 输入:s = "RLLLLRRRLR" 输出:3 解释:s 可以分割为 "RL", "LLLRRR", "LR", 每个子字符串中都包含相同数量的 'L' 和 'R'。 示例 3: 输入:s =...
871efab23bdb595a6d782bc77da471e4d51dc6f8
PriyankaDeshpande9/PythonML
/Python_ASG_3.5.py
1,110
4.15625
4
'''5.Write a program which accept N numbers from user and store it into List. Return addition of all prime numbers from that List. Main python file accepts N numbers from user and pass each number to ChkPrime() function which is part of our user defined module named as MarvellousNum. Name of the function from main pyth...
0bc3ef01e3ffadd97cdec552805b9ec597ae08c0
sebachandiadiaz/Capstone_UAI
/Capstone_Project_UAI.py
3,219
3.765625
4
#%% md quite el cambio # Actividad k-means (color quantization) #Una de los usos de k-means es color quantization. Para ello se necesita realizar los siguientes pasos #1. Cargar una imagen a su gusto (ojalá que no sea una imagen muy grande) #2. Transformar el set de datos a una matriz de nx3 #3. Aplicar k-means...
d2de08122ea15e8d610ab9cc67d8c5dfb8e85be4
xiaochenai/leetCode
/Python/Best Time to Buy and Sell Stock.py
597
3.640625
4
# Say you have an array for which the ith element is the price of a given stock on day i. # If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. class Solution: # @param prices, a list of integer # @return...
040efcef64e8102ffc064e3668fe07cf5fe91b38
wbratz/CITC-1301
/module4/bratz_william_assign4.py
988
4.03125
4
print("Enter a number 0 - 36") user_entry = int(input()) if user_entry >= 0 and user_entry <= 36: if user_entry == 0: print("The monster color is: purple") elif user_entry >= 1 and user_entry <= 10: if (user_entry % 2) == 0: print("The monster color is: black") else: ...
356f1e47afcbcf6430641a28e467622f5d8cf1c6
rizasif/kth-dd2421-assignment1
/python/ass2.py
803
3.734375
4
import math def entropy(dataset): "Calculate the entropy of a dataset" "Assuming the values are 0-4" n = len(dataset) s0 = dataset.count(0) s1 = dataset.count(1) s2 = dataset.count(2) s3 = dataset.count(3) s4 = dataset.count(4) p0 = float(s0)/float(n) p1 = float(s1)/float(n) ...
81a2dccad737bc89a95fddfae336e612e1d04c9b
SOUFIANE-AIT-TALEB/Python-Discovery
/partie2.py
1,194
3.78125
4
# exo1: vraie ou faux ? un="" deux="février" if len(un)==0: print(False) else: print(True) if len(deux)==0: print(False) else: print(True) # exo2: Calculer mon âge année_en_cours = int(input("Saisissez l'année actuel ? ")) année_de_naissance = int(input("Saisissez votre année de naissance ? ")) Vous_ê...
b9c2d106c68f49a2892ac9dcb4cf001f307d6582
xizhang77/LeetCode
/Previous/200_Number_of_Islands.py
1,152
3.859375
4
''' Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Ex...
598b6182138df59ac8f2d1caa85f8dd57772c4fd
jasonpark3306/python
/.vscode/OOP/python.oop.py
2,379
3.71875
4
class User : def log(self) : print("Users") class Teacher(User) : def log(self) : print("I'am a teacher!") class Customer(User) : def __init__(self, name, membership_type) : self.name = name self.membership_type = membership_type # print("customer created") def...
b5538596f5f4c27ed6c56cc8fa1ee8789ae63761
gschen/sctu-ds-2020
/1906101048-杨丽娟/day0303-作业.py/作业-1.py
381
3.984375
4
'''1、 创建Person类,属性有姓名、年龄、性别,创建方法personInfo, 打印这个人的信息''' class Person(object): def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def personInfo(self): print(("name:%s,age:%s,sex:%s")%(self.name,self.age,self.sex)) yang=Person("yang",18,"女") yang.personInfo(...
c11fc7a11738efcefbc9080177ac59c27a808921
ljmf00/PRACTICE-PYTHON
/7_List_Comprehensions.py
1,527
4.4375
4
""" Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. """ """ The idea of a list comprehension is to make code more compact to accomplish tasks involving li...
0097018fa6f3d799481ae86ce8602b377066407e
kayleighgalbraith/number_game
/number_game.py
745
3.703125
4
import random random.seed() games_played=0 while True: guesses=0 k=random.randint(1,100) #print(k) while True: x= input("Enter your guess: ") guesses=guesses+1 x=int(x) if x==k: print("YAY! it took you", guesses, "guesses") break ...
1f0094cf86be94d03edde800904421bba71cc288
mspontes360/Programacao-Python-Geek-University
/section4/exercicio27.py
341
4
4
""" Leia um valor de área em hectares e apresente-o convertido em metros quadrados. A fórmula de conversão é M = H * 10000, sendo M área em metros quadrados e A a área em acres. """ hectares = float(input("Enter an area value in hectares: ")) square_meters = hectares * 10000 print(f'The area is square meters is: {s...
bfadc07a034d305eb6140c382124957d906a77b2
malay190/Assignment_Solutions
/assignmrnt7/ass7_5.py
289
4.15625
4
#Q.5- Write a function to find factorial of a number but also store the factorials calculated in a dictionary def fact(x): if x==1 or x==0: return 1 else: f=x*fact(x-1) return f d={} for x in range(5): num=int(input("enter any number:")) a=fact(num) d[num]=a print(d)
5f5d5c51947fc721b279ddfa4e3f6a28b71b6ffa
jgeiser47/Aircraft_Dynamics_Simulation
/sim_math.py
1,383
3.65625
4
#################################################################################################### # Description: Various math functions used throughout simulation # Author(s): Joshua Geiser # Last Modified: 12/2018 import numpy as np import csv # Integrate a variable with respect to time assuming linear correlat...
a847f3f4f843c900ad3380e37533c0fe01f8a00e
DayGitH/Python-Challenges
/DailyProgrammer/20120403C.py
3,007
3.765625
4
""" The objective of this exercise is to maintain a list of Strings in memory that support undo and redo. Write a program that allows the user to add, edit, delete, undo, and redo entries in a list. You must be able to undo and redo everything you've done during the execution of this program. After each command is run,...
9fd9726373941f70f3ec0cfe3efd1a545644e7cc
jwf-ai/datastructure
/Sort/ShellSort.py
420
3.90625
4
# encoding: utf-8 def shell_sort(arr): d = len(arr) while d > 0: d = d // 2 for x in range(d): for i in range(x+d,len(arr),d): temp = arr[i] j = i while j > 0 and temp < arr[j-d]: arr[j] = arr[j-d] ...
9458b3c95ec624aeb42e9b8203c76f6a95036b70
Huxhh/LeetCodePy
/51-100/070ClimbStairsEasy.py
1,205
3.6875
4
# coding=utf-8 """ 思路: 方法一:暴力递归,会超时 方法二:在递归时发现会造成大量的重复计算,例如计算10时会计算9 8,计算9时会计算8 7,因此采用记忆搜索,在计算的同时使用数组保存每个 中间过程的值存储下来,可以提高效率 方法三:动态规划,动态方程为mem[i] = mem[i - 1] + mem[i - 2] 时间复杂度 O(n) 空间复杂度 O(n) """ def climbStairs(n): def getClimbStairs(x): if x == 1: return 1 if x == 2: ...
b9f92ee53bbfc6204897ace3436f7b98539c7567
harris44/PythonMaterial
/00_Basic/02_Basics/02_String_Opertaions/02_StringOperations.py
4,366
4.46875
4
#!/usr/bin/python """ Purpose: Demonstration of String Operations """ language = 'Python Programming' print 'language = ', language print 'type(language) = ', type(language) junkData = '$%^%^&^* &^\'*&^ * uhk' print 'junkData = ', junkData print 'type(junkData) = ', type(junkData) print print 'STRING OPER...
272cd341668f9fa1e6436154756865cf2fdf5741
perxpective/Text-to-Ascii
/main.py
1,188
3.671875
4
# __ __ __ #/ /_/ /_ ____ _____ / /_______ #/ __/ __ \/ __ `/ __ \/ //_/ ___/ #/ /_/ / / / /_/ / / / / ,< (__ ) #\__/_/ /_/\__,_/_/ /_/_/|_/____/ import pyfiglet word = input("What word do you want transformed to ASCII: ") mresult = pyfiglet.figlet_format(word) def fun(): font = input...
3860ddf9f4dcfcb1045bb890f353ae83455dc9ee
Trent-Dell/Refresh
/Set3/numsToText.py
420
3.859375
4
#!/usr/bin/env python3 # AUTHOR: Trent Brunson # COURSE: ANLY 615 # PROGRAM: Letter e counter # PURPOSE: Count the letter e in a string. # INPUT: user string of characters # PROCESS: treat the input string as a list of characters # OUTPUT: number of e's in the input # HONOR CODE: On my honor,...
9808d2683eb4246e8f44788e61074bfceb84d650
PrashanthVangipurapu/Python-Programs
/square_root.py
86
3.734375
4
a=int(input()) print ('user input is',str(a)) print ('the square root is',str(a**0.5))
1ad1bc5bb4cc5ca231e9782f6de66232302d6fb1
Majed-Mouawad/Sudoku-Game
/SudokuSolver.py
3,233
4.25
4
# Code written by Majed Mouawad board = [ [0,2,0,0,0,0,0,0,0], [0,0,0,6,0,0,0,0,3], [0,7,4,0,8,0,0,0,0], [0,0,0,0,0,3,0,0,2], [0,8,0,0,4,0,0,1,0], [6,0,0,5,0,0,0,0,0], [0,0,0,0,1,0,7,8,0], [5,0,0,0,0,9,0,0,0], [0,0,0,0,0,0,0,4,0] ] def find_e...
b6df9db4fa0f00cf93dbcc052e7cc24e8ff30e97
SzymonEks/Kurs-Python2021-main
/#homeworks/dom8/Caesar_Cipher.py
421
4.125
4
def encrypt(text, s): result = "" for i in range(len(text)): char = text[i] if (char.isupper()): result += chr((ord(char) + s - 65) % 26 + 65) else: result += chr((ord(char) + s - 97) % 26 + 97) return result text = input("podaj słowo do zaszyfrowania ") s ...
6aa48a1c396d22b5d74da744a91df66e55048dad
IldarBaydamshin/Coursera-Python-basic
/week_4/chislo-sochietanii.py
900
3.90625
4
""" По данным целым числам n и k (0≤k≤n) вычислите C из n по k. Решение оформите в виде функции C(n, k). Для решения используйте рекуррентное соотношение: C K|N = C K|N-1 + C K-1|N-1 см по ссылке https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/ QEiwQ/chislo-sochi...
a165fa6d8cf96d6a8eb7c53bd33c28e243a9e525
coldhair/Conda
/Try020.py
355
3.625
4
# return语句 def sum1(arg1, arg2): total1=arg1+arg2 print('函数内:',total1) return total1 # 调用sum函数 total1= sum1(20, 30) print('函数外:',total1) # return语句 def sum2(arg1, arg2): total2=arg1+arg2 print('函数内:',total2) return None # 调用sum函数 total2= sum2(20, 30) print('函数外:',total2)
6143fa2503f8c39149f918c356445350b94af6e9
ulikoehler/ProjectEuler
/Euler17.py
348
3.75
4
#!/usr/bin/env python3 from num2words import num2words def filterLetters(s): return filter(lambda c: c != " " and c != "-", s) def numLetters(n): return sum(1 for x in filterLetters(num2words(n))) if __name__ == "__main__": print(sum(numLetters(n) for n in range(1, 1001))) #for i in range(1, 1001): ...
62eefbdb161beeff7f4a0602008a7f6d214f235f
Meghashrestha/assignment-python
/2.py
386
4.3125
4
#Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the #empty string. def string(str1): if len(str1)>1: print(str1[0]+str1[1]+str1[-2]+str1[-1]) else: print("empty string") print(stri...
da73aeb52839e381d50838d2fcaf110dd3fa7966
henriquelima12/algoritmos-e-programacao
/estruturas de condição(if-else)/exercicio_5.py
321
3.90625
4
#Autor: Henrique Lima #Data: 25/03/2020 #Receber valor do produto e exibir valor da venda. valor_produto = float(input("Digite o valor do produto: ")) if valor_produto < 20.00: print(" O valor da venda é de R$: " ,(valor_produto * 1.45)) else: print(" O valor da venda é de R$: " ,(valor_produto * 1.30)) ...
89292d2418442c20d28c47d46ee07ce1ccb77f69
JenZhen/LC
/lc_ladder/company/two_sigma/Wildcard_Matching.py
1,982
3.796875
4
#! /usr/local/bin/python3 # https://www.lintcode.com/problem/wildcard-matching/description # Example # 判断两个可能包含通配符“?”和“*”的字符串是否匹配。匹配规则如下: # # '?' 可以匹配任何单个字符。 # '*' 可以匹配任意字符串(包括空字符串)。 # 两个串完全匹配才算匹配成功。 # # # 函数接口如下: # # bool isMatch(const char *s, const char *p) # # 样例 # 一些例子: # # isMatch("aa","a") → false # isMatch("aa...
c07aa460dfd65d54affa7363ee4ee43167ee33f6
ahmet-ari/ahmetari_swd
/password.py
730
4.0625
4
#!/usr/bin/python3 import random import string source = string.ascii_letters + string.digits question = input('How many digits is the password? ') default_result_str = ''.join((random.choice(source) for i in range(8))) def create_password(password_len): custom_result_str = ''.join((random.choice(source) for i ...
c1d18055497c3bee147f74461fba40712425b7f8
BitPunchZ/Leetcode-in-python-50-Algorithms-Coding-Interview-Questions
/Algorithms and data structures implementation/graphs/dfs/DfsRecursive/recursiveSolution.py
616
3.90625
4
from collections import defaultdict # This class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): self.graph = defaultdict(list) def setEdge(self, u, v): self.graph[u].append(v) print(self.graph) def DFS(self, ...
751cd7688e9f27d72f34421e279f0660e82ea37c
SlaviGigov/SoftUni
/02_Data_Types_and_Variables/04. Sum of Chars.py
120
3.84375
4
n = int(input()) total = 0 while n>0: x = input() total += ord(x) n -= 1 print(f"The sum equals: {total}")
4f79cf7073b9293c189fd9928f24118a556d7621
gohan8895/Survival-mode
/python_basics.py
9,579
3.625
4
#!/usr/bin/python3 import pygame # from math import sqrt import string import time # Waypoin 1: Say Greeting def hello(name): return "Hello " + ' '.join(name.strip().split()) + "!" # Test wp1 # name = input('what\'s your name? ') # print(hello(name)) # Waypoin 2: Pythagorean Theorem def calculate_hypotenuse(a, b...
0f18db3c2d8fafa6fb0a2c0fcc220b1d12cbc383
cmtm/numericalMethods
/A3/polyTest.py
228
3.515625
4
from Polynomial import Polynomial p1 = Polynomial([2.4,3.2,4.0]) p2 = Polynomial([0.0, 3.2, 1.1, 5.5, 2.0, 0.0]) print(p1) print(p2) p3 = p1 + p2 print(p3) p4 = p3 * p1 print(p4) p5 = p4.scale(1/51) print(p5)
c68ee45228c9f2ce1deaef392285a96ef1ab4633
carlos7ags/reversi_game_minimax
/othello/tile.py
578
3.546875
4
class Tile: """A tile""" def __init__(self, x, y, dimension, player): self.x_coord = (x*dimension) + (dimension/2) self.y_coord = (y*dimension) + (dimension/2) self.x = x self.y = y self.dimension = dimension self.player = player self.TILE_DIM = dimension...
9fa7f4389d75f75a79c1ecd47751d0d4c6c0ad0b
Martin2877/Dcrypt
/CaesarCipher.py
455
3.65625
4
# -*- coding: utf-8 -*- # Caesar cipher # 凯撒密码加解密 code = """I love you!""" sr1 = "abcdefghijklmnopqrstuvwxyz" sr2 = sr1.upper() sr = sr1 + sr1 + sr2 + sr2 st = code sResult = "" for rot in range(26): for j in st: if j == " ": sResult = sResult + " " continue i = sr.find(j)...
c8d40b67cf1934dd7639158ab5f50151a8efbce4
mechkro/TestGrounds
/test3.py
1,228
3.53125
4
import tkinter as tk class newwin3(object): """ """ def __init__(self, master): self.master = master self.emptycurrent() self.addnew() #-------------------------------------- def emptycurrent(self): """ """ for i in self.master.winfo_children(): ...
7aed3ba36660781c8c3fb5480412ba8264e98254
liyi0206/leetcode-python
/179 largest number.py
392
3.59375
4
class Solution(object): def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ nums = sorted([str(x) for x in nums], cmp = self.compare) res = ''.join(nums).lstrip('0') return res or '0' def compare(self, a, b): return [1, -1][a+...
b297e8020676cdfb23a211ad4614da46a43c554a
cookies5127/algorithm-learning
/leetcode/default/700_search_BST.py
1,220
4
4
from utils import build_binary_tree from utils.types import TreeNode ''' 700. Search in Binary Search Tree Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't ex...
2fe8e70aa31fda2e9287525cf70a35d400eefc85
niuyacong/python
/preview(高级).py
7,390
3.875
4
# 高级特性 # 切片 L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] print(L[0:3]);# ['Michael', 'Sarah', 'Tracy'] 从索引0取到索引3,不包括索引3,最后一个元素索引是-1 print(L[:3]);# ['Michael', 'Sarah', 'Tracy'] 不写起始索引,默认是0 print(L[-2]);# 取出索引为-2的元素 Bob print(L[-2:-1]);# ['Bob'] print(L[-3:-1]);# ['Tracy', 'Bob'] print(L[:]);# 原样复制['Michael', 'Sar...
292fc4691d482519592ad122ac26bd52f0c1b964
tecnology8/PythonBasics
/datatype.py
437
3.734375
4
print("Hello World") print('Hello world') print('''Hello world''') print("""Hello World""") print(type("Hello World")) print("Bye" + "World") #Numbers #integer print(30) #Float print(30.20) #Boolean True False #List [10,20,30,40,50,60] ['Hello', 'Bye', 'Good Morning'] #Tuples (10,2...
89875ff6233cc1a41070b81f3a323ecc501fc36c
daone92277/programming_exercises
/Week1/things_to_know.py
950
4.125
4
# Data types # strings #"hello" # "world" #'asdf' #ints, floats (decimals) #3,4, 3.5 , 21 , 423,4 (all consodered numbers) #print type(3) #print type(3.5) #booleans #true, false # Control Flow #lastName = "greene" #print "my first name is david " + lastName #myAge = 39 #print " ...
40633416be9b67ba03571279d29dfffa1773707d
bholanathyadav/PythonPractice
/PrimeNum.py
633
4.125
4
# To print all prime numbers occurring between two different numbers dt. 12th Feb 2019 # Also to check if a number is prime dt 12th Feb 2019 num = int(input("Enter a number: ")) x = 0 for i in range(1, num+1): if num%i == 0: x += 1 if x == 2: print("It's a prime number\n") else: print("It'...
3ed7f6fbf16b25010256e094e8eb1d080c856a6e
FailedChampion/CeV_Py_Ex
/ex011.py
512
3.859375
4
# Faça um programa que leia a largura e a altura de uma parede em metros, # calcule a sua área e a quantidade de tinta necessária para pintá-la, # sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. lar = float(input('Largura da parede: ')) alt = float(input('Altura da parede: ')) print('Sua pa...
7b4cf6b710dcf8ad5b18aa3f64bca5a0b7a483b9
maybeee18/HackerRank
/Python/String Split and Join.py
279
3.859375
4
""" Created on Tue Apr 10 14:17:17 2018 @author: Nodar.Okroshiashvili """ line = "This is a string" def split_and_join(line): line = line.split(" ") line = "-".join(line) return line line = input() result = split_and_join(line) print(result
ba6e1a3b717528125bd99bcd0d1c81eace3bd742
yoDon/electron-python
/python/calc.py
3,019
3.859375
4
""" A calculator based on https://en.wikipedia.org/wiki/Reverse_Polish_notation """ from __future__ import print_function def getPrec(c): if c in "+-": return 1 if c in "*/": return 2 if c in "^": return 3 return 0 def getAssoc(c): if c in "+-*/": return "LEFT" ...
c60c18702ee6f6f81625989fd82a818e528a3a82
ShiftingNova/Jordan-Walker
/prep4.py
194
3.875
4
feet = int(input("Number of feet:\n")) inch = feet*12 meter = round(feet*0.3048 , 3) rod=round(feet/16.5 , 1) print("\nInches: "+str(inch)) print("Meter: "+str(meter)) print("Rods: "+str(rod))
684b90410e247829c700c4d660df1eedb8aecdca
syedshameersarwar/maze_solving_pi
/factorial.py
317
4.28125
4
def recursion_fact(num): if num <= 1: return 1 else: return num*recursion_fact(num-1) num = int(input("The number please: ")) if num < 0: print("Sorry no negative numbers!") elif num == 0: print("this number is 0 !") else: print("The factorial of number is: ", recursion_fact(num))
a1e9236330c928f263515a8da4463ba478e15117
Fhernd/Python-CursoV2
/parte11/11.6_funciones_recursivas.py
1,790
4.34375
4
# Funciones recursivas: print('Funciones recursivas:') # n! # 5! = 1 * 2 * 3 * 4 * 5 = 120 def factorial_iterativo(n): """ Calcula el factorial de un número. (Enfoque iterativo.) Parameters: n: Número de factorial a calcular. Returns: Factorial """ resultado = 1 for i in range(1...
e813eaabf45f5e9a74ad7179bdfe83c1cbaf0301
IgorEM/RevisandoPython
/execoes.py
812
3.640625
4
lista = [0,1] arquivo = open('teste.txt','r') try: divisao = 10 / 1 #se der erro aqui ele nao executa nada que tá abaixo numero = lista[1] x = 1 # print('Fechando Arquivo') # arquivo.close() # except Exception as ex: # exception tree python # print('erro desconhecido. Erro: {}'.format...
8e239dfa061fbddeb49faf19cb7685ebd8ad6634
MahonriM/Listsubjects
/subjectlist.py
134
3.671875
4
lstmta=[] x=0 while x<5: materias=input('Inserta la [0]° materia').format(x) lstmta.append(materias) x=x+1 print(lstmta)
d7269179db70f361fab5274e99b68e216a7ec3dc
begsener/PythonCourse
/ex21.py
680
4.09375
4
#exercise 21 def add(a,b): print ("ADDING %d + %d" %(a,b)) return a + b def subtract(a,b): print ("SUBTRACTING %d - %d" %(a,b)) return a - b def divide(a,b): print ("DIVIDING %d / %d" %(a,b)) return a / b def multiply(a,b): print("MULTIPLYING %d and %d" %(a,b)) return a * b print ("Let'...
b7febc44cc70527d1b693c074ffeef5d4684b771
PriyankaBuchkul/PythonPractice
/exception/Age even or odd.py
637
3.984375
4
#age def age_getter(age): if age < 0: raise ValueError ('Only positive intergerd allowed') if age %2 == 0: print("Age is Even") else: print("Age is Odd") while True: n=int(input("Enter any age :")) if n=="d": break else: t...
5c9443fca0c54cce524a8f0fd4d91c1dc47fa377
SahilTara/ITI1120
/ASSIGNMENTS/Assignment 3/a3_300018569.py
11,072
4.09375
4
import random def shuffle_deck(deck): '''(list of str)->None Shuffles the given list of strings representing the playing deck ''' # YOUR CODE GOES HERE print("Shuffling the deck...") random.shuffle(deck) def create_board(size): '''int->list of str Precondition: size is even po...
55b2c59001d9214c68a7d730f90035b9aac8f07b
imanshgupta/pythoncodes
/constructors.py
194
3.8125
4
class Abc: def __init__(self,x,y): self.x=x self.y=y def add(self): print(self.x+self.y) ob=Abc(5,6) ob.add() class Cal(Abc): ob=Abc(5,5) ob.add()
a88f033115e0d6ba8354e21109c8cc7f08514cd6
Cheepsss/Jubilant-Jellyfish
/sprites.py
8,933
3.625
4
class Drawable: def __init__(self): self.parts = [] def draw(self): wholePart = "" for part in self.parts: wholePart+=part return wholePart class Player(Drawable): """ Every draw, create_body and delete function works the same. Draw functi...
74330f8dfb6d181eaf54a02fe284f2132a40fcb6
furkanoruc/furkanoruc.github.io
/Python Programming Practices - Daniel Lyang Book/ch5 copy/assignment_19_ch_5.py
495
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 05:04:33 2021 @author: furkanoruc """ #radius of earth import random import turtle import math number = eval(input("Enter a number between 1 to 15: ")) k = number for i in range (1, number+1): for j in range (1, k): print (end = "...
0cf6c40aa01d2767349f49ca7cafc011987ce63a
wattaihei/ProgrammingContest
/AtCoder/CPSCO2/probG.py
2,116
3.546875
4
class UnionFind(): # 作りたい要素数nで初期化 def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rnk = [0]*(n+1) # ノードxのrootノードを見つける def Find_Root(self, x): if(self.root[x] < 0): return x else: self.root[x] = self.Find_Root(self.root[x]) ...