blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2ea23abd8086888898e9990be20ba11ebadd02e2 | rostam/Experiments | /python/python-code-samples/TestingEvaluationML/anotherTest.py | 5,977 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Diabetes Case Study
#
# You now have had the opportunity to work with a range of supervised machine learning techniques for both classification and regression. Before you apply these in the project, let's do one more example to see how the machine learning process works fro... |
4d09c4c6782c12470c7ad19b72fb89443acdd978 | QinmengLUAN/Daily_Python_Coding | /wk11_HT_uniqueOccurrences_LC1207.py | 1,056 | 3.953125 | 4 | """
1207. Unique Number of Occurrences
Easy: Hash Table
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1.... |
0209d97e93a70d10bdb739783605bba86104327d | marioleonardo/informatica_1_lab | /laib3/es6.py | 321 | 3.71875 | 4 | import math
num = float(input("Qual è il numero?\n"))
num = math.ceil(num)
if (num <= 4 and num >= 0):
print("A" if num == 4 else "", end="")
print("B" if num == 3 else "", end="")
print("C" if num == 2 else "", end="")
print("D" if num == 1 else "", end="")
print("F" if num == 0 else "", end="")
|
9006f0371809f41105ebb23c3ca395ee86772882 | qzying/leetcode-private | /python/best-time-to-buy-and-sell-stock-iii.py | 1,870 | 3.75 | 4 | r"""
给定一个数组,它的第i个元素是一支给定的股票在第i天的价格。
设计一个算法来计算你所能获取的最大利润,你最多可以完成两笔交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入:prices = [3,3,5,0,0,3,1,4]
输出:6
解释:在第4天(股票价格 = 0)的时候买入,在第6天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3。
随后,在第7天(股票价格 = 1)的时候买入,在第8天(股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3。
示例 2:
输入:prices = [1,2,3,4,5]
输出:4
... |
edcf8b46cb6b094d6bb14c1f55a68230c42a7aaa | BackupTheBerlios/elisa-svn | /trunk/elisa/utils/misc.py | 438 | 3.515625 | 4 | import os
def file_extension_matches(filename, pattern_list):
path, extension = os.path.splitext(filename)
# strip ext separator
extension = extension[1:]
extension = extension.lower()
return extension in pattern_list
def file_is_picture(filename):
return file_extension_matches(filename,('jpg'... |
670a71dd45009dd3cc1b73174c4b093c0a90805a | tcandzq/LeetCode | /Stack/ReverseSubstringsBetweenEachPairOfParentheses.py | 1,202 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# @File : ReverseSubstringsBetweenEachPairOfParentheses.py
# @Date : 2020-02-25
# @Author : tc
"""
题号 1190. 反转每对括号间的子串
给出一个字符串 s(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
示例 1:
输入:s = "(abcd)"
输出:"dcba"
示例 2:
输入:s = "(u(love)i)"
输出:"iloveu"
示例 3:
输... |
b1928474f0b8fca4f0cb0ac1705b8c58c8b09e6c | gohst9/misc | /my_queue.py | 1,412 | 4.21875 | 4 | class Queue_item:
#キュー内の要素にはそれ自体の値と次の値へのリンクがある
def __init__(self,v,next=None):
self.value = v
self.next = next
class Queue:
def __init__(self,v=0):
self.first = None
self.last = None
def push(self,v):
#キューの一番後ろに値を付け足す
if self.first == None:
se... |
ac5d146845124c159ccee1090552add807fd87eb | jmaitoza/ECE256_Lab2 | /Lab2/caesar_encrypt.py | 1,248 | 4.09375 | 4 | #!/usr/bin/env python3
import os
import sys
shift = int(sys.argv[1])
plaintext = open("plaintext.txt", "r") #opens plaintext file
plntxt = plaintext.read().strip()
encrypted = ""
for c in plntxt:
# if not c.isalpha():
# pass
# continue
#if c.isupper(): # checks if plain text is capital letters
c_uni = ord(c) #... |
70167c3c529371165544332fd791aa5ddf66cec0 | plenari/omfPython | /mpy0.0/fit_circle.py | 2,952 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
计算excel文件里铁磁斯格明子的直径,只能含有一个斯格明子
>>>main(path,length=[0,1000],step=2e-9,name='M%d.xlsx',dname=3):
>>>length[start,stop],
>>>这个只能处理方格的情况,每隔格子的长度为step
>>>dname:希望用输入路径中倒数第几个来命名结果,比如:
>>>D:\\relax700\\relax250Hz700\\txt\\excel,倒数第三个,所以dname=3
>>>step,保存到excel的直径将乘以这个数字
>>>name,文件的格式,数字用%... |
0a25cecdfdf8f6eae74ce90af5971649d0da15d0 | SalahCoder/Rock-Paper-Scissors | /main.py | 1,488 | 4.09375 | 4 | import random
option_choosen = int(input("what do u choose \n type\n 0 for Rock ⚫️ \n 1 for paper 📄\n 2 for scissors ✂️ : "))
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)... |
7d39b12fb86bfcf572329dca9ae91c83da28c75e | ElshadaiK/Competitive-Programming | /red_and_blue.py | 687 | 3.65625 | 4 | def maximizer(reds, blues):
red_sum = 0
blue_sum = 0
max_red = 0
max_blue = 0
for red in reds:
red_sum += int(red)
max_red = max(max_red, red_sum)
for blue in blues:
blue_sum += int(blue)
max_blue = max(max_blue, blue_sum)
return max_blue+max_red
if __nam... |
d4e5b77c4a5c8e22ed20ca0e6c80a74e1dbf0780 | jjlicky/python-basic | /파이썬 기초(조건문,반복문,복합자료형,함수)/함수예제 sumAll3.py | 157 | 3.5 | 4 | def sumAll(*values):
sum=0
for i in values:
sum+=i
print("1부터 10까지의 합은 %d 입니다."%(sum))
sumAll(1,2,3,4,5,6,7,8,9,10)
|
e4ed7b98a241eedea5d0dc9420c788c52419a833 | Prakashchater/Daily-Practice-questions | /largest.py | 1,167 | 3.859375 | 4 | # def large1(arr):
# mx = arr[0]
# for i in range(len(arr)):
# if arr[i] > mx:
# mx = arr[i]
# return mx
#
# if __name__ == '__main__':
# arr = [70, 11, 20, 4, 100]
# print(large1(arr))
# def large2(arr):
# mx = max(arr[0], arr[1])
# secmx = min(arr[0],arr[1])
#
# f... |
3c313bd2c0d10b1ffa8686c3c9fe523b28a43a75 | aswaniramachandran/programming-lab-aswani | /CO1 PG 13.py | 176 | 3.65625 | 4 | n=int(input("Enter a limit:"))
print(f"Enter {n} colour names:")
c=[]
for i in range(0,n):
c.append(input())
for i in range(0, n):
print(c[0],c[n-1])
break
|
a9f37012ed908abdc5db839bc1d9a2ea4156dcd2 | ahatzz11/advent-of-code | /2019/02/two.py | 1,477 | 3.59375 | 4 | #!/usr/bin/env python
# part one: 3402634
# part two: 5101069
import sys
def main(args):
f = open("input.txt","r")
instructions = f.read().split(",")
i = 0
for instruction in instructions:
instructions[i] = int(instruction)
i += 1
current_index_offset = 0
while(instructio... |
cf912e0a6b85487110eca93a0be942a8185c33a4 | LucasMaiale/Libro1-python | /Cap3/Programa 3_29.py | 1,329 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Solución del problema 3.29
Calcula e imprime el costo de un paquete turístico de acuerdo
con el destino, el nivel y la cantidad de días de duración.
"""
destino = input('Ingrese el tipo de destino (playa/colonial/arqueológica): ')
nivel_paquete = input('Ingrese ... |
d379cfc6f12a7bfe6edc398c146dbf16fc86c578 | katesem/sololearn | /us_date_to_eu.py | 461 | 3.78125 | 4 | s = input()
if '/' in s:
s = s.split('/')
print(('/').join([s[1],s[0],s[2]]))
else:
d = {
"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
... |
042d46b3933a28a92448696bf6fffe96a648d9a1 | BurlaSaiTeja/Python-Codes | /Lists/Lists06.py | 228 | 4.28125 | 4 | """
Write a Python program to generate all permutations of a list in Python.
"""
import itertools
print(list(itertools.permutations([1,2,3])))
"""
Output:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
"""
|
a1dcfdcf71ead60e6957be78bf81baeecd27b3a9 | Abhijit2505/Survival-Analysis | /Abhijit/Nelson Aalen Estimator/NA_estimator.py | 2,684 | 3.609375 | 4 | # importing the required python libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from lifelines import NelsonAalenFitter
# reading the data into python dataframe
telco_data = pd.read_csv('telco_customer.csv')
# filtering and preparing the data to the required form... |
bfb6ba4f9b944beee17cf3609107882c7a3c1c96 | ataylor89/leetcode | /problem0110.py | 1,476 | 3.546875 | 4 | class Solution(object):
def isBalanced(self, root):
if root == None:
return True
self.assignHeight(root)
if root.left == None and root.right == None:
return True
elif root.left != None and root.right == None:
return root... |
c157ab69c10a9d670ff2a28653ad592e22d00fa7 | avinash-mishra/codeInPython | /pythonConcepts/os_module.py | 1,361 | 4.46875 | 4 | # Creating and removing files and directories with Python os module
"""This is done with the os module, which has lots of methods for handling files and dirs"""
import os # this line will import os module
# Make a new file.
# Simply opening a file in write mode will create it at specified location, if it doesn't exi... |
659fca32acee07d20c8ef117512d6f06d238fe16 | BROjohnny/Python-A-Z-and-BasicPrograms- | /10 Dictionary/dictionary.py | 515 | 4.15625 | 4 | #this is how to define dictionary in python
pythonDic = {}
#this is how add values for dictionary
pythonDic = {'janidu' : 'most kind person i ever met' , 'yoshini' : 'most angryful girl i ever met'}
print(pythonDic.items())
print(pythonDic.keys())
print(pythonDic.values())
pythonDic['hansika'] = 'she is pretty but ... |
21a1707916b1019e4d08fa2d0c028edb7a6fed00 | jasonlingo/RoadSafety | /Map/Shapefile.py | 879 | 3.71875 | 4 | import shapefile as shp
def ParseShapefile(filename):
"""
Extract GPS points from a shapefile.
Args;
(String) filename: the address of a shapefile.
Return:
(list) shapePoint: a list of GPS point in the given shapefile.
"""
# Read the shapefile and get its shape records.
ctr =... |
2b079fa9f884419fba9061341f0e8200390dbcdd | jack-x/HackerEarthCode | /E_NotInRange.py | 2,388 | 3.625 | 4 | '''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
def sumNatural(num):
return int(num*(n... |
13fbaa6dc28208e99f2c170776df929d28a40ede | jineshpaloor/ProjectEuler | /p07.py | 841 | 3.953125 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
def main():
# n = 6
# p = 13
# while n < 10001:
# p = p + 2
# is_prime = True
# for i in range(2,p/2 + 1):
# if p % i == 0:
# ... |
6b3820b099a6d33c188d8441145dbdf2a7d52bec | liorbraun/wordplay | /Functions_Logic.py | 2,040 | 3.625 | 4 | import random
import pandas as pd
from player import add_player
from wordgame import listofplayers
def add_player_func(playername, word, opponent):
try:
add_player(playername, word, opponent)
except:
pass
def get_random_word():
try:
for player_word in listofplayers:
... |
1a6dd83c2de641d61f367260cbd1e381956f5034 | jgarte/Python | /Chapter 03/substitutecrypt.py | 263 | 3.8125 | 4 | def substitutionEncrypt(plainText,key):
alphabet = "abcdefghijklmnopqrstuvwxyz "
plainText = plainText.lower()
cipherText = ""
for ch in plainText:
idx = alphabet.find(ch)
chipherText = cipherText + key[idx]
return cipherText
|
458aa7b7e8015db201c1c8563d93c48d849cd634 | moodycam/MARS-5470-4470 | /Hopkins/Homeworks/Week 3/Hopkins_Exercises_WK3.py | 4,235 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 14:52:51 2019
@author: srv_veralab
"""
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
person = input('Enter your name:')
#%%
"""
Exercise 1
"""
def scary():
person = input('Enter your name: ')
# Creates ... |
9bb843ef70a895d700911c9e0bddb50f661e8af4 | laxur1312/py4e | /ex_07_01.py | 244 | 3.765625 | 4 | print('python shout.py')
fname=input('Enter a file name: ')
try:
fhandle=open(fname)
except:
print('Archivo no encontrado')
exit()
for line in fhandle:
rline=line.rstrip()
rline=rline.upper()
print(rline)
|
f71986ca7dd932abde2d6f7f95646ee246375328 | shehryarbajwa/Algorithms--Datastructures | /Algorithms-Project 1/Task3.py | 2,893 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('/Users/shehryarbajwa/algorithms-challenges/texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('/Users/shehryarbajwa/algorithms-challenges/calls.csv', 'r') as f:
reader... |
2cfa7b3b6a9288d3b6ce7f68943ddc1ec0d38b10 | abhicse32/SPOJ_codes | /DIVCHK.py | 280 | 3.96875 | 4 | num= input()
for i in range(num):
str_=raw_input()
div=input();
len_=len(str_)-1;
two=1;
num_=0;
while len_ >=0:
num_+=int(str_[len_])*two;
two*=2;
len_-=1
#print (num_)
if num_%div==0:
print ("\nDivisible By %d"%div)
else:
print ("\nNot Divisible By %d"%div)
|
6ff46cb8e308a6981806070bae61917799e420b2 | Anirban2404/LeetCodePractice | /621_leastInterval.py | 2,048 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 14:38:35 2019
@author: anirban-mac
"""
"""
Given a char array representing tasks CPU need to do. It contains capital
letters A to Z where different letters represent different tasks. Tasks could
be done without original order. Each task could b... |
6b54d7ae0e3df857db649e5616523be341eefd2e | fabiovpcaumo/curso-de-python | /semana04/aula02/exercicio_10.py | 3,384 | 3.796875 | 4 | """
Classe Bomba de Combustível: Faça um programa completo utilizando classes e métodos que:
Possua uma classe chamada bombaCombustível, com no mínimo esses atributos:
tipoCombustivel.
valorLitro
quantidadeCombustivel
Possua no mínimo esses métodos:
abastecerPorValor( ) – método onde é informado o valor a ser abastecid... |
d0cb8cf48b393d29401b23dd7a098329029e64bb | Sewez/projecteulersol | /prob4.py | 1,327 | 3.953125 | 4 | # Problem 4
# Find the largest palindrome made from the product of two 3-digit numbers.
# Function to check palindomic numbers
def check_palin(int_list):
j = 0
# Simple loops to compare the current value for it's mirror in the list
for i, x in enumerate(int_list):
if i == (len(int_list) - 1 - i):... |
64bdffc88dd3b3fc3ea5f967d016477141ee9643 | abrosen/classroom | /itp/spring2021/gobbler.py | 4,489 | 3.921875 | 4 | class Player:
def __init__(self, color):
self.color = color
self.pieces = []
self.pieces.append(Piece(color,3))
self.pieces.append(Piece(color,3))
self.pieces.append(Piece(color,2))
self.pieces.append(Piece(color,2))
self.pieces.append(Piece(color,1))
... |
18bff0d9c0ee4fb8b6609bdddac547a8d5172fbc | Rajan-Chaurasiya/Python-Practice | /splitex.py | 116 | 3.703125 | 4 | filename = input("enter a file name: ")
f_exten = filename.split(".")
print("the extension is: " +repr(f_exten[-1])) |
653545660ac6e8f2707ac4d1c913812c19626edd | aymane081/python_algo | /arrays/contains_duplicates.py | 531 | 3.640625 | 4 | class Solution(object):
def contains_duplicates(self, numbers):
number_set = set(numbers)
return len(numbers) != len(number_set)
def contains_duplicates2(self, numbers):
"""
:type numbers: list
:rtype : Boolean
"""
numbers.sort()
for i in range(1... |
deed9b7d5cb6bdb260cfba2165767bd8f0061878 | shangjiadong/algorithm | /numBitStrings/bitstrings.py | 896 | 3.96875 | 4 | """
3. Number of bit strings of length n that has
1) no two consecutive 0s.
2) two consecutive 0s.
>>> num_no(3)
5
>>> num_yes(3)
3
[HINT] There are three 3-bit 0/1-strings that have two consecutive 0s.
001 100 000
The other five 3-bit 0/1-strings have no ... |
421053db4de77630c3aeb7309ae830896bf46deb | vishalagrawalit/Competitive-Programming | /Codechef-June_Challange-2017/Triplets.py | 1,716 | 3.546875 | 4 | def binarySearch(arr, l, r, x):
if l>r:
return -1
if x>=arr[r]:
return r
mid = (l+r)//2
if arr[mid]==x:
return mid
if mid>0 and arr[mid-1]<= x and x<arr[mid]:
return mid-1
if x<arr[mid]:
return binarySearch(arr, l, mid-1, x)
return binarySearch... |
ac1350ea905e0fd409f24e4542cd661bf014fb6d | kayvera/random_python_files | /name_cases.py | 601 | 3.765625 | 4 | full_name = "Mikayla Rivera"
message = "Hello " + full_name + "," + " is the coolest ever!"
print(message)
print(full_name.title())
print(full_name.upper())
print(full_name.lower())
print('\tWarren Buffett once said,"Price is what you pay.\n\tValue is what you get."')
famous_person = "Warren Buffett"
mess... |
aebcdc6d32100c50f30dc123668b20850e6559b3 | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/shmken002/question2.py | 414 | 4.1875 | 4 | # program to check the validity of a time entered by the user as a set of three integers
#shimabukuro kenneth
#28 february 2014
hours = eval(input("Enter the hours:""\n"))
minutes = eval(input("Enter the minutes:""\n"))
seconds = eval(input("Enter the seconds:""\n"))
if (0 <= hours <= 23) and (0 <= minutes <= 59... |
2528eef32d526d21201252ed2256a842c5f2216c | NikheelP/Spark_ | /spark/widget/sample/sample_color_variable.py | 9,494 | 3.625 | 4 |
class COLOR_VARIABLE_CHILD():
def __init__(self, value):
self._color_value = value
@property
def set_value(self):
'''
return the color value
'''
return self._color_value
def get_value(self):
'''
return the color value
'''
return ... |
96729bbbf26ddbb2c41a592e8bd426523f3d4b9b | Arthurmf01/PROGRAMING-WITH-PYTHON- | /Exercices | 347 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 14:35:38 2018
@author: arthurmaroquenefroissart
"""
#%%
def linear(number, lst):
for i in range(len(lst)):
if number == lst[i]:
return i
return None
def hello():
name = input("What's your name ? ")
p... |
e20ca2cb2b36e99f94bb9ef206851cd49793915c | vilaron/Complejidad2020II | /clase_2/bfs.py | 779 | 3.625 | 4 | #cada posicion de la lista representa a un nodo y lo que hay en esa posicion representa los nodos adyacentes a ese nodo
#lista de adj, visitados y cola o queue
#grafo no dirigido
adj = [
[1,2],
[0, 3 , 4],
[0 ,4 , 5],
[1, 6],
[1 , 2 , 6 ],
[2 ,6],
[3 , 4 , 5]
]
visitados = [False] * len... |
27c7733ac3ab2c6ee367eb537c65b76ffb73a5c3 | ryzzhov-al/TaskStepik | /Taskstepik.py | 3,122 | 4.09375 | 4 | """
Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...
(число повторяется столько раз, чему равно). На вход программе передаётся неотрицательное
целое число n — столько элементов последовательности должна отобразить программа.
На выходе ожидается последовательность чисел, зап... |
26116f1b8924c50c70a09e215e4386f5fc81edb3 | scrypti/Udacity | /ArtificialIntelligence/Localization/kalman_filters.py | 1,931 | 3.703125 | 4 | from math import *
import warnings
# make predictions about future positions
# measurement meant updating our belief (and renormalizing our distribution).
# motion meant keeping track of where all of our probability "went" when we moved
# Kalman Filter:
# measurement update: bayes rule (multiplication)
# motion upda... |
2bab9a82b515cff5eaa7f1e179987b026f2f3d09 | Liza333/Python | /laba 1/Task9.py | 1,508 | 3.625 | 4 | # Напишите программу, имитирующую работу банкомата. Выберите
# структуру данных для хранения купюр разного достоинства в заданном
# количестве. При вводе пользователем запрашиваемой суммы денег,
# скрипт должен вывести на консоль количество купюр подходящего
# достоинства. Если имеющихся денег не хватает, то необходимо... |
1110db582484a26a41aa336f6dfb3d0b3f912b3d | sross1418/PythonExamples | /Turtle Example.py | 3,579 | 4.625 | 5 | # turtle documentation: https://docs.python.org/3/library/turtle.html
# Challenges: add a command to make the turtle draw a circle of a specified diameter
# add a command to change the turtle's color
# add a command to tell the turtle to move to a certain set of coordinates
import turtle
t = turtle.Turtle()
def turt... |
9870fde109c97a853ccb0268a165038bf2e6cc3c | evad37/python-bits-and-pieces | /Calculator.py | 3,415 | 3.8125 | 4 | """
Calculator.py
A calculator that takes input as a string from the user, and recursively solves
the given problem. Reports "divide by zero" errors and bracket mismatch errors.
"""
def add(a,b):
if a is None or b is None:
return None
return a + b
def minus(a,b):
if a is None or b is N... |
a0a054eee73c04771deffdad9b789a80883b2bac | RavikrianGoru/py_durga | /telsuko_one/py_basics/10_prime_check.py | 206 | 3.96875 | 4 | # num = int(input("Enter positive number: "))
num = 83
num = int(num/2)
for i in range(2, num):
if num % i == 0:
print("Not prime")
break
else:
print("Prime")
print("Bye")
|
ca7f48d6367d4eabc5706b88f3b30b12852a8921 | apitman91/problem-solving | /project-euler/p1.py | 160 | 3.859375 | 4 | def p1(n):
"""Sums all multiples of 3 and 5 less than n"""
set = [i for i in range(1, n) if i % 3 == 0 or i% 5 ==0]
return sum(set)
print(p1(1000)) |
419b22f3679fcda55083a82c19a35b034b235352 | hyphenliu/TensorFlow_Google_Practice | /Deep_Learning_with_TensorFlow/1.4.0/Chapter04/2. 学习率的设置.py | 3,524 | 3.734375 | 4 | # #### 假设我们要最小化函数 $y=x^2$, 选择初始点 $x_0=5$
# #### 1. 学习率为1的时候,x在5和-5之间震荡。
import tensorflow as tf
TRAINING_STEPS = 10
LEARNING_RATE = 1
x = tf.Variable(tf.constant(5, dtype=tf.float32), name="x")
y = tf.square(x)
train_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y)
with tf.Session() as sess:
s... |
a9306f484cad43c8ea224c51a8811fbbc336f0a2 | hshafy/semtest | /src/main.py | 2,463 | 3.75 | 4 | """Main"""
import csv
import sys
def read_csv(filename):
"""
Read CSV data and return a list with reocrds
"""
# TODO: get filename from script argument and check path and validate
data = []
with open(filename, newline='') as file:
reader = csv.DictReader(file)
try:
... |
6fcec8ce9310565eada36790a1726d9784f76416 | rewonderful/MLC | /src/归并排序.py | 1,290 | 4 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
def merge(nums):
if len(nums) < 2:
return nums
mid = len(nums)//2
leftpart = merge(nums[:mid])
rightpart = merge(nums[mid:])
return mergesort(leftpart,rightpart)
def mergesort(left,right):
result = []
i = 0
j = 0
while i<len(lef... |
3079ae52457f06417737d1a195c4e110e8142cc7 | Endlex-net/Demo_of_design_patterns_by_python | /proxy_pattern/demo.py | 1,318 | 3.578125 | 4 | from abc import ABC, abstractmethod
class Subject(ABC):
"""主题类"""
@abstractmethod
def request(self):
pass
class RealSubject(Subject):
def request(self):
raise NotImplementedError
class ProxySubject(Subject):
def request(self):
raise NotImplementedError
class TonyRe... |
82c722a169742a41e145c7c53dacd7a25011503e | jmshih/clothes_detector | /download_images.py | 862 | 3.5 | 4 | import argparse
import csv
import os
import sys
from urllib import request
def parse_args():
parser = argparse.ArgumentParser(description='script to download images')
parser.add_argument('--file', help='file containing image urls')
parser.add_argument('--output', help='directory to which to write images')
... |
1e970fb7e9f38b4a869ebe187a606e93b829d97a | lovepreetbegu/lovepreetbegu | /3rd programme interchang2.py | 138 | 4 | 4 | X = input("enter value of x ")
Y = input("enter value of y")
temp = X
X=Y
Y = temp
print("value of X",X)
print("value of Y",Y)
|
24ce85ab2f75d6744e9226d214a21d06c0d95346 | zhumike/python_test | /算法/冒泡排序.py | 1,500 | 3.796875 | 4 | class solutionMethod:
def bubble_sort(self,arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
#改良版本
"""
因为冒泡排序必须要在最终位置找到之前不断
交换数据项,所以它经常被认为是最低效的排
序... |
73b0560c33f081fd72ea3cf7ba6561b4f343b544 | elaneyc/wallbreakers | /week4/stacks/valid_parens.py | 717 | 3.59375 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
# Helper method to return opening brace
def getOpen(p):
if p == ")":
return "("
elif p == "]":
return "["
... |
741d61f62f7d1cc625916bff1706af794780c984 | tope628/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 702 | 4.53125 | 5 | #!/usr/bin/python3
"""Add Integer Module
This module takes 2 integers and/ or floats, and adds them.
otherwise raise a TypeError exception with the message a must be an
integer or b must be an integer. Floats must be casted into integers.
"""
def add_integer(a, b):
"""
Args:
a (int): The first par... |
c30ef439685a615c30d4514accf822512a3bab8e | javvidd/gitProject | /Sep_03_files_execption_summary/exception_handling.py | 793 | 3.59375 | 4 | # exception (errors) handling
# 03-Sep - Done
def division(a, b):
try:
print(a/b)
except ZeroDivisionError as zerodv:
print(f"u cant divide by ZERO - err: {zerodv}")
except (TypeError, NameError) as errmsg:
print(f"check yur input - err: {errmsg}")
# raise errmsg # will sh... |
bfb046b84c0848b3bda806e96502410ad6511851 | zarix908/Crossword | /model/file_reader.py | 770 | 3.53125 | 4 | import sys
class FileReader:
def read(self, file_name):
try:
with open(file_name, 'r') as file:
return list(map(lambda el: el.strip(), file.readlines()))
except FileExistsError:
self.error(file_name, is_exist_error=True)
except FileNotFoundError:
... |
1bfa2109139b1671a1e60e39e3f05f1c92c6d2b1 | lucnortiz/pooej2 | /modulo_helado.py | 932 | 3.53125 | 4 | class Helado:
__gramos= 0
__sabores= []
def __init__(self,gr,sbr):
self.__gramos= gr
self.__sabores= sbr
def __str__(self):
cadenaHelado = 'Gramos: '+ str(self.__gramos)
for i in range(len(self.__sabores)):
cadenaHelado += '\nGusto... |
9b1a4963f5ca7054de39a09508e8b2685b0e1b81 | akhilakr06/pythonluminar | /data_collections/list/nexting.py | 150 | 3.71875 | 4 | #nexting possible
# l=[1,2,3,[5,6,[8,9]]]
# print(l)
lst=[1,2,3]
lst.append(9)
print(lst)
lst.remove(2)
print(lst)
lst.clear()
# del lst
print(lst)
|
2d7e71b8f051faf614840e65225548eb31f5de9b | MiguelMontoya-R/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 567 | 3.59375 | 4 | #!/usr/bin/python3
"""[summary]
"""
def read_lines(filename="", nb_lines=0):
"""[summary]
Keyword Arguments:
filename {str} -- [description] (default: {""})
nb_lines {int} -- [description] (default: {0})
"""
counter = 0
if nb_lines <= 0:
with open(filename, 'r') as f:
... |
858659c6e38706fd893a5b6eadff40ce2aaa7cf2 | alexagrchkva/for_reference | /theory/14th_sprint/B.in_place_quick_sort.py | 2,697 | 4.03125 | 4 | # success try: 49534211, 16 мар 2021, 21:55:36, 1.532s, 29.95Mb
def in_place_quick_sort(array, compare_func=None) -> None:
"""
Just one more version of in place quick sort algorithm. Array is
sorted on place, without extra memory usage. Default sorting is ascending.
@param array: Any iterable of object... |
62b72c00290591f7171927252c435f3bcb727e8c | wjpe/EjemplosPython-Cisco | /ej13.py | 134 | 3.640625 | 4 | #ciclo for que imprime 2 a la X potencia
pow = 1
for exp in range(16):
print("2 a la potencia de ", exp, "es", pow)
pow *= 2 |
4d50463042048bdde3cd25963ebd94a6bdd28e6a | anrl-utd/clearShallowAtEase | /Experiment/mlp_Vanilla_camera.py | 3,997 | 3.53125 | 4 | from keras.models import Sequential
from keras.layers import Dense,Input,Lambda, Activation, add, Flatten
from keras.models import Model
import keras.layers as layers
def define_vanilla_model_MLP(input_shape,
num_classes,
hidden_units = 32):
"""Define a nor... |
af113d96ad81c4c5245dee8e7cabb533fd8879c5 | xxNB/sword-offer | /leetcode/heapqqq/find_median_from_data_stream.py | 2,190 | 3.828125 | 4 | class Heap:
def __init__(self, cmp):
self.cmp = cmp
self.heap = [None]
def __swap__(self, x, y, a):
a[x], a[y] = a[y], a[x]
def size(self):
return len(self.heap) - 1
def top(self):
return self.heap[1] if self.size() else None
def append(self, num):
... |
08c8f99dba6fcfce683e9e49eba1e3aff7781c7d | Conanjun/Leetcode_Practice | /leetcode_543.py | 2,329 | 4.375 | 4 | # -*- coding: utf-8 -*-
# Author: Conan0xff
# Mail : 1526840124@qq.com
# Func : leetcode_543
from utils.BinaryTree import TreeNode
'''
Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path betwe... |
3b561c5a7281736458316a16aaf5fc5db9526646 | Inkatha/PythonPluralsight | /python-scripts/phoneEmailScraper.py | 663 | 3.578125 | 4 | #! python3
import re, pyperclip
# TODO: Create a regex for phone numbers
re.compile(r'''
# 415-555-0000, 555-0000, (415) 555-0000, 555-000 ext 12345, ext.12345, x.12345
((\d\d\d)|(\(\d\d\d)))? #area code (optional)
(\s|-) # first separator
\d\d\d # first 3 digits
- # separator
\d\d\d\d # last 4 digit... |
aae92bf397af6734a10f169bcde2e12c7bf4a4e5 | malaggang2/project_euler | /problem_41~80/problem_41.py | 959 | 3.765625 | 4 | # Problem_41
# Pandigital prime
# We shall say that an n-digit number is pandigital if it makes use of all the
# digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
#
# What is the largest n-digit pandigital prime that exists?
import time
def is_prime(n):
if n == 1:
re... |
a50434d826bd01b70c10f90b62abc04b676d3f44 | Angelpacman/codecademy-py3 | /Unit 02 Strings and Console Output/02 Date and Time/3-Extracting Information.py | 177 | 4.0625 | 4 | from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
print (now.year)
print (now.month)
print (now.day)
|
bb4566515aecfe1ef4ade3a15396a6b5009f400b | yasuo-/python_lesson | /chapter01/range_function.py | 539 | 4.1875 | 4 | """
range関数
"""
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# for なら
for i in num_list:
print(i)
# めんどくさい...
for j in range(10): # 0から9まで表示される
print(j)
for k in range(2, 10): # 2からスタート
print(k)
for l in range(2, 10, 3): # 3飛ばし
print(l)
# 10回処理する
for h in range(10):
print('hello')
... |
370f72a8b93b9db6908c3335c0eb50fd190832ae | tanshinjie/FoundationOfCyberSecurity | /cyber_lab6/primes_template.py | 1,484 | 3.609375 | 4 | # 50.042 FCS Lab 6 template
# Year 2019
"""
Tan Shin Jie
1003715
"""
import random
MR_ROUND = 40
def square_multiply(a, x, n):
res = 1
for i in bin(x)[2:]:
res = res * res % n
if i == "1":
res = res * a % n
return res
def miller_rabin(n, a):
# Check is n is 2 or 3
... |
e714929c319460b65728ef23e6858f1c34f80aac | CloudChaoszero/Data-Analyst-Track-Dataquest.io-Projects | /Python-Programming-Beginner/Python Basics-1.py | 2,159 | 4.625 | 5 | ## 1. Programming And Data Science ##
england = 135
china=123
india=124
united_states=134
## 2. Display Values Using The Print Function ##
china = 123
india = 124
united_states = 134
print(china)
print(india)
print(united_states)
## 3. Data Types ##
china_name = "China"
china_rounded = 123
china_exact = 122.5
prin... |
b4f3fbffbf8940cbb1adbcf83122c3c98421891b | Bhartendu-Kumar/Computer-Pointer-Controller | /src/input_feeder.py | 1,754 | 3.609375 | 4 | '''
This class can be used to feed input from an image, webcam, or video to your model.
Sample usage:
feed=InputFeeder(input_type='video', input_file='video.mp4')
feed.load_data()
for batch in feed.next_batch():
do_something(batch)
feed.close()
'''
import cv2
from numpy import ndarray
class Inp... |
14f235d471e3a4024cc183afb1d1389fcce0addb | samueljml/URI-Online-Judge | /Strings/1237/1237.py | 637 | 3.5 | 4 | while 1:
try:
fra1 = input()
fra2 = input()
if len(fra1) <= len(fra2):
menor = fra1
maior = fra2
else:
menor = fra2
maior = fra1
idf = 0
for i in range(len(menor), 0, -1):
cont = 0
j = i
... |
eedb392a74a3fdec7c66c516369b97b81dbe7d37 | parrot125/myPy | /16_vote_eligibility.py | 314 | 4.125 | 4 | loop = 0
while loop == 0:
try:
age = int(input("Enter the age of the candidate:"))
loop = 1
except:
print("Invalid input")
loop = 0
if age > 18:
print("Eligible to vote.")
elif age < 0:
print("Please enter a positive age.")
else:
print("Not eligible to vote.")
|
a002fec1ed9442782a735ce6bd3ec37b67c873e4 | carlosbognar/Estudos | /Conjuntos.py | 866 | 4.375 | 4 | # Conjuntos são estruturas de dados que não possuem elementos duplicados.
# Podemos aplicar operações matemáticas aos conjuntos.
a = set('abcdefghijkla')
b = set('abcdefx')
print(type(a))
print(a) # imprime todas as letras do conjunto a, sem duplicidade
print(a - b) # imprime o conjunto de letras em a ... |
7a22c700bfe0a61f8142bebcb3c19c51218e87c2 | gutierrecunha/urionlinejudge_python | /URI_1329 - (8672793) - Accepted.py | 226 | 3.6875 | 4 | # -*- coding: utf-8 -*-
while True:
quant = int(input())
if quant == 0:
break
num = list(map(int,input().split()))
print("Mary won",num.count(0),"times and John won",num.count(1),"times") |
081cd0007e071af17efeb5a363cfa75afcfd0417 | jiankangliu/baseOfPython | /PycharmProjects/untitled1/demo.py | 312 | 3.703125 | 4 | # 复数,输入
n = 1
n1 = 2
print(n+n1)
# n2=int(input("请输入第一个数:"))
# n3=int(input("请输入第二个数:"))
# print(n2+n3)
a,b,c=1,[1,2,3],"liu" #多个变量赋值
print(a)
print(b)
print(c)
b1=1
b2=2
print(b2<b1)
c=complex(1,2)
print(c.real)
print(c.imag)
print(c) |
46e080c36913598ce5278f6b29c65b396e80cf18 | salfaris/CS50 | /pset7/houses/roster.py | 786 | 3.625 | 4 | from sys import argv, exit
from cs50 import SQL
# Check len of CLI
if len(argv) != 2:
print("Usage: roster.py house_name")
exit(1)
# Get house name
house = argv[1]
# Get access to sqlite database students.db
db = SQL("sqlite:///students.db")
# Query for student roster
roster = db.execute("SELECT * FROM stud... |
e15ab2773d71e7e77f6d9942e1712d7bc06db6ca | GalinaR/hailstone_sequence | /main.py | 805 | 4.34375 | 4 | """
Pick some positive integer and call it n.
If n is even, divide it by two.
If n is odd, multiply it by three and add one.
Continue this process until n is equal to one.
"""
def main():
num = int(input("Enter a number: "))
result = 0 # variable that will be the result of the action and then the original valu... |
9d0533e0383cc2762e0b9f22f99a795f3c1f463d | hanmeimei222/CorePythonEx | /for.py | 146 | 3.640625 | 4 | squared = [x**2 for x in range(4)]
for i in squared:
print i,
sqdEvens = [x**2 for x in range(8) if not x%2]
for i in sqdEvens:
print i,
|
a6b749265854050a22e63036bc09748b8fe70ee6 | bvchand/algorithmic-toolbox | /Week-4/4.1_Binary_Search.py | 999 | 3.8125 | 4 | # python3
import math
def binary_search(a, low, high, key):
if high < low:
return -1
mid = low + math.floor((high - low) / 2)
# print("mid, a[mid]:", mid, a[mid])
if key == a[mid]:
return mid
elif key < a[mid]:
return binary_search(a, low, mid-1, key)
else:
ret... |
0683e12c6d8a59f033694d9f6d703362b7f6e1f0 | dhpn3/Atividades_MetodosNumericos | /Aulas/06-17/Numpy/06-17_intro_NumPy.py | 2,711 | 4.09375 | 4 | import numpy as np #para dar um apelido e n ter que digitar numpy sempre
# www.numpy.org
#python padrão:
v = [1, 2, 3, 4]
#v.append(5) coloca 5 no final do vetor/da lista
print(v)
print(type(v))
print(type(v[0]))
vet = np.array(v) #criando vetor no numpy
#1 jeito de criar vetor no numpy é passando uma lista do pytho... |
e58b699c1bb83fc953cd6996b446a4c9bfea7dce | ktny/atcoder | /ABC084/d.py | 596 | 3.625 | 4 | Q = int(input())
from functools import lru_cache
@lru_cache(maxsize=None)
def is_prime(n: int):
if n == 2:
return True
if n == 1 or n % 2 == 0:
return False
for p in range(3, int(n**0.5)+1, 2):
if n % p == 0:
return False
return True
like_2017s = []
for i in range(3... |
7e8583b9565658deba77d10efb8cd14ab8e25d42 | rafaelperazzo/programacao-web | /moodledata/vpl_data/34/usersdata/130/12894/submittedfiles/moedas.py | 682 | 3.828125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=input('Digite o valor de a:')
b=input('Digite o valor de b:')
c=input('Digite o valor de c:')
if a>=b:
qa=0
qb=0
if c%a==0:
qa=c//a
print(qa)
print(qb)
else:
qa=c//a
d=c%a
if d%b==0:
qb=... |
bc4c830f0313ae511cee21d9af0f64d8bb09be4c | Erkebulannn/seminar3 | /exercise1.py | 166 | 3.859375 | 4 | a= input('Введите числа: ')
b= input('Введите числа: ')
c= input('Введите числа: ')
if((a==b)or(a==c)or(b==c)):
print('yes')
|
362652fd22d05e1301fe42717101ba8cf3cc338d | viniciu-sena/Python-Logica | /lista05/L5E08.py | 145 | 3.890625 | 4 | # Feito por Kelvin Schneider
#08
num = int(input("Digite um numero: "))
def contar(num):
print("Quantidade de digitos: ", len(str(num)))
contar(num)
|
2548004dff28e2db89afae83b3c1f3ad2c6c2cd6 | adichouhan14/python-assignment | /py assignments/module 7/car.py | 249 | 3.84375 | 4 | #The __str__ method
class Car:
def __init__(self,color,mileage):
self.color=color
self.mileage=mileage
def __str__(self):
return f'A {self.color} car with mileage {self.mileage}'
car=Car('RED',20)
print(car)
|
e014caf6f868c367460df9d8fea9bb2b363ad255 | danapplegate/AdventOfCode2020 | /src/aoc2020/9/solution.py | 1,638 | 3.921875 | 4 | #!/usr/bin/env python3
import argparse
import sys
def is_valid(numbers, target_index, preamble_size):
preamble = numbers[target_index - preamble_size : target_index]
target = numbers[target_index]
complements = set()
for n in preamble:
if n in complements:
return True
compl... |
bdaf2c1f20b1bcea4d5820f613d8c3696d692917 | giancarlo-garbagnati/dsp | /python/q8_parsing.py | 1,473 | 4.40625 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79
# goals against opponents, and had 36 goals scored against them). Write a
# program... |
24b5f5a4125c5d2040ff6f7868421cd822b1bd0f | andersonbispos/secPython | /wordlist.py | 150 | 3.578125 | 4 | import itertools
import string
resultado = itertools.permutations(string.ascii_letters + string.digits, 5)
for i in resultado:
print(''.join(i)) |
671b1459dd44a026bdfb7732310467ffda43a19b | cocvu99/head-first-python | /chapter1/page18to22.py | 717 | 4.25 | 4 |
movies = [
"The Holy Grail", 1975, "Terry Jone @ Terry Gilliam", 91,
["Graham Chapman",
["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]
]
print(movies[4][1][3]) ## Result: Eric Idle
print("----------")
print(movies)
print("----------")
for each_item in movies:
print(ea... |
842527b86d081d90eed10f15ac1fece49005627e | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/box_volume.py | 415 | 3.625 | 4 | #Create a function that gets an object arguments with height, width and length of a box and returns the volume of the box.
#Examples
#volume_of_box({ "width": 2, "length": 5, "height": 1 }) ➞ 10
#volume_of_box({ "width": 4, "length": 2, "height": 2 }) ➞ 16
#volume_of_box({ "width": 2, "length": 3, "height": 5 }) ➞ 3... |
f15339cb6d1b7353c66a4be054f11a5c19aea223 | gabqueiroz/roaming | /PacoteFuncoes.py | 1,472 | 3.546875 | 4 | import os
import zipfile
from TransformacaoRomming import TrasformarRomming
class PacoteFuncoes():
@staticmethod
def descompactar(dir_name, extension):
# change directory from working dir to dir with files
os.chdir(dir_name)
for item in os.listdir(dir_name): ... |
93301089a2a4a8689dbf71ab6c03d55b60cb4ba0 | mullevik/advent-of-code-2019 | /day_06.py | 1,752 | 3.90625 | 4 | from typing import Dict, List
def bfs(start: str, end: str, graph: Dict[str, List[str]]) -> int:
queue: List[str] = [start]
visited = set()
distances = {}
for node in graph.keys():
distances[node] = 0
while queue:
current = queue.pop(0)
for child in graph[current]:
... |
236d2b467e39c74e657d7250ffdfa0230f69f63d | tordjoha/kattis-problems | /python/cetvrta.py | 336 | 3.6875 | 4 | points = []
x = []
y = []
for __ in range(0, 3):
points.append(list(input().split()))
for i in points:
x.append(i[0])
y.append(i[1])
points = [0, 0]
for i in range(0, 3):
if x.count(x[i]) == 1:
points[0] = x[i]
if y.count(y[i]) == 1:
points[1] = y[i]
print('{} {}'.format(points[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.