blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
723b78203a20105fcd8297c27d7d5b4520aa3c80 | MelonsAway/todo-manager | /todo/manager.py | 576 | 3.59375 | 4 | class Manager(object):
def __init__(self):
# filename = "testing.txt"
pass
def show():
txt = open("testing.txt")
# print(f"Here's your file {txt}:")
print(txt.read())
txt.close()
def add():
target = open("testing.txt", 'a')
line1 = input()
ta... |
806d552645bd0773a43bad8d5e71731c35e42fc3 | pratimasakinala/python | /python/loop_list.py | 385 | 3.859375 | 4 | def censor(text, word):
result = []
lists = text.split()
print( lists )
for item in lists:
if item == word:
string = ""
for char in item:
string += "*"
result.append(string)
else:
result.append(item)
result = " ".join... |
25c643fcd4e1c128f59eda97a31d0a118856bb18 | knromaric/Algorithms-and-Data-Structure-in-python | /steps/steps.py | 1,111 | 4.34375 | 4 | '''
* Directions
Write a function that accepts a positive number N.
The function should console log a step shape with N
levels using # character. Make sure the step has spaces on the
right hand side!
* Examples
Steps(2):
'# '
'##'
steps(3):
'# '
'## '
... |
d614197c27c764b95120e6c99ef87650c2801bad | queenie88/cs231a-1 | /ps3/hog/main.py | 11,410 | 3.84375 | 4 | import numpy as np
import skimage.io as sio
from scipy.io import loadmat
from plotting import *
import math
'''
COMPUTE_GRADIENT Given an image, computes the pixel gradients
Arguments:
im - a grayscale image, represented as an ndarray of size (H, W) containing
the pixel values
Returns:
angles - ndar... |
fbaf3646e9266f2166ba24b554190a0fbba066c9 | Dervinransiel/Ejercicios_Colecciones_Clases | /Num. menor y mayor.py | 271 | 3.828125 | 4 |
lista = [5,2,40,20,25,10,100,500,60,30]
menor = None
mayor = None
for numero in lista:
if menor==None and menor==None:
menor = numero
else:
if numero < menor:
menor = numero
print(f"El numero menor es: {menor}")
|
3cb39d0fca1874ce2c6eb12f9f81c4f093311982 | omarhatem97/Deep-Learning-Framework | /visualization.py | 353 | 3.8125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def visualize (loss, epochs, learning_rate):
"""
draw graph between number of epochs on x-axis and losses on y-axis
"""
plt.plot(np.squeeze(loss))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(lea... |
33215f0c5e9fe8e26bf7bbfa50453254567b8fda | o-90/project-euler | /200/thirties/one-hundred-and-thirty-four.py | 1,358 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# 134)
# Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that
# 1219 is the smallest number such that the last digits are formed by p1 whilst
# also being divisible by p2. In fact, with the exception of p1 = 3 and p2 = 5,
# for every pair of consecutive primes, p2 > p1... |
ea61304bd295885c5cb4072bbce33f7994cd4fd2 | eshagen/HW06 | /ex03_a.py | 877 | 4.0625 | 4 | #!/usr/bin/env python
# Day 6 ex02
# Read roster.txt and print the number of names containing the letter 'e'
# Function also should print the names
##############################################################################
def print_e():
e_count = 0
e_names = []
# Open file to read
with open("roster.txt" , "r... |
27dd8bc893018d6b5abf8e8d436d58cb984d7e08 | Yongsin0/ai109b | /copy-範例/02-optimize/05-integerProgramming/integerProgramming1.py | 993 | 3.890625 | 4 | # 解決問題 https://en.wikipedia.org/wiki/Integer_programming
from mip import *
m = Model(sense=MAXIMIZE)
x = m.add_var(name='x', var_type=INTEGER, lb=0)
y = m.add_var(name='y', var_type=INTEGER, lb=0)
m += -x + y <= 1
m += 3*x + 2*y <= 12
m += 2*x + 3*y <= 12
m.objective = maximize(y)
m.write('integerProgramming1.lp')
m.m... |
0d8396cedc08420287ff9d294d66c9e82cab050f | host1812/python-tutor | /algorithms/array_pair_sum1.py | 549 | 3.71875 | 4 | import unittest
def pair_sum(lst, n):
result = []
for x in lst:
if x > n: continue
for y in lst:
if x + y == n and (min(x,y),max(x,y)) not in result:
result.append((min(x,y),max(x,y)))
return result
class TestAnagram(unittest.TestCase):
def test_array_pairsu... |
c755923ca87ca5f617558e373b8e15f0f6725971 | madalina-caleniuc/QA--COP | /Part 6.py | 1,287 | 4.09375 | 4 |
# ex1 -the sum of n numbers from user input
print("Ex 1")
n_numbers = input("Enter numbers separated by space ")
numberList = n_numbers.split()
print("All entered numbers ", numberList)
def sum_list():
sum1 = 0
for num in numberList:
sum1 += int(num)
print("Sum of all entered numbers = ", sum1)
... |
1b149e611ae2c92baf3751f081766b88c393a23b | K4153RR/LeetCode-Python | /74 Search a 2D Matrix.py | 793 | 3.78125 | 4 | class Answer(object):'''74. Search a 2D Matrix'''
def searchMatrix(matrix, target):
def _searchMatrix(start, end):
if end <= 0:
return False
elif end == start + 1:
return matrix[start/len(matrix[0])][start%len(matrix[0])] == target
e... |
65781640a4af6eef760909c87bfb9112847d440b | awchisholm/guizero | /eventgui2.py | 894 | 4.03125 | 4 | from guizero import App, TextBox, PushButton, Text, info
app = App()
# Function definitions for your events go here.
def btn_go_clicked():
info("Greetings","Hello, " + txt_name.value)
def btn_go2_clicked():
info("Greetings","Hello, " + txt_name.value + " " + animal_name.value)
# Your GUI widgets go here
lbl_... |
cba95b6770e3acb985f41919e7b201bc1773a3ba | sciarrilli/advent_of_code_2020 | /07/day7_did_not_work.py | 1,493 | 3.765625 | 4 | #!/usr/bin/env python3
with open('input.txt') as f:
data = [line.rstrip() for line in f]
baglist = data
ending_with_gold = []
bagset = []
print(f'length of baglist: {len(baglist)}')
for item in baglist:
if ' shiny gold bags.' in item:
ending_with_gold.append(item)
if ' shiny gold bag.' in item:... |
a17a17544345cbdc5d34a81bbb7f1c823297e2e0 | alvin-qh/leetcode-work | /867.转置矩阵.py | 581 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=867 lang=python3
#
# [867] 转置矩阵
#
from typing import List
# @lc code=start
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
"""
Args:
matrix(List[List[int]]): 输入矩阵
Returns:
List[List[int]]: 转置后的矩阵
... |
55d658a2e097b7043425f2f1b4708fae9fcf336a | Mahfuz2811/Codeforces | /NearlyLuckyNumber.py | 436 | 3.84375 | 4 |
def check_lucky(lucky_number):
lucky_number = str(lucky_number)
lucky_count = 0
for i in lucky_number:
if i == '4' or i == '7':
lucky_count += 1
if lucky_count == len(lucky_number):
return 1
else:
return 0
number = input()
count = 0
for digit in number:
... |
bcc0cd7ed3d483c6116d75a0ecca40be760819a2 | ronakHegde98/InstagramBot | /timefunctions.py | 1,766 | 4.125 | 4 | def time_difference(start, end):
"""
Calculate number of minutes elapsed between two standard time strings
Args:
start: int: start time of task
end: int: end time of task
Returns:
minutes: number of minutes elapsed
"""
#convert standard times into military
start = military_time(start.u... |
44809db0f08304b48488616fcd729e4a247c9750 | SUNKOKLU/Python-Document | /作业/劉孫和作業4,3,2/劉孫和_Python作業2,3/作業3_劉孫和/3.2.py | 245 | 3.84375 | 4 |
# coding: utf-8
# In[1]:
def NonRecursiveGcd(x,y):
while(y):
x , y = y , x % y
return x
a,b,c=input ("Input three numbers: ").split()
a,b,c=int(a),int(b),int(c)
x1=NonRecursiveGcd(a,b)
print("gcd=",NonRecursiveGcd(x1,c))
|
06f36a7a3f2c90bac2aad6afeecd44c72fa49937 | logicxx88/Learnpy | /01-笨方法学python/ex09.py | 224 | 3.703125 | 4 | days="Mon Tue Wed Thu Fri Sat Sun"
months="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days:",days)
print("Here are the months:",months)
print("""
第一行
第二行
第三行
""")
|
4ef9751f83751f9f87d278b8e5bc8634e83a021a | GeorgiyDemo/FA | /Course_I/Алгоритмы Python/Part1/семинары/pract7/task_11_module.py | 1,712 | 3.734375 | 4 | class Task11_1:
"""
Список задается пользователем с клавиатуры.
Удаление из списка элементов, значения которых уже встречались в предыдущих элементах
"""
def __init__(self, DEMKA_class):
self.DEMKA_class = DEMKA_class
self.processing()
def check_digit(self, e):
try:
... |
0ee2e803c4514774f88c7c6693632810db44447f | titojlmm/python3 | /Chapter2_Repetition/2_03_Exceptions.py | 365 | 3.859375 | 4 | try:
print("Input the first term of the division: ")
a = float(input())
print("Input the second term of the division: ")
b = float(input())
c = a / b
except ValueError:
# Si alguno de los términos de la operación no es un número.
c = 0
except ZeroDivisionError:
# Si se intenta dividir por cero. Es decir... |
f8051ffad2139da3fe265bd6327c33dcb31cd57c | rlpmeredith/cn-db-and-api | /databases/Exercise_02.py | 1,795 | 3.84375 | 4 | '''
Using sqlalchemy which the necessary code to:
- Select all the actors with the first name of your choice
- Select all the actors and the films they have been in
- Select all the actors that have appeared in a category of you choice comedy
- Select all the comedic films and that and sort them by rental rate
- U... |
fb94b6834e6cb16711d485062265c9ae3b75dccd | Johnnie-Yeung/Python-for-Data-Analysis | /matplotlib的使用/7_Temperature.py | 922 | 3.890625 | 4 | # 假设通过爬虫你获取到了北京2016年3,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温和随时间(天)变化的某种规律?
from matplotlib import pyplot as plt
y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]
x_3 =... |
3beee85d16a5b1fcdf9c376f40800c3b41b541f0 | jonepl/Investment-Portfolio-App | /app/Stocks.py | 28,618 | 3.765625 | 4 | import datetime
from dateutil.relativedelta import *
import pandas_datareader.data as web
from app.Asset import Asset
from app.Investment import Investment
"""
LINKS:
https://investopedia.com/articles/investing/060313/what-determines-your-cost-basis.asp
https://www.investopedia.com/ask/answers/05/costbasis.asp... |
dbe3fbe61960f69ad3408e820ff6affa8e7bfe45 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4143/codes/1675_1932.py | 456 | 3.96875 | 4 | a = float(input("Distancia dos olhos 1:"))
b = float(input("Distancia entre o narize o queixo 1:"))
c = float(input("Distancia dos olhos 2:"))
d = float(input("Distancia entre o nariz e o queixo 2:"))
e = float(input("Distancia dos olhos 3:"))
f= float(input("Distancia entre o narize o queixo 3:"))
eq1=(a/b)
eq2=(c/d... |
6aee328c9f7266bcf3a74d6b411870b50fcf9fbc | jaybhagwat/Python | /Dictionary/Dict.py | 1,683 | 3.875 | 4 | #WAP to accept a sentence from user and return dictionary containing count of each characters occuring in it.
def Dictionary(inp_str):
result={}
for ch in inp_str:
if result.get(ch) != None:
result[ch] += 1
else:
result[ch]=1
return result
def main():
inp_str=eval(input("Enter a sentence"))
d1=Dict... |
bbcd59e9cf7b8d022f5c0bba0947233e2abfcfd2 | leach/python-demo | /work4/datetime1.py | 235 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
d = datetime.datetime.now()
print(d)
print(d.timestamp())
print(d.today())
print(d.year)
print(d + datetime.timedelta(minutes=100))
print(d + datetime.timedelta(days=100)) |
7b1d6eab5cf431fb84729bddba76993f8c4a9792 | sanidhyamangal/interviews_prep | /code_prep/abstract_structures/linked_list/part_linked_list.py | 1,189 | 4.09375 | 4 | #!/usr/bin/env python
__author__ = "tchaton"
''' This function divides a linked list in a value, where everything smaller than this value
goes to the front, and everything large goes to the back:'''
from .base import Node, LinkedList
def test():
ll = LinkedList()
List = [5, 6, 9, 98, 53, -1, 5, 6]
f... |
30ecf2c82f486f910fbba89134149411cab799ec | apoorvsaini/Coding-Challenges | /three_sum.py | 1,524 | 3.5625 | 4 | #----------INCOMPLETE---------
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
non_zero_list = []
result_list = []
result_set = []
last = 0
second_last = 0
#find consecutive zero ... |
8d5e5305172a318fb76ad199983ab18a96c97403 | giuliana-marquesi/estudo-python | /coursera/retangulo_vazado.py | 642 | 4.25 | 4 | #retangulo
# Escreva um programa que recebe como entradas (utilize a função input) dois números #inteiros correspondentes à largura e à altura de um retângulo, respectivamente. O #programa deve imprimir uma cadeia de caracteres que represente o retângulo informado #com caracteres '#' na saída.
largura = int(input("dig... |
df994bc8b606d38421fa782449a75e8a53631156 | bravandi/python-projects | /graph-sampling/Estimator.py | 3,929 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import sqrt, exp
import random
import scipy.stats
class Estimator(object):
def __init__(self):
self._n = 0
self._M = 0
self._S = 0
def __str__(self):
return '\t{:.4f}\t{:.4f}'.format(self._mean, self.confidence())
de... |
4de88b404dfa1dd185b0344260414818d9f4a19a | harshithkumar2/python_programes | /unlucky_number.py | 519 | 3.5625 | 4 |
def realsum(arr):
sums = 0
leng = len(mylist) - 1
if leng == 0:
return sums
else:
if 7 in mylist:
for i in range(leng):
if mylist[i] == 7:
mylist[i + 1] = 0
mylist[i] = 0
else:
contin... |
0a4c5b903bf20f8a75d4439acbbab36d5bbe653a | gyuvi02/PythonDataExercises | /SVR.py | 1,450 | 3.640625 | 4 | #Importing the libraries
import numpy as np
import matplotlib.pyplot as pl
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Splitting the dataset into Training and Test sets
# from sklearn.model_selection import ... |
9dc10517b96f6c53cb737c152f7dda4f938bb711 | Shikhar15606/AI-melody-generator | /algorithms/genetic.py | 3,072 | 3.84375 | 4 | from random import choices, randint, randrange, random, sample
from typing import List, Optional, Callable, Tuple
Genome = List[int]
Population = List[Genome]
PopulateFunc = Callable[[], Population]
FitnessFunc = Callable[[Genome], int]
SelectionFunc = Callable[[Population, FitnessFunc], Tuple[Genome, Genome]]
... |
dbe270c968e7647dae97255c63b4a83d1b3314b5 | ananya2011/AnanyaPythonPractice | /test4.py | 218 | 3.5625 | 4 | a = input('enter number 1 \n ')
b = input('enter number 2\n')
c = input('enter number 3\n')
d = input('enter number 4\n')
e = (int(a) + int (b) ) - (int (c) + int (d))
print(' The calculation of 4 number is' + str (e)) |
abc325ca593b3b19647d89d63bcc488a7aa17527 | Isabeli10/Programacao | /Python/Exercicio16.py | 405 | 3.96875 | 4 | a = float(input('Digite o primeiro valor: '))
b = float(input('Digite o segundo valor:'))
c = float(input('Digite o terceiro valor:'))
if a+b>c and a+c>b and b+c>a:
if a==b and b==c:
print ("O triângulo é equilátero")
elif a==b or b==c or a==c:
print("O triângulo é isósceles")
else:
... |
8e90e269119a20762ea21f289c612fbe6953d7e3 | yaricom/Plastic-UNet | /src/utils/rle_encode.py | 1,827 | 3.546875 | 4 | # The script to encode bitmap masks using run-length encoding (RLE).
# https://en.wikipedia.org/wiki/Run-length_encoding
import numpy as np
def encode(im):
"""
Performs RLE encoding of provided binary mask image data with shape (r,c)
Arguments:
img: is binary mask image, shape (r,c)
Returns: r... |
d49bd8f3cf68b76236225e3609b9c4797e5913aa | Qooller/Python | /Lesson 4/F no sum.py | 496 | 4 | 4 | # Напишите рекурсивную функцию sum(a, b), возвращающую сумму двух целых неотрицательных чисел.
# Из всех арифметических операций допускаются только +1 и -1. Также нельзя использовать циклы.
a, b = int(input()), int(input())
def sum2(a, b):
if b == 0:
return a
else:
a = a + 1
return su... |
2934e64b15424043762fdeaaa326c04da8e5ab63 | asimkaleem/untitled | /ch5_test.py | 5,631 | 3.71875 | 4 | # coding=utf-8
#example 5.1
#
# n = 5
# while n > 0:
# print "hello there", n
# print "printing condition", n > 0
# n = n-1
# print "Blastof"
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#example 5.1
# n = 10
# while True:
# pr... |
5cbb44de957999f3a96dbf4df3088deb6202065a | gabrieldrakar/organizacao_de_clientes | /organizador.py | 1,166 | 3.6875 | 4 |
import os
if os.path.isdir ('arquivos') == False:
os.mkdir('arquivos')
os.chdir('arquivos')
cwd = os.getcwd()
print (cwd)
arquivo1 =input('nome do arquivo: ') +'.txt'
if os.path.exists(arquivo1) == False:
arquivo= open(arquivo1, 'w+')
elif os.path.exists(arquivo1) == True:
arquivo=open ( arquivo... |
73b10dd9a1e07072945d6a64716e91eab65922be | ComradeMudkipz/lwp3 | /Chapter 4/prettyPattern.py | 550 | 3.703125 | 4 | # Chapter 4
# prettyPattern.py - Draws a pretty pattern.
import turtle
def make_window(color, title):
w = turtle.Screen()
w.bgcolor(color)
w.title(title)
return w
def make_turtle(color, size):
t = turtle.Turtle()
t.color(color)
t.pensize(size)
return t
def draw_square(s):
for ... |
abf04f9a208a912061bdc8ece2199cfa4971bec3 | kinect59/Python-Programming-for-Machine-Learning | /Python/Vectors-Matrices-And-Arrays/calculate_dot_product_between_two_vectors.py | 241 | 4 | 4 | # calculate dot product between two vectors
# Load library
import numpy as np
# Create two vectors
vector_a = np.array([1, 2, 3])
vector_b = np.array([4, 5, 6])
# Calculate the dot product
print(np.dot(vector_a, vector_b))
|
22bcf7266a0b1946375440c77a28ea85cb401672 | jsarraga/HackerRank-Problems | /interview_prep/greedy_luckBalance.py | 1,306 | 3.828125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the luckBalance function below.
def luckBalance(k, contests):
# sort in decreasing order
contests.sort(reverse=True)
luck = 0
for contest in contests:
# we can lose as many uninmportant contests as we want and ... |
f5a3954d34ad3f608820964539f052c90b4e19f5 | Asintesc/PROGRAMACION | /Práctica 6/Ej12.py | 650 | 3.953125 | 4 | #Práctica 6 Ej12
#Albert Sintes Coll
import random
import time
random.seed (time.time ())
minimo = int (input ( "Dime el valor mínimo:"))
maximo = int (input ( "Dime el valor máximo:"))
print('Piensa un número entre %d y %d a ver si lo puedo adivinar: ' %(minimo,maximo))
while True:
numero = random.randint... |
81a9febed882272a5d9f4ff75565c5415b6db14d | alufuredi/Interactive-games-in-python | /memory game.py | 2,165 | 3.578125 | 4 | # implementation of card game - Memory
# The game allows you to open only two cards at a time
# You are expected to remember positions of numbers and match them
# You can find live, working copy at the url below
# http://www.codeskulptor.org/#user47_cW0p0QjRXu_0.py
# Click the play button to start
import simp... |
b0b46de6b0abd79474c1444c383c76af479aac72 | chenlei65368/algorithm004-05 | /Week 3/id_295/LeetCode_127_295.py | 2,469 | 3.828125 | 4 | # 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
#
# 每次转换只能改变一个字母。
# 转换过程中的中间单词必须是字典中的单词。
# 说明:
#
# 如果不存在这样的转换序列,返回 0。
# 所有单词具有相同的长度。
# 所有单词只由小写字母组成。
# 字典中不存在重复的单词。
# 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
# 示例 1:
#
# 输入:
# beginWord = "hit",
# endWord = "cog",
# wordList = ["hot","dot",... |
5984c0ceb97ccb06359773103396ccc151552902 | MrRuban/lectures_devops2 | /Python/samples3/iterators/iter_next.py | 667 | 3.875 | 4 | #!/usr/bin/env python3
str_str = "abcdef"
str_iter = iter(str_str)
print(str_iter == iter(str_iter))
iter_file = open('/etc/passwd')
print( '__iter__' in dir(iter_file) and '__next__' in dir(iter_file) )
iter_map = map(lambda x: x+1, range(10))
print( '__iter__' in dir(iter_map) and '__next__' in dir(iter_map) )... |
58f361d6240b059b695889f14bc3ebefda01c1f1 | DamonTan/Python-Crash-Course | /chapter10/ex10-11.py | 763 | 3.71875 | 4 | import json
def get_new_number():
filename = 'favorite_number.json'
numbers = input("What is your favorite numbers?\n")
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
return numbers
def get_stored_number():
filename = 'favorite_number.json'
try:
... |
3ff7972fe047705e7bc7e2cebc3445a4c73b4999 | DavidZwit/DestructableMapTesting | /python/collision.py | 1,172 | 3.515625 | 4 | import math
import Vector2
def checkIfPointIsInPolygon (testPoint, points) :
returnBool = False
for point in points :
if (point.y < testPoint.y and point.y >= testPoint.y
or point.y < testPoint.y and point.y >= testPoint.y) :
if (point.x +( testPoint.y - point.y ) / ( point.y - ... |
7b086e88cbed309438f6acbce55ad753d38e04fc | villamormjd/data-science | /MathplotlibCourse/MatplotlibExercise.py | 870 | 4.03125 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10)
y = x * 2
z = x ** 2
"""
• Create a figure object callef 'fig' using plt.figure()
• Use add_axes to add an axis to the figure canvas at [0,0,1,1]. Call this new axis ax.
• Plot(x,y) on that axes and set the labels and titles to match the plot.
"... |
677e3bc42ae657b9358f142fc2bc5d84a7de734a | wakashijp/study-python | /Learning-Python3/Chapter05/Section5-1/if_and.py | 427 | 3.90625 | 4 | # randomモジュールのrandint関数を読み込む
from random import randint
size = randint(5, 20) # 5〜20の乱数を生成する。
weight = randint(20, 40) # 20〜40の乱数を生成する。
# 判定(両方の条件がTrueの時合格)
if (size >= 10) and (weight >= 25):
result = "合格"
else:
result = "不合格"
# 結果の出力
text = f"サイズ{size}、重量{weight}:{result}"
print(text)
|
b4925151cfaed1f2e5a95d95c8ddb08f2a60d132 | smirnoffmg/codeforces | /379A.py | 307 | 3.65625 | 4 | # -*- coding: utf-8 -*-
a, b = map(int, raw_input().split(' '))
candles = a
candle_ends = 0
hours = 0
while True:
hours += candles
candle_ends += candles
candles = candle_ends / b
candle_ends = candle_ends % b
if candle_ends < b and candles == 0:
print(hours)
break
|
24b4804cbfb2f3da962ad098f3582a3cff1e6890 | ichnv/ichpython | /game.py | 232 | 3.671875 | 4 | map = [['1','2','3','4'],['5','6','7','8']]
def init():
for i in map:
map[i][:]="-"
def drawMap():
for i in map:
print(i)
#def randomStorage():
#def randomPlayer():
#def checkStorage():
#def move():
#def main():
# intMAp() |
af819ef3d5985bd2e7a74cffef9796a6e7823be9 | yhkl-dev/python-learn-note | /train/question_3.py | 699 | 4.1875 | 4 | """
使用递归和迭代两种方式实现生成斐波那契数列,计算出第100个数字并比较差异。(可选:使用yield关键字完成任务)
"""
def fib_recusive(n):
if n < 3:
return 1
else:
return fib_recusive(n - 1) + fib_recusive(n - 2)
def fib(n):
return fib_iter(1, 0, n)
def fib_iter(a, b, n):
if n == 1:
return a
else:
return fib_ite... |
13036a9e56867cfee78741821b908fef17940f06 | Eileen-Nasert/myEx | /ex32.py | 1,500 | 4.46875 | 4 | print "ex32"
print "Loops and Lists\n"
#creating three lists/arrays (with square brakets and commas)
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # using different data types
# this first kind of for-loop goes through a list (for ak... |
167a40b2ece02dfe6582c36ea7907ea62c0809d9 | Wcksjdk/--------------- | /测试器.py | 182 | 3.546875 | 4 | #__author:"LIN SHIH-WAI"
#date: 2017/10/12
dict1={1:{1,2,3,4,5,6,7,8,9,10,'中国','日本',('泰国','德国')}}
print(len(dict1))
print(len(dict1[1]))
list=[1]
list.append()
print(list) |
93272fc0422fa8ec1a857344f24d045ea7d446b3 | concreted/project-euler | /006.py | 804 | 3.703125 | 4 | """
Project Euler Problem #6
=========================
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum... |
678643abc9f8bc4117bcebfe013f64999cfae391 | digipodium/string-and-string-functions-wahidali7355 | /Q_23.py | 67 | 3.875 | 4 | word = input("")
y=word.count("fyi")
print("it contain ",y,"fyi") |
d580833a918b4b0574191fedbee7457190c06093 | SatishDivvi/Log-Analysis | /loganalysis.py | 2,499 | 3.890625 | 4 | #!/usr/bin/env python3
# "Database code" for the Log Analysis Report.
import psycopg2
def db_connect():
"""
Create and return a database connection and cursor.
The functions creates and returns a database connection and cursor to the
database defined by DBNAME.
Returns:
conn, cur - a tu... |
54a3e66a6e96b2fb0a167cef52b8c31efe8b327d | arsaikia/Data_Structures_and_Algorithms | /Data Structures and Algorithms/Python/LeetCode/Queue Reconstruction by Height Solution.py | 411 | 3.5625 | 4 | import itertools
from typing import List
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
res = []
for k, g in itertools.groupby(sorted(people, reverse=True), key=lambda x: x[0]):
for person in sorted(g):
res.insert(person[1],... |
1cc902959b799e9e690aba59df063fb1a353c0ce | VladimirBa/python_starter_homework | /004_Loop Statements/004_practical_1.py | 314 | 3.875 | 4 | H = int(input('Высота "правого" прямоугольного треугольника: '))
i = 0
while i < H:
j = 0
while j < H:
if j <= H - i - 2:
print(' ', end='')
j += 1
else:
print('*', end='')
j += 1
i += 1
print()
|
d909bf995ec18dfb4cd282945f7d23cd42197820 | vitorponce/algorithms | /graphs_and_trees/binary_tree.py | 3,308 | 4.1875 | 4 |
class BinaryTree(object):
def __init__(self, value, compare=None):
"""
Simple implementation of BinaryTree
Args:
value (any type you want, but be consistent)
Kwargs:
compare (function to compare two values)
"""
self.value = value
... |
bc7a9ec064eb2fd7d7391f9c160d179f2b94cb5d | Shivakumar98/LeetCode | /Top Interview Questions(Easy Collection)/Array/Two Sum.py | 1,634 | 4.09375 | 4 | Given an array of integers nums and and integer target, return the indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], ... |
fa7d25ee0fe56149b9a4b5cc8a08640ea6277174 | green-fox-academy/marijanka | /week-4/Monday/list_sum.py | 182 | 3.90625 | 4 | numbers = [4, 5, 6, 7, 8, 9]
a = sum(numbers)
print(a)
def sum(num_list):
num = 0
for i in num_list:
num += i
return num
numbers = sum(numbers)
print(numbers)
|
6f5433c98caad927a2900142a53ea38a126627b0 | abhishekcodes/ProjectEulersolution | /Mathematical _programming/prob14.py | 852 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 13:49:41 2019
@author: Durgesh
"""
"""def n_even(n):
n = n/2
return n
def n_odd(n):
n = 3*n+1
return n
def seq_length(x):
arr = []
arr.append(x)
return max(arr)
for n in range(1,1000000):
count= 1
while (n!=... |
6a0344fe5946a9a791363e048cc68327c63ff49b | SannatKumar/Python_Coding | /Lists/sorting_list.py | 331 | 4.15625 | 4 | # This program sorts and reverse the numbers
#also checks that it doesn't sorts alphabets or strings
number_list =[500, 5, 27, 1, 15, 9 ]
alphabet_list = ['Dog', 'Zebra', 'Apple', 'kiitos', 'Queen']
number_list.sort()
alphabet_list.sort()
print(number_list)
print(alphabet_list)
number_list.reverse()
print(numbe... |
322c802746b34b55118ffdecb29e35988e4746e4 | tanvigupta5215/imagefilters | /warhol_filter.py | 1,581 | 4.40625 | 4 | """
This program generates the Warhol effect based on the original image.
"""
import random
from simpleimage import SimpleImage
N_ROWS = 2
N_COLS = 3
PATCH_SIZE = 222
WIDTH = N_COLS * PATCH_SIZE
HEIGHT = N_ROWS * PATCH_SIZE
PATCH_NAME = 'images/simba-sq.jpg'
def main():
final_image = copying_patch()
# TODO: ... |
18d2451fa3271e10fa7f9d31e6862070bfe92dd8 | noel7781/ITE4053_DeepLearning | /image classification/image_show.py | 371 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
# 각 숫자 라벨별 class
# 0: airplane
# 1: automobile
# 2: bird
# 3: cat
# 4: deer
# 5: dog
# 6: frog
# 7: horse
# 8: ship
# 9: truck
x_train = np.load("data/x_train.npy")
y_train = np.load("data/y_train.npy")
plt.imshow(x_train[0], interpolation="bic... |
0c286bd36a24a29c6c2bc152aac5e53c9b9d4d87 | martinstangl/iWeek_IntroducingPython | /x01_first_steps/00a_hello_world_basic_data_types.py | 1,742 | 4.34375 | 4 | from datetime import datetime
print("Hello world!") # ein Kommentar
a = 5 # eine variable
print(a)
print(type(a)) # Typ wird zur Laufzeit ermittelt
a = "5"
print(a)
print(type(a)) # Typ wird zur Laufzeit ermittelt
a = True
print(a)
print(type(a)) # Typ wird zur laufzei... |
1480db4910e0c54e1dc6a37355c62a1d146a5ef2 | F8F-Bearcat/Coursera_Discrete_Optimization | /AlgThHW02_App01.py | 5,098 | 3.921875 | 4 | '''
This module is used to create the compute_in_degrees function. This will enumerate the number of
directed edges that point to each node.
'''
import random
def make_complete_graph(num_nodes):
'''
Input: a count of the number of nodes in the desired complete graph
Complete means every node connects to... |
3a31aa8e3b6b0183f97f41fa6555c54db92a6c0a | parulsajwan/python_all | /string.py | 233 | 3.96875 | 4 | #strings are immutable
first_name="parul"
last_name="s"
name=first_name+last_name
print(name)
first_name1="parul"
last_name1=2
name1=first_name+str(last_name)
print(name1)
first_name2="parulsajwan"
print( (first_name2+"\n") *3) |
13815d465d51d5159c14fe0dde596b20613f66c6 | Beckyme/Py104 | /ex20add.py | 1,108 | 4.28125 | 4 | # -*- coding:utf-8 -*-
'''
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(curre... |
a349b744f34ece3d4900565d792690d759f4316e | Cisplatin/Snippets | /euler/python/P40.py | 593 | 3.828125 | 4 | """
Champernowne's Constant
Problem 40
"""
BASE = 10
MINIMUM, MAXIMUM = 0, 6
if __name__ == '__main__':
# We first calculate the constant as a string. Because numbers have more
# than one digits, we estimate that we only need to calculate up to 10^5
constant = reduce(lambda x, y: x + str(y), xrange(BASE *... |
2ebd2c25b0f4b3f47242afe83cb3a5e0651aeedf | ops-guru/workshops | /instructor/azure/101/setup_scripts/strip_emails/strip_emails.py | 269 | 3.53125 | 4 | # Call this function with a list of student emails
def strip_emails(email_list):
import json
new_list = []
for email in email_list:
formatted = email.split('@')[0]
new_list.append(formatted)
final = json.dumps(new_list)
print(final) |
f80cd668f0f34c37056947973285568f5d5fd6cd | hyperprism/Stepik | /Stepik/Unit_3 Функции. Словари. Интерпретатор. Файлы. Модули/27.py | 625 | 4.125 | 4 | '''Напишите функцию modify_list(l), которая принимает на вход список целых чисел, удаляет из него все нечётные значения, а чётные нацело делит на два. Функция не должна ничего возвращать, требуется только изменение переданного списка, например:'''
def modify_list(l):
a = 0
x = len(l)
while a < x:
i... |
05ddc789c3d659c5a6f3731a649b1b167d9e9428 | Aasthaengg/IBMdataset | /Python_codes/p03080/s695262582.py | 165 | 3.53125 | 4 | N = int(input())
s = input()
red = 0
blue=0
for c in s:
if c=='R':
red+=1
else:
blue+=1
if red>blue:
print("Yes")
else:
print("No") |
748d137cd6ac9e9000ceae84a68343a04b18bccc | kawasaki2254/Python_100problem_practice_problem | /基本文法/No.9.py | 360 | 3.890625 | 4 | '''
問題9.問題6で出力していた数字(=3の倍数)を持つ
「辞書」を作成しましょう。作成する辞書は、以下のように
{◯番目:数値}の形にします。
'''
d = {}
for i in range(1, 31):
if i % 3 == 0:
index = f'{i // 3}番目'
d[index] = i
print(f'作成したリスト : {d}') |
601434968de8abb55e70abe6719888d3d2448bdc | irhadSaric/Instrukcije | /stringovibrojevi.py | 296 | 3.625 | 4 | n = int(input())
proizvod = 1
while n != 0:
zadnja = n % 10
if zadnja % 2 != 0 and zadnja < 6:
proizvod *= zadnja
n //= 10
print(proizvod)
n = input()
proizvod = 1
for cifra in n:
if int(cifra) % 2 != 0 and int(cifra) < 6:
proizvod *= int(cifra)
print(proizvod) |
13e56b592ff6bed783b07bcde5ebffd2b57afb25 | sanatbatra/ArtificialIntelligenceAssignments | /assgn1_iterative_deepening_hill_climbing.py | 7,214 | 3.671875 | 4 | import random
def read_input():
f = open("input_assignment1", "r")
task_lengths = [float(length) for length in f.readline().split(' ')]
processor_speeds = [float(speed) for speed in f.readline().split(' ')]
third_line = f.readline().split(' ')
deadline, target = float(third_line[0]), float(third_li... |
1eaf50720a1bb92473bebe2f94e36e7fdd09e80f | mjr/python-para-zumbies | /q06.py | 376 | 3.515625 | 4 | # -*- coding: utf-8 -*-
dst_a_pcr = int(input('Qual distância a percorrer(em km)? '))
vlc_mda_esp = int(input('Qual a velocidade média esperada para a viagem(em km/h)? '))
def tempo(distancia, velocidade):
return distancia / velocidade
tempo_da_viagem = tempo(dst_a_pcr, vlc_mda_esp)
print('O tempo da viagem será... |
d23664342bfa2f97a34a088bfd839a10628a9362 | shirsho-12/Machine-Learning-Basics | /perceptron.py | 1,542 | 3.75 | 4 | # Algorithm using Rosenblatt's perception rule
import numpy as np
class Perceptron():
"""Perceptron classifier
Parameters:
l_rate - learning rate (between 0.0 and 1.0)
n_iter - passes over the training dataset, i.e epochs
Attributes:
w_arr_ - 1d array of weights after fittin... |
0e7cd86bb2a5ddad011a4923e5fc25750e179164 | bai3/arithmetic | /每日一码/2.11.py | 541 | 3.671875 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
a = [pRoot]
d = 0
while a:
... |
6e1d51631bc1179082454c494e97fb8050deef8f | kawashima-mozart/python_app | /maze_show.py | 1,253 | 3.75 | 4 | from tkinter import *
tile_size = 20
#迷路データを取り込む
def load_map_data():
from maze_data import data
return data
#迷路を表示
def draw_map(cv,data):
#左から右下へと描画
rows = len(data)
cols = len(data[0])
for y in range(rows):
y1 = y *tile_size
y2 = y1 * tile_size
for x in range(cols):
x1 = x * tile_size... |
7f357ed1756a8f1a37cbc8411ac2d281900af75d | DianaG98/PythonExamples | /ejercicio3.py | 130 | 4 | 4 | n=0
acum=0
while(n<5):
numero=float(input("Ingresa calificacion: "))
acum=acum+numero
n+=1
print("El promedio es: ",acum/5) |
18784dae3bcdc9a392b10d23246cf50cd44b67de | bennettjs/Blockchain | /blockchain.py | 5,726 | 3.828125 | 4 | ### Understanding blockchains by building one.
# Core concept: chunks of data (blocks) chained together with unique hashes.
# Within each block is a hash backwards to the previous block. This gives the
# chain immutability: If a previous block was compromised, all subsequent
# blocks would have the incorrect hash.
# P... |
f2186ef86b239363ff6f69a89ec4512b2ee44ffc | carlshan/puzzles | /advent_of_code/2020/day13/day13.py | 1,954 | 3.890625 | 4 | """
Advent of Code 2020
Author: Carl Shan
Day 13: Shuttle Search
"""
raw = open("day13.in").read().splitlines()
timestamp = int(raw[0])
buses = [int(elem) for elem in raw[1].split(',') if elem != 'x']
def part1(timestamp, buses):
earliest_times = [(timestamp // bus) * bus + bus for bus in buses]
earliest = e... |
55f6a4d52f1dd8e7ca22d6a84d90948c8f9abafd | Heathercoraje/EDX-Introduction-to-Computer-Science-and-Programming-Using-Python | /week2/pset2/problem3.py | 686 | 4.0625 | 4 | monthlyInterestRate = annualInterestRate/12.0
newBalance = balance
lowerBound = balance/12
upperBound = (balance*((1+monthlyInterestRate)**12))/12
while (newBalance > 0):
newBalance = balance
month = 1
target = round((lowerBound + upperBound)/2,2) # by cent
while (month <= 12):
newBalance -= t... |
b7c60cc965567bc6e4fdd10c7b772c59dd69fe20 | lintanghui/leetcode | /algorithms/python/reverse/reverse.py | 791 | 3.578125 | 4 | """
Source: https://leetcode.com/problems/reverse-integer/
Author: Lin Tanghui
Date : 2015/11/1
"""
"""
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
... |
c2355e414c5711275a01ba3f7a79c75117762653 | andyc1997/Data-Structures-and-Algorithms | /Data-Structures/Week6/is_bst.py | 3,255 | 4.09375 | 4 | #!/usr/bin/python3
import sys, threading
sys.setrecursionlimit(10 ** 8) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
# Task. You are given a binary tree with integers as its keys. You need to test whether it is a correct binary
# search tree. The definition of the bin... |
5196cd3c735d2b79ac1b88ed074d090e8b66e5a6 | madeibao/PythonAlgorithm | /py数组中的奇数和偶数来相互的交换.py | 378 | 3.671875 | 4 |
# 数组中的奇数和偶数来进行相互的交换。
class Solution(object):
def exchange(self,nums):
i, j = 0,len(nums)-1
while i < j:
if nums[i]%2==0:
i+=1
elif nums[j]%2==1:
j-=1
else:
nums[i],nums[j] = nums[j], nums[i]
i+=1
j-=1
return nums
if __name__ == '__main__':
s = Solution()
nums = [1,2,3,4]
pri... |
e2c864e1d5a3068d165e6d35ae21b36181edb079 | Nambyungwook/Algorithm_python | /Baekjoon_11651.py | 258 | 3.546875 | 4 | N = int(input())
location = []
for i in range(0, N):
x, y = map(int, input().split())
location.append([x, y])
sortedLocation = sorted(location, key=lambda x:(x[1], x[0]))
for i in range(0, N):
print(sortedLocation[i][0], sortedLocation[i][1]) |
62ecda0fc9f1dc78aec264f7139f7df6d7e1d207 | xia0nan/CodeWars | /001.py | 1,042 | 3.9375 | 4 | """
Day 1: 2019-04-12
Title: Your order, please
Link: https://www.codewars.com/kata/your-order-please/python
Description:
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 wi... |
5b3698c04a12f1005da121348474a08f19320084 | cromox1/rosalind | /bs13LCSM.py | 2,661 | 3.65625 | 4 | __author__ = 'cromox'
'''
( http://rosalind.info/problems/lcsm/ )
Problem
A common substring of a collection of strings is a substring of every member of the collection. We say that a common
substring is a longest common substring if there does not exist a longer common substring. For example, "CG" is a
commo... |
60fc6311e8dcc18d3013a89a41102aca4a147132 | AlanViast/Python_Note | /CH3/readTextFile.py | 453 | 4.125 | 4 | #!/usr/bin/env python
'readTextFile.py -- read and diaply text file'
import os
# get filename
fName = raw_input("Enter a file name > ")
print
if not os.path.exists(fName) :
print "File not found"
else :
try:
fObj = open(fName)
except IOError, e:
print " *** file open error ***", e
el... |
8211af9a69577a20a17c75d36c3dc076d3b1b468 | Jamboii/wireless-driveway-security-system | /integration/file1.py | 3,949 | 3.5625 | 4 | #!python3
# essentially the cellular script
# reads in file contents, sends file, deletes file from existence, looks for new contents
# also can receive commands from the aether (some phone) and give them to the Mot. System
# these commands will be stored in another file
import os
import sys
import time
import cv2 as... |
e45a66877efc9b89b7f91ce219c4236deeab67f4 | NFEL/DjangoPaeez99 | /W2/linked_list.py | 1,744 | 4.0625 | 4 | class Element:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.root = None
self.length = 0 # Optional
def __increment_length(self):
self.length += 1
def add_begin(self, elm):
if self.root == None:... |
149dfb6539b234b6e1aa84b9416030523213092f | DinoBektesevic/nbody | /nbody/particle.py | 5,644 | 3.875 | 4 | import numpy as np
class Particle:
"""
Describes a hard-sphere-like particle with position, velocity, mass and
radius in 2D space.
Usage:
a = Particle(position, velocity, radius, mass)
b = Particle((x, y), (vx, vy), r, m)
dt = a.dt2Hit(b)
a.move(dt)
b.move(dt)
... |
bb5e575d4eac63d3986e338d6da0dba6505a73db | DeeMATT/PythonExercises | /iter.py | 254 | 3.875 | 4 | data = [1, 2, 3, 4, 5]
i = iter(data)
while i:
try:
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
except StopIteration:
print('end of iteration') |
e237fc216434c2d191f4a1a82d09cc78567ffad2 | mediumwolf/adventure_game | /Text Adv Game/rpg/room.py | 2,181 | 3.65625 | 4 | class Room():
def __init__(self,room_name):
self.name = room_name
self.description = None
self.linked_rooms = {}
self.character = None
self.item = None
def set_description (self, room_description):
self.description = room_description
def ge... |
7a58aea9d8c61383daa98784b63136fc7768e2dc | Heenjiang/python_tutorial | /sourceCode/manipulating_files_directories.py | 1,464 | 4.0625 | 4 | '''
What if you want to manipulate these direcories and files in a Python program?
In fact, the commands provided by the operating system just simply call the interface functions
provided OS, and also Python has some built-in modules can directly call those interface funcions
provided by operating system
Like os,os.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.