blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c62a92a9e9d3ac9829db7c400dd9744b669ee1af
sangm1n/problem-solving
/LeetCode/reverse_string.py
731
4.125
4
""" author : Lee Sang Min github : https://github.com/sangm1n e-mail : dltkd96als@naver.com title : Reverse String description : Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input ar...
eb4c3a67fbf77f6bd651b5a51360de28c0137416
ericbollinger/AdventOfCode2020
/day10/second.py
1,061
3.71875
4
#with open("demo2.txt", "r") as f: with open("input.txt", "r") as f: lines = f.readlines() adapters = [int(l.strip()) for l in lines] adapters.sort() lo = adapters[0] hi = adapters[len(adapters)-1] # Add the outlet and your device to list adapters.insert(0, 0) adapters.append(hi+3) # Work backward to det...
01dc7da92797ddd9cd72b744c3fc0d67c5bc63db
sahiljajodia01/Competitive-Programming
/leet_code/kth_largest_element_in_an_array.py
708
3.625
4
# https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/800/ ###### Again a hashmap follwed with sorting that hashmap. Complexity: O(n) + O(klogk) where k is number of distinct elements ##### class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: ...
8bae3c27458e0fe4d6007ce206e001662439511d
the9sjeric/ProjectAioi
/Practice/No_10/10.3_error.py
852
3.953125
4
# try: # print(5/0) # except ZeroDivisionError: # print("You can't divide by zero!!!") # filename = "alice.txt" # try: # with open(filename) as f: # text = f.read() # except FileNotFoundError: # print(f'{filename} is not exist!') # title = "Alice in Wonderland" # print(title.split()) # chang...
20f298a836fb35e5d2e4097d2af1f0f1b934e73d
HopeCheung/leetcode
/leetcode-second_time/stack/leetcode71(Simplify Path).py
497
3.609375
4
class Solution: def simplifyPath(self, path: 'str') -> 'str': ans = path.split("/") i, stack = 0, [] while i < len(ans): if ans[i] == "" or ans[i] == ".": i = i + 1 elif ans[i] == "..": if len(stack) != 0: stack...
5cbc4abc2dfffb61ca36dde9ebfbd756e203102b
manusoler/code-challenges
/projecteuler/pe_10_summation_of_primes.py
465
3.5625
4
from utils.decorators import timer from .pe_3_largest_prime_factor import prime_iter """ The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ def summation_of_primes_below(n): summation = 0 for p in prime_iter(): if p > n: break ...
493454fd6b6417be95cd9a85d62ff8915aa7417a
hutanugeorge/Data-Structures-Python
/LinkedList.py
3,016
4
4
class LinkedList: class node: def __init__(self, value = None): self.value = value self.next = None def __init__(self): self.head = None self.tail = self.head self.lenght = 0 def append(self, value): new_node = self.node(value) if n...
0d4bb9b3b2ceac7baab2929f12b42bf3ec6c374b
annazwiggelaar/LCPython_week3
/3.4.4.7.py
230
4.09375
4
length_a = int(input("What is the length of side a?")) length_b = int(input("What is the length of side b?")) c_squared = (length_a ** 2) + (length_b ** 2) c = c_squared ** 0.5 print("The length of the hypotenuse is", c)
24582fbdc6ca6e96c19134003e1b03aade82b4df
sourishjana/demopygit
/file_writing.py
263
4.1875
4
f=open('abc','w') f.write("i love to code") #now if we want to again write in the"abc" file then if we reuse f.write it will not work #then i love to code will be replaced by the new line #so we have to append the file #run the code to write #see at abc
acf50aebdbd10132f2dbcbf0ae47b4cc43b681f3
coparker/CST205Proj2
/A2.py
1,908
3.765625
4
""" work on making a function that will take a black image and put that into the GPU so that the graphics card can do the work to make it faster. also make the function input an image so that it doesnt have to be just a black image. """ import sys import sdl2 import sdl2.ext import time import Audio """ @Author: Na...
0cd1d37841af39413b84b369e8493180637e2dd4
devng/code-puzzles
/src/devng/adventofcode/day09/day09.py
1,573
4
4
#!/usr/bin/env python # Make the script compatible with python 3.x from __future__ import absolute_import, division, print_function, unicode_literals import re import itertools line_regex = re.compile(r"(\w+) to (\w+) = (\d+)") cities = set() distances = dict() def parse_line(line): m = line_regex.match(line)...
1aa83375bc92f392edf4b13218eb293fb6037337
thaynagome/teste_python_junior
/teste_1020.py
848
4.21875
4
#!/usr/bin/env python # -- coding: utf-8 -- #Solicita inserção de dias de idade do usuario dias = int(input("Digite sua idade em dias: ")) #Divide dias por 365 e no resultado obtém apenas a parte inteira da divisão anos = dias // 365 # Obtem o resto da operação e divide por 30 com objetivo de obter a parte inteira ...
ec1fe0b40f30b2da1f1b4f4626f72874497e478c
rafaellamgs/prog_comp2018.1
/exercicios19_09/L06Q3.py
210
4
4
valor = int(input('Informe um número para ver seu fatorial:')) fatorial = 1 for numero in range(valor, 0, -1): fatorial = numero * fatorial print('O fatorial de {0} é {1}.'.format(valor,fatorial))
293abe21fc42001f4d8d8e7f4f3856b9003c422d
daisyzz/First-Program
/HangMan 2.py
1,750
4.0625
4
import random import time commands = ['start', 'easy', 'quit'] words = ['pizza', 'lemon', 'orange'] def start(): print(""" HangMan by Owen Commands start - to get a word easy - play extra lives quit - exit the game""") if len(words) < 1: print("You tried all of our word's congrats!!!!!") prin...
c4caac9e5391b2b81451f070ce26f2dcdf2a3e0e
kartika14/data_incubator_April-2018
/day5.py
6,907
3.5625
4
# All the images are on a public dropbox folder that is going to self destruct in 7 days. # Use pythonanywhere's servers to host this folder, so the script can run on the cloud. # Why is it going to self-destruct in 10 days? For one, I wanted to see if I can do it. For 2, incase some # robot decides to download it over...
74eb59a548373ab473e032aa72b7c032b01a607d
cionx/programming-methods-in-scientific-computing-ws-17-18
/solutions/chapter_03/exercise_03_08.py
428
4
4
### (1) from trapeze import trapeze ### (2) from math import sin, pi n = 1 s = 0 while 2 - s >= 1.E-6: # sin is concave on [0,pi] -> estimate too small n += 1 # can skip n = 1 because it results in 0 s = trapeze(sin, 0, pi, n) print("Estimate for integral of sin from 0 to pi using trapeze:"...
3649a8a88995fc1f0aeac7d004c21f9ef6f8948f
c-a-c/PythonStudy
/master/2019June26Wed/list2.py
334
4.03125
4
int_str = [1,"2",3,"4",5,"6",7,"8",9,] # # Use Range Function # print("Use Range Function") # for i in range(len(int_str)): # print(int_str[i], type(int_str[i])) # print() # Get One Element print("Get One Element") for i in int_str: print(i, type(i)) print() # # Print List # print("Print List") # print(int_str, ty...
6ba3c9cd6d99269dcad040d14c5f5a3f3d491b38
PatrickCHennessey/Data_Visualization_Project
/app.py
3,918
3.578125
4
from flask import Flask, render_template, request, redirect, url_for import pymongo import json # create instance of Flask app app = Flask(__name__) # create route that renders index.html template @app.route("/") def index(): """Main/default path that serves index.html from the templates folder""" return re...
e238cf956d6ea59e80770b83fa92c781497b3dcb
AngryGrizzlyBear/PythonCrashCourseRedux
/Part 1/Ch.8 Functions/Passing an Arbitrary Number of Arguments/Try_it_yourself_5.py
2,078
4.34375
4
# 8-12. Sandwiches: Write a function that accepts a list of items a person wants # on a sandwich. The function should have one parameter that collects as many # items as the function call provides, and it should print a summary of the sandwich # that is being ordered. Call the function three times, using a different nu...
fec6c1430762e599a85f98344c9ba9b2eea56f76
ekjellman/interview_practice
/epi/5_2.py
959
3.953125
4
### # Problem ### # Swap two given bits in a given number. (Assume it's 64 bit) ### # Work ### # Questions: # Can we assume the numbers are positive, since it's Python? (Yes, we're # them as a bitvector) def swap_bits(num, a, b): a_value = num & (1 << a) b_value = num & (1 << b) if a_value == b_value: return...
230b56d6d2a771ed45a5c0b2835b88c5a65c0756
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s06_layout/s062_grid/tk_6_grid.py
481
4.28125
4
""" Tkinter rewrite last program using grid layout relative position ref: #2 """ from tkinter import * root = Tk() # create a label widget label1 = Label(root, text='Athensoft').grid(row=0, column=0) label2 = Label(root, text='Python Programming').grid(row=1, column=5) label3 = Label(root, text='III').grid(row...
efced363b92d2ca7c92212da7184bbf9f258b5f8
ruthiler/Python_Exercicios
/Desafio062.py
619
4.0625
4
# Desafio 062: Melhore o DESAFIO 061, perguntando para o usuário se ele # quer mostrar mais alguns termos. O programa encerrará quando ele disser # que quer mostrar 0 termos. print('-*-' *10) termo = int(input('Digite o primeiro termo: ')) razao = int(input('Digite a razao: ')) cont = 10 contador = 0 total = 0 while ...
08b6baae3cc698edb3d8e3ff992e31ada5f240c8
Sreekanthrshekar/Verified
/01_python_basics/class_oop.py
3,894
4.4375
4
#GEOMETRIC CLASSES ''' This document is all about creation of geometric classes ''' import math # Create a class named 'Cylinder' which takes in height and radius and # has the following methods: volume of the cylinder, surface area of the cylinder class Cylinder(): ''' This class takes in radius and height an...
a1ae7b89b29feda2b052ba87516cd20554a22ef1
Anz131/luminarpython
/Functions/var length args.py
1,552
3.640625
4
#variable length arguments #accept any no of args in same method #using * and return as tuple #** for key value pair amnd return as dictionary # def add(*args): # print(args) # add(10) # add(10,20) # add(10,20,30) # def add(*args): # res=0 # for num in args: # res+=num # return res # print(ad...
aa10f4bdc7ab3340ed500c1b87a4da8b522375ef
yrao104/2018-Summer-Python
/Unit3/ChangeTendered.py
1,526
4.15625
4
''' Yamuna Rao 6/25 Directions: Write an application that reads the purchase price and the amount paid. Display the change in dollars, quarters, dimes, nickels, and pennies. The input value has to be in decimal value (exclude the dollar sign). You are not allowed to use if statements or loops! Note: You may be off a p...
5c9a4ea1c4311bf6b24326beee02a8e40bce514a
DerekTeed/python-challenge
/PyBank/main.py
1,822
3.6875
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os import pandas as pd import numpy as np # Module for reading CSV files import csv df = pd.read_csv("excelBank.csv") print(df) something1 = df.sum(axis = 1) print(df['Profit/Losses']) profitChange = df['Prof...
561d45623fc3f1cae045c17dc8098ae678d2bf51
LucianErick/URI
/matematica/Area.py
374
3.8125
4
a, b, c = input().split(" ") a = float (a) b = float (b) c = float (c) pi=float (3.14159) aTriangulo=(a*c)/2 aCirculo=pi*(c*c) aTrapezio=((a+b)*c)/2 aQuadrado=b*b aRetangulo=a*b print("TRIANGULO: ""%.3f"%(aTriangulo)) print("CIRCULO: ""%.3f"%(aCirculo)) print("TRAPEZIO: ""%.3f"%(aTrapezio)) print("QUADRADO: ""%.3f"...
1733473895bfd9f927d1b50eb194e02ba115181f
Abhipsanayak92/Python--Support-Vector-Machine-SVM-
/Risk Analytics-SVM - Revised.py
5,382
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np # In[2]: #loading training and test data train_data=pd.read_csv(r'D:\DATA SCIENCE DOCS\Python docs\risk_analytics_train.csv',header=0) test_data=pd.read_csv(r'D:\DATA SCIENCE DOCS\Python docs\risk_analytics_test.csv', header=0)...
3570b65aefcb633ceac9492ade3684753136754b
andreboa-sorte/Python-aula-2
/ex2.py
699
3.9375
4
class Extenso(): def chama_extenso(self): num=int(input('digite um numero entre 1 a 5, para se tornar extenso: ')) if num==1: print("Um") elif num==2: print("Dois") elif num==3: print("Tres") elif num==4: print("Quatro") ...
2ca59c63aa5f64b6e36046013a714031423e4073
fagan2888/personal_learning
/coursera_interactive_python/03 Assignment.py
1,620
3.734375
4
""" Template for 'Stopwatch: The Game' """ import simplegui # define global variables t = 0 position_timer = [60, 100] position_score = [210, 30] width = 250 height = 200 x = 0 y = 0 # define helper function format that converts time split # into minutes, seconds and tenths of a second. # Formatted string in the fo...
14df96169cb902b42e309adc428e246b49e28a40
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/837.py
575
3.546875
4
def flip(pancake, start, size): for j in xrange(start, start + size): pancake[j] = 1 - pancake[j] def countflip(pancake, size): pancake = [(1 if p == "+" else 0) for p in pancake] N = len(pancake) - size flips = 0 for i in xrange(0, N + 1): if pancake[i] == 0: flip(panca...
4d29b62a0345545285ce369be3530de0481e61b4
JoaoPedroBarros/exercicios-antigos-de-python
/Exercícios/Exercícios Mundo 1/ex032.py
162
3.921875
4
a = int(input('Digite um número:')) if a%4 == 0 and a%400 == 0 or a%100 != 0: print('Esse é um ano bissexto.') else: print('Esse ano não é bissexto')
cbd5d31d33f171e19aea751ab40380f8b35fb058
lobzison/python-stuff
/PoC/fiftheen_puzzle.py
17,701
3.546875
4
""" Loyd's Fifteen puzzle - solver and visualizer Note that solved configuration has the blank (zero) tile in upper left Use the arrows key to swap this tile with its neighbors """ # import poc_fifteen_gui class Puzzle: """ Class representation for the Fifteen puzzle """ def __init__(self, puzzle_he...
6776d476626f4e22c46a3f88f690cd43afb5f4ba
MarceloFilipchuk/CS50-PSET6-Cash
/cash.py
1,143
4.3125
4
# Prints the minimum possible ammount of coins needed to give in change def main(): # Prompts the user for change try: change = float(input("Change owed:")) while change <= 0: change = float(input("Change owed:")) except ValueError as err1: print(err1) print("Inse...
2ae2cab47c90f804b8790a777de864eb00cff7e5
malvina-s/Daily-Python-Challenges
/Day 11_option2
426
3.796875
4
#!/python3 #Maximum integer import random as r list = [] for i in range(1,101): list.append(i) number = r.choice(list) counter = 0 print (number) for i in range(1,100): x = r.choice(list) if x>number: number = x counter += 1 print (x, ' <== Update') else: print (x) ...
914ac56e5ca7fe4b61b38bb64faa34b6802fa3f8
samyhkim/algorithms
/498 - diagonal traverse.py
856
4.21875
4
def find_diagonal_order(mat): if not mat: return diagonal_order = [] lookup = {} # Step 1: Numbers are grouped by the diagonals. # Numbers in same diagonal have same value of row+col for i in range(len(mat)): for j in range(len(mat[0])): if i + j in lookup: ...
60de6873ed44aced92b27254dcdec42512aceacc
nagask/leetcode-1
/30 Substring with Concatenation of All Words/sol.py
2,592
3.890625
4
""" String not empty, words can be repeated. Brute force: create all the permutations of the words array, and check if any of them is a substring. Use a sliding window and two data structure to support the algorithm: - a dictionary to count the appearances of each item of words - another dictionary to count the appear...
3467326f13cc02c121b7ecc9984002dff0ddbd05
KatherineSandys/Python
/Web Page Reloader/auto time.py
3,240
4.125
4
""" Program to auto fill in time sheets Ideas -Add Task Number to Questions -Add Project number to the Questions -Change order of questions. -Questions on a form instead of indiviual -Save the pervious answers to a file -load those pervious answers when starting program so you can just skip items with the cor...
4500116c792db03d0996c438cdfc745586619055
Divisekara/Python-Codes-First-sem
/PA2/PA2 2013/PA2-3/2013 - CA - 03 - Vowels/2013 - CA - 03 - Vowels.py
809
3.765625
4
#CA - def getText(): #To get text from input and check for any errors. try: fileOpen=open("FileIn.txt","r") words=fileOpen.read().plit() fileOpen.close() except IOError: print "File Error!" else: ...
31ac1276e9a1517e0e5a47300c2c77b66f03c315
janakimeena/Python_Code
/Ganesha_Papa.py
2,338
3.859375
4
import turtle screen = turtle.Screen() screen.setup(width=1.0, height=1.0) def move_To(x,y): turtle.penup() turtle.goto(x,y) turtle.pendown() turtle.speed(15) turtle.pensize(7) turtle.showturtle() turtle.bgcolor("black") # three lines turtle.pencolor("white") move_To(-36,200) turtle.forward(30) move_To(-36,190...
57b45bdd16157db291bf39ebfdb1f6ba52eb464b
SerhiiDemydov/HomeWork
/HW4/HW4_class.py
1,943
4.125
4
# 1. Create a Vehicle class with max_speed and mileage instance attributes class Venicle: def __init__(self, max_speed, mile): self.max_speed = max_speed self.mile = mile # 2. Create a child class Bus that will inherit all of the variables and methods of the Vehicle class and will have seating_capa...
90d6b6625832d09641bcb6f79063375e71d7275b
matey97/Programacion
/Boletín1/Ejercicio6.py
191
3.921875
4
''' Created on 1 de oct. de 2015 @author: al341802 ''' from math import sqrt a=float(input("Dame un número:")) raiz= sqrt(a) print("La raíz cuadrada del número es:{0:.3f}".format(raiz))
598f37dfae073811c1b0661ab036e591ca3a1954
wabscale/bigsql
/bigsql/Query.py
1,284
3.546875
4
from . import Sql class Query(object): session=None def __init__(self, table_name): self.table_name = table_name if isinstance(table_name, str) else table_name.__name__ def all(self): """ Return all models for table :return: """ return Sql.Sql.SELECTFROM(s...
6d73006fe0837bd02f31c1c052a805b911501374
MaxIsWell42/CS-1.2-Intro-Data-Structures
/Code/histogram.py
3,020
4.0625
4
from pprint import pprint import sys import random # histogram = {'one': 1, 'blue': 1, 'two': 1, 'fish': 4, 'red': 1} # Helped by github.com/ysawiris def stripWordPunctuation(word): return word.strip("&.,()<>\"}{'~?!;*:[]-+/&—\n ") def open_file(source_text): #open and read file f = open(source_tex...
d6ef25a312ed55fbcb8221c11b810de412441501
btv/project_euler
/problem_7/python/problem7_4.py
456
3.984375
4
#!/usr/bin/python3 import math def is_prime(divided): divisor = [3] sqrt_divided = int(math.sqrt(divided)) while divisor[0] <= sqrt_divided: if divided % divisor[0] == 0: return False divisor[0] += 2 return True if __name__ == "__main__": # using a list to store each int value data = [1,...
64273b94f1c92bd78849962e2ba04edea530cb20
elanorigby/LoveYouLikeXO
/board.py
1,500
3.734375
4
# just draw the board class Board: def __init__(self): self.wall = "+---+---+---+" self.cells = "| {a} | {b} | {c} |" self.rows = [ {'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}] def _part(self, row): ...
b45cec7d28e1e13ecf94d112343a56dbc9d2bc8e
creageng/lc2016
/59_Spiral_Matrix_II.py
1,229
3.8125
4
# Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. # For example, # Given n = 3, # You should return the following matrix: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] class Solution(object): def generateMatrix(self, n): """ :type n: int ...
63273ade42c6ec0eb2136ef1e366bf5de8faf251
prajwal60/ListQuestions
/learning/BasicQuestions/Qsn83.py
405
4.125
4
# Write a Python program to test whether all numbers of a list is greater than a certain number. sample = [4,5,6,7,8,9,10] mini = min(sample) n = int(input('Enter any number ')) if mini > n: print("All of them in list are greater") else: print('Some of them in list are smaller') #Another Approach sample2 =...
e92d5f4f575c0162194b5914c436ba1fc94f5eda
SkaTommy/Pythongeek
/Lesson3/example3.py
798
4.125
4
# 3. Реализовать функцию my_func(), # которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. #1.Принимает на ввод 3 позиционных аргумента #2.Сравнивает между собой находя 2 наибольшие #3.Возвращает сумму наибольших arg1 = int(input("Введите первый аргумент: ")) arg2 = int(input(...
965d1b9e658e9c34347c447afb8edaed1f6486a7
hammadhaleem/parser
/v3/TimeParser/classes/dayAndTime.py
2,044
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils import * class OpenTimesByDay(object): """Process the day. """ def __init__(self, day, lis): self.day = day self.times = lis self.day_vector = [day] def __str__(self): return self.day def __repr__(self): return "<"+Utils().listToString(s...
92862ae98c5d734a2677997a49b6d0a02f4e826a
fayyozbekk/Python-projects
/guessing_game/main.py
3,296
3.5
4
import csv from random import randint from os import path def update_leaderboard(attempts, user_name): if path.exists("leaderboard.csv"): leaderboard_data_list = [] new_sorted_leaders = [] with open("leaderboard.csv", "r") as leaderboard: leaderboard_data_list = [leader for le...
fb49c63e057ecc0a5f59f7bc9921f93cae05372b
bfish83/Python
/searchEngine.py
3,670
3.734375
4
# Barret Fisher # barret.fisher@uky.edu # CS115 Section 5 # 11-19-12 # Program 4: Search engine # Purpose: Search database file to find URL's that match user search, and output # results to webpage, and record data in secret file # Preconditions: Inputs from user(name, database, search, case setting, w...
0d1e57cfe85dc3a5710d1c340d3fc7fb89270e8f
abantikatonny/Statistics-Codes
/Assignment 1/Question number 3.py
2,557
3.6875
4
import numpy as np import pandas as pd import scipy.stats # import the data file data = pd.read_csv('C:/hmm/courses/3rd semester/Special topics/Assignment 1/data_master.csv', delimiter=',') # creating a database for US because it has the highest date_reported data States_database = data[data['Country'] == 'United Sta...
49cf4cc3e37c4c98c6eaddebfe10c0b568b73332
omuen/Muen-In-Python
/history/Test-Muen-20200123.py
472
3.84375
4
def check(): print(' *') print(' *') print('* *') print(' *') print('Happy New year') def MerryChristmas(): ##Happy## print(' *') print(' ***') print(' *****') print('*******') print(' *') MerryChristmas() print('_____________________________________________________...
45d8c01a543e57bc68ba185961653b22bdd8f10d
zhangye-bot/Python-W3school-100-problems
/Problem37.py
341
3.796875
4
print('请输入10个数字: ') i = 0 number_list = [] while i < 10: number = int(input("输入一个数字: ")) number_list.append(number) i = i + 1 for i in range(0,len(number_list)): print(number_list[i]) print('排列之后:') number_list.sort() for i in range(0,len(number_list)): print(number_list[i])
cafeca9055858a2bcdbc73e2cc12cb219864be6c
malaikaandrade/Python
/Basico/Clase2/entradas (1).py
461
3.9375
4
print("Suma de dos numero") num1 = input("Ingresa el primer número:") num2 = input("Ingresa el segundo número:") resul= num1 + num2 print(resul) #en esta parte los esta tratando como cadenas y solo las esta concatenando, para que los pueda realmente sumar se tiene que convertir el dato a un entero print("Suma de dos...
45b1bb87545ff3044e548b898ef8b8782576ac87
GlobalYZ/recruitmentDjango
/pythonBasis/lesson_02_Python入门/06.格式化字符串.py
1,290
4.09375
4
# 格式化字符串 a = 'hello' # 字符串之间也可以进行加法运算 # 如果将两个字符串进行相加,则会自动将两个字符串拼接为一个 a = 'abc' + 'haha' + '哈哈' # a = 123 # 字符串只能不能和其他的类型进行加法运算,如果做了会出现异常 TypeError: must be str, not int # print("a = "+a) # 这种写法在Python中不常见 a = 123 # print('a =',a) # 在创建字符串时,可以在字符串中指定占位符 # %s 在字符串中表示任意字符 # %f 浮点数占位符 # %d 整数占位符 b = 'Hello %s'%'孙悟空' pri...
9521b428753418d5f786318cbe3464eb9592b293
jae-hun-e/python_practice_SourceCode
/뼈대코드/5/5-20.py
120
3.515625
4
def insertion_sort(xs): if xs != []: return insert(xs[0],insertion_sort(xs[1:])) else: return []
b99c829719a20f1216b2c86210757be6914b2b74
Team-Tomato/Learn
/Juniors - 1st Year/Nirmal/DAY 3/matrix_multiplication.py
1,216
4.125
4
p1=int(input("Enter the rows for matirx_1: ")) q1=int(input ("Enter the columns for matrix_1: ")) print("Enter the elements for matrix_1: ") matrix_1 =[ [int(input()) for i in range(p1)] for j in range(q1)] print("matrix_1 is: ") for i in range(p1): for j in range(q1): print(format(matrix_1[i] [j], "<...
85a717787387b6aefb8ace79a931a097ad5a61ff
nexiom1221/Phyton-Practice
/예제/practice7.py
387
3.84375
4
def std_weight(height, gender): if gender== "남자": return height * height * 22 else: return height * height * 21 # height = 175 # gender = "남자" height, gender= map(str,input("키와 성별을 입력하세요:").split()) weight = (round(std_weight(height / 100 ,gender), 2) print("키 {0}cm {1}의 표준 체중은 {2} 입니다.".format(hei...
6f15039a8357581e98fd29c1037f91d68447589c
ekeydar/selfpy_sols
/ex6.1.2.py
360
4.21875
4
def shift_left(my_list): """ shifts list of 3 elements to the left :param my_list: list of len 3 :type list :return: list of len3, shifted left :rtype list """ a, b, c = my_list return [b, c, a] def main(): print(shift_left([0, 1, 2])) print(shift_left(['monkey', 2.0, 1])) ...
e46e2b0a9d5a9c2be9667296fc2597d1dd6af0f6
Changvang/Python_project
/Tictactoe/game.py
4,392
4.03125
4
# Board # display board # play game # handle turn # check win # check rows # check columns # check diagonals # check tie # flip player # --------------- Global Variables --------------------- flip = True # Game Board hold data of the game board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"] # Two play...
2d2c54168177e3b2208bb0c17f0ddfd9fa730e4d
jachin/coderdojotc-python
/tower2.py
602
3.609375
4
# Written by Jessica Zehavi for CoderDojo Twin Cities - www.coderdojotc.org #!/usr/bin/python import mcpi.minecraft as minecraft import mcpi.block as block # Connect to the Minecraft server world = minecraft.Minecraft.create() # Get the player's current position and store the coordinates [x,y,z] = world.player.get...
918a8b3c1522d604743860c3cfc45a6fc0e5e132
ptabis/pp1
/05-ModularProgramming/8.py
295
3.796875
4
import turtle def drawSquare(x,y,n): pen = turtle.Turtle() pen.penup() pen.setposition(x,y) pen.pendown() for i in range(0, 4): pen.forward(n) pen.right(90) for i in range(1, 5): for j in range(1, 5): drawSquare(-300+i*100, 300-j*100, 100)
dfcc71deba408a41d7bf0031fd67e111e4e66404
AnotherOneWithAFace/logic-gates
/and.py
876
4.15625
4
def main(): print("This program emulates the functionality of an AND logic gate") print("Enter either a 1 or a 0, twice") print("Don't enter anything other than 1 or 0") x = input() y = input() if x == "0": bool1 = False elif x == "1": bool1 = True else: bool1 = "...
30132cd72458b94cd244412d9dcdc108a5674c6f
yatikaarora/turtle_coding
/drawing.py
282
4.28125
4
#to draw an octagon and a nested loop within. import turtle turtle= turtle.Turtle() sides = 8 for steps in range(sides): turtle.forward(100) turtle.right(360/sides) for moresteps in range(sides): turtle.forward(50) turtle.right(360/sides)
2c5fd6b8cc0433918e8745b1e999ad068be97e2b
jeffthemaximum/CodeEval
/Python/Easy/word_to_digits.py
332
3.734375
4
test = "zero;two;five;seven;eight;four" my_dict = { 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9' } my_array = test.split(';') output = '' for num in my_array: output += my_dict[num.rstrip()] p...
a9685c0da5e93ebc12e2a43cfca9f17622849be8
Mrhairui/python1
/other/find_object.py
1,148
3.90625
4
from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: n = len(matrix) if n == 0: return False m = len(matrix[0]) t = n*m if t == 0: return False left = 0 right = t - 1 if m...
371ee9c8d120ec2196ed4446bc1b90b772c83799
himangi6550/Python-programs
/sumarray.py
307
3.78125
4
N = int(input()) # Get the array numArray1 = list(map(int, input().split())) numArray2 = list(map(int, input().split())) sumArray = [N] # Write the logic here: for i in numArray1: sumArray[i]=i # Print the sumArray for element in sumArray: print(element, end=" ") print("")
b1b51ef59247dad427fad0e5a35206943e4f7a04
gizat/EulerProject
/Problem 009.py
389
3.828125
4
# Problem 9 # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def main(): for a in range(1, 1001): for b in range(a+1, 1001): for c in range(b+1, 1001): if a**2 + b**2 == c**2: if a + b + c == 1000: ...
23c0b044646efa5d370ebc82e84255e60b7aa730
ChinmayN30/Python-Projects
/Project_WeightConversion.py
357
4.0625
4
Weight = input("Enter your weight: ") weight_Unit = input("(L)bs or (K)gs: ") if weight_Unit.upper() == "L": UserWeight = float(Weight) * 0.45 print(f"Your weight in Kgs is {UserWeight}") elif weight_Unit.upper() == "K": UserWeight = float(Weight) / 0.45 print(f"Your weight in Lbs is {UserWeight}...
c5e088b2f392ad4273935b5cfba2424032921cdf
mmaatuq/brain_storming
/dice3.py
603
3.5
4
def compute_strategy(dices): assert all(len(dice) == 6 for dice in dices) best_index=0 MMax=0 strategy = dict() strategy["choose_first"] = True strategy["first_dice"] = 0 l=find_the_best_dice(dices) if l!=-1: strategy["first_dice"] = l else: for i in dices: ...
c60a42a96fe0ab125f874fff4bb34e60de0e4129
haoccheng/pegasus
/leetcode/btree_pre-inorder.py
601
3.53125
4
def build_tree(preorder, inorder): if len(preorder) == 0: return None elif len(preorder) == 1: return TreeNode(preorder[0]) else: root = preorder[0] inorder_root = inorder.index(root) left_inorder = inorder[:inorder_root] right_inorder = inorder[inorder_root+1:] left_preorder = [e for ...
58c6fbf69e3e3d5dfd3ff73b7819dd5f5bbc959e
saadkang/PyCharmLearning
/controlstructure/whileloopdemo.py
1,755
4.0625
4
""" Execute Statements repeatedly Conditions are used to Stop the Execution of loops Iterable items are String, List, Tuple, and Dictionary """ x = 0 while x < 10: print("The value of x is: "+ str(x)) x = x + 1 print('*'*40) print('*'*40) # So like established before after the while block whatever is indented ...
181fff03ae41ed98f906ef03d8b65587a7199cf8
Gabriel01osabuede/AndrewOsabuedeGabriel
/Calculator.py
354
4.5
4
#Calculating the area of a circle # storing 3.14 in a variable called pi pi = 3.14 # Accepting input (radius) from the user. radius = float(input("Type in the raduis of the circle : ")) # Using the formula to calculate the Area Area = (pi * radius ** 2) # Printing out the calculation to the console. print(" Area of...
a691e46fbd42c10f80785af9c27f111be523c5da
abbbhardwaj/Encryption
/src/UsingClass.py
1,043
3.859375
4
import random import time # Class that generates password 3 times class PwGenerator: password = '' def generator(self, length_of_password, chars): p = 0 if p in range(3): for pwd in range(length_of_password): self.password += random.choice(chars) prin...
bd626435d991674b91d349f1a2db9351ebfbd14b
oddduckden/lesson2
/task3.py
899
4.15625
4
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц # (зима, весна, лето, осень). Напишите решения через list и через dict. month = int(input('Введите номер месяца в году: ')) seasons_list = ['зима', 'зима', 'весна', 'весна', 'весна', 'лето', 'лето', 'лето', 'о...
c04c7c3c2ea49d99c94095e2364d7017c05c6b40
Liss19/Examen
/explv2.py
635
3.703125
4
import re class inicio2: def op2(self): expresion= input("Escribe una cadena: ") print(expresion) numeros="" letras="" numero=re.compile('[0-9]') letra=re.compile('[a-zA-Z]') for x in range(0,len(expresion)): buscar=numero.search(expresio...
9fd6953ca0aacdf0b4b3f7c93d6b9e9ae61bbd3a
tongxindao/notes
/imooc_python3_class/ten/c12.py
191
3.8125
4
import re s = "Life is short, i use python, i use python" r = re.search("Life(.*)python(.*)", s) # print(r.group(0, 1, 2)) print(r.groups()) # r = re.findall("Life(.*)python", s) # print(r)
5e61a757b3de77df4184aefc269de8d73b8a182e
tkshim/leetcode
/leetcode_0905_SortArrayByParity.py
242
3.859375
4
#!/usr/bin/env python #coding:utf-8 def checkNumber(X): odd = [] even = [] for x in X: if x % 2 == 0: odd.append(x) else: even.append(x) return odd + even print checkNumber([1,2,3,4])
e7b4409ed1c14d182255a3c9f3ca2b677e3c69c5
hkelder/Python
/Homework/singelton.py
890
4.34375
4
# Write a program in which you have a class, and you can instantiate object of it. # However, there is a restriction that you can create maximum of 1 object. # When 1 single object has been created out of that class, we must not be able to create more objects. # Code within the class is irrelevant but it should support...
6ac765e4b77b85c045e0a88fadb1c76239a5db1c
SAURABH5969/K-Means-Clustering
/PreProcess.py
805
3.515625
4
import pandas as pd import numpy as np import matplotlib as plt from scipy.stats import mode class PreProcess: df=pd.DataFrame({}) def __init__(self,dataFrame): self.df = dataFrame self.fillNaAndNorm() self.groupByCountry() #fill na and normalize def fillNaAndNorm(self): ...
66cac4d5612dad98b0c1d7a239cb8cb00abac905
GuavaLand/IntroToCS
/L10_daysBetweenDatesOfficial.py
2,158
4.25
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import os os.chdir('C:\Sources\IntroToCS') def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < daysInMonth(year, month): return year, month, day + 1 else: if month == 12...
6ee72e244b2984a10776dd7643aa61107a7d342f
blueeric/Python
/Stack.py
744
3.875
4
class Stack(): def __init__(self,size): self.stack=[] self.size=size self.head=-1 def isEmpty(self): if self.head==-1: return True else: return False def isFull(self): if self.head+1==self.size: return True else: ...
aa33f426d54a2b04f0b2b5f72136b1ac84ae389d
GMillerA/100daysofcode-with-python-course
/days/19-21-itertools/code/Stoplight.py
681
3.90625
4
import itertools import sys from time import sleep import random def sleep_timer(): return random.randint(3,7) def stoplight(): """Stoplight that cycles through colors""" colors = 'Red Green Yellow'.split() symbols = itertools.cycle(colors) for color in symbols: if color == "Red...
9ecee629f60b23bcc1e0611bfdf1bf8416baea33
seandewar/challenge-solutions
/hackerrank/easy/2d-array.py
802
3.65625
4
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/2d-array import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): largestsum = -sys.maxsize - 1 for y in range(len(arr) - 2): for x in range(len(arr[y]) - 2): h...
81289f361b3ef20a1f5ed80d36cf3db1516237fc
siggimar92/ProgAssignment1
/Lexer.py
2,708
3.875
4
from Token import Token import string from sys import stdin __author__ = 'Hrafnkell' class Lexer(object): ''' Diagnoses each token and describes it for the computer ''' def __init__(self): self.c = "" #self.string = "" #self.string = stdin.read() #self.string = self.string.re...
a72c4a2ba6d24b7c25b79b5dbfdac7a1f8209742
QuangTran999/projectBDS
/projectBDS/GUIbds.py
3,624
3.578125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from tkinter import * from tkinter.ttk import * import matplotlib matplotlib.use("TkAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg win = Tk() win.title("Home price prediction") win.geo...
193c3165bf8e887a0eba82b5fb7f33b8c4f8f53e
AlfredPianist/holbertonschool-higher_level_programming
/0x0A-python-inheritance/101-add_attribute.py
620
4.0625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """101-add_attribute This module contains a function that adds a new attribute to an object if possible. """ def add_attribute(obj, name, value): """Function that adds a new attribute to an object if possible. Args: obj (:obj:): The object to be added a new ...
de2ef567c217662741efde592d745285d5d5ffdd
hylyujj/python_Interview
/peponacciSequence.py
710
3.765625
4
#-*- coding: utf-8 -*- def firstFibFunc(n): before, after = 1, 1 for i in range(n): yield before before, after = after, before + after gen = firstFibFunc(5) for i in gen: print(i) def consumerFibFunc(): before, after = 0, 1 while True: yield before before, after = after, before + after ...
c2eda2ed6bddd7871085e5023ea887b93f6a94b0
huntercollegehighschool/srs2pythonbasicsf21-mtcl17
/part1.py
335
4
4
""" Define a function sumofsquares that takes an integer input number. The function then adds all the first n perfect squares (starting from 1). For example, sumofsquares(3) should return 14, since 1 + 4 + 9 = 14. """ def sumofsquares(number): i=1 sumsquares=0 while i<=number: sumsquares+=i**2 i+=1 re...
4fbcc9755f9937195aea55434de1e98207fdb9c9
fewva/my_python
/9/random1000.py
502
3.5625
4
import random a = [random.randint(-1000, 1000) for i in range(10)] #10 элементов просто легче проверить) imin = a.index(min(a)) imax = a.index(max(a)) if imax < imin: imax, imin = imin, imax kol = len(list(filter((lambda x: x < 0), a[imin:imax + 1]))) print(f'Список выглядит так: {a}, его максимальный элемент: {max...
3205f3552dae627d5c6a3249be24cf674645a7bf
gpapad14/DataAnalysisWorkshop
/PredictSurvivalB_titanic_data.py
910
3.703125
4
# In this portion of the assignment you should create a more complex heuristic with an accuracy of 80% or more. # You are encouraged to use as many of the elements in the csv file as you need. import pandas predictions = [] df = pandas.read_csv("titanic_data.csv") wrong=0 for passenger_index, passenger ...
071d923391aab89b7562c238c3d71f7c11e6c32b
shankar7791/MI-10-DevOps
/Personel/Yash/Python/23feb/Pro7.py
662
4
4
# Program 7 : Write a Python program that accepts a string and calculate the number of digits and # letters. ''' s = input("Enter the string : " ) digits=letters=0 for i in s: if i.isdigit(): digits=digits+1 elif i.isalpha(): letters=letters+1 print("Number of Letters", letters) print("Number o...
0d23d8fe2a67fe377bdb81e7ce836369de117b58
anaschmidt/Aprendendo-a-programar
/Aulas/condicional.py
571
4.03125
4
# Condicional (IF - ELSE) if: Ponto no problema ex:. if (expressão condicional): #código: quando eu tenho códigos desalinhados, são chamados de bloco identação: processo de separa os blocos ''bonitinhos'' # else: uma opção, não é obrigatório.0000000000000000000 #operadores lógicos: == != > < >= <= #fazer uma variavel...
296ee8466ab356a30bbe17e100ff28c85b5eca6f
seershikab/assignment-4.py
/assignment4.3.py
78
3.625
4
def fact(n): if n==1: return n else return n*fact(n-1) print(fact(5))
dd18d6fd077cfe660a6e62d0a274505bb34893eb
primegoon/homework
/twice/2.py
267
3.65625
4
a, b = input('숫자 두 개를 입력하세요: ').split() a = int(a) b = int(b) print('덧셈은 : ', a + b) print('뺄셈은 : ', a - b) print('곱셈은 : ', a * b) print('나눗셈은 : ', a / b) print('몫은 : ', a // b) print('나머지는 : ', a % b)
a892d3c424ef0e876830ec268e11b5cc26ea89db
Arality/learnpython
/Lesson 4.py
477
3.8125
4
# Functions # A function is a transportable section of code that you use to stop doing the same thing over and over again. It is defined by the key word def name(arguments): #def LogFunction(paramater): # print(paramater) # Returns # Sometimes you want your fuction to do things and give you the resu...
fc1116ba3c3671987e99dbf6d66953bbe0f98103
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Udemy/Lendo_Recebendo_dados/pep8.py
2,123
3.859375
4
""" PEP8 - Python Enhacement Proposal São propostas de melhorias a Linguagem Python The Zen of Python import this A ideia da PEP8 é que possamos escrever códigos Python de forma Pythônica ************************************************************************************ [1] - Utilizar camel case para nomes de cla...
eb2d21919bcf351569b4de102380a95502f59a4b
monicajoa/AirBnB_clone_v2
/web_flask/2-c_route.py
1,227
3.75
4
#!/usr/bin/python3 """ C is fun This module holds a script that starts a Flask web application web application must be listening on 0.0.0.0, port 5000 Routes: /: display “Hello HBNB!” /hbnb: display “HBNB” /c/<text> display “C ” followed by the value of the text variable using the option str...