blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a6af5269d8deb4c6787e69dd854eb1d7f1dea7a8 | zunayedsyed/list-practice | /main.py | 496 | 3.828125 | 4 | # list
# create a function
def list():
x=[5,6,7,8]
y=len(x)
sum=5
sum*=y
print("sum=",sum)
# conditional logic
z=5
if z<sum:
print("weird")
# function call
list()
# list swap
# create a function
def listswap():
x=[1,2,3]
y=5
z=int(input())
if z in x:
print("swapmode")
temp=y
y=z
z=temp
print("y=",y... |
520a7ca114440422421018cf9f285cf2930af7ce | vSzemkel/PythonScripts | /cp-tasks/binary_operator.py | 930 | 3.515625 | 4 | #!/usr/bin/python3
#
# Binary operator
# https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435c44/00000000007ec290
from random import randint
fn_cache = {}
def fn(a, b):
if (a,b) in fn_cache:
return fn_cache[(a,b)]
ret = randint(0, 10**18)
fn_cache[(a,b)] = ret
return ret
c... |
90de23275cbf5d05b7adef62dff2b25d0624caf9 | liuchao111/Test1.1 | /newstudentssystem.py | 6,345 | 3.65625 | 4 | # 这是一个简单的学生信息管理系统,主要功能是对学生信息进行
# 1,增删改查 2,保存到文件 3,从文件中读取信息
# 制作人刘超
def gongneng():
print("---------------学生信息管理系统---------------\n"
"1,添加学生信息\n"
"2,删除学生信息\n"
"3,修改学生信息\n"
"4,显示所有学生信息\n"
"5,将学生信息保存到文件(xueshengxinxi.txt)\n"
"6,读取文档学生信息(xueshengxinxi.txt)\n... |
3c7ccaca5bf7bcf5c68c14517bb56cceeeec996b | pfdamasceno/data-structures-algorithms | /chapter-01/P1.36.py | 1,008 | 4.25 | 4 | '''
P-1.36 Write a Python program that inputs a list of words, separated by whitespace,
and outputs how many times each word appears in the list. You
need not worry about efficiency at this point, however, as this topic is
something that will be addressed later in this book.
'''
def count_words(text):
'''
input... |
8988148eda0c24c5c29bf3201bed1bab74d1b678 | GeoGamez/Python | /PythonPrograms/triangle.py | 400 | 4.1875 | 4 | #input for both programs
integer= int(input("Please enter a number 1 or greater: "))
#triangle
if integer == 1:
print("*")
else:
print('*') #the starting triangle always only has 1 *
for x in range(0,integer-2): # this for loop prints all the hollow chucks and to ensure inputting 1 and 2 don't make *'s I subtract... |
c4bedcb4f9462b2dec19aa823eddd438526e793f | prhod/mailsender | /src/mysmtp.py | 2,001 | 3.5625 | 4 | from smtplib import SMTP, SMTPAuthenticationError
from email.base64mime import body_encode as encode_base64
import base64
class mySMTP(SMTP):
def auth(self, mechanism, authobject, *, initial_response_ok=True):
"""Authentication command - requires response processing.
'mechanism' specifies which aut... |
9f46d296bf6148a94c08b0c3fc98e4412306601b | Dadajon/100-days-of-code | /competitive-programming/hackerrank/algorithms/implementation/043-library-fine/lib_fine.gyp | 978 | 3.5625 | 4 | def library_fine(return_day, return_month, return_year,
expect_day, expect_month, expect_year):
if return_year > expect_year:
return 10000
if return_year < expect_year:
return 0
if return_month > expect_month:
return 500 * (return_month - expect_month)
if return_... |
fe8aa084942310901710d3174bafd51e2ced96ee | OCoderO/Elements-of-Software-Design---UT-Austin | /Expression Tree - A17/ExpressionTree.py | 5,808 | 3.65625 | 4 | # File: ExpressionTree.py
# Description:
# Student Name: Rosemary Cramblitt
# Student UT EID: rkc753
# Partner Name: Wendy Zhang
# Partner UT EID: wz4393
# Course Name: CS 313E
# Unique Number: 52240
# Date Created: 4/17/21
# Date Last Modified: 4/19/21
import sys
operators = ['+', '-', '*', '/', '//', '%',... |
2f8d3c620fc13ba966c2fc16421040467575cdd2 | erneslobo/Python_Basico_2_2019 | /Tarea4/Tarea4.py | 2,028 | 3.953125 | 4 | #Suponga que se tiene una lista de listas que se tiene diversas cantidades por persona.
# La primera columna con números representa la cantidad en miles de colones que tienen en la cuenta del banco,
# la segunda columna la cantidad en crédito en miles de colones y
# la tercer columna en miles de colones en deuda.
hoja... |
a21cb56d6d59115421d6531bbf648ad60156d75e | gregariouspanda/Julia-learns-python | /generate_story.py | 745 | 3.875 | 4 | import sys
import create_dictionary
import random
def main():
num_words = sys.argv[2]
word_dict = create_dictionary.create_dictionary(sys.argv[1])
print(generate_story(word_dict, int(num_words)))
def generate_story(word_dict, num_words):
story = ''
words = 0
last_word_added = word_dict['$'][... |
3ad7122c083bcf7ed8d8a5a4937ef9400bc9030b | freebz/Foundations-for-Analytics-with-Python | /ch01/ex1-6.py | 1,150 | 4.1875 | 4 | print("Output #14: {0:s}".format('I\'m enjoying learning Python.'))
print("Output #15: {0:s}".format("This is a long string. Without the backslash\
it would run off of the page on the right in the text editor and be very\
difficult to read and edit. By using the backslash you can split the long\
string into smaller st... |
1b1bf66df81fdb3960523c915521fdcb6f46d2d2 | jimas95/Intro_to_AI | /lab4/student_code.py | 3,436 | 3.53125 | 4 | import common
# return true if game is over (Tie)
# check if the board if tie (full)
def is_tie(board):
res = True
for item in board:
if(item==0):
res = False
return res
# max value of minimax
def max_value(state):
v = - 1000000
# check state
result = common.game_status(state)
# if... |
78ff3b3df166ced7acecf3d475e1c731887cf903 | rupesh1219/python | /games/guess_the_number.py | 1,220 | 4.3125 | 4 | ########################################################################
# generate a random number
# user has to guess the random number generated and will input via console
# then compare the output and input - indicate whether the guess is too
# high or low , if correct give a positive indication
# lets say we give ... |
27cd9964735e227d870f0b56988319245a7e4fca | ddeneau/Simulations | /OrbitSim.py | 6,700 | 3.546875 | 4 | # Simulation of two dimensional orbital mechanics.
# All numerical values are scaled down for no real noticeable performance improvements.
# This is simply done to improve code readability and does simplify some calculations (for me).
import numpy
import scipy.constants
import pygame
import random
WIDTH = 1400
HEIGHT =... |
1056f7199d51ed5c70721450513df7bba1c47b89 | leilei92/Coding-Algorithm | /DFS/valid_parentheses.py | 711 | 3.6875 | 4 | # given n pairs of parenthese, write a function to generate
# all combinations of well-formed parentheses
# for example: n = 3
class Solution(object):
def validParentheses(self, n):
answers, sequence = [], []
self.bt(answers, sequence, n, 0, 0)
return answers
def bt(self, answers, se... |
a370294aeaa1aeeb3a146c2d8c6e9e2a86d923ec | EHwooKim/Algorithms | /프로그래머스/level2/42585.py | 460 | 3.578125 | 4 | def solution(arrangement):
answer = 0
count = 0
pre_open = False
for bracket in arrangement:
if bracket == '(':
count += 1
pre_open = True
else:
if pre_open == True:
count -= 1
answer += count
else:
... |
4db51652518fef57ac9790e7fe0a8088c1d15c12 | woodyhoko/CSES.fi | /Introductory Problems/Permutations.py | 172 | 3.625 | 4 | s = int(input())
if s==1:
print(1)
elif s<4:
print("NO SOLUTION")
else:
print(' '.join(str(x) for x in range(2,s+1,2)),' '.join(str(x) for x in range(1,s+1,2))) |
ca9ae852accb440c6114a6c9ba568109f48d5c87 | sanyatishenko/PythonEDU | /if.py | 437 | 4.28125 | 4 | ###################################
# Условный оператор if-elif-else
###################################
a = int(input('Введите число: '))
if a < 0 :
print("Число", a,"отрицательное.")
elif a == 0 :
print("Ноль.")
else :
print("Число", a,"положительное.")
# Короткая запись if
print(a,"не равно нулю") if ... |
3775ec7628085b56b4ee20a556459ac940d38e76 | rtsaunders19/_python_ | /mod.py | 141 | 3.5 | 4 |
try:
a = 20
b = 0
print(a/b)
except ZeroDivisionError:
print('hey this is an error')
finally:
print('this always shows') |
14cce1981162db3593f8e542342d1ff87f0d5e12 | fifa007/Leetcode | /src/house_robber.py | 973 | 3.828125 | 4 | #!/usr/bin/env python2.7
'''
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that
adjacent houses have security system connected and it will automatically contact
the police if two adja... |
f623caaaf1541fef2af5b0d74574d2e66993b16d | jorgesanme/Python | /Ejercicios/Pildoras/nota_if_.py | 469 | 3.953125 | 4 | def evalua(nota):
valoracion="aprobado"
if nota<0:
print("nota no validad")
elif 0<nota<5:
return "suspenso"
elif 0<nota>=5 and nota<6:
return "aprobado"
elif 0<nota>=6 and nota<8:
return "bien"
elif nota>=8 and nota<9:
return "notable"
else:
r... |
77d66875a60529bbb4fb634cd51d12abb165c3a4 | 0xJinbe/Exercicios-py | /Ex 045.py | 599 | 4.25 | 4 | """Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro número elevado ao segundo número. Não utilize a função de potência da linguagem."""
print("base ^ expoente:")
base=int(input("Base: "))
expoente=int(input("Expoente: "))
potencia=1
count=1
while count <= expoente:
potencia *=... |
95bc7e2ca5482232a1225a7c77d5f3bfc449593d | sungis/test-code | /service_examples/radix_tree.py | 11,633 | 3.875 | 4 | from collections import deque
class RadixTree:
def __init__(self):
"""
Create a Radix Tree with only the default node root.
"""
self.root = RadixTreeNode()
self.root.key = ""
self.size = 0
def insert(self, key, value, node=None):
"""
... |
d9e7519d897251a3a79f9278ad7ee99272415a91 | Python87-com/PythonExercise | /day09_20191111/w.py | 343 | 3.75 | 4 | count = 1
# 纸张厚度
thickness = 0.01
# while 循环里需要计算单位的一致性,如果改成米的话,则前面输出的厚度会出现科学计数法
while thickness < 8848430:
thickness = thickness * 2 # 这里也可以写成 thickness *= 2 效果是一样的
count += 1
print(thickness)
print(count - 1)
|
7f7593d3b04e41fe5445d67367150ccc60e23d83 | FatemehRezapoor/LearnPythonTheHardWay | /LearnPythonTheHardWay/E11_12AskQuestion.py | 516 | 4.1875 | 4 | # May 31, 2018
# Exercise 11-13
# ** ASK FOR INPUT FROM USER **
print('How old are you?')
age = input()
print('How tall are you?')
height = input()
print('I am %s years old and I am %r tall' % (age, height)) # The user input is string
# Another Method to combine print with input command
age = input('How old... |
e76f993f41ffeb13abdc6977b41ae139713df80e | RubennCastilloo/master-python | /09-listas/predefenidas.py | 707 | 4.28125 | 4 | cantantes = ['Megan Nicole', 'Dua Lipa', 'Bebe Rexha']
numeros = [1, 2, 5, 8, 3, 4]
# Ordenar una lista
print(numeros)
numeros.sort()
print(numeros)
# Añadir elementos
cantantes.append("Bruno Mars")
print(cantantes)
cantantes.insert(1,"David Bisbal")
print(cantantes)
# Eliminar elementos
cantantes.pop(1)
cantantes.r... |
3b3648d8a9018ddaa341def031213dd0036c21f9 | rafal-mizera/UDEMY | /kurs_dla_poczatkujacych/for.py | 1,444 | 3.546875 | 4 | data = ['Error:File cannot be open',
'Error:No free space on disk',
'Error:File missing',
'Warning:Internet connection lost',
'Error:Access denied']
elements = []
for el in data:
elements = list(el.split(":"))
if elements[0] == "Error":
print(elements[0].upper(),element... |
6373856fc1455785061a30e6aae8cf425b410bea | Lithika-Ramesh/Amaatra-Grade-12-Lab-Programs | /Lab programs/lab prog 14.py | 207 | 3.65625 | 4 | #WAP to count the number of words present in text files
#july 22
f=open("Lithika/story.txt","r")
str=f.read()
l=str.split()
c=0
for i in l:
c=c+1
f.close()
print("total number of words =",c) |
0be8d3e48914bc166644992fc683e0ebbbde4609 | sunilkumarvalmiki/data-visualization-web-app-using-streamlit | /app.py | 6,508 | 3.75 | 4 | # importing the packages
import streamlit as st
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("Agg")
import seaborn as sns
import pandas as pd
import numpy as np
DATA_URL = ("movies_data.csv")
st.markdown("# Self Exploratory Visualization on movies data")
st.markdown("Explore ... |
a3b2989e85d1c2caf759db21119aa1d4fb89d8b2 | j0hnk1m/leetcode | /easy/70.py | 557 | 3.71875 | 4 | n = 3
# recursive - o(2^n) runtime, o(n) space
def climbStairs(n):
if n == 0 or n == 1:
return 1
return climbStairs(n-1) + climbStairs(n-2)
# recursive w/ memoization - o(n) runtime, o(n) space
def climbStairs(n):
memo = {0: 1, 1: 1}
res = helper(n, memo)
return res
def helper(n, memo... |
49c80bb1c05c364f878748966c48455acda86282 | huang199408/pycharm_test | /test1.py | 400 | 3.71875 | 4 | # coding=utf-8
# 有三个办公室,还有8个老师等待随机分配
import random
# 先创建3个办公室
offices = [[], [], []]
# 假设8个老师是ABCDEFGH
teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
b = 0
while b < len(teachers):
a = random.randint(0, 2)
if len(offices[a]) < 3:
offices[a].append(teachers[b])
b += 1
for temp in offices:... |
895c365884bfd0bca8dc19a484e9a3b1415bc925 | BWatson019/AboutMe | /Test2Pt2.py | 1,707 | 4.125 | 4 | """
Author: <Brittney Watson>
Description: <Create a program that uses concepts from this class (be creative!)>
"""
import random
import Test2Pt2b #importng prime numbers program from another file
WORD = ('cyber', 'security', 'rocks')
word = random.choice(WORD)
correct = word
hint = word[0] + word[(len(word)-1):(len... |
5a216f3631f5906a9db7d37f39957443bead0575 | RhythmShift/Python3-Parsing | /Python3_Project.py | 617 | 3.6875 | 4 | #This is the Python3 project to parse a log file
import urllib.request
import re
import os
from datetime import time
from datetime import date
from datetime import datetime
urllib.request.urlretrieve("https://s3.amazonaws.com/tcmg476/http_access_log", "Amazon_Logfile.txt")
#Opens and reads the text file. Clos... |
344baf58de047ec1e819a9fb18f6725f8430113d | tuhiniris/Advanced-JavaScript-Codes | /Faster Algorithms/_/uniquesort.py | 327 | 3.890625 | 4 | from collections import defaultdict
def def_value():
return False
def uniqSort(arr):
memo = defaultdict(def_value)
result = []
for i in range(len(arr)):
if memo[arr[i]]==False:
result.append(arr[i])
memo[arr[i]]=True
#print(memo)
result.sort()
return(result)
ans = uniqSort([4,2,2,3,2,2,2])
prin... |
746d336c638406229fb5c1ebca48db92d14b1c7b | kazuma-shinomiya/leetcode | /234.palindrome-linked-list.py | 711 | 3.734375 | 4 | #
# @lc app=leetcode id=234 lang=python3
#
# [234] Palindrome Linked List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> boo... |
7c2788a91794b3aa87fa3f3539742702f04c973f | PolozSabina/Homework | /Homework_16.py | 367 | 3.5 | 4 | v1 = 13
v2 = 18
def have_trains_crashed(v1, v2):
distance_train__a = 4
distance_train__b = 6
time_train__a = distance_train__a / v1
time_train__b = distance_train__b / v2
return time_train__b <= time_train__a
if have_trains_crashed(v1, v2):
print('Поезда столкнутся')
else:
print('Поезда не... |
f091e5d5251a33333b2d3d490f7705ee08417f89 | JamesDevaney1150/Python-Essentials | /tictactoe.py | 3,752 | 4.46875 | 4 | #TIC TAC TOE
#LAST UPDATED 26/09/2021
##1-Define the board
tttboard=[]
for i in range(3): #a for loop that creates 3 new lists inside the ttboardlist
row = ["-" for i in range(3)] #the print statement then creates a new line after every list
tttboard.append(row) ... |
fbdc865b350c314c00504ce735f615267be10db3 | anatulea/codesignal_challenges | /Python/09_Drilling the Lists/62_checkParticipants.py | 1,535 | 3.78125 | 4 | '''
You're organizing murder mystery games for your coworkers, and came up with a lot of ideas for various groups of participants. The ith 0-based game can be played only if there are at least i people registered for it. Game number 0 is a beta that you will try out with your friends, so there's no need for participant... |
fdc0c83b8447ebec3dca5d601509ed8b8dc11a52 | kimgeonsu/python_19s | /!.py | 107 | 3.75 | 4 | n=int(input("숫자를 입력하세요:"))
for i in range (1, n) :
n= n*i
print(n)
|
782c83abf018cbdef660a0b652c19e847d286a55 | filipnovotny/algos | /dynamic_programming/fib.py | 331 | 3.53125 | 4 | def memoize(f):
mem = dict()
def helper(n):
if n in mem:
return mem[n]
else:
mem[n] = f(n)
return mem[n]
return helper
@memoize
def fib(n):
if n==0:
return 0;
elif n==1:
return 1;
else:
return fib(n-2)+fib(n-1);
print... |
e0d949c721a707691e2425f26bab64fedf69aea5 | YaChenW/Data-Structure | /Graph/PrimMST.py | 8,692 | 3.78125 | 4 | #索引最小堆
class indexMinHeap:
def __init__(self,data=list()):
self.data = data #最小堆
if len(data)>0:
self.index = list(range(len(data)))
self.reIndex = list(range(len(data)))
else:
self.index = list() #保存原index下的元素在最小堆中的位置
self.reIndex = lis... |
25018d2b46770d64947c8aa5979b0d61eba40db4 | anurag1212/code-catalog | /code/ds-algo-python/chapter6/R-6.6.py | 405 | 3.65625 | 4 | def bracketmatch(s,i=0,opens="[({",closes="])}"):
if i>=len(s):
return True
if s[i] in closes:
return i
if s[i] in opens:
next = bracketmatch(s,i+1)
if type(next) is bool:
return False
if opens.find(s[i]) == closes.find(s[next]):
return bracket... |
01c027153bca83297a74f0bf56f512dd3c679de5 | varshajoshi36/practice | /leetcode/python/easy/ExcelSheetNumber.py | 570 | 3.78125 | 4 | '''
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
'''
import string
def titleToNumber(s):
"""
:type s: str
:rt... |
0d9749f2ecc9c5e22e3069ac1e7b82e33218a431 | irvanardynsyh/Lab_1-2 | /Lab 1.py | 1,152 | 3.90625 | 4 | # Penggunaan End
print("PENGGUNAAN END")
print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('y')
print('Z')
print("\n")
# Penggunaan Separator
print("PENGGUNAAN SEPARATOR")
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep=''... |
85c560ccf2850185742b5a602632268fa6bc07f7 | tillyoswellwheeler/python-learning | /hackerrank_challenges/division.py | 686 | 4.125 | 4 | #----------------------------------------------
# HackerRank Challenges -- Division
#----------------------------------------------
# ------------------------------------
# Task
# Read two integers and print two lines. The first line should contain integer division, a//b .
# The second line should contain float divi... |
d68fe861a80437aa7df982272ee1d513723f0492 | yurimalheiros/IP-2019-2 | /lista1/roberta/questao4.py | 499 | 3.921875 | 4 | # Função Definir alarme
# Autor Roberta de Lima
from datetime import datetime, timedelta
# Função Estática
print("ALARME")
dt = datetime(2019,11,3, 14)
hrAlarme = dt + timedelta(hours=51)
print("Sendo 14hrs, daqui a 51hrs o alarme tocará às ",hrAlarme.strftime("%H:%M "))
# Função dinâmica
#tempo = int... |
e4b2ac61ad90e2442bf978b9cb88e25ed60107df | davidalejandrolazopampa/Mundial | /10.py | 163 | 3.9375 | 4 | f=int(input("ingrese F°: "))
c=((f-32)*5)/9
if 46>f and 29<f:
print(c)
elseif f==46:
print("Limite Inferior")
else :
print("Limite Superior")
|
8b98a523b681beca19d2dc28977bece86a23ab93 | carterjin/digit-challenge | /PNG_digit_question.py | 2,767 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 11:34:04 2020
@author: Kami
"""
import itertools
testdigits = range(1,10)
# Shunting-yard_algorithm
##https://en.wikipedia.org/wiki/Shunting-yard_algorithm
def op_prec(char):
if char == '*' or char == '/':
return 3
else:
... |
8f17255ddd95781518148019efc8d0ba4bb9a6c3 | ebrisum/Basictrack_2021_1a | /Week 3/excercise_3_4_4_6.py | 467 | 3.984375 | 4 | numbers = [83, 75, 74.9, 70, 69.9, 65, 60, 59.9, 55, 50,
49.9, 45, 44.9, 40, 39.9, 2, 0]
for grade in numbers:
if grade>=75:
print(grade,":First")
if 70<=grade<75:
print(grade,":Upper second")
if 60<=grade<70:
print(grade,":Second")
if 50<=grade<60:
print(grade,":Third")... |
a7890ad585b4345e0741613923f9d9761b2c6dc6 | zyga/arrowhead | /xkcd518.py | 3,193 | 3.890625 | 4 | #!/usr/bin/env python3
from arrowhead import Flow, step, arrow, main
def ask(prompt):
answer = None
while answer not in ('yes', 'no'):
answer = input(prompt + ' ')
return answer
class XKCD518(Flow):
"""
https://xkcd.com/518/
"""
@step(initial=True, level=1)
@arrow('do_you_un... |
a99032c42eec0b666fa080cf77d9941763b974c4 | nektarios94/Palindrome-exercise-written-in-Python | /Python_code/main.py | 441 | 4.03125 | 4 | from palindrome import palindrome
list = []
while (True):
string = input("Please type a string of characters (press 'e' to exit): ")
if string != 'e' and string != 'E':
list.append(string)
if palindrome(string) and (len(string) > 1): # excluding single characters
print ('\'%s\' is ... |
efd7e7dac25515a879b03a2ccb10e43cc18b2136 | aschiedermeier/Programming-Essentials-in-Python | /Module_6/6.1.3.6.existingVariables.py | 2,313 | 4.375 | 4 | # 6.1.3.6 OOP: Properties
# Checking an attribute's existence
# in Python you may not expect that all objects of the same class have the same sets of properties.
class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1
exampleObject = Exampl... |
a19aaf4285dcc0804b2066d9dd86a6e2db02cdb1 | CosmoAndrade/PythonExercicios2020 | /65.py | 3,885 | 3.828125 | 4 | '''
Crie uma Fazenda de Bichinhos instanciando vários objetos bichinho e mantendo o controle deles através de uma lista. Imite o funcionamento do programa básico, mas ao invés de exigir que o usuário tome conta de um único bichinho, exija que ele tome conta da fazenda inteira. Cada opção do menu deveria permitir que o ... |
1f7ba5b1b98bc5778ef3063d7b64d212420f2f0b | kinetickansra/algorithms-in-C-Cplusplus-Java-Python-JavaScript | /Algorithms/Recursion/Python/GenerateParenthesis.py | 304 | 3.59375 | 4 | def bracket(n, asf, open, close):
if n == 0:
if open == close:
print(asf)
return
if open > close:
bracket(n - 1, asf + ")", open, close + 1)
# if close
bracket(n - 1, asf + "(", open + 1, close)
n = int(input())
bracket(2 * n, "", 0, 0)
|
390fa0ed3d42e6ccc00c10ee0077e45e71a3561c | nishathapa/Inception-Machine | /Handling.py | 416 | 3.5 | 4 | try:
# p=5/0
p = 78
j= 98
r=p/0
f = open("ac.txt")
for line in f:
print(line)
except FileNotFoundError as e:
print(e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e)
# except FileNotFoundError:
# print("printed error")
# except Zero... |
2f2a50f5ac17e986eb8878d6e7d6ad8184b9b8d6 | vicky-xiaoli/html | /python1/py0911.py | 508 | 3.859375 | 4 |
# 11有一个列表['a','b','c','a','e','a'], 使用for循环统计a出现的次数,并删除其中的所有a元素
# lis = ['a','b','c','a','e','a',"a","a"]
# count = 0
# for i in lis: #循环列表
# if i == 'a':
# count = count + 1 #当i是a的时候,每循环一次加一次
# print(count) #循环结束后,打印最后次数
# for j in range(count): #按计数引循环a
# lis.remove("a") ... |
faf19d0133e060b5ee5a5ec77abed36c9d117505 | shonshch/compilationHw3 | /CompilationTests/hw3/make_submission.py | 813 | 3.671875 | 4 | #!/usr/bin/python3
import os
from zipfile import ZipFile
import glob
import sys
if len(sys.argv) == 3:
tz1 = sys.argv[1]
tz2 = sys.argv[2]
else:
tz1 = input("Enter the first Teudat Zehut: ")
tz2 = input("Enter the second Teudat Zehut: ")
code_files = glob.glob('*.c') + glob.glob('*.cp... |
bc2fa3a03d6a42b43501c4cd440dfec17c746ec8 | smrsassa/Studying-python | /curso/PY2/while_true/ex4.py | 652 | 3.75 | 4 | #exercicio 69
homems = mulheresvinte = dezoito = 0
while True:
print ('-'*60)
print ('Cadastre uma pessoa')
print ('-'*60)
idade = int(input('Qual sua idade: '))
sexo = str(input('Qual seu sexo: [M/F] '))
print ('-'*60)
if sexo in 'Mm':
homems += 1
elif sexo in 'Ff' and idade < 2... |
296851fe24b6c08ff92ad0c61ae8321e2edb0a5f | jrcamelo/IF968-Projetos-e-Listas | /Atividades/Lista8/PythonDB.py | 6,099 | 3.6875 | 4 | # João Rafael
def menu():
dados = []
while not dados:
limparTela()
print("MENU PRINCIPAL DO BANCO DE DADOS",
"\nEscolha a operação que deseja realizar:",
"\n1. Registrar Pessoa",
"\n2. Procurar Pessoa",
"\n3. Alterar Registro",
... |
6a6263a9f7079fd401cf0fa6862e1dceaff79d74 | amullenger/PyBank_Exercise | /main3.py | 3,025 | 3.875 | 4 | import os
import csv
my_file = os.path.join('', 'budget_data.csv')
"""Create lists for seperately storing all months, profit/loss figures, calculated differences in P/L,
and a master list of lists to store all data with P/L converted to float type"""
month_list = []
P_L_List = []
P_L_Difference = []
master_list = [... |
ebd80b7a1750ed164559c89537b5ac64fbf01bd5 | Lianyihwei/RobbiLian | /Lcc/pythonrace/PYA710.py | 249 | 3.609375 | 4 | #TODO
from tabnanny import check
dict = {}
while True:
key = input("Key: ")
if key == "end":
break
value = input("Value: ")
dict[key] = value
search_key = input("Search key: ")
print(search_key in dict.keys()) |
5c121c3cb65d337966e5a5bb07d28b3fe8d636cf | lucky-star-king/javaInternet | /作业6/test.py | 372 | 3.640625 | 4 | # def printname(name="mmi"):
# print(name)
# # printname()
# def rever(a,b):
# a,b=b,a
# a,b=1,2
# rever(1,2)
# print(a,b)
# def summ(*args):
# m=0
# for x in args:
# m+=x
# print(m)
# li=[1,2,4,5,6,23,4]
# summ(*li)
def fi(n):
if n==1:
return 0
return 1 if... |
d5d3f724b78cdc2c98630bcf7ab271f8487099ad | juandsuarezz/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 381 | 4.03125 | 4 | #!/usr/bin/python3
"""Documentation of a load from json file function"""
import json
def load_from_json_file(filename):
"""creates an object from a json file
Arguments:
filename (str): file to load the string
Returns:
JSON object represented by the string
"""
with open(filenam... |
70f828c5a4f4617979fe6125c854d7b180e9c8a8 | harishtm/learningpython | /quick_sort.py | 658 | 4.28125 | 4 | import sys
def quick_sort(array):
array_length = len(array)
if array_length <= 1:
return array
else:
pivot = array[0]
greater = [element for element in array[1:] if element > pivot]
lesser = [element for element in array[1:] if element <= pivot]
return quick_sort(les... |
c400e001b057ad2daca11d8eb29e2326d624d44c | jasonluocesc/LeetCode | /Solution/14_LongestCommonPrefix.py | 845 | 3.65625 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
strs.sort(key=len)
if len(strs[0]) == 0:
return ""
if len(strs) == 1:
return strs[0]
fi... |
7741b75d914b23e80bfe789b667e1a44ff578a7a | christophgockel/tictactoe | /test_player.py | 1,148 | 3.53125 | 4 | from unittest import TestCase
from mock import Mock
from player import Player, PlayerO, PlayerX
from board import make_board
class TestPlayer(TestCase):
def test_player_has_symbol(self):
o = Player(Player.O)
x = Player(Player.X)
self.assertEqual(Player.O, o.symbol)
self.assertEqua... |
cf0c72d92d72bbdefc08b922a1b5c4893932cfe8 | Shalom5693/Data_Structures | /Recursion/ProductSUM.py | 192 | 3.765625 | 4 | def productSum(array,m=1):
# Write your code here.
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element,m+1)
else :
sum += element
return sum * m
|
69e9c2b46842145279e4f3b4c82be222f522d632 | arotanskiy/Homeworks | /P110_exam.py | 2,702 | 3.6875 | 4 | """
This module generates an address for delivery service with random street, build and flat numbers
"""
import random
import json
import re
streets_file = 'py110_exam_base.json' # source file with country, city and streets
def test_mode(*args):
"""
This function to use test mode
:param args:
:retu... |
44b99118b4faca2060bbd5c5a07833d89a2c5663 | mohanad1996/GraduationProject | /length_review.py | 407 | 3.625 | 4 | import csv
def get_avg_len():
length=0
count=0
with open('C:/Users/admin/PycharmProjects/Graduation-Project/Output.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
length+=len(row[2])
#print(len(row[2]))
#print(row[2])
... |
6d17efae48c109b50faae5158dfb8fe51586deeb | mayflower6157/Leetcode | /1089.Duplicate zeros/solution.py | 674 | 3.6875 | 4 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
n = len(arr)
raw_arr = arr.copy() # Assignment don't create a new list
duplicated_arr = []
for i in range(n):
if (len(d... |
4f854135a950b1cc355926629972f5c038aa39f4 | shanminlin/Cracking_the_Coding_Interview | /chapter-10/11_peaks_and_valleys.py | 436 | 4.0625 | 4 | """
Chapter 10 - Problem 10.11 - Peaks and Valleys
Problem:
In an array of integers, a "peak" is an element which is greater than or equal to the adjacent integers and
a "valley" is an element which is less than or equal to the adjacent integers. For example, in the array
{5, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {5,... |
9b061c9fe9c44c2916fafa917b4b949d11acd3c5 | torothin/Bookstore_python | /BradsBookStore.py | 6,912 | 4.28125 | 4 | #Brad Duvall
#Book Store App V1 (Attempt to complete prior to performing exercise)
#1/25/17 to 2/6/17 (Estimated 30-40 hours to complete)
#Uses SQLite3 and Tkinter to create an executable bookstore app
#
from tkinter import *
import sqlite3
window=Tk()
window.resizable(0,0)
#Creates the initial database ... |
87dcd996c0fdf037719fbff5a9f82d5598ca6b13 | dishamisal/LeetCode | /Shuffle-the-Array.py | 658 | 3.609375 | 4 | # Problem:
# Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
# Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Solution:
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
final = []
parts = len(nums) / n
import numpy as np... |
ed751fd6a5664c1a954ad4b54b1a681fe5b1285d | rafaelperazzo/programacao-web | /moodledata/vpl_data/107/usersdata/260/52354/submittedfiles/questao3.py | 265 | 3.578125 | 4 | # -*- coding: utf-8 -*-
p=int(input("digite o valor de p: "))
q=int(input("digite o valor de q: "))
dp=0
dq=0
for i in range(1,q*p,1):
if q%i==0:
dq=dq+1
if p%i==0:
dp=dp+1
if dp==2 and dq==2 and q==p+2 :
print("S")
else:
print("N")
|
25009cc18729f29b77d0a5f91b9a2ee9623a6404 | Tiago1704/VariosPython | /QS con Pila.py | 1,004 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 02:05:17 2018
@author: Tiago Ibacache
"""
import P
def quicksortConLista (pila, izq, der):
pila = P.Pila()
P.crearpila(pila)
i = izq
d = der
med = pila[(izq + der)/2]
while (i <= d):
while pila[i] < med and d <= d... |
70713f4fecb95092cf6bdc8bb6dc1a0502554e63 | ramkishorem/pythonic | /session3_list_loop/19.py | 404 | 3.671875 | 4 | """
Drill 5: MyVengers
> Create myvengers = ['Thor','Iron Man','Black widow','Hawkeye']
> create a copy called yourvengers
> replace yourvengers elements with your favourites, you may
add more too
> Compare elements of myvengers and yourvengers and
make sure they are different.
> Print lasted 2 Avengers on my lis... |
52d6aaf1b6f38bf00968ce27cdbdd24fb75fe87f | rohitdanda/MachineLearning | /DataProcessing.py | 1,403 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plot
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import LabelEncoder,OneHotEncoder,StandardScaler
from sklearn.model_selection import train_test_split
#importing the data from CSV file
datasets = pd.read_csv('Data.csv')... |
bf08bde0df8f7e9f417f71246ffca5263ee119c5 | rafz10/scripts20181 | /Lista 10 - Funções/Teste Numero Primo.py | 223 | 3.734375 | 4 | def primo(n):
'''
Metodo para checar se é primo
'''
for i in range(2,n):
if n % i == 0 :
print ('Não é primo')
break
else:
print('È primo')
primo(8)
|
1093ec614de401ce2dc148f8964c63b6e77bf5f2 | saurabhwasule/python-practice | /Nice_training_material/core_python_hands-final/mytest.py | 430 | 3.546875 | 4 | from pkg.MyInt import MyInt
import unittest
class MyTest(unittest.TestCase):
def test_add(self):
"""Testing addition functionality"""
a = MyInt(2)
b = MyInt(3)
c = a + b
self.assertEqual(c, MyInt(5))
def test_less(self):
"""Testing less functionality"""
... |
9a9b87db301eb76a2614f69ee019517858e626c5 | davidm3591/Code-Cheats-Settings | /python/code_hints_tips/python_str_vs_repr.py | 810 | 3.953125 | 4 | # ######################################################################
#
# Python str() vs repr()
#
# ######################################################################
def brk_ln():
print("")
# ### str() vs repr() ### #
# Example 1 of str()
str_intro = "Example 1 of str()"
print(str_intro)
s = "H... |
4e16314b882b6417273982a89b874561fbd4a351 | Aleksey-Bykov1/Python_algorithms | /lesson_3_home_work.py | 7,640 | 4.125 | 4 | # -------------------------------------------- 1 ----------------------------------------------------
''' 1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне
от 2 до 9.'''
# Без использования словаря
n = list(range(2, 100))
multiples_2 = 0
multiples_3 = 0
mu... |
e70e63a99989cd4a11b56fa5ace40fa9027387d4 | jphafner/project-euler | /euler_004.py | 727 | 4.3125 | 4 | #!/usr/bin/env python
"""
A palindromic number reads the same both ways. The largest palildrome made
from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import sys
from numpy import sqrt
def orig():
"""
My original solution... |
1ebfe11587081abb883c0d02ff651dbaa9e218c8 | bes-1/lessons_python | /dz_4_4_berezin.py | 145 | 3.65625 | 4 | begin_list = [1, 5, 5, 6, 15, 4, 4, 4, 23, 12, 12, 3, 4]
answer_list = [el for el in begin_list if begin_list.count(el) < 2]
print(answer_list)
|
53ad2d65583f075e8d4b1e825c079d75bf4c0abd | roctbb/GoTo-Start-2017 | /Lesson 1/bw_dog.py | 617 | 3.5 | 4 | from PIL import Image
file = input("введите имя картинки:")
im = Image.open(file)
pixels = im.load()
for i in range(im.width//2):
for j in range(im.height):
r, g, b = pixels[i, j]
S = (r+g+b)//3
if S < 100:
pixels[i, j] = (255,255,255)
else:
pixels[i, j] = (0... |
1febdb5fe1371bae2a608f450da740926bca3afd | hsuBnOediH/AlgoExpert | /getYoungestCommonAncestor.py | 1,472 | 3.53125 | 4 | # This is an input class. Do not edit.
class AncestralTree:
def __init__(self, name):
self.name = name
self.ancestor = None
def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):
a_set = set()
cur = descendantOne
while cur is not None:
a_set.add(cur.name)
... |
88543273f1431ddc8f12b7462f833274ff4b02a2 | antikytheraton/algorithms | /algorithms/graph.py | 644 | 3.859375 | 4 | '''
Copyright (c) 1998, 2000, 2003 Python Software Foundation.
All rights reserved.
Licensed under the PSF license.
'''
graph = { 'A':['B','C'],
'B':['C','D'],
'C':['D'],
'D':['C'],
'E':['F'],
'F':['C']}
def find_path(graph, start, end, path=[]):
path ... |
64482d5db77dd7ccfd43fcc9375c4ec2f2b3a99c | krishnamohan152/Code-Forces | /4A_Watermelon.py | 249 | 3.75 | 4 | #! /usr/bin/env python
# Headers
import sys
# Input
Get_Num = input()
# Main Code
def main(Get_Num):
if int(Get_Num) == 2:
print("NO")
elif int(Get_Num) % 2 == 0:
print("YES")
else:
print("NO")
if __name__ == '__main__':
main(Get_Num) |
a4a2ddf8cca4f927cc1f8e118b4981bb864ba130 | giuschil/Python-Essentials | /python_classes/python.classi_punto_cartesiano.py | 631 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 22:40:08 2018
@author: giuschil
"""
#programmazione ad oggetti oop
# voglio creare una classe che crei l'oggetto punto cartesiano
import math
class Punto:
def __init__(self,x,y):
self.x = x
self.y = y
def to_stri... |
f2809d1aa718fa3c363f14dca8fad47f991ecd49 | shakhobiddin/Python | /Question 4 (sentence).py | 418 | 4.15625 | 4 | #Take the users input
words = input("Enter your sentence to translate to pig latin: ")
print ("You entered: ", words)
#Now I need to break apart the words into a list
words = words.split(' ')
#Now words is a list, so I can take each one using a loop
k=""
for i in words:
if len(i) >=0 :
i = i + "%say" % (... |
3c398626e2fdf939f7d15dd2c17caaa2a9baed70 | anipshah/geeksforgeeks_problems | /jumpGame.py | 211 | 3.75 | 4 | def jump_game(arr):
n = len(arr)
jump = 0
for i in range(n):
if i > jump:
return False
jump = max(jump, i + arr[i])
return True
arr=[1,3,0,1,2]
print(jump_game(arr))
|
89fab55233c379ea166239057ee496ecfcdfdc61 | praveendk/programs | /loops/forLoopRange.py | 82 | 3.5625 | 4 | # practise for loop range
for x in range(10):
if x == 6:
continue
print(x) |
12103863497d5642cd9f399503878567ed17bc08 | PARKJUHONG123/turbo-doodle | /MOST_USAGE/SORT.py | 4,327 | 3.765625 | 4 | def bubble_sort(arr):
# time = O(n^2)
# space = O(n)
# In-place Sort (다른 메모리 공간 필요 X length 안에서만 해결 가능)
# Stable Sort (같은 값의 순서가 바뀌지 않음)
length = len(arr)
for i in range(length):
for j in range(1, length - i):
if arr[j - 1] > arr[j]:
temp = arr[j - 1]
... |
4579f3237510f36d057d7f0e28a74d9a6b6437e0 | taech-95/python | /Beginner/PasswordGenerator.py | 1,372 | 3.796875 | 4 | import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4',... |
3ce584840840749a9c99808e070729ca7c95929b | Adefreit/cs110z-f19-t4 | /Lesson 14/list_example_2.py | 706 | 4.09375 | 4 | # Gets # of swimmers from user
num_swimmers = int(input())
# Keeps Track of the Total
total = 0
# List to Hold Swim Times
times = []
# Loop to get all swim times
for i in range(num_swimmers):
# Get Each Individual Time
swim_time = int(input())
# Puts Time in List
times.append(swim_time)
... |
906f2d82c978e539c757aed0bbbd36823e8f3e1c | ais-climber/notakto-player | /v2_lstm/heatmap.py | 4,329 | 3.640625 | 4 | """
A script for producing a heatmap of a Notakto strategy.
For a given strategy S, we play S in a variety of games.
From these games, we collect the most likely responses
of S to a given move m, and make a heatmap of these responses.
"""
from Board import Board
from FeatureLayeredNet import FeatureLayeredNet
from str... |
69f83b91a4c81f5ad15bc904422b9c6c650ea253 | nancydemir/Hackerrank | /hackerDayPrintFunction.py | 148 | 3.59375 | 4 |
if __name__ == '__main__':
x = 0
n = int(input())
for i in range(0,n):
print(x + 1,end = "")
x += 1
|
04bc869ae553c647f72354c0c68873d94177cd52 | timid-one/cs-115 | /Notes/traceAndBinExercise.py | 3,439 | 3.828125 | 4 | # two-part exercise
from cs115 import map
'''
Part 0
Here is a memoized version of edit distance.
Your task: make it trace the calls to fastED_help, indented
according to recursion depth. Hint: add a parameter to fastED_help.
'''
def fastED(first, second):
'''Returns the edit distance between the strings first a... |
f82fbcb63e59ca54da9df7d38fd9d87e4fe6195b | khuang110/CS-362-Homework-4 | /name.py | 318 | 3.671875 | 4 | # Make a full name as input to run unit test on
# By: Kyle Huang
def name(first, last):
if not isinstance(first, str) or not isinstance(last, str):
raise TypeError("Does not contain string")
else:
return first + " " + last
if __name__=="__main__":
print(name("Kyle", "Huang"))
... |
e2a4d88c5f532a900ec2121d564394acdb4cc9ed | Sumyak-Jain/Python-for-beginners | /while_0.py | 96 | 3.671875 | 4 | a=int(input("enter a number"))
i=1;
while i<11:
print("%d X %d = %d" % (a,i,a*i))
i=i+1
|
ca6f62f9010d790b4ffbb1a14c80e4b6a599cf06 | kaobeosolu78/Practice_Projects | /Project_Euler_Problems/Factorial Sum.py | 322 | 3.6875 | 4 | def factorial(n):
fact = 1
for k in range(0,n+1):
if n == 0:
return 1
elif k != n:
fact *= (n-k)
return (fact)
fact_100 = str(factorial(100))
answer = 0
hold = []
for k in fact_100:
hold.append(int(k))
for k in hold:
answer += k
print (answer)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.