blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6610b6e86f1ed82c852c6826fb28b2dec1aaa829 | RichInCode/projectEulerProblems | /summationOfPrimes.py | 481 | 3.734375 | 4 | import largestPrimeFactor
import math
def summationOfPrimes( x ):
runningSum = 2
lastPrime = 3
i = 3
while i < x:
if largestPrimeFactor.isPrime( i ):
runningSum = runningSum + i
lastPrime = i
print i
i = i+2
print runningSum
def... |
d0477d1e044926b376c50a804abccb60d1edd35b | jfenton888/AdvancedCompSciCode | /CS550 Fall/September 22/RandomNumberGen_1.py | 366 | 3.859375 | 4 | import random
play = 1
while play == 1:
numGen = int(random.uniform(1,100))
numPick = int(input("Pick a number between 1 and 100"))
print(numGen)
while numGen != numPick:
if numGen == numPick:
print("Correct")
else if numPick < numGen:
print("Too Low")
else if numPick > numGen:
print("Too High")
pl... |
d07ee30572a6179ab1853136b3b44401d7fb1ff6 | ljia2/leetcode.py | /solutions/range/056.Merge.Intervals.py | 1,545 | 4.125 | 4 | # Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
"""
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[... |
b97ac7d0fea0b78b3518f0e195ffe6ef4d36c9c9 | CleberSilva93/Study-Exercicios-Python | /Exercício Udemy/ex08.py | 714 | 3.921875 | 4 | #coding: utf-8
__author__ = 'Cleber Augusto'
########################
#### Cleber Augusto ####
########################
print("Determine o intervalo")
det = int(input("Valor Inicial:\n"))
det2 = int(input("Valor Final:\n"))
l = []
for a in list(range(det,det2)):
x = 0
c2 = a%2
if a==0:
continue
... |
d97b37eedf6cdd121c96e97b46f9275a914d0fc7 | duk1edev/tceh | /003_tryexcept_func_homework/self_practice.py | 2,165 | 3.703125 | 4 | import random
# 1 Функция которая выбрасивает случаено одно из исключений
import random
error_list = [
(TypeError, 'Error1'),
(ValueError, 'Error2'),
(RuntimeError, 'Error3')
]
# random.shuffle(error_list)
error, message = random.choice(error_list)
print(error, message)
def random_error_maker():
try... |
7653f13e5061299335a99843b612224e9575a3c4 | Vaskovics/My_100_projects | /07_Hagman_game/07_Hagman_game.py | 1,935 | 3.921875 | 4 | import random
logo = '''
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |... |
4263fcbc8fcd7773c978a7f8f484d62da5add528 | ghensto/python | /supermarket.py | 1,311 | 3.921875 | 4 | # CSCI 2061, Assignment 09, Problem 02
# Abiola Adimi
# Supermarket program.
#Main function.
def main():
#Shopping dictionary
shoppingList = {'potato':2, 'lettuce':5, 'onion':1}
#Inventory dictionary
inventory = {'potato':6, 'lettuce':0, 'onion':32, 'carrot':15}
#Prices dictionary
prices... |
755cd0470530a975393031526cb76cfeacb06921 | penghuiping/python-learn | /src/c1_basic/StringTest.py | 945 | 3.71875 | 4 | # coding=utf-8
import re
# 字符串拼接
a = "hello" + "," + "world"
print("字符串拼接:", a)
print("字符串大写", a.upper())
print("字符串小写", a.lower())
print("字符串截取", a[0:5])
print("判断字符串是以特定格式开始", a.startswith("hello"))
print("判断字符串是否包含特定字符串", "hello" in a)
# trim
a = " hello "
print(a.strip())
# 使用正则表达式抓取固定电话
b = "我家的固定电话为021-12345... |
ae95a8039720a1447824bf97b9f0786630896397 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2680/60759/280659.py | 352 | 3.671875 | 4 | def getPath(x1, y1, x2, y2):
global ans
if x1 == x2 and y1 == y2:
ans += 1
else:
if x1 < x2:
getPath(x1+1, y1, x2, y2)
if y1 < y2:
getPath(x1, y1+1, x2, y2)
ts = int(input())
for t in range(ts):
x2, y2 = map(int, input().split(' '))
ans = 0
getPa... |
a00c8b65d45c9478893eefafd4fe4184644188ee | shivam-02/Adventures-in-Python | /eg25.py | 98 | 3.59375 | 4 | def add(x,y):
print(y)
return x+y
print(add(y=10,x=20))
#print(add(y=10,20))
print(type(add)) |
1e27a182fe435185dad830e3919799498ace443f | Clockwick/DataStructureP2 | /VIM.py | 3,568 | 4 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
show_str = ""
current = self.tail
while current:
show_str += current.data ... |
f4b2d3d6909fc2b2e09c1b1a16b547942c6707ce | ZodiacSyndicate/leet-code-solutions | /easy/437.路径总和-iii/437.路径总和-iii.py | 1,562 | 3.734375 | 4 | #
# @lc app=leetcode.cn id=437 lang=python3
#
# [437] 路径总和 III
#
# https://leetcode-cn.com/problems/path-sum-iii/description/
#
# algorithms
# Easy (46.92%)
# Total Accepted: 3.5K
# Total Submissions: 7.4K
# Testcase Example: '[10,5,-3,3,2,null,11,3,-2,null,1]\n8'
#
# 给定一个二叉树,它的每个结点都存放着一个整数值。
#
# 找出路径和等于给定数值的路径总数。
... |
bbdbae511d743172c6923212fe36196459201995 | kwanhur/leetcode | /two-sum.py | 1,129 | 3.640625 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
import operator
class Solution(object):
"""
https://leetcode-cn.com/problems/two-sum/description/
"""
def add(self, nums):
return operator.add(nums[0], nums[1])
def twoSum(self, nums, target):
ret = {}
for i in range(len(nums))... |
2bb9d6db0b20972baef19c889564f2153354daec | SMS-NED16/pcc-data-vis | /rw_and_plot/15_3_molecular.py | 879 | 3.65625 | 4 | import matplotlib.pyplot as plt
from random_walk import RandomWalk
"""Simulating brownian motion of a pollen grain"""
#Create a RandomWalk object and populate it with values
data_points = 5000
pollen_rw = RandomWalk(data_points)
pollen_rw.fill_walk()
#Specifying figure dimensions
plt.figure(figsize=(4.5, 4.5), dpi=1... |
04c637619420b23507b08d7da39bf615667988ff | YanaQ/python | /lesson2/hw_2_5.py | 1,551 | 3.515625 | 4 | # 5. Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы
# с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них.
# Подсказка. Например, на... |
6d67c7f5031cfee88314fe32f26aced6a22534da | RohitSavant24/Python | /assign3.py | 88 | 3.859375 | 4 | age=int(input('Enter Age:'))
print('Entered Age:',age)
age=age-10
print('New Age:',age)
|
e2bb6c24c843ad5ad9a0d533ba55dffed3ca18e8 | AyaanShaikh1/Backup-Python | /backup.py | 425 | 3.5 | 4 | import os
import shutil
# path
path = 'C:/Users/Imtiyaz shaikh/Desktop'
print("Before Moving File: ")
print(os.listdir(path))
# source
source = 'C:/Users/Imtiyaz shaikh/Desktop/Project/68'
# destination
destination = 'C:/Users/Imtiyaz shaikh/Desktop'
# move content from source to destination example... |
8fc75caf824c91a3c39827b338efa6b60ff627d7 | minosys-jp/tempcloud | /current.py | 177 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime, time
def current():
now = datetime.datetime.now()
return int(time.mktime(now.timetuple()))
d = current()
print d
|
7220da761faba6244710ce6b06e9c2879f3b96ca | smitajani/HB-Homework | /produce_summary.py | 1,571 | 3.828125 | 4 |
""" Open raw data files the and print to the sales report
"""
# Iteration-1: Fix the report to print correct values - melon, count & amount,
# on each line
# Iteration:2: Code cleanup and optimization
# Open the file object passed as the argument, loop through each row and do the
# following:
# - Strip spaces on ... |
228b7f0596af443423582da39ae4560db4355a70 | Viktor-Paul/review | /2020_07_06/sql_02.py | 504 | 3.6875 | 4 | """
pymysql.py读操作
"""
import pymysql
db = pymysql.connect(host='localhost',
port=3306,
user='root',
password='',
database='stu',
charset='utf8')
cur = db.cursor()
sql = "select * from class_1 where class_num = 3;... |
0d80b80aafc32e73a94f6e20d0c299f4a12feade | HaidiChen/Coding | /python/linkedlist/odd_even_merge.py | 617 | 4.125 | 4 | # reorder the linked list in such a way that even nodes followed by odd nodes.
# time complexity is O(n)
# space complexity is O(1)
class Solution(object):
"""
Solution class to the question.
"""
def even_odd_merge(self, L):
if not L:
return L
even_head, odd_head = L, L
... |
cc9f38516fb0fe87b8f1080f981d3c1cdc97e463 | yinhuax/leet_code | /datastructure/daily_topic/NumArray.py | 1,169 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : 597290963@qq.com
# @Time : 2021/3/1 5:59
# @File : NumArray.py
from typing import List
"""
给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
实现 NumArray 类:
NumArray(int[] nums) 使用数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums... |
b9f4ac7c5494beb61103ab3cc9b2af091f218b19 | mivargas/ejercicios-de-python | /documentacion.py | 317 | 3.78125 | 4 | def suma(num1, num2, num3):
""" calcula las sumade 3 elementos
pasados por parametro a esa funcion"""
print(num1+num2+num3)
def resta(num1, num2):
print(num1-num2)
def potencia(base, exponente):
print(pow(base, exponente))
suma(2,4,7)
print(suma.__doc__) # imprimir la documentacion en consola
help(suma) |
1583aa3fe4f6777afb617482530e14c37870c2b4 | minotaur423/Python3 | /Python-Scripts/milestone1_pj.py | 4,553 | 4 | 4 | def display_board(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
pr... |
609ef79c9ba865d1199d6cabcdf67ee9a3c9d984 | besenthil/Algorithms | /algoexpert/reconstruct_BST.py | 884 | 3.640625 | 4 | # This is an input class. Do not edit.
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# o(n) - time
def reconstructBst(preOrderTraversalValues):
head = BST(preOrderTraversalValues[0])
idx = 1
while idx < len(p... |
09d3f8dcfd4e0c181f2644fcdd5ccd3182c03760 | ericgarig/daily-coding-problem | /209-longest-substring-of-3-stirngs.py | 1,965 | 4.15625 | 4 | """
Daily Coding Problem - 2019-05-05.
Write a program that computes the length of the longest common subsequence of
three given strings. For example, given "epidemiologist", "refrigeration", and
"supercalifragilisticexpialodocious", it should return 5, since the longest
common subsequence is "eieio".
"""
def solve_... |
1b370c41914d68504d62e115a794d61880249f59 | pengyuhou/git_test1 | /leetcode/236. 二叉树的最近公共祖先(again).py | 656 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root, p, q):
if not root:
return None
if (root.left == p and root.right == q) o... |
50ac3eef475b272a34714cdff9b99859c372643f | vasyanch/stepik | /Algorithms_theory_practic_methods/Greedy_algorithms/Theory/My_heap/My_heap.py | 1,196 | 4.03125 | 4 | def siftdown(heap, i):
while 2 * i < len(heap) :
j = i #j - индекс наибольшего из тройки
if heap[2 * i] > heap[i]:
j = 2 * i
if 2 * i + 1 < len(heap) and heap[2*i + 1] > heap[j]:
j = 2 * i + 1
if i == j:
break
... |
e0c98333fdba84a21f5592911e9b3abc7c37eb4c | Emanuelvss13/ifpi-ads-algoritimos2020 | /cap_07_iteracao/Lista_Fábio_03_em_for/fabio_iteracao_Q11_LimitesPrimos.py | 858 | 3.90625 | 4 | def main():
limiteInferior = int(input('Digite o Limite Inferior: '))
limiteSuperior = int(input('Digite o Limite Superior: '))
if limiteInferior <= 0:
print('O limite inferior tem que ser acima de zero(0).')
else:
for i in range( limiteInferior, limiteSuperior+1):
... |
941dae9f8e8bac54342791bb14aa88b39cf4fc2a | Kipkorir-Gideon/News-Api | /tests/test_articles.py | 1,246 | 3.71875 | 4 | import unittest
from app.models import Articles
class ArticlesTest(unittest.TestCase):
'''
Test Class to test the behavior of the Articles class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = Articles('Yuri2','Yuri Gagari'... |
06e61b07f4da1394ad93e9c9fadbcac449172ba5 | woongsup123/python-practice1 | /6_numberOfMultiplesOfThreeAndSum.py | 222 | 3.890625 | 4 | number_list = []
for i in range(1, 30):
number_list.append(i)
num = 0
sum_of_nums = 0
for number in number_list:
if number % 3 == 0:
num += 1
sum_of_nums += number
print(num)
print(sum_of_nums)
|
2c9947f6088e8aca27cc8b56d42d597dc6c7d02d | nibsdey/PythonToy1 | /Exercise3_1.py | 199 | 4.03125 | 4 | hours=float(input("Enter hours: "))
rate=float(input("Enter rate: "))
if (hours > 40):
extra=hours - 40
pay = (40 * rate) + (extra * (1.5 * rate))
else:
pay = hours * rate
print("Pay: "+ str(pay)) |
592870b2b4ba106e101e44ce08c5e66c0d756b00 | raywongstudy/python_workshop | /exercise.py | 466 | 3.625 | 4 | import time
name = input("what is your name:")
print("Hello "+name+" welcome you!")
sleep_time = input("How long you want to sleep:")
if(int(sleep_time) < 10):
time.sleep(int(sleep_time))
else:
print("the sleep time so long!")
print("please wake up!")
# 引入 requests 模組
import requests
# 使用 GET 方式下載普通網頁
r = req... |
e9361d494bf42beb0ddcd7331d4a34b81c379f88 | tea2code/make-it-hit | /graphics/tkdrawer.py | 1,184 | 3.6875 | 4 | from abc import ABCMeta, abstractmethod
from formulary import screenconvert
class TkDrawer(metaclass = ABCMeta):
''' Base class for objects which can draw something using tk.
Member:
color -- The color of the line (string).
fill -- The fill color (string).
line -- The line width (float).
... |
8f189e5815342ccb7cffb936e91511098c92c885 | vlarkov/geekhub_homeworks | /lesson 2 hw/task12.py | 276 | 3.609375 | 4 | # Задание 12*
# Дана строка. Удалите из нее все символы, чьи индексы делятся на 3.
my_str = "0123456789"
new_str = ''
i = 0
for i in range(len(my_str)):
if i % 3 != 0:
new_str += my_str[i]
print(new_str)
|
4fcae09789bf1a8deee32a0f90a6efec8aa8f088 | TeknikhogskolanGothenburg/Python20_Python_Programming | /23Sep/sorting_objects.py | 636 | 3.96875 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age}"
def comp(person):
return person.age
def main():
p1 = Person("Pia", 45)
p2 = Person("Lars", 34)
p3 = Person("Ove", 67)
p4 = Person("... |
15890fbf96cb735dcf16fb5f30d8a057f0fe995a | ddzumajo/python-scripts | /covariance_mm.py | 1,639 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
This script computes the covariance of fluctuations between two matrix.
Example: density_covariance = <mu*nu> - <mu><nu> = A - B
Author: DiegoDZ
Date: 24 june 2016
Modified: 16 december 2016
run: >> python convariance_mm matrix1 matrix2 > output_file
"""
import numpy as np
import sys
... |
6c2d499dcb5a5ebfbce15aee554294e86089c596 | mariachacko93/luminarDjano | /luminarproject/pythoncollections/list demo/pair.py | 347 | 3.8125 | 4 | # input-->3...o/p-->1,2
list=[2,3,4,1,6]
element=int(input("enter the number"))
list.sort()
low=0
# print(len(list))
up=len(list)-1
while(low<up):
total=list[low]+list[up]
if(total==element):
print("pairs=",list[low],",",list[up])
break
elif(total>element):
up=up-1
elif(total<el... |
9a36ece6f5217aa89718ce817d755ff0148c7191 | iWaleedibrahim/elementry-python | /conditionals/conditions.py | 183 | 4.125 | 4 |
# if else, if elif elif ... else
loc = "Bank"
if loc == "AutoShop":
print("GetACar!")
elif loc == "Bank":
print("GetMoney!")
else:
print("I Don't know where are we!")
|
85df9bf29f3cdcb9c3c7fc739ca6b35fe75d195d | pcolt/CS50-Web-Programming | /Testing_CI-CD/test1.py | 598 | 4 | 4 | # unittest comes for free with Python
import unittest
# import the function that I want to test
from prime import is_prime
class Tests(unittest.TestCase):
def test_1(self):
"""Check that 1 is not prime"""
#call class Tests itself with self and use methods inherited from TestCase
self.assertFalse(is_prime(1))
... |
f83727d72e86b9078dfa503b2e633afda4fdd139 | jonathanqbo/moncton-python-2020 | /week8/homework/andy_guess_10.31.py | 2,036 | 3.640625 | 4 | import turtle
import random
MTN=100
def ct(x,y,hide=False,color='red',size=2,pencolor='blue',pensize=2,heading=90,speed='fastest'):
a=turtle.Turtle()
if hide:
a.hideturtle()
a.shape('turtle')
a.color('red')
a.shapesize(size)
a.setheading(heading)
a.pensize(pensize)
a.pencolor(p... |
93b7dd9d19520f7346286eb4c2cd93a1a527fcfa | SamuelChanYankah/entry_programing | /Vending machine.py | 3,073 | 3.765625 | 4 | class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def updateStock(self, stock):
self.stock = stock
def buyFromStock(self):
if self.stock == 0:
# raise not item exception
pas... |
19b156cfaf0918a7e7cf97ee34344943a3931914 | AnTznimalz/python_prepro | /gcd_n.py | 656 | 3.734375 | 4 | '''GCD_N by ศิษย์เทพปอง#2'''
def gcd():
'''Func. gcd for finding gcd of N numbers'''
last = int(input())
cat = 1
rat = 0
for _ in range(last):
num = int(input())
dog = cal(num)
if dog != 0:
if dog % cat == 0 or cat % dog == 0:
rat = cat
... |
3518f3bd9658a59ac79c34629655916589f8a963 | bellos711/python_practice | /python/OOP/chaining_methods.py | 1,613 | 3.90625 | 4 |
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance=0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdraw(self, amount):
self.account_balance -= amount
return... |
6e706dbc943eb4671029e2c7b5500c5e28d5b5ee | dephiloper/independent-coursework-rl | /preparation/05_v_learning/minimax_tictactoe.py | 2,568 | 3.78125 | 4 | import collections
import math
import random
import copy
from typing import Tuple, List
from gym_tictactoe import TicTacToeEnvironment
BOARD_WIDTH = 3
BOARD_HEIGHT = 3
env = TicTacToeEnvironment()
saved_action = -1
wanted_depth = 9
def random_move(obs: Tuple):
return random.choice(possible_moves(obs))
def pos... |
a68219764191ab80380fb829c1b143327f33bde2 | sumanshil/TopCoder | /TopCoder/python/ntree/MaxDepthOfNaryTree.py | 1,474 | 3.6875 | 4 | import sys
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
"""
if root is None:
return 0
... |
899571ac902e1bdcb454bc722e0f611e79ea800e | LauraPeraltaV85/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/100-weight_average.py | 194 | 3.6875 | 4 | #!/usr/bin/python3
def weight_average(my_list=[]):
z = 0
y = 0
if not my_list:
return 0
for x in my_list:
z += (x[0] * x[1])
y += x[1]
return (z / y)
|
49ae4ceb888194c11d883faae3cfbba878184ccc | jvpupcat/holbertonschool-higher_level_programming | /0x03-python-data_structures/9-max_integer.py | 361 | 3.90625 | 4 | #!/usr/bin/python3
def max_integer(my_list=[]):
length = len(my_list)
if length == 0:
return None
else:
sort_list = sorted(my_list)
length2 = len(sort_list)
largest = my_list[0]
for i in range(1, length2):
if sort_list[i] > largest:
largest... |
5310f19ee91cdc53c7145a1a478463944d276d0e | rosario17/cursos_gauss | /funcion_suma.py | 704 | 3.984375 | 4 | def funcion_Suma(A,num1):
A= A+int(num1)
return A
def funcion_Resta(A,num2):
A=A-int(num1)
return A
def funcion_Multiplica(A,num1):
A=A*int(num1)
return A
def funcion_Divide(A,num1):
A=A/int(num1)
return A
A=0
while True:
operacion=raw_input("Teclee una operacion +,-,*,/, 0 para salir ")
if operacion ... |
b5f60d872be25819e62fea305f184222b8c442f0 | seasign10/STUDY | /00_Supplementary classes/03_algorithm/supplementary/보충 수업/JUNGOL/day2/145_반복제어문3 - 형성평가6.py | 246 | 3.8125 | 4 | num = int(input())
strnum = ''
empty = (2*num) - 2
for i in range(1, num+1):
# strnum += str(i)
# print(strnum) # 숫자가 제대로 출력되는 것을 확인
strnum += str(i) + ' '
print(' '*empty + strnum)
empty -= 2
|
d907c554416d0154709ef1cdb58763044a1886f8 | nikhilbhatewara/HackerRank | /Python/Day1_Quartiles.py | 1,311 | 4 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
digits = int(input())
values_input = input()
values_list = list(values_input.split(' '))
values = [int(v) for v in values_list]
#get median of series
def getmedian(digits, values):
values = sorted(values)
mid = (digits - 1) // 2
if digits % 2 != 0:
return ... |
131c3146b7721220e776277f378116f35d94d94a | 2019-a-gr1-python/py-guevara-sanandres-juan-diego | /Funciones/Funciones.py | 1,536 | 3.890625 | 4 | #Funciones
def hola_mundo():
print("Hola estupida")
hola_mundo()
#Argumentos requeridos la f es chevere porque te permite de todo
def sumar_dos_numeros(num1,num2):
return num1+num2
print(f"Suma {sumar_dos_numeros(1,2)}")
#Opcionales
def imprimir_universidad(nombre='EPN'):
print(f"{nombre}")
imprimir_universidad()
#... |
7c4feba01a1ee48c3973ef51d0f74b5c1820dd01 | Aasthaengg/IBMdataset | /Python_codes/p03424/s882315101.py | 95 | 3.5 | 4 | n=int(input())
if "Y" in list(map(str,input().split())):
print("Four")
else:
print("Three") |
2f7275fbe0353c95b36c5b3043d62d48ab3c9cc5 | HyunSeokJeon/coding_plus_algorithm | /algorithm_basic/weeklyquiz/week6/q3.py | 424 | 3.609375 | 4 | nums = [1, 0, -1, 0, -2, 2]
target = 0
answer = list()
for a in range(len(nums)):
for b in range(a+1, len(nums)):
for c in range(b+1, len(nums)):
for d in range(c+1, len(nums)):
if (nums[a] + nums[b] + nums[c] + nums[d]) == target:
lista = [nums[a], nums[b], n... |
19406fc028d47566054f88a03f110427838ea0a3 | wimurad1981/DS8008-NLP | /wiki/utils.py | 1,039 | 3.65625 | 4 | import requests
def get_text_from_wikipedia(title, wiki_domain='en.wikipedia.org'):
"""
Retrieve Wikipedia article content as plain-text
:param title: Title of Wikipedia article
:param wiki_domain: API domain (e.g., en.wikipedia.org)
:return: Article content as plain-text
"""
res = reque... |
eb3e37d69bb5da18918d96e021ca3a38c08553ca | firoj557/python-tutorial | /print pyramid in repetet number program.py | 296 | 3.890625 | 4 | """ Author: Firoj Kumar
Date: 10-05-2020
This program print pattern !"""
x=4
for i in range(0,x):
for j in range(0,x-i-1):
print(end=" ")
for j in range(0,i+1):
print('{}'.format(i),end=" ")
print( )
"""output 0
1 1
2 2 2
3 3 3 3 """ |
5857f5ebf4009a69f425c30946e729d141fe4d58 | guyhth/udacity-dsnd-prj2 | /data/process_data.py | 3,935 | 3.515625 | 4 | # Import libraries
import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
""" Load messages and categories datasets and merge into a single DataFrame
Arguments:
messages_filepath (str): path to messages dataset (CSV... |
4353617f8c65ba42d08e0a6e4ee77d022a4d8c83 | dantclee/how-to-think-like-a-computer-scientist | /10.4.py | 484 | 3.640625 | 4 | import time
nterms = int(input('Terms start from 0. Enter term: '))
#nterms = 35
if nterms == 0:
print('{0}th term is 0'.format(nterms))
elif nterms == 1:
print('{0}st term is 1'.format(nterms))
else:
two_term_b4 = 0
one_term_b4 = 1
count = 1
while count < nterms:
sum = two_term_b4 + o... |
feb43d752e520dd362cf64a80cc11ebd01cab227 | blogdoon/dailycodingproblems | /solutions/queen.py | 586 | 3.546875 | 4 | def n_queens(n, board=[]):
if n == len(board):
return 1
count = 0
for col in range(n):
board.append(col)
if is_valid(board):
count += n_queens(n, board)
board.pop()
return count
def is_valid(board):
cur_row, cur_col = len(board)-1, board[-1]
... |
46ef53f171db78bab0e002a0305c8979351034c5 | CBPHAM/King_Takehome | /libraries/southwest_date_helper.py | 1,965 | 4.40625 | 4 | from datetime import datetime
from dateutil import parser
def format_my_date(mydate):
"""
Simple function to take a date in the format %m/%d/%Y and convert it to a format that is used on Southwest's calendar picker.
For example, given date 05/23/2019 return may-23
This is required to make sure that w... |
4f16777053779ee769ba60bc84e735f13cf6ece1 | bkaczmarczik28/python-challenge | /PyBank/main.py | 2,773 | 4 | 4 | #this is main.py in PyBank
import csv
import os
#Identify csv file
csvpath = os.path.join("Resources", "budget_data.csv")
#initialize variables
totalMonths=0
totalAmount=0
sumChange=0
profit = 0
loss = 0
previous = 0
#Open the file using the "write" mode
with open(csvpath, newline="") as csvfile:
#identify... |
4f49ce14d0b4b21e2ab1ddb0807782b38e1b110c | calfdog/Robs_automation_tools | /misc_utils/time_a_function.py | 758 | 3.96875 | 4 | """
Description: Can be used for timing test and such. timing_function takes a decorated function as an
arg and returns the time it took for the function to complete.
Developer: Rob Marchetti
"""
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.... |
4d33f64cf9be68762ac35b4effd7bfe0e99504fe | ChristineKarimi/Project-euler | /tests.py | 858 | 3.5625 | 4 | #
import unittest
import smallest
class TestSmallest(unittest.TestCase):
def tearDown(self):
smallest.start_point = 1
def test_range_generator(self):
input = 20
range_length=len(smallest.range_generator(input))
self.assertTrue(range_length==20)
def test_start_point_exi... |
a23cd094920e41fdb3cd5dc6847510487c6019e9 | tsharretts/GEOG673_Python_Fall2020_UniversityDelaware | /Week02_Matplotlib.py | 2,269 | 4.5625 | 5 | # Tyler Sharretts
# Week 03 Matplotlib Tutorial
### Import Matplotlib
import matplotlib.pyplot as plt
import numpy as np
### The "easy" way
# Defining the x and y
x = np.arange(0,100,0.01)
y1 = np.cos(x)
y2 = np.sin(x)
# 3 different plots and their labels (run first two separately and then last one... |
78929e52202ccea2c3be9f49c1881d1fdc8f242e | AndrewZhaoLuo/Practice | /Euler/Problem46.py | 1,098 | 3.953125 | 4 | # -*- coding: cp1252 -*-
'''
It was proposed by Christian Goldbach that every odd composite number can be written
as the sum of a prime and twice a square.
9 = 7 + 212
15 = 7 + 222
21 = 3 + 232
25 = 7 + 232
27 = 19 + 222
33 = 31 + 212
It turns out that the conjecture was false.
What is the smallest odd composite tha... |
2d6f6c4a79de066b4007dc995e08ab3012e2f8f6 | barvaliyavishal/DataStructure | /GeeksForGeeks/CommonElements.py | 1,217 | 3.828125 | 4 | '''
this is a common element problem from GeeksForGeeks and
link and defination of this problem is given below
https://practice.geeksforgeeks.org/problems/common-elements1132/1
Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.
Note: can you take care of the duplicat... |
793a29b213d725f4ff22afe29c67576d6a9e6240 | pietr1n/aulaslpoo2sem21 | /aula2.py | 180 | 3.953125 | 4 | def main():
#
nota1 = int(input("Digite a nota 1:"))
nota2 = int(input("Digite a nota 2:"))
#
if (nota1 + nota2)/2 >= 5:
print("Passou")
#
else:
print("Bombou")
main()
|
09868a7c12dac8af534d27832f2bbde223b47ea9 | philipwerner/python_data_structures | /Tree/node.py | 536 | 3.921875 | 4 | """Node class module for Binary Tree."""
class Node(object):
"""The Node class."""
def __init__(self, value):
"""Initialization of node object."""
self.value = value
self.left = None
self.right = None
def __str__(self):
"""Return a string representation of the nod... |
46977ec88522e4d5df2ac727cd6725eb64359986 | mwele/web-scraping | /inheritance.py | 483 | 3.71875 | 4 |
class Contact:
all_contacts=[]
def __init__(self,name,email):
self.name=name
self.email=email
Contact.all_contacts.append(self)
#print(all_contacts)
#c=Contact()
class Supplier(Contact):
def order(self,order):
print("if this were a real system we would send" "'{}' order to '{}' ".format (order,self.name))... |
96d18eeb866636b04fb2adfacbdf5d8bf798e97b | jpbot/adventofcode | /2020/day10.py | 3,178 | 3.8125 | 4 | #!/usr/bin/env python
#
# ===============================================================
# ADVENT OF CODE
# ===============================================================
# DAY 13 Shuttle Search: find the shuttle bus you wait the
# shortest time for. Buses depart at timestamp 0 and
# every <bu... |
3bb4024bdb389ac6de67558a31c5838b9af20740 | XinheLIU/Coding-Interview | /Python/Algorithm/Sorting/Templates/Selection Sort Linked List.py | 705 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def selectionSort(self, head):
"""
input: ListNode head
return: ListNode
"""
# dummy node
self.next = head
tail = self
w... |
5c31708d09d234c397060cb53f505721bb87aa5c | abriggs914/Coding_Practice | /Python/ChatGPT3/demo_pong.py | 859 | 3.8125 | 4 | import tkinter as tk
# Create the window
window = tk.Tk()
window.title("Pong")
# Create the canvas
canvas = tk.Canvas(window, width=600, height=400)
canvas.pack()
# Create the paddles
left_paddle = canvas.create_rectangle(10, 150, 30, 250, fill="white")
right_paddle = canvas.create_rectangle(570, 150, 590, 250, fill... |
1b27c1f28acf650b785282155102b8d1a4085593 | fox-io/udemy-100-days-of-python | /day_005.py | 5,941 | 4.25 | 4 | """
Day 5 Practice
"""
import random
def for_loop():
names = ["Karen", "Bob", "Joe"]
for name in names:
print(name)
# for_loop()
def average_height():
total_heights = 0
heights = input("Enter a list of heights, separated by spaces: ").split()
for height in range(0, len(heights)):
... |
d731b3e51e91490e9937e23bd1cef121c1f4905e | r4isstatic/python-learn | /if_lang.py | 250 | 4.03125 | 4 | #!/usr/bin/env python
#This does an if statement, but tests it against a known set of values, rather than a number.
language = raw_input('Please enter a programming language: ')
if language in ['C++','python','Java']:
print language, "is great!"
|
bf09f9775a49202b6393c78765f12bc9d88e1153 | dielew/core_python | /p27.py | 128 | 3.671875 | 4 | #!/usr/bin/env python
while True:
str = raw_input('Plz input a string')
i = 0
while i < len(str):
print str[i]
i += 1
|
ec997d782b4776d3f5412d9a9628e8376774576e | xuxu829475/Pythonstudy | /xi_04_个人信息.py | 649 | 4.21875 | 4 | # 在python中,定义变量是不需要指定变量的类型的
# 在运行的时候,python解释器,会根据赋值语句等会右边的数据
# 自动推导出变量中保存数据的准确类型
# str 字符串类型
name = "小明"
# int整数类型
age = 18
# bool 布尔类型 真 True 假 False
gender = True
# float 浮点类型
height = 1.75
weight = 75
print(name)
# 字符串拼接 两个字符串用 + 相连
last_name = "张"
print(last_name + name)
# 字符串多次输出 用 *
print((last_name + name) *... |
2385692ad562e8dabfbbd0d59f86e37998f36ca6 | csalonso/python | /guessing_number.py | 363 | 3.875 | 4 | import random
def guessing_number():
number = random.randint(0, 100)
user_input = int(input('Digite um número: '))
while (user_input != number):
print('Errou')
if(user_input > number):
print('Alto')
else:
print('Baixo')
user_input = int(input('Digite ... |
08008169f146b72c3d28627b05022bd51c0d2128 | Tigul/pycram | /src/pycram/designator.py | 9,145 | 3.515625 | 4 | """Implementation of designators.
Classes:
DesignatorError -- implementation of designator errors.
Designator -- implementation of designators.
MotionDesignator -- implementation of motion designators.
"""
from inspect import isgenerator, isgeneratorfunction
from pycram.helper import GeneratorList
from threading impor... |
750bb3d0f4e64b301a883d02e7c02444306b43b8 | aksh0001/algorithms-journal | /questions/arrays_strings/BinarySearch.py | 750 | 3.921875 | 4 | """
Implement binary search.
@author a.k
"""
from typing import List
def search(A: List[int], target: int) -> int:
"""
Givens a sorted list, A, returns the index of element target.
:param A: list of numbers
:param target: target element
:Time: O(log(n))
:return: index of target if exists.
... |
5f071db3364e823a99acc705e0200a238dc3c4ef | SeanM743/coding-problems | /intpal.py | 392 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 2 20:56:12 2019
@author: seanm
"""
#This version reverses the integer and compares it to the original int. If they are equal it's a palindrome
def intPal(n):
rev = 0
revn = n
while revn >= 1:
x = revn%10
revn = revn//10
... |
551644a423582080c883ea07990bc059d713bb06 | dpctrey/Python | /Core Reference Examples/Exercise Files/02 Quick Start/inherAndPoly.py | 1,527 | 4 | 4 | # Using Inheritance and Polymorphism
class myActions:
def sing(self): return self.strings['sing']
def covering(self): return self.strings['covering']
def speak(self): return self.strings['speak']
def fur(self): return self.strings['fur']
class Dog(myActions):
strings = dict(
sing = "AA... |
53f2c894a6386f857762ce6b39b60f69cf2beebe | prakhar21/Learning-Data-Structures-from-Scratch | /tree/top_view_tree.py | 685 | 3.859375 | 4 | from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def top_view(root, hd, q):
if root == None: return q
if hd in q:
q[hd].append(root.data)
else:
q[hd] = [root.data]
top_view(roo... |
d9cf121ff7809cb336ea4b76a927ce59dde6ead0 | himankjn/DS-ALGO | /Python DS & ALGO/graphs/traversals/bfs,dfs.py | 1,086 | 3.53125 | 4 | from collections import deque
from collections import defaultdict
class Graph:
def __init__(self,V):
self.V=V
self.edges=defaultdict(list)
def addedge(self,src,dest):
self.edges[src].append(dest)
def dfs(self,src):
visited={}
self.dfs_helper(src,visited)
... |
bf62f4c5bbf23e252cf916f55e6428c737ffd3fb | misszhao1121/python-study | /python06_文件操作/01-文件復制附件.py | 334 | 3.734375 | 4 | def copy():
copyfile = input("請輸入你要膚質的文件名")
f = open(copyfile,"r")
strl = f.read()
position = copyfile.rfind(".")
new_file = copyfile[:position]+"附件"+copyfile[position:]
l = open(new_file,"w+")
l.write(strl)
print("復制文件結束")
f.close()
l.close()
copy()
|
cb2316faae4ad6834e004eef8403f31f85f500b1 | inhumanitas/python_course | /material/data_iteration.py | 1,504 | 3.609375 | 4 | # coding: utf-8
# ---------------------------------------------------------------------------
# Iterator
# list iteration
for el in [1, 2, 3, 4, 5]:
print el
lst = range(5)
lst_iterator = xrange(5)
print lst, lst_iterator
for el in lst_iterator:
print el
for el in lst_iterator:
print el
class SimpleI... |
161752a78748403e2b727e2c84cabbe2f884adf5 | u73535508/270201030 | /lab7/example6.py | 297 | 3.96875 | 4 | numbers1 = [2,3,4,20,5,5,15]
numbers2 = [10,20,20,15,30,40]
intersections = []
numbers1=set(numbers1)
numbers2=set(numbers2)
for i in numbers1:
if i in numbers2:
intersections.append(i)
print("Intersection",intersections)
union = list(numbers2)+list(numbers1)
print("Union",set(union)) |
3a30fce72d8aa4482bb7c9ebd3a3a3a42aad12e7 | jeremyosborne/ant_cities | /src/entities/components/facing.py | 759 | 3.5 | 4 | from entities.components.component import Component
from common.calc import Heading
class Facing(Heading, Component):
"""Which direction our entity is facing.
This is in regards to navigational heading where the nose of a ship or
aircraft might not be facing in the vessels velocity direction.
... |
62cd09c212d30ecfec01a10511b8e6e7bfb3dd0e | vitorbarbosa123/lp1-python | /Semana2/cilindro/cilindro.py | 670 | 3.734375 | 4 | # Universidade Federal de Campina Grande
# Bacharelado em ciências da computação - 2020.2e
# Aluno: José Vitor Barbosa Maciel - Matrícula: 120210954
# Atividade-titulo: Área do cilindro
# Objetivo do código:
diametro = float(input())
altura = float(input())
raio = diametro / 2
area_base = 3.141592653589793 * ( rai... |
413fb367029a2873a1f2ba483d8beeef2e4b748b | sdpb/matrix_calculator | /calculator/operations.py | 877 | 3.578125 | 4 | from numpy import transpose
from numpy.linalg import matrix_rank, det
class Operate:
def __init__(self, matrix, operation, scalar=2):
if operation == 'determinant':
self.result = Determinant(matrix)
elif operation == 'rank':
self.result = Rank(matrix)
elif operati... |
18cce10d424a577828eda50680f56a4a6ff502a3 | duzhencai/python_course_old | /GuessNumberGame.py | 880 | 3.90625 | 4 | #!/usr/local/bin/python2.7
import random
def play_game(num):
while True:
a = int(raw_input("please input a number:"))
if a > num:
print "The number is bigger"
elif a < num:
print "The number is zsmaller"
else:
print "You are right!"
... |
072374d81472c8e99f48859e65db0a811579f5f8 | sunita6/python-assignment4 | /assignment4/pythonassignment41.py | 713 | 4.4375 | 4 | print("program to extract substring\n")
string=input("enter a sentence of ur choice:\n").lower()
search_letter=input("\nenter the search letter:").lower()
length=len(string)
index=0
if length>0:
if search_letter in string:
count=string.count(search_letter)
index=string.index(search_letter)
p... |
7909dab2765e176baa1318de046e8b827d47b7dc | betty29/code-1 | /recipes/Python/67671_functiunzip_simple_listlike/recipe-67671.py | 740 | 3.90625 | 4 | def unzip(p, n):
"""Split a list-like object, 'p', into 'n' sub-lists by taking
the next unused element of the main list and adding it to the
next sub-list. A list of tuples (the sub-lists) is returned.
Each of the sub-lists is of the same length; if p%n != 0, the
shorter sub-lists are padded with '... |
14819a37c6526a0239f7bee3419aa399f00f3ae7 | yangboyubyron/DS_Recipes | /zSnips_Python/Plotting/Scatter.py | 301 | 3.765625 | 4 |
#----------------------------------------------------------
# EXAMPLE COMPARE IMPORT METHODS
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6]
y=[2,3,4,5,6,7]
plt.plot(x,y)
plt.show()
import matplotlib.pyplot
from matplotlib.pyplot import plot, show
x=[1,2,3,4,5,6]
y=[2,3,4,5,6,7]
plot(x,y)
show()
|
e78ed299a50f5d893a284fbcecb95891dbf6d716 | meet1509/Hotel-Management-System | /check_in.py | 1,101 | 3.625 | 4 | from tkinter import *
from tkinter import messagebox
from guests import Guest
#gui for check in window
def submit():
gname = str(name.get())
ph = int(phone.get())
room = int(room_no.get())
guest = Guest()
if not guest.check_in(gname, ph, room):
messagebox.showinfo("Room not found", "Room not... |
60ac2210df6235c0e3468538ffe6d28825dce63e | PauloGunther/Python_Studies | /Teorias/5.1_Exemplos.py | 1,755 | 3.90625 | 4 | from time import sleep
from random import randint
# AREA DO TERRENO
def area(x, y):
a = x * y
print(f'A area de um terreno {x}x{y} é de {a:.2f}m².')
a = float(input('Comprimento: '))
b = float(input('Largura: '))
area(a, b)
# FORMACATAO ACOMAPNHA TEXTO
def form(texto): # funcao
tamanho = len(texto)
... |
91dd0759ba0d351ab5aa38dbee41a8d90ea0f3ee | phyrenight/python-practice-projects | /collatz conjecture/collatz conjecture.py | 326 | 3.953125 | 4 | userNumber = int(raw_input("Please choose a number: "))
original = userNumber
steps = 0
while userNumber != 1:
if(userNumber % 2) == 0:
userNumber = userNumber /2
steps += 1
else:
userNumber = (userNumber * 3) + 1
steps += 1
print " To get %s to 1 it took %s steps " % (original, ... |
2334bc92ebaa271ce8789d04f326432e083a6503 | Soulor0725/PycharmProjects | /python3/twoweek/test3.py | 201 | 3.59375 | 4 | #输入数字输出中文星期
weeks="星期一星期二星期三星期四星期五星期六星期日"
n=input("输入数字1-7:")
pos=(int(n)-1)*3
weeksday=weeks[pos:pos+3]
print("是:"+weeksday) |
46005ec7c842c8e92b0bcc4d9e31b471f2c9bd6d | TheCyberMonster/ds-and-algo-in-python3 | /sorting algorithms/merge sort.py | 913 | 4 | 4 | # tutorial link https://www.youtube.com/watch?v=_trEkEX_-2Q
def mergesort(arr):
if(len(arr)>1):
mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
while(i<len(left) and j<len(right)):
... |
0037ce094b4d62c54e9dbe8853f9fd3b4e876093 | assuncaofelipe/Python-DataStructure | /q7.py | 460 | 4.25 | 4 | #coding: utf-8
#!python3
# 7) Converta uma temperatura digitada em Celsius para Fahrenheit. F = 9*C/5 + 32. 8)
# Faça agora o contrário, de Fahrenheit para Celsius.
t_c = int(input('Temperatura em Celcius: '))
t_F = (9*(t_c /5)+32)
print('Temperatura em F: ', t_F)
## conversão de Fahrenheit para Celsius
#... |
68eef874f13808c98034192deec5ada12e2827fa | lychiyu/AdvancePython | /chapter03/self_ex.py | 753 | 3.796875 | 4 | # coding: utf-8
"""
Created by liuying on 2018/9/13.
"""
"""
python自省: 通过一定的机制查询到对象的内部结构
"""
# coding: utf-8
"""
Created by liuying on 2018/9/13.
"""
from chapter03.class_method import Date
class Person:
name = 'Person'
class Student(Person):
name = 'Student'
def __init__(self, school_name):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.