blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fec822b2e26dbfb531d76bae706493ce2c6bb77e | MiguelSislianSuez/ejerciciosPython | /CalcularMediaAsignatura.py | 805 | 3.9375 | 4 | '''
Un alumno desea saber cual será su calificación final en la materia de Algoritmos.
Dicha calificación se compone de los siguientes porcentajes:
• 55% del promedio de sus tres calificaciones parciales.
• 30% de la calificación del examen final.
• 15% de la calificación de un trabajo final.
'''
parcial1 = float(inpu... |
fa76d1c8a0325a6da856228ab121f1e153bd492c | alexandra-sharrky/99-python | /6fromthelast.py | 413 | 4 | 4 | # It is 6-th programming problem
# Find out whether a list is a palindrome.
# A palindrome can be read forward or backward; e.g. (x a m a x).
# http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html
s = input("Enter your list")
l = len(s)
for i in range(l//2):
if s[i... |
9be729100c2e59a1125fa92a56238ca020bf9ece | alineayumi/python-appbrewery | /day012/number-guessing-game.py | 1,318 | 3.921875 | 4 | import random
from os import system, name
# import sleep to show output for some time period
from time import sleep
from art import logo
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linu... |
c9bdf8788dbcd4833faed8085ea4cb02329eff57 | SboneloMdluli/ELEN4017---first-submission | /Socket Programming with Multithreading/multthread.py | 1,085 | 3.8125 | 4 | #!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadID, name, counter, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.delay = delay
def ... |
3f568d642113d0a6f29e59dff445f6cd9a7eb18e | bhavesh622/Sem6 | /Machine Learning/workingwithnum.py | 152 | 3.53125 | 4 | import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(type(a))
print(a.shape)
b =np.array(a[:2, 1:3])
b[0,0]=77
print(a)
print(b) |
8467843446de5ae40836687a62b60b5da70de250 | chenqim/Python3 | /python_note_20170718_1.py | 2,502 | 3.828125 | 4 | #python基础知识
#保留字,即关键字
#输出所有的关键字
import keyword
print(keyword.kwlist)
#这是一个单行注释
print('Hello, World!') #这也是一个单行注释
'''
这是一个多行注释的第一行
这是一个多行注释的第二行
这是一个多行注释的第三行
。。。
'''
#if条件判断
#用缩进来表示代码块,不需要使用{},但在条件完时需要加:
#缩进的空格数是可变的,但相同的代码块需要有相同的缩进
if 1 == 1:
print('Hello, World!')
else:
print('Oh, No!')
#多行语句
total = '这是一条很长... |
3d4c9f78a3c31b17c20814e2b20f1d0614c35376 | NichHarris/leet-code | /addStrings.py | 1,095 | 3.59375 | 4 | # https://leetcode.com/problems/add-strings/
# Nicholas Harris
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# Fast way
# return str(int(num1) + int(num2))
# Man... |
20414012f75be570861a17b67822972f5a645129 | heroca/heroca | /ejercicio105.py | 908 | 3.796875 | 4 | paises=[]
temperaturas=[]
promediotemp=[]
for x in range(4):
nom=raw_input("Ingrese el nombre del pais:")
paises.append(nom)
temp1=int(input("Ingrese primer temperatura:"))
temp2=int(input("Ingrese segunda temperatura:"))
temp3=int(input("Ingrese tercer temperatura:"))
temperaturas.append([temp... |
c9283290d349b3585d746c042d0c523f36f20f3f | ArnavSharma10/pythoncodes | /2017 calender.py | 187 | 4.15625 | 4 | #import datetime
#now = datetime.date(201, 7, 14)
#print(datetime.date.today().year)
import calendar
year=2017
for month in range(1,13):
print(calendar.month(year,month))
|
7b6d21c221f3e32d919a579271d8217ac1cb1f58 | anagorko/inf | /fibonacci/fibonacci.py | 1,547 | 4.25 | 4 | """
Iterative and recursive computation of nth Fibonacci number.
"""
import unittest
import timeit
def iterative(n: int) -> int:
"""Compute nth Fibonacci number. Iterative version."""
sequence = [1, 1]
for _ in range(n - 2):
sequence.append(sequence[-1] + sequence[-2])
return sequence[-1]
... |
dfb1c1602c792d5afb02f447163108488e39b3c6 | iamuhammadkhan/SSUET-Python-Practice | /Chapter 8/Exercise 8-3.py | 257 | 3.515625 | 4 | def make_shirt(size, message):
print('You have ordered a ' + size + ' shirt with the message "' + message + '" printed on it')
make_shirt('xl', 'hellow world')
make_shirt(message='I am the best', size='M')
make_shirt('L', message='Travel to be wise') |
777d2e03238506cdb07e2c4f1bf992de4c2502ad | OpenSource-Programming/PythonTraining | /022021/Mo/Kavya/kavyanataraj-dev_py_03_CtoF.py | 501 | 4.3125 | 4 | #Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
Celsius = int(input("Enter a temp in Celsius(integers only): ")) # input() is used take user input & int is used so that Celsius value(string) entered by user i... |
dab8d9639a71a7882b04cd533c8aeb63fef2d8cc | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /single_input_2_multiple_values.py | 990 | 4.09375 | 4 | # -----------------------------------------------------------------------
# How to convert a single input value into multiple values within a list
# Made with ❤️ in Python 3 by Alvison Hunter - February 28th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------... |
5725417b3d1a0dfeba5eec493ebbd5fbcc0f7515 | jmescpos/empresa | /Empleado.py | 3,080 | 3.828125 | 4 | __author__ = 'Juanma'
class Empleado():
"""Clase empleado de una empresa"""
def __init__(self, nombre, apellidos, dni, direccion, edad, email, salario):
"""Constructor clase empleado.
Este metodo se encarga de inicializar los diferentes atributos de un objeto empleado
con los paramat... |
f9c4f25552524697720b642a706d0d646766a4c9 | slmsshk/Deep-Learning-in-Python | /Gradient_Descent.py | 883 | 3.5 | 4 | from sklearn.metrics import mean_squared_error
import numpy as np
import matplotlib.pyplot as plt
def pred(input_data, target, weights):
return ((input_data * weights).sum())
def get_slope(input_data, target, weights):
preds = pred(input_data, target, weights)
error = target - preds
slope = 2 * input_... |
951086772a5d6b2db87b40e29948cf8424c57a90 | easykatka04/ft_strtlist.py | /ft_sum_even_lst.py | 198 | 3.796875 | 4 | def ft_len(s):
l = 0
for i in s:
l += 1
return l
def ft_sum_even_lst(a):
b = 0
for i in range(ft_len(a) - 1):
if i % 2 == 0:
b += a[i]
return b
|
3f03397f93354c3d2d063a6eac1d55968ecfc819 | SujanMaga/Python-prac-for-ref. | /test/Conditional_Expression/05_else_optional.py | 77 | 4.0625 | 4 | # else is optional
a = 5
if a<3:
print("Yes")
elif a>3:
print("No") |
4a435bd7de9cec6712735d578d9f9d56027e56dc | pwang867/LeetCode-Solutions-Python | /0430. Flatten a Multilevel Doubly Linked List.py | 2,981 | 3.984375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = va... |
285490d331caabdac456f4d334da7427bae9f689 | DicoMonteiro/projetos-dio | /curso_python_security/gerador_wordlists.py | 293 | 4.03125 | 4 | import itertools
# resultado = itertools.permutations('abc', 3)
string = input('String a ser permutada: ')
resultado = itertools.permutations(string, len(string)) # Realiza a permutação de combinações possíveis com relação a string passada
for i in resultado:
print(''.join(i)) |
0b741b43029c52dfd5368ebb98c659cfbe3bc25d | iamvickypedia/vickypedia-lab | /python-lab/fizzBuzz.py | 655 | 4.40625 | 4 | """
A short program that prints each number from 1 to 100 on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
"""
def fizzBuzz(lim):
for ... |
01aab857ca07b1a4a7b3a02e7eb7f18cabc02ad1 | Sailormoon10/monthly_savings | /monthly_save.py | 867 | 4.34375 | 4 |
#User needs to create and stick to a monthly budget. Based on their
#input, the program will show the user if they have overspend.
budget = float(input("Enter the amount budgeted for the month: "))
expense = float(input(" Enter an expense (or enter 0 to quit): "))
totalExpense = expense
while expense != 0:
expe... |
a246d0f22c5dc0eea3e41b98cfb1e3ccb35a887f | AnweshDahal/python_work | /newgame.py | 1,446 | 3.828125 | 4 | # this is the third example of number guessing and scroing system
from random import randint
import sys
import time
def numGen(a,b):
return randint(a,b)
def loopLogic(a):
if a == 70:
return 50
elif a == 50:
return 30
elif a == 30:
return 10
else:
return 5
... |
a75d1eab3fc917649e1478b9a7cf23106a1be436 | Skill-Zozo/Project-Euler | /palindromeproducts.py | 963 | 4.1875 | 4 | import math
def is_palindrome(num):
number_as_string = '%d' % num
return number_as_string == number_as_string[::-1]
def three_digit_factors(N):
# if x is a factor of y, then either x or the co factor of x is <= sqrt(y)
candidates = []
if N%2==0:
candidates = range(2, int(math.sqrt(N)) +1)
else:
candidates ... |
e989ae9b286af0f77ed3d9f178ddc2627d65d26a | amigo564/CodeChef_Details | /CodeChef_DetailsViaUsername.py | 1,838 | 3.703125 | 4 | import requests
from bs4 import BeautifulSoup
userName = input("If You don't have Internet this program will automatically shutDown\nEnter CodeChef UserName: ")
while(True):
url = "https://www.codechef.com/users/"+userName
html = requests.get(url)
soup = BeautifulSoup(html.text,'html.parser')
ti... |
0e066fb0a4efbe90d166fbc9a513c9b6818e6150 | stupidchen/leetcode | /src/leetcode/P744.py | 360 | 3.546875 | 4 | import bisect
from typing import List
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
i = bisect.bisect_right(letters, target)
if i >= len(letters):
i = 0
return letters[i]
if __name__ == '__main__':
print(Solution().nextGreatestLette... |
c2cb731652dac29cfda148a6fc5dca23ece05e85 | nsshayan/Python | /WayPoints/Test.py | 1,615 | 3.5625 | 4 | import Tkinter
from PIL import ImageDraw, Image, ImageTk
window = Tkinter.Tk(className=" Track Image")
image = Image.open("track.png")
image = image.resize((900, 600), Image.ANTIALIAS)
#-------------------------------------------------- draw = ImageDraw.Draw(image)
#-------------------------------------- ... |
b853c2a298cd670c2c871dbdb56491cd920c7d5f | sch0nik/python-project-lvl1 | /brain_games/games/calc.py | 1,343 | 4.28125 | 4 | """Главный элемент игры Calc."""
from random import choice, randint
RULES_OF_THE_GAME = 'What is the result of the expression?'
def calculating(number_a, number_b, operator):
"""ВЫчисление значения в зависимости от оператора.
Args:
number_a: целое число.
number_b: целое число.
opera... |
1b83ff052595eacd314783ed7b1668bb9c5303e3 | adomjanovic/sorting-algorithms | /algorithms/merge.py | 2,413 | 4 | 4 | from utils.algorithm import AlgorithmHelper
'''
divide and conquer, comparison based, stable
not in place, require additional memory, but for linked list its only O(1)
good implementation of quicksort outperform mergsort
Divide into 2 collections. Mergesort will take the middle index in the collection and split it int... |
3d8e5d3a845509569eaf38011af2beb9cc9854fd | FrozenLemonTee/Leetcode | /reverseWords_151/reverseWords.py | 1,463 | 4.125 | 4 | """
151. 翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词。
说明:
无空格字符构成一个 单词 。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
示例 1:
输入:"the sky is blue"
输出:"blue is sky the"
示例 2:
输入:" hello world! "
输出:"world! hello"
解释:输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入:"a good example"
输出:"ex... |
f8d60ebb2da6e3c33af6fe9a6bdc75c9d863141e | traders-see/pytohn1 | /pandaslianxi/csv 1.py | 3,467 | 3.546875 | 4 | '''
read_csv 就是导入数据
'''
import pandas as pd
df = pd.read_csv('/home/taodi/文档/学习群/pycharm/51bitqunt-master/pandas_basic/binance_btc_1min.csv',
skiprows=0,
#是打印前几行
#nrows=20,
#改成日期格式
parse_dates=['open_time'],
#指定列设置为in... |
e89c3a3f6df21ac81811a5c85bbe6a80f6131639 | samiam567/physics_engine | /Legacy programs/Programs/Doorator.py | 1,416 | 3.578125 | 4 | print ("Do you have trouble finding what to do? Try out the Doorator! Just type in what you want to do, and get cooking!")
cat = input("So, will it be video games, or other?")
if (cat == ("video games")):
ocat = input("computer, console, or mobile?")
elif(cat == "other"):
ocat = input("educational, or other?"... |
78c591d3573fc45c1613b0f0eea2fb47e1540700 | uwenhao2008/python100- | /python100题目/test24试一试别的方法.py | 925 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author:Wen
Time:2019年03月22日 10:39
tip-->兴趣是最好的老师<--
"""
# 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
"""
------------------------------------------------------
思路:分子,分母可以看做是错位的斐波那契额数列
可以试一试纯数列解决的方法
------------------------------------------------------
"""
def ... |
2219fe965db37fe049dd2f6ebc69e0e587763cd7 | darechkin/Basics_Of_Python_HSE | /venv/solution12.py | 201 | 3.765625 | 4 | n = int(input())
a = 'The next number for the number'
b = 'The previous number for the number'
print(a, ' ', n, ' ', 'is', ' ', n + 1, '.', sep='')
print(b, ' ', n, ' ', 'is', ' ', n - 1, '.', sep='')
|
f19464c233b874cb818fe45629d07e92fa62e97a | bcaldwell87/Coding-Dojo-Python | /python/fundamentals/for_loop_basic2.py | 8,913 | 4.5 | 4 | # Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big".
# Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5]
def biggie_size(lst):
for i in range(len(lst)):
if lst[i] > 0:
lst[i] = "big"
... |
29441e1f70df9be3dc2b143c5c93d355b9cf277b | ncbi/ngs-tools | /tools/tax/bin/cut_points.py | 1,259 | 3.765625 | 4 | #!/opt/python-2.7env/bin/python
import sys
#import argparse
def median_of(v):
v = list(v)
v.sort()
return v[len(v)/2]
def is_break_point(line, pos, level):
LOW_CONNECTIVITY = 70
BEGINNING = 70
END = 140
if pos < BEGINNING:
if line[pos] < LOW_CONNECTIVITY/3:
return True
else:
return False
distance_t... |
7f161c647263fb4e714d1dbc527308ce3fe60937 | jinurajan/Datastructures | /hackerrank/interview_preparation_kit/Arrays/2d_arrays.py | 2,368 | 4.03125 | 4 | """
2D Array - DS
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
An hourglass in is a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
There are hourglasses in . An hourglass sum is the sum of an hourglass' values. Ca... |
fd6ae855ed7f9964e5c93580d2262cc47421fb8a | YogaMegantoro/Python_Fundamental | /01 Intro To Phyton.py | 4,195 | 3.5625 | 4 | # Variabel
nama = "Andi"
print("nama:", nama)
usia = 22
usia = 32
print("usia:", usia)
jomblo = True
print("status:", jomblo)
# Data Type
print("\n")
nama = "Yoga"
usia = 22
jomblo = True
print(type(nama))
print(type(usia))
print(type(jomblo))
# Numbers & Arithmetic Operators
print("\n")
usiaAndi = 40
usiaBudi = 2... |
36ccda1351d09c1ae304f54824662cc18fbe7ad8 | EvilNOP/Algorithms | /QuickSort/QuickSort.py | 716 | 3.71875 | 4 | from random import shuffle
def partition(seq, left, right):
currentIndex = left - 1
pivotElement = seq[right]
for index in range(left, right):
if seq[index] <= pivotElement:
currentIndex += 1
seq[currentIndex], seq[index] = seq[index], seq[currentIndex]
seq[currentIndex + 1], seq[right] = seq[ri... |
1dc62c07ff1cd42619385c6652f570165d742aef | sangm1n/problem-solving | /BOJ/2751.py | 267 | 3.53125 | 4 | """
N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
"""
import sys
N = int(sys.stdin.readline())
arr = []
for i in range(N):
arr.append(int(sys.stdin.readline()))
arr.sort()
[print(num) for num in arr]
|
3cc518c2c59a16934b587086f5e52c8fabbf5c96 | renukadeshmukh/Leetcode_Solutions | /1021_RemoveOutermostParentheses.py | 2,273 | 3.84375 | 4 | '''
1021. Remove Outermost Parentheses
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where
A and B are valid parentheses strings, and + represents string concatenation.
For example, "", "()", "(())()", and "(()(()))" are all valid parentheses
strings.
A valid parentheses string S is pr... |
e381274e5d1776f05785669344d274b4c6129d98 | RafaelMaldivas/Mundo3 | /ex086.py | 729 | 4.1875 | 4 | #Matriz em python
print('Multiplicação de matrizes')
matriz1 = [[0,0,0],[0,0,0],[0,0,0]]
matriz2 = [[0,0,0],[0,0,0],[0,0,0]]
matriz = [[0,0,0],[0,0,0],[0,0,0]]
for l in range(0,3):
for c in range(0,3):
matriz1[l][c] = int(input(f'Digite o valor [{l} , {c}] da matriz 1'))
print('-=-'*30)
for l in range(0,3):... |
d71fc8cb953a4f1c445ae4b894ed47e081c6ae4a | jlcatonjr/Learn-Python-for-Stats-and-Econ | /In Class Projects/In Class Examples Spring 2019/Section 2/removeListElementsPop.py | 701 | 3.8125 | 4 | #removeListElementsPop.py
# define list1 and list2
list1 = ["red", "blue", "orange", "black", "white", "golden"]
list2 = ["nose", "ice", "fire", "cat", "mouse", "dog"]
#identify what is printed in for loop
print("lists before deletion: ")
# use for loop to print lists in parallel
for i in range(len(list1)):
print... |
d11f025bb1efcd27a66858bc09a4dab59bd294d7 | leohowell/leetcode-python | /catalog-two-pointers/283.py | 480 | 3.59375 | 4 | # 283. 移动零
# https://leetcode-cn.com/problems/move-zeroes/
# 我的解答
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = 0
right = len(nums)
while length < right:
if nums[lengt... |
c34beee59a36cccf9f65d42f8ee3b460bf06b0a4 | CapsLockAF/python-lessons-2021 | /HW6/t7.py | 583 | 3.703125 | 4 | # У списку знайти елементи, які в ньому зустрічаються тільки один раз,
# і вивести їх на екран.
from random import randint
lenList = int(input("Enter a length of list: "))
startRandom = int(input("A random range start from (<0): "))
endRandom = int(input("A random range end from (>0): "))
list1 = [randint(startRando... |
14a3c9f982aba26cc34203b05822cd33bdb053fb | IngeniousArtist/compiler_CSE420 | /src/Lab2/dfa.py | 1,414 | 3.828125 | 4 | def main():
n = int(input("Enter a number")) #number of inputs
inputs = []
for x in range(n):
newline = input() #next input
newline = newline.lower() #convert to lowercase
newline = newline.strip() #trim
inputs.append(newline) #add to list
print(inputs)
for i... |
19de498b53f73347399204f79d95704a7897138c | kias-git/coding-practice | /hacker-rank/python/py-if-else.py | 221 | 3.890625 | 4 | import sys
n = int(raw_input())
if n % 2:
print "Weird"
if not n % 2 and n in range(2,6):
print "Not Weird"
if not n % 2 and n in range(6,21):
print "Weird"
if not n % 2 and n > 20:
print "Not Weird"
|
4f8b5624d5a8bba14003e3791db98b552042a825 | kiennt/algorithms | /src/com/kiennt/codility/09_max_slice_sum.py | 1,943 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].
Write a function:
int solution(int A[], int N);
that, given an array A... |
7b1cd0e0297afc96f50049b4de35baf2c19f39b1 | tdidierjean/coursera_statistics | /monty.py | 673 | 3.640625 | 4 | from random import randint
from random import choice
N = 1000
def simulate(N):
K = 0
###insert your code here###
for i in range(N):
doors = [1, 2, 3]
realDoor = randint(1, 3)
# print(realDoor)
pickedDoor = randint(1, 3)
# print(pickedDoor)
doors.remove(picke... |
1ecd438f859f7997c29f480aba287dee1b64b2bd | waltermblair/CSCI-220 | /ch6.py | 117 | 3.53125 | 4 | def cube(x):
answer = x*x*x
return answer
def main():
y = 3
answer=cube(y)
print(answer)
main()
|
7ff0cd8f4bcc3e3286f3a5c3195f50a8c619207a | brightredchilli/cs231n | /assignment2/cs231n/classifiers/cnn.py | 7,092 | 3.59375 | 4 | import numpy as np
from cs231n.layers import *
from cs231n.fast_layers import *
from cs231n.layer_utils import *
class ParamHolder:
"""
A simple class to make writing weight variables less ugly.
"""
def __init__(self, param_name, params):
"""
Inputs:
- param_name: The prefix for the param. For ex... |
33cb403231b317fff3999a336d03826a957983dd | QingQing3319/heima | /MachineLearning1/BigDataClass9/day02/14.1exception_while_break_if_elif_else.py | 693 | 3.921875 | 4 | #_*_ coding: utf-8 _*_
# @Time : 2019/12/3 11:43
# @Author : Z
# @Email : S
# @File : 14.1exception_while_break_if_elif_else.py.py
number = 90
while True:
try:
# 用户输入猜测数字
guessNumber = int(input("Please input your guess number:"))
# 判断
if guessNumber == number:
pr... |
cb7fe6f660192fad6c715f0819c0a3832091cc5e | meat00/my-leetcode-python | /0013roman-to-integer.py | 759 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
def romanToInt(self, s: str) -> int:
trans_tbl = {
'I' : 1 ,
'V' : 5 ,
'X' : 10 ,
'L' : 50 ,
'C' : 100 ,
'D' : 500 ,
'M'... |
7aa99870f7d6572b4d95756ff45eab2b2574ee5f | Tishacy/Algorithms | /code/1 genetic_algorithm.py | 4,287 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""A Genetic Algorithm (GA) Test
Decsription of GA:
--------------------
SETUP
step 1: Initialize: Create a population of N elements, each with randomly generated DNA.
DRAW
step 2: Selection: Evaluate the fitness of each element of the population and build a mating pool.
step 3: Rep... |
94a005706c2f4711f11367e4ba3a3cd27c3ef6bb | QAMilestoneAcademy/PythonForBeginners | /Projects/turtle_race.py | 2,110 | 3.921875 | 4 | from turtle import Screen, Turtle
from random import randint, choice
import turtle
import time
s=Screen()
s.bgcolor("white")
track = Turtle()
# track = turtle.Turtle()
track.speed('fastest')
track.penup()
track.goto(-100, 200)
for step in range(15):
track.write(step, align='center')
track.right(90)
track.fo... |
52d9eaa693a68d29ff7841b3dddf965b66d8b1c8 | adesai1973/python-challenge | /PyBank/main.py | 4,021 | 3.703125 | 4 |
import os
import csv
csvpath = os.path.join('.', 'Resources', 'budget_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#print(csvreader)
#First line in csv file is a header, so extract it in csv_header list
csv_header = next(csvreader)
#print(f"CSV Header:... |
893b4a4e9ae7425b274f48baaa4bce0bcc63e776 | SURBHI17/python_daily | /src/quest_23.py | 293 | 4.03125 | 4 | #PF-Prac-23
def divisible_by_sum(number):
#start writing your code here
sum=0
temp=number
while(temp>0):
rem=temp%10
sum+=rem
temp//=10
if number%sum==0:return True
else: return False
number=42
print(divisible_by_sum(number)) |
af06ef75f89a812e089c81d257a170453b20c212 | vaibhavpund/Project2 | /Array.py | 237 | 4.15625 | 4 | from array import *
arr= array('i', [5,65,34,23,22,46])
n=int(input("Enter the length of array: "))
for i in range(n):
x=int(input("Enter the elements: "))
arr.append(x)
print("The array elements are as follows: ")
print(arr) |
216c3effa51c3473efc54c53de381bb1a5a7d1cc | kathan214/python-for-Everybody-coursera- | /assignment4.1.py | 144 | 3.984375 | 4 | # The code below almost works
name = input("Enter your name")
print("Hello",name)
# make sure that name's 1st latter should be capital
|
2f53ca389fa18730f5ca60991bab5b8d63791807 | rohegde7/competitive_programming_codes | /cchef-Decreasing_String(easy).py | 677 | 3.515625 | 4 | # Author of the code: Rohit Hegde - hegde.rohit7@gmail.com (https://www.github.com/rohegde7)
# https://www.codechef.com/problems/DECSTR
# Problem Code: DECSTR
# status: Accepted, ET 0.01 secs
tests = int(input())
for i in range(tests):
k = int(input())
full_string = 'zyxwvutsrqponmlkjihgfedcba'
... |
a9ba0b532408d4ad174e4e5afb18104b8dd088b8 | mjaw10/assignment | /Stretch and challenges 1.py | 473 | 3.96875 | 4 | #input width
#input lengtgh
# -2m from tength + width
# code to work out how much it will cost to turf a garden wih a 1m boarder around the perimiter
width = float(input("Enter the width of your garden: ")) - 2
length = float(input("Enter the length of your garden: ")) - 2
area = width * length
cost = 10 * are... |
d94ef9399df603305e9d9e168647ea59fa3f2f05 | imnomee/100-days-of-code-Python | /18/e5.py | 472 | 3.578125 | 4 | import turtle
import random
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
turtle.colormode(255)
t = turtle.Turtle()
t.speed('fastest')
def draw_spirograph(size):
for x in range(int(360 / size)):
t.circle(100)
... |
ae7af7a9e31f47cefc19c348f4068903aab0966e | sainihimanshu1999/Web-Scraper- | /codes/scraper2.py | 716 | 3.609375 | 4 | import requests
from bs4 import BeautifulSoup
url = 'https://webscraper.io/test-sites/e-commerce/allinone'
res = requests.get(url)
print(res)
soup = BeautifulSoup(res.text, 'html.parser')
# print(soup)
# print(soup.select('p'))
#print(soup.select('.title'))
'''
because it's a list we can get all text simply, either... |
cec594e4579cb412b5c1dadc6657ab554855670c | singi2016cn/python-start-programming | /15/15.5/random_walk.py | 1,638 | 4.15625 | 4 | """方法 fill_walk()很长。请新建一个名为 get_step()的方法,用于确定
每次漫步的距离和方向,并计算这次漫步将如何移动。然后,在 fill_walk()中调用
get_step()两次:
x_step = get_step()
y_step = get_step()
通过这样的重构,可缩小 fill_walk()的规模,让这个方法阅读和理解起来更容易"""
import matplotlib.pyplot as plt
from random import choice
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, nu... |
762fd3046112a8419f13c763392d18d49af336dd | hshrimp/letecode_for_me | /letecode/361-480/461-480/466.py | 2,141 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: wushaohong
@time: 2021/2/5 下午4:04
"""
"""466. 统计重复个数
由 n 个连接的字符串 s 组成字符串 S,记作 S = [s,n]。例如,["abc",3]=“abcabcabc”。
如果我们可以从 s2 中删除某些字符使其变为 s1,则称字符串 s1 可以从字符串 s2 获得。
例如,根据定义,"abc" 可以从 “abdbec” 获得,但不能从 “acbbe” 获得。
现在给你两个非空字符串 s1 和 s2(每个最多 100 个字符长)和两个整数 0 ≤ n1 ≤ 106 和 ... |
870ecd7b02371c23199c478e9e553396c283cba0 | gracenng/Salam-Technica | /data_process.py | 3,172 | 3.5 | 4 | import requests
import pandas as pd
import csv
from google.cloud import bigquery
import jwt
def convert():
import PyPDF2
# creating a pdf file object
pdfFileObj = open('tax1.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
... |
a4d6e6bb0358a262db5d76df02f57b55b7060c4c | aroraayush/python-js-leetcode-ques | /python/trees/same_tree/same_tree.py | 886 | 3.875 | 4 | class Node:
def __init__(self, val, left=None, right = None):
self.val = val
self.left = left
self.right = right
class Solution:
# Checking if 2 trees are equal
def is_same(self, n1 : Node, n2: Node) -> bool:
if n1 == None and n2 == None:
return True
if n... |
628dc8774401168ece0fd62c4fb9aed58c1f8714 | hyunwoojeong123/Algorithm | /Tech_Interview/Stack.py | 798 | 4 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
#push
def push(self,data):
new_node = Node(data)
new_node.next = self.top
self.top = new_node
#pop
def pop(self):
if... |
411ed96c66fbbae9101d41a17c8feb28204c160d | yushinna/python-project-03 | /phrasehunter/character.py | 613 | 3.625 | 4 | class Character:
"""
The Character instance is responsible for holding the state of a given single character.
"""
def __init__(self, char: str):
self.original = char
self.was_guessed = False
def guess(self, gss: str) -> None or bool:
if self.was_guessed:
return ... |
e6559d1f061d96ee61fbd687b6448a07fa83444a | anshitmishraa/anshitmishra-codeforces-atcoder | /atcoder/abc189/D.py | 212 | 3.515625 | 4 | N = int(input())
S = [input() for _ in range(N)]
def rec(index):
if index > 0:
if S[index - 1] == "OR":
return 2 ** index + rec(index - 1)
else:
return rec(index - 1)
else:
return 1
print(rec(N)) |
16eb115a822691d2b7bf95189d977f5979c20b5f | Jose-G-Melo/PizzariaLuigiApp | /lerDados.py | 545 | 3.703125 | 4 | # importando módulo padrão para trabalhar com json
import json
# consulta no "banco de dados" se o usuário está cadastrado no sistema
def consultarCadastro(email, senha):
user = open("database/usuarios.txt", "r", encoding="UTF-8")
for pessoa in user:
usuario = json.loads(pessoa)
email_pessoa = usuario["ema... |
d37d2fb4dff1c83cb50d9be9b89cfe3255c9e144 | Suraj-Kaple/Sudoku-solver-generator | /sudoku_generator.py | 2,241 | 3.78125 | 4 | import random
def empty_location(board,pos):
for i in range(9):
for j in range(9):
if board[i][j]==0:
pos[0]=i
pos[1]=j
return True
return False
def row_check(board, row, num):
if num in board[row]:
return True
r... |
c4ba7864864d4a2987366a56039ca0b3d56850a4 | HonniLin/leetcode | /history/8.String-to-Integer-(atoi).py | 956 | 3.546875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : 8.String-to-Integer-(atoi).py
@Time : 2020/07/20 23:48:32
@Author : linhong02
@Desc : None
"""
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
:desc 实现 atoi
"""
... |
526c3c09a89ae6ee265ec3fabe5d4c000f9d25ec | Nehanavgurukul/if_ques_python | /waterfilter.py | 179 | 3.859375 | 4 | water=int(input("water dalo"))
if(1>water):
print("to aur pani bharna")
elif(1<water and 10>water):
print("to aur nahi bharna ")
elif(water>10):
print("pani over hai") |
a4050ecb9ae38edfb1b039f3267eaea9aaa98c4e | dmorand17/udemy-rest-api-flask | /archive/section5/app/test/test.py | 976 | 4.15625 | 4 | import sqlite3
from sqlite3.dbapi2 import connect
# Testing out interacting with a sqlite db
connection = sqlite3.connect("resources/data.db")
# Query and Store results
cursor = connection.cursor()
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_table)
user = (1, "jo... |
d883390d1ba951a50e7ed2c8f6c2b2ca291bf764 | gitbuda/optframe | /common/solution_buffer.py | 1,501 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Object which purpose is to pass solutions between algorithms.
'''
from common.solution import Solution
class SolutionBuffer(object):
def __init__(self):
'''
Initialize the buffer.
'''
self.buffer = []
def configure(self, con... |
dcacd15396ef3487a66d92fc85bd595e68fdf3e3 | manuelamercado/structures-algorithms-nanodegree-projects | /P1/task5.py | 3,349 | 4.625 | 5 | """
Blockchain
A Blockchain is a sequential chain of records, similar to a linked list. Each block contains some information and how it is connected related to the other blocks in the chain. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data. For our blockchain we will be ... |
c8bc85b41d110214117dbac353521f89020d23b7 | CLgithub/pythonLearn | /day8/02-匿名函数使用.py | 417 | 3.921875 | 4 | #对元素为字典的列表进行排序
stus=[{"name":"aa","age":18},{"name":"bb","age":20},{"name":"cc","age":19}]
x=[11,22,33,12,43,32]
print(x)
x.sort(key=lambda xn:xn) #sort(key=func)func为一个函数,每次比较时都会调用这个函数,把x的每个元素当成一个参数传递给这个函数,并且函数有返回
print(x)
#print(stus[0]["name"])
stus.sort(key=lambda s:s["age"])
print(stus)
|
bebe162a65bc9bc068b6af5f2bc68d4e4d5a4775 | parshuramsail/PYTHON_LEARN | /paresh47/I-F-EL-SE-EL-I-F.PY | 185 | 4.03125 | 4 | loc="college"
if loc=='bank':
print("yes its a bank")
elif loc=="school":
print("wel come")
elif loc=="colle":
print("yeh you are wright")
else:
("oh you are wrong")
|
0c40d22410e82083c557f282d906e23f4edd91db | pl6c2/Python-ML-DL | /ICP4/MultipleLinearRegression.py | 1,086 | 3.625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
wine = pd.read_csv('winequality-red.csv')
# wine.dropna()
print(wine.isnull().sum())
df = pd.DataFrame(wine)
print('top 3 correlated columns are :\n' + str(df[df.columns[:]].corr()['quality'][:11].sort_values(ascending=True)[5:8]))
# X = wine[['... |
08922cade7b34fdd3867c95ed3ccd2730e085fe9 | nuriengincatak/Python_practice | /practice_python/25th Guessing Game Two.py | 2,795 | 4.28125 | 4 | #In a previous exercise, we’ve written a program that “knows” a number and asks a user to guess it.
#This time, we’re going to do exactly the opposite. You, the user, will have in your head a number
# between 0 and 100. The program will guess a number, and you, the user, will say whether it is too high,
# too low, or y... |
735f930a6225919415d020bddf76d01cf303dec0 | kltjrcks/move_test | /programmers/pSolution5.py | 192 | 3.65625 | 4 | # -*- coding : utf-8 -*-
#직사각형 별찍기
a, b = map(int,input().strip().split(' '))
for n in range(b):
answer = ''
for m in range(a):
answer += '*'
print(answer)
|
1c2148e925a82bdfb351475401e84980a6cb176a | tusharsadhwani/daily_byte | /p13_array_intersection.py | 875 | 4.28125 | 4 | """
Given two integer arrays, return their intersection.
Note: the intersection is the set of elements that are common to both
arrays.
Ex: Given the following arrays...
nums1 = [2, 4, 4, 2], nums2 = [2, 4], return [2, 4]
nums1 = [1, 2, 3, 3], nums2 = [3, 3], return [3]
nums1 = [2, 4, 6, 8], nums2 = [1, 3, 5, 7], retu... |
833de3411f9c737486770c7e010fb31c80122987 | ljh-712/python | /员工管理系统.py | 1,652 | 3.75 | 4 | # 显示系统欢迎信息
print('-' * 20, '欢迎使用员工管理系统', '-' * 20)
# 创建列表保存员工
emps=['\t悟空\t男\t\t28\t\t花果山',]
while True:
# 显示用户选项
print('请选择所要做的操作')
print('\t1、显示员工列表')
print('\t2、添加员工列表')
print('\t3、删除员工列表')
print('\t4、退出系统')
user_choose = input('请选择[1-4]:')
print('-' * 62)
# 根据用户选择做操作
if user_... |
6ad76069e05dfd6e042019b7996bc49f19db250a | paulkarayan/projecteuler | /problem37.py | 2,813 | 3.78125 | 4 | # truncatable primes
import math
def findprimes(limit, sieve, plist, stop_length): # sieve of eratosthenes w/ tricks
#print(limit, sieve, plist, "inputs")
if not plist:
sieve = [1] * int(math.sqrt(limit))
sieve[0] = sieve[1] = 0
start = 0
else:
start = len(sieve)
... |
96008b2a1b87cc39dafbe43006e69e113c13e656 | yash1th/stackoverflow-questions | /programs/46937126.py | 156 | 3.921875 | 4 | date = input('Enter date in the format (DD.MM.YY) : ')
dd, mm, yyyy = date.strip().split('.')
print('day = ',dd)
print('month = ',mm)
print('year = ',yyyy)
|
19ee4da40e08f75c5944b48499d085a89732e64f | runnedrun/olinoboat | /scripts/go_short.py | 3,506 | 3.5 | 4 | #!/usr/bin/env python
# go_short.py provides functions for think.py
# At a high level, go_short.py tells think.py how much it would like to go in every direction around the boat
#
# 04/14/13 - The logic behind the go_short.py takes the boat position (GPS) and the next waypoint position (GPS) and tells think.py it real... |
a08251e6c1e3c23abdef014233fbc96df86113e8 | pleasure2cu/fileTransferProgram | /fileTransferClient.py | 3,815 | 3.78125 | 4 | import socket
import os
import basicOperations # own python file
def getName(path):
""" this function extracts the name of the file out of the path to it """
# for linux users
name = path.split('/')[-1]
# for windows users
name = name.split('\\')[-1]
return name
# here the user input is pro... |
2e63717e38fd23ccea3c46b9dd878724984b5c40 | atulrc/ML-ex1 | /ex1py/warmUpExercise.py | 479 | 4.09375 | 4 | # Scientific and vector computation for python
import numpy as np
def identityMatrix():
"""
Example function in Python which computes the identity matrix.
Returns
-------
A : array_like
The 5x5 identity matrix.
Instructions
------------
Return the 5x5 identity ma... |
3bc6bb1cbb238575f8130362fff26ffc510c5737 | aravind225/hackerearth | /n pattern.py | 279 | 3.953125 | 4 | """
N N
NN N
N N N
N NN
N N
"""
n=int(input("enter the number of rows:"))
for i in range(1,n+1):
for j in range(1,n+1):
if (i==j) or (j==1)or (j==n):
print("N",end="")
else:
print(" ",end="")
print()
|
96b5c91a2ac5fc596c995a85550dbd2af3ebc2c7 | ZeHaoW/LeetCode | /7nice/Solution.py | 779 | 3.609375 | 4 | class Solution(object):
# 我的解法
def reverse(self, x):
if x > 2**31-1 or x < -(2**31-1):
return 0
strnum = str(x)
if x <0:
strnum = strnum[1:]
res = strnum[::-1]
if res[0] == 0 :
if int(res[1:]) > 2**31-1:
retur... |
efdcc527077120c89656dcb677dd70c7f088852f | basbasrattakiat/Python | /Rattakiat_python/Ex _ การใช้ List.py | 427 | 3.71875 | 4 | friend = ["jan","cream","phu","bam","aom","pee","bas","kong","da","james"]
friend[9]="may"
friend[3]="boat"
friend.append("dome")
friend.append("poondang")
friend.insert(1,"csa")
friend.insert(8,"ped")
friend.remove("aom")
friend.pop(3)
del friend[7]
friend.clear()
del frthisiend
print(friend)
animal = {"cat","dog","r... |
5af38a67f1de1ba0e6446cd175c207c30fab1647 | eryem-reyem/2020 | /day_2.py | 756 | 3.828125 | 4 | # https://adventofcode.com/2020/day/2
def read_puzzle(file):
with open(file) as f:
return [x for x in f]
new_list = read_puzzle('day_2.txt')
passwort_count = 0
for i in new_list:
a = i.split(':')
int_1 = int(a[0].split('-')[0])
int_2 = int(a[0].split(' ')[0].split('-')[1])
letter = a[0].s... |
dabd0a3fa0a1a7addd1b329e20fbba5d00832812 | Baistan/FirstProject | /lists_tasks/Задача9.py | 266 | 3.546875 | 4 | numbers = [10,15,20,-5,-5,25,30,40,50,60,-1]
i = 0
while i < len(numbers):
sec_num = numbers[i]
i += 1
if numbers[i] > 0 and sec_num > 0:
print(numbers[i],sec_num)
elif numbers[i] < 0 and sec_num < 0:
print(numbers[i], sec_num)
|
c6ce7e5d5bd9919d8eac0c2d63fe8a98c65edf39 | liu666197/data1 | /8.13/04 中奖.py | 525 | 3.578125 | 4 | # 中奖的彩票
zhongjiang = {'red': [20,22,14,18,12,8],'blue': 16}
# 自己的彩票
me = {'red': [21,20,25,14,18,4],'blue': 16}
# 自己买的红球
red = me['red']
# 自己买的蓝球
blue = me['blue']
# 红球的中奖个数
redCount = 0
for i in red:
if i in zhongjiang['red']:
redCount += 1
# 蓝球的中奖个数
blueCount = 0
if blue == zhongjiang['blue']:
blueCo... |
e2011fdefa7bdb92fc3212acb763501d14bae2a9 | MicaelSousa15/PTS | /08.py | 233 | 3.734375 | 4 | L = ['arroz','feijão','batata']
print(L[0])
# Em print (L[0]) vai aparecer somente arroz... porque cada str na lista é um numero
# arroz 0, feijão 1, batata 2
# sempre começando do 0, então: (L[0]) arroz, (L[1]) feijão e etc... |
f2adea01e31fa450161164c67cf7976cd95c3c2d | adolgert/cascade | /src/cascade/core/log.py | 777 | 3.515625 | 4 | import logging
def getLoggers(dotted_module_name):
"""
Returns two loggers. The first is in the namespace that's passed-in.
The second inserts ".math" as the second module, so ``cascade.core.log``
becomes ``cascade.math.core.log``.
Args:
dotted_module_name (str): The name of the module, u... |
5ef0e1a34cde0edc60bb0051000cafd67b11616a | kapil87/LeetCode | /mergeSortedArray.py | 807 | 3.75 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
count = m +n -1
m -= 1
n -=... |
9c5c95f7e47984403b499087d91830711f50ef4d | Saradippity26/Beginning-Python | /airtravel.py | 4,419 | 4.40625 | 4 | """
Create an flight class: Model for aircraft flights
keyword for class: class Class\initializer\constructors in other languages
(naming conventing for class is uppercase first letter)
"""
class Flight: # Class
"""
A Flight with a particular passenger aircraft
"""
# Python does not have private, pub... |
c47905664da44749eb6ea54ca332f88294966a40 | vencabot/intro_to_python | /total_beginner_projects/virtual_pet/virtual_pet_day_4.py | 4,822 | 3.859375 | 4 | def feed_pet(game_state):
pets_food = input(
"What do you want to feed " + game_state["pets_name"] + "? ")
print()
if pets_food in game_state["pets_favorite_foods"]:
game_state["pets_happiness"] += 20
elif pets_food in game_state["pets_hated_foods"]:
game_state["pets... |
3ec91057c16440b08ee42e6e0394ea445fa088c7 | J297-hub/exercicios-de-python | /Pacote Dowload/pythonProject/aula020ex098.py | 733 | 3.703125 | 4 | from time import sleep
def contador (i, f, p):
if p <0:
p *=-1
if p == 0:
p=1
print('-'*20)
print(f'Contagem de {i} até {f} de {p} em {p}')
sleep(2.5)
if i<f:
cont=i
while cont <=f:
print(f'{cont} ',end='')
sleep(0.5)
cont+=p
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.