blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d7cae83cb063a4b47c23287ba6c39c368fb3b004 | bhuvaneshkumar1103/talentpy | /product_recursive.py | 367 | 4.3125 | 4 | '''
Write python recursive function to perform multiplication of all elements of list L.
'''
#the function multiply will call itself untill lenth of the list.
def multiply(L,n = 0):
prod = 1
if n < len(L):
prod = L[n]*multiply(L,n+1)
return prod
L = [1,2,3,4,5,6,7,8,9]
print("The product o... |
e9b1a95439de18605e3ff3f2be101f40fe4e1639 | himrasmussen/SomeRepo | /narcissisticNumbers.py | 654 | 3.734375 | 4 | # Narcissistic Numbers
# [
# 153, 370, 371, 407, 1634, 8208,
# 9474, 54748, 92727, 93084, 548834
# 1741725, 4210818, 9800817, 9926315
# ]
# The number is equal to the sum of its digits raised to the power of number
# of digits
def narNum(i):
value = 0
for n in str(i):
value += int(n)**... |
6e87e9c9ffa87c6efe66eb57e31e5559e3f006dd | likewen623/Stylometric-Analyser-PY | /.gitignore/preprocessor_29330440.py | 1,185 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 21 19:18:43 2018
Name: Kewen Deng
Student ID: 29330440
Last modified date: May 24 2018
Description:
In this file, I have defined a class that will perform the basic preprocessing on each input text.
This class have one instance variable which is a list that... |
d4f2e4790f66d43347815daa2ac80b6c423593c0 | Roger-Coelho/Fibonacci | /fibrecursivo.py | 418 | 4.125 | 4 | print("Fibonacci Recursivo")
#Função de Fibonacci recursivo
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
ans = fib(n - 1) + fib(n - 2)
return ans
#Informa a quantidade de interações do n-ésimo termo de Fibonacci
n = int(input("Informe o número ... |
e6da4c869f1f65084b1e9ae8802906875abd6de3 | MorrisHsia/ECE364-python-bash-shell | /labs/Lab00/simpleCode.py | 1,949 | 3.90625 | 4 | #!/usr/bin/env python3.7
#######################################################
# Author: Alex Gheith
# email: gheith@purdue.edu
# ID: ee364j20
# Date: 01/07/2019
#######################################################
import os
import math
from operator import itemgetter
def getVec... |
859bf9fa4c766af143cdec9a85399a30ff1003b2 | Michael-Beukman/ERLEcosystemSimulation | /simulation/utils/utils.py | 6,812 | 3.734375 | 4 | from typing import List, Tuple
import numpy as np
class Point2:
""" A simple 2d point class """
def __init__(self, x, y):
self.x = x;
self.y = y;
def dist(self, other: "Point2"):
return np.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
def __repr__(self) -> str:
... |
6aa49279774160e725ce8cda9a7de69cb773ceff | SaudiWebDev2020/Omaima_Abuzaid | /Assignments/Python/Assignments/For_Loops_Basic_I.py | 1,101 | 3.8125 | 4 | ## Print all integers from 0 to 150.
for i in range (0,151,1):
print(i)
## Print all the multiples of 5 from 5 to 1,000
x=5
while x <=1000:
print(x)
x= x*5
##Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Coding Dojo".
for n in range (1,101):
if n%5==0:
... |
e97c6451b0b7cc17066c51b7621fabed334f37b8 | bpl-code/short_projects | /hangman.py | 1,995 | 4.0625 | 4 | #hangman.py
#A game of hangman
from random import randint
def main():
#add a while run
#start game initialise all needed var
word,guessLetter,guesses = startGame()
play = True
guessesLeft = 10
print(type(guesses))
while play:
#displayword
displayWord(word,guesses)
#... |
0f07da6e36a718d38cef8973dc7bf99c02d1d22b | hchaoshun/ML-Coursera | /ex1/linear_regression_with_multiple_variable.py | 1,404 | 3.703125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
# 批量梯度下降
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.rav... |
400917c9ac76be41cb9adc8a3a77463c014218de | 21seya/ExerciciosBasicoPython | /aula92.py | 230 | 3.734375 | 4 | a = [1,2,3,4,5]
aux = a[:]
b = []
print("lista =",a)
while len(b) != len(a):
menor = aux[0]
for ele in aux:
if ele < menor:
menor = ele
b.append(ele)
aux.remove(ele)
a = b
print("lista =",a)
|
291a83b8d4f34707681d3a48c6505051f0209d74 | xilousong/test_git | /002三角形.py | 119 | 3.5 | 4 | def Sanjiaoxing():
i=1
while i <=5:
j=1
while j<=i:
print("*",end='')
j+=1
print()
i+=1
Sanjiaoxing()
|
a55562a3ace25ac58197c401947630fe27b66db0 | Danny7226/MyLeetcodeJourney | /normal_order_python/15.3Sum.py | 2,610 | 3.578125 | 4 | '''
tags: 2 pointers
15. 3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solutio... |
4b6f144516a438f41cd3ed990d29700eecc04c3f | feiwenli/PythonLearning | /Practice/copy_test.py | 1,330 | 3.71875 | 4 | # coding=utf-8
import copy
import keyword
# copy 为浅拷贝,只是拷贝了list,list中的对象还是原来的对象,改变了原来的对象,拷贝对象也会随之改变
# deepcopy 则会创建被拷贝对象中的所有对象的拷贝
# keyword 模块记录了所有的关键字
print(keyword.iskeyword('if'))
print(keyword.kwlist) # 所有关键字列表
class Animal:
def __init__(self, species, number_of_legs, color):
self.species = species... |
1aa54bd2755e98aca1548931960ceba6e0c1c286 | singamcet/AEG-with-vsM | /Coherence/coherence.py | 1,776 | 3.65625 | 4 | import re
import math
def coh(file_1,file_2):
dict_1 = {}
dict_2 = {}
count1 = 0
count2 = 0
sum = 0
#file_1 = raw_input("Enter 1st file name:") #takes in the first file name
#file_2 = raw_input("Enter 2nd file name:") #takes in the second file
with open(file_1,"r") as f1:
for line in f1: #loop to handle... |
8b0b37bee5b37fb7982a9f4fc18a458f07269c89 | RyzenMe/Beijing-Jiaotong-University-BigData-Homework | /Code/Chapter-2/Chapter-2.13.py | 1,813 | 3.578125 | 4 | import numpy as np
def mean(data):
sum = 0
mean = 0
for i in range(len(data)):
sum = sum +data[i]
mean = sum/(len(data)) #len(data)=12。range 是从0到11.
return mean
def min_max(data): #max_min归一化
x_max = max(data)
x_min = min(data)
... |
3bdcf83f9a06da49bbfec15b96de0154b980b963 | marko-knoebl/courses-code | /python/2018-09/basics/string_formatting.py | 561 | 4.125 | 4 | city = "Vienna"
temperature = 28.3
# "alte" Syntax
print("weather in %s: %f°C" % (city, temperature))
# neue Methode: .format
print("weather in {1}: {0:.2f}°C".format(temperature, city))
print("weather in {c}: {t:.2f}°C".format(c=city, t=temperature))
# Mit Tupel
parameters = ("Vienna", 28.3)
print("weather in {}: ... |
566774edd066942d09e32e62bddb4cbb3bd2b206 | philippprestel/git-project-bikeshare | /bikeshare.py | 7,920 | 4.3125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
city_list = ["chicago","new york city","washington"]
month_list = ["all","january","february","march","april","may","june"]
da... |
bc42d1d17b4ef7c11d27bfb2df8bcc58ecd00f37 | HelalChow/Pyhton-Basics | /Lab/Lab 12/Person Class.py | 2,275 | 4.125 | 4 | class Person:
def __init__(self, name, age):
self.Name = name
self.Age = age
self.Hobbies = []
def addHobby(self, newHobby):
self.Hobbies.append(newHobby)
def deleteHobby(self, oldHobby):
self.Hobbies.remove(oldHobby)
def birthday(self):
print("H... |
3579dcd7b535ecf9456ecf6c12a749e96846afdb | Arquedy/atom | /while3.py | 161 | 4.09375 | 4 | numero = int(input("Digita um numero que eu vou soma-lo: "))
soma = 0
while numero > 0:
soma = soma + (numero % 10)
numero = numero // 10
print(soma)
|
52c1bdca7c031f8be489a3e35fff5e487207b798 | TorpidCoder/Python | /PythonCourse/DataStructure/selectionSort.py | 405 | 3.84375 | 4 | __author__ = "ResearchInMotion"
def selectionSort(mylist):
sortValues = range(0 , len(mylist))
for i in sortValues:
minval = i
for j in range(i+1 , len(mylist)):
if(mylist[j]<mylist[minval]):
minval = j
if(minval != i):
mylist[i] , mylist[minval] ... |
658721c40d4ebc057eb6bbe351e09a890afbb508 | mukund7296/Python-Brushup | /04 Type Conversion.py | 581 | 4.28125 | 4 | # Data Type Conversion
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
# generate random number
i... |
86f78aaf3814ec5a60eb06e9fdc593bb3bfb666b | vivek-mishr/Python | /reverse3.py | 256 | 3.78125 | 4 | class Solution:
# @param A : string
# @return string
def reverseWords(self, A):
arr=A.split(" ")
arr2=reversed(arr)
return " ".join(arr2)
sol = Solution()
x = input("enter the string ")
y = sol.reverseWords(x)
print(y) |
df347b417d901d294454303bb18c51e5e4d1a5ce | pcampese/python | /arguments.py | 1,015 | 4.03125 | 4 | #!/usr/bin/env python
"""Testing out python arguments."""
import argparse
def main():
"""This is the main function."""
parser = argparse.ArgumentParser(description='My Sample Description.')
parser.add_argument('-f', '--filename',
required=True)
parser.add_argument('-w', '--wiz... |
b83cb4f57bfa0d150ae464779ae780af562b82e9 | GUI-nephelo/cvFaceMaker | /__init__.py | 4,151 | 3.671875 | 4 | import face_recognition
import cv2
def main():
# This is a demo of running face recognition on a video file and saving the results to a new video file.
#
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the... |
43a65773498874c4743408243f69221a276d5d42 | BambooRonin/Ian_Lukas_dz_9 | /task_9_4.py | 2,286 | 4.0625 | 4 | class Car:
def __init__(self, name, colour, speed, police=False):
self.name = name
self.colour = colour
self.speed = speed
self.police = police
print(f'Новая машина: {self.name}, цвет {self.colour}, полицейская {police}')
def go(self):
print(f'{self.name... |
0d7d95bae2236f6e74234a774d03b931b8bff590 | rrk569/ragul | /eveninterval.py | 119 | 3.546875 | 4 | num=raw_input().split()
num1=int(ra[0])
num2=int(ra[1])
for j in range(num1+1,num2):
if(j%2==0):
print(j),
|
f8c61dab9ada4b623b6489ff5d271713598bea3d | wendlers/mpfshell | /mp/retry.py | 1,738 | 3.6875 | 4 | import time
from functools import wraps
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""
Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/Py... |
ca89b92430f7a8186ad5ccd330c4d3b5ed22d132 | blumoestit/100DaysPython | /Day3/Leap_year.py | 539 | 4.21875 | 4 | #### Write a program that works out if a given year is a leap year.
## on every year that is evenly divisible by 4
## except every year that is evenly divisible by 100
## unless the year is also evenly divisible by 400
year = int(input("Which year do you want to checck?"))
if year % 4 == 0:
i... |
d965b7bb1c454e2c8f92952decc79d38c61ea75a | 008karan/Python-projects | /can you guess.py | 523 | 3.671875 | 4 | import random
n=0
z=[]
m=[]
k=0
while k!='q':
x = random.randint(1, 9)
y = int(input("enter your no.\n"))
n=n+1
z.append(x)
m.append(y)
if x==y:
print("you are lucky")
break
elif x>y :
if x-y>=3:
print('guessed too low')
else:
print('you are close')
elif x<y :
if y-x>=3:
... |
c82bbe9a39a27020200a1a8e9e418585fef2185c | Santos-Gustavo/CodeWars-Python | /<5 kyu> Simple Pig Latin.py | 464 | 3.875 | 4 | ''''
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
''''
def pig_it(text):
text = text.split()
ftext=''
points=['.','!','?',';',',']
if text[-1] in points:
for word in text:
ftext += ' '+word[1:]+word[0:1... |
03ce7f98aefd20de89daea93a141c3128bf21083 | Rokkai/PyFinal | /FinalQuestion2.py | 905 | 4.125 | 4 | import math
import cmath
"""Calculate all vlaues for right triangles when the sides are no greater than 20"""
#sides
a=int(raw_input("Input side -a-. Value must be under 20"))
b=int(raw_input("Input side -b-. Value must be under 20"))
c=None
#angles
A=None
B=None
C=90
def findHypo():
"""Return the hypotenuse of ... |
0b21a9d5479743619c96977ec28dd0116af6c982 | anooprh/leetcode-python | /algorithm/a070_Climbing_Stairs.py | 707 | 3.703125 | 4 | import os
class Solution(object):
def climbStairs(self, n, table={}):
"""
:type n: int
:rtype: int
"""
if n in table: return table[n]
if n == 0:
ans = 0
elif n == 1:
ans = 1
elif n == 2:
ans = 2
else:
... |
77524d26d040089794ee1dd40bf1dc63567c5a56 | Hachero/SensorX | /_Docs/course_code/example.py | 604 | 3.5625 | 4 | __author__ = 'Hachero'
import math
print('number 1 \t The Larch \nnumber 2 \t The Horse Chestnut')
name = 'Mike'
age = 48
print(name +' is ' + str(age))
bun_price = 2.40
money = 15
quantity = money//bun_price
print(quantity)
print(math.pi)
print("Python was created by Guido van Rossum.")
print("He's referred to as th... |
510952ff15fc9d455540ae0fda1e4df06c9b4a57 | ShahzaibRind/Python_Programms | /faulty calculator.py | 660 | 4.03125 | 4 | x = int(input("Enter first Number"))
print("press + for Addition")
print("press - for subtraction")
print("press * for Multiplication")
print("press / for Division")
a = input()
y = int(input("Enter second Number"))
if a=="+" or a=="-" or a=="*" or a=="-":
if a == "+":
if x == 56 and y == 9:
pri... |
407a7436756657aa170bc6202127d4e859ff0864 | Moeh-Jama/Kattis-Problems | /Simple Problems/test.py | 1,141 | 3.578125 | 4 | word = 'stairs'
s = 'erres airs ears ares aires'
e = 'eet eat'
collection = []
collection.append(s)
collection.append(e)
'''
for i in s.split():
collection.append(i.strip())
for i in e.split():
collection.append(i.strip())
for i in collection:
print(i)
'''
Yes_and_No = []
phrases = ['apples and pears','plates of m... |
85a837ac70d99195f1be02df2b9e9e02c1b4b713 | SegFault2017/Leetcode2020 | /134.gas-station.py | 822 | 3.734375 | 4 | #
# @lc app=leetcode id=134 lang=python3
#
# [134] Gas Station
#
# @lc code=start
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
""" Strategy 1: Greedy
Runtime: O(n), where n is the size of gass and cost
Space:O(1)
Args:
gas (List[... |
d5b59c594186544021c382eeff9832e9cdff7206 | ZavrazhinMA/PythonPart1 | /hw_4_7.py | 1,520 | 4.21875 | 4 | """7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fact(n).
Функция отвечает за получение факториала числа,
а в цикле необходимо выводить только первые n чисел... |
6f717d886fcf891d2145be7f5b42aab52b87c92d | ahmd-nabil/remove-website-names | /remove_sitename.py | 351 | 3.515625 | 4 |
import os
import os.path
def walk(cwd, txt):
for el in os.scandir(cwd):
if el.is_file() and txt in el.name:
new_path = el.path.replace(txt, "")
os.rename(el.path, new_path)
elif el.is_dir():
walk(el, txt)
if __name__ == '__main__':
cwd = os.getcwd()
tx... |
659e73a544c020b9e50dba56671ab948f18a7b1f | marinabel1/automation-master | /borrow/newbie/model/LoanApplication.py | 672 | 3.609375 | 4 | class LoanApplication:
""" Модель заявки на займ для первичника """
def __init__(
self,
term=None,
amount=None,
borrower=None,
):
self.id = None
self.term = term
self.amount = amount
self.borrower = borrower
self.number... |
31c5b126295d6e85a0369ab7733e93d315bc188a | typemegan/Python | /StudyNote/queue | 1,428 | 4.28125 | 4 | #!/usr/bin/env python
#coding:utf-8
'''
Queue(队列):
- 入队(enqueue)
- 出队(dequeue)
Python中队列的实现:
collections.deque()
'''
from collections import deque
"创建队列"
deque() -> deque obj #创建空队列
deque(non-iterable) #创建队列,队列包含一个元素(非迭代)
deque(iterable) #创建队列,队列包含多个元素(元素个数为迭代对象-字符串/列表/元祖/生成器/字典等的元素个数)
deque([iterab... |
dc84756937754bfedee5d9fe3c6c2364a3cf7b2b | syurskyi/Algorithms_and_Data_Structure | /Algorithmic Problems in Python/Backtracking/MazeProblem.py | 1,628 | 3.875 | 4 |
class MazeProblem:
def __init__(self, mazeTable):
self.mazeTable = mazeTable
self.mazeSize = len(mazeTable)
self.solutionTable = [[0]*self.mazeSize for x in range(self.mazeSize)]
def solveMaze(self):
if self.solve(0,0):
self.showResult();
else:
print('No feasible solution has found...')
... |
2ce3b6d21d2cae11df481455afd8f659dfbe8fe9 | jfidelia/insertion_algoritm | /insertion.py | 420 | 4.09375 | 4 | numbers = [5,3,8,1,4,9,7,2,6]
def insertionSort(numbers):
for x in range(1, len(numbers)):
key = numbers[x]
y = x-1
#print('if '+str(numbers[x])+' is less than '+str(numbers[x-1]))
while y >= 0 and key < numbers[y]:
numbers[y+1] = numbers[y]
#print("swap")
y -= 1
numbers[y+1]... |
504923cac71869b08997a7528ad4fa4b4fd7feab | h-yaroslav/pysnippets | /lections/dict_I.py | 2,501 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# Словарь (хэш, ассоциативный массив) - это изменчивая структура
# данных для хранения пар ключ-значение, где значение однозначно
# определяется ключом. В качестве ключа может выступать неизменчивый
# тип данных (число, строка, кортеж и т.п.).
# Порядок пар ключ-значение про... |
0a0ebcfdb097e79dd8b4af116abad127fdf74da8 | IamFive/skeleton-h5flask | /goblin/common/tools/strlib.py | 2,185 | 3.5 | 4 | # -*- coding: utf-8 -*-
#
# @author: Five
# Created on 2013-4-24
#
"""
strlib.py
"""
def after(s, pat):
# returns the substring after pat in s.
# if pat is not in s, then return a null string!
pos = s.find(pat)
if pos != -1:
return s[pos + len(pat):]
return ""
def rafter(s, pat):
# r... |
27dd0c726e69ba66d90b6772a28eb22613889c9b | uscliufei/Optimization-in-Cloud-Computing | /plot.py | 795 | 3.625 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
x = [i for i in range(200)]
total_cost = []
for i in range(250):
if i < 50:
cost = random.uniform( (200 - i) * 900, (200 - i) * 1000)
total_cost.append(cost)
elif i >= 50 and i < 100:
cost = random.uniform( (200 - i) * 80... |
8cf0d946cafdd8437d38ca016d01b80760641577 | umnstao/lintcode-practice | /twoPointers/148.sortColors.py | 1,045 | 4.03125 | 4 | class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
# write your code here
if nums is None or len(nums) <= 1:
return
left = 0
right = len(nums) - 1
cur = 0
while cur <= righ... |
88bf992693c15d79bcf7113b73bcb2a250112ea4 | costacoz/python_topics | /filter_examples.py | 516 | 4.125 | 4 | """
Examples of filter() built-in function usage.
filter() returns iterator.
To get normal output for print, after filter() usage, need to use list()
"""
def is_number(a):
return isinstance(a, int)
stash = ['ab', 5, ('1', 51), '11', 777]
print(list(filter(is_number, stash))) # simple case of filt... |
600e228c98604b6793db545c92d8b19616125df0 | Sangdol/python-test-driven-learning | /tests/test_named_tuples.py | 1,596 | 4.21875 | 4 | """
Documentation for namedtuple
https://docs.python.org/3/library/collections.html#collections.namedtuple
Documentation for typing.NamedTuple
https://docs.python.org/3/library/typing.html#typing.NamedTuple
"""
from collections import namedtuple
from typing import NamedTuple
def test_named_tuple():
Point = named... |
8a8f9357d4a1fc0ce78dd1984923e24b873f4e0a | wasiwasi/pycote | /ch6_sort/basic_sort.py | 1,024 | 3.640625 | 4 | import time
array = [7, 5, 3, 4, 5, 1, 9, 6, 8, 2]
#선택
# for i in range(len(array)):
# min_index = i
# for j in range(i+1, len(array)):
# if array[min_index] > array[j]:
# min_index = j
# array[i], array[min_index] = array[min_index], array[i]
# print(array)
# 삽입
# for i in range(1, l... |
571ce5e8d54230450d06778b81c95d984e12ce5e | debajyoti-ghosh/Pythonshala | /Itertools/itertools_product/itertool_product.py | 375 | 3.859375 | 4 | from typing import ChainMap
from itertools import chain, repeat, product
list1 = []
list2 = []
list1 = [int(item) for item in input("Enter item of 1st list:").split()]
list1.sort()
print(list1)
# list2 = [int(item) for item in input("Enter item of 2nd list:").split()]
# list2.sort()
# final_list=list((list1,list2))
... |
f020a5c0c1635cb639c9c9b47db4512b1edc6044 | jiangshshui/leetcode | /sixthPage/290_WordPattern.py | 881 | 3.6875 | 4 | class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
m={}
str=str.split()
if len(str)!=len(pattern):
return False
for index,ch in enumerate(pattern):
if ch n... |
cf299a8d433fc0ca7edb22b055b405ffa0c29083 | bhaskarwagatakar/Git_and_Github_Learning | /Git and GitHub.py | 8,047 | 3.84375 | 4 | """
---------------------------------------
|Git and GitHub Tutorial For Beginners|
----------------------------------------
YouTube Tutorial Link: https://www.youtube.com/watch?v=3fUbBnN_H2c
Git:
Git is a version c... |
c105970dc3d52aa6a14f51af8b7cc51b323e2291 | pacis32/Data-Structure-and-Algorithm-Problem-Solutions | /LeetCode/StringAndNumbers/reverseInteger.py | 641 | 3.953125 | 4 |
# Given a 32-bit signed integer, reverse digits of an integer.
def reverse(self, x: int) -> int:
reversedInt = 0
number = 0
if x > 0:
while math.floor(x) is not 0:
number = int(x % 10)
x /= 10
reversedInt = (reversedInt * 10) + number
else:
x *= -1... |
24efa44044cf258adcba98611db674f3d3cd82f6 | ho-hwa/pythonSeminar | /chapter5/class.py | 261 | 3.59375 | 4 | #class.py
class Calculator:
def __init__(self):
self.result = 0
def adder(self, num):
self.result += num
return self.result
cal1 = Calculator()
cal2 =
Calculator()
print(cal1.adder(1))
print(cal1.adder(3))
print(cal2.adder(4))
print(cal2.adder(3))
|
f1e021b9fa94fe4bb5297e039ee8a3cbaeb7b48b | WangRongsheng/Python-functions | /functions/hex函数详解.py | 795 | 4.28125 | 4 | '''
描述
hex() 函数将一个整数转换成十六进制字符串。
语法
hex 语法:
hex(x)
参数说明:
x -- 整数。
返回值
返回十六进制字符串。
'''
print(hex(12)) #输出12的八进制 0xc
print(hex(-120)) #输出-12的二进制 -0x78
print(type(hex(12))) #输出oct(12) 的类型 <class 'str'> 所以不能直接计算
print(int(hex(10),base=16)+int(hex(15),base=16)) #输出 25
#base 参数不可为空 为空默认参数为10进制 会报错 ValueEr... |
e66df34ae6624786de81561bf9ef02ffbe44cf3e | mbednarski/fractal | /fractal/cuda_tutorial_01.py | 1,379 | 3.5625 | 4 | import numpy as np
from numba import cuda
import matplotlib.pyplot as plt
import math
"""
Cuda tutorial 01
In this ex we are going to perform a few most fundamental operations.
1. Allocate a 1D array with size 4096 elements on the device (not in RAM, but in the GPU memory)
2. Set block size
3. Compute the required ... |
1c26f3d8e26afc5528f5a03e81a9d8f24ffcb6a9 | Richiewong07/Python-Exercises | /python-assignments/turtle-graphics/turtle2.py | 410 | 3.671875 | 4 | from turtle import *
def star ():
for i in range(5):
forward(100)
right(144)
def draw_circle ():
pencolor('orange')
width(10)
circle(180)
# move into position
up()
forward(50)
left(90)
forward(50)
left(90)
down()
# draw the square
forward(100)
left(90)
forward(100)
left(90)
forwar... |
ae85995be88b9cf35280366a2345915c8c96da8d | gustavodomenico/Python-Exercises | /Strings/007_first_half.py | 262 | 3.921875 | 4 | # Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
def first_half(str):
return str[: len(str) / 2]
assert first_half('WooHoo') == 'Woo'
assert first_half('HelloThere') == 'Hello'
assert first_half('abcdef') == 'abc'
|
e1f285237204974dffc6eb9323466fd192efd629 | zain08816/Coding-Problems | /Set #1 Problems/Dailys/#123 rightTriangle.py | 104 | 3.515625 | 4 | def rightTriangle(sides):
sides = sorted(sides)
a, b, c = sides
return (a**2 + b**2) == c**2 |
26270fc93c7c68172f8298743e7a372f71bbf1dc | ko-tech/pythone-dev | /Chapter 9/9.6-Ice_Cream_Stand.py | 1,304 | 4.21875 | 4 | #9-6 Ice Cream Stand:
class Restaurant():
"""Simple Restaurant Class"""
def __init__(self, r_name, r_cuisine):
"""Initialize name and cuisine attributes"""
self.r_name = r_name
self.r_cuisine = r_cuisine
self.number_served = 10
def set_number_served(self, number):
... |
0a542b565689ff8d6a073b1ea828ec0fdb5148a9 | Ryanme513/FinalProject | /WordCount.py | 799 | 3.828125 | 4 | # essay = "Enter the equation below and hit submit. If you need to fix your work, go back to the prior screen"
def lettercount(essay):
space = essay.count(" ")
period = essay.count(".")
comma = essay.count(",")
questionmark = essay.count("?")
exclamationmark = essay.count("!")
y = len(essay) - s... |
5d37b3ac095f5102ae7e5a05c08204c1b57a137b | benevolentprof/inf1340_2015_asst2 | /exercise3.py | 1,336 | 4.09375 | 4 | #!/usr/bin/env python
""" Assignment 2, Exercise 3, INF1340, Fall, 2015. DBMS
This module performs table operations on database tables
implemented as lists of lists.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
def union(table1, table2)... |
39b98c837d01476b8145b0ed941b80022597c6b9 | pranaymarella/Harvard-CS | /CS_50/problem_set_6/mario.py | 920 | 4.0625 | 4 | import cs50
def main():
# make sure user gives a positive integer no greater than 23
while True:
print("Height: ", end='')
h = cs50.get_int()
if (h >= 0 and h <= 23):
break
# draws the pramid
draw_pyramid(h)
# draws the pyramid based on the h (height) given
def... |
9d340e7d657210ea17b2930754ac97660e528741 | jacksonw765/PhraseCatch | /scripts/importer.py | 1,692 | 3.515625 | 4 | import argparse
import os
def remove_duplicates(values):
output = []
seen = set()
for value in values:
if value not in seen:
output.append(value)
seen.add(value)
return output
def text_to_list(text_file):
with open(text_file) as f:
word = f.readlines()
... |
617b9ca55b236cbd8494d5c1addee94d34b27b0a | patmizi/code2learn-back-end | /code2learn-back-end/test-relation.py | 82 | 3.765625 | 4 |
for letter in 'Python': # First Example
print ('Current Letter :', letter) |
18f8228ddd51cd6a22d9156076c4f3addb5d6140 | 4RG0S/2020-Fall-Jookgorithm | /김송이/[2020.09]/[2020.09.28]17413.py | 723 | 4.03125 | 4 | def main():
str = input()
word = ''
result = ''
tag = False
for c in str:
if c == ' ':
if tag == False: # 꺽쇠 x
result += word[::-1]
result += c
word = ''
else: # 꺽쇠 O
result += word
res... |
63e505a200cc68763ec323765d2adc8be7aa69e8 | wissam0alqaisy/python_begin_1 | /begin_2/0_formatting.py | 3,014 | 4.34375 | 4 | ###############################################
# #
# Created by Youssef Sully #
# Beginner python #
# Formatting 1 #
# #
################################... |
ed0e11ba4500333bb3fe04dfb2b38902c30aaceb | davideguidobene/cinema-web-app | /app/utils/utils.py | 921 | 3.765625 | 4 | """Funzioni di utilità generale"""
import re
def shorten_text(text, max_len):
"""Tronca il testo alla lunghezza data, aggiungendo 2 punti di sopsensione
Args:
text (str): testo da troncare
max_len (int): massima lunghezza del testo finale
(compresi i 2 punti di sospensione)
... |
e5996511d29b10f573ebd07cbc4ad2250c4be04d | nwthomas/code-challenges | /src/daily-coding-problem/easy/intersecting-lists/test_intersecting_lists.py | 1,372 | 3.796875 | 4 | from intersecting_lists import SinglyLinkedList, get_intersection_of_lists
import unittest
class TestIntersectingLists(unittest.TestCase):
def test_returns_intersecting_value(self):
"""Returns the Node where two singly-linked lists intersect"""
list_1, list_2 = self.generate_intersecting_lists([51,... |
c5775ad4c74ebd5ccb1ae14fad4be61c3058f9cb | mjbrundage/BitShift | /shiftRight.py | 265 | 3.890625 | 4 | """
Program: shiftRight.py
Programmer: Matt Brundage II
Date: 4/7/21
Shifts bits one place to the right and prints the result.
"""
#Input the string
string = input("Please Enter the String: ")
#Shift bit
shiftRight = string[-1]+string[0:-1]
#Print result
print(shiftRight) |
c14a1b59f0ac66d0abc2cd52b6336efb082d5f83 | Jeanzw/LeetCode_Practice | /Python/Array/27. Remove Element.py | 754 | 3.671875 | 4 | # 题目中说了:
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
# 那么我们只可以改原来的内容,相当于用如果一样,那么就继续扫,如果不一样那么就替代之前的内容
# 然后得到长度,输出这个长度就好
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
point = 0
for i in nu... |
287ae427798413284cc5c9ee99545de0f36f0931 | sakars1/python | /inheritance.py | 476 | 3.890625 | 4 | class Child:
def __init__(self,name,age):
self.age=age
self.name=name
def display(self):
print("Name: ",self.name)
print("Age: ",self.age)
class Student(Child):
def __init__(self,degree,Child):
self.degree=degree
self.name=Child.name
self.age=Child.ag... |
7541aa782f30bf9cac2c58de0338aa42d1a8bd76 | ABCmoxun/AA | /AB/linux2/day12/student_project2/student_info.py | 1,582 | 3.875 | 4 | # student_info.py
def input_student():
lst = [] # 创建一个空列表用于存储学生的信息(字典)
while True:
n = input("请输入学生姓名: ")
if not n:
break
a = int(input("请输入学生年龄: "))
s = int(input("请输入学生成绩: "))
# 创建一个新的字典
d = {'name': n,
'age': a,
'score':... |
370d15d1092fa359b0aed032ee407eb307c963ae | Ratatou2/Algorithm_Interview | /+a. 두 자릿수 배열 조합.py | 676 | 3.609375 | 4 | from itertools import combinations
items = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
n = int(input())
for i in range(1, n+1):
print(list(map(''.join, combinations(items, i))))
''' <combination 공부>
- 알고보니 조합을 일일이 짤필요없이 파이썬은 따로 라이브러리에 가지고 있었다...
- 속도도 월등히 빠름
- 위 코드 해석은 일단 조합(combination)을 불러온 다음
- list에 적어 넣... |
7a1764838011cad9842aa5924f020feec3b860a0 | hmhuan/advanced-python | /itertools.py | 1,306 | 3.71875 | 4 | from itertools import count, cycle, repeat
from itertools import groupby
import operator
from itertools import accumulate
from itertools import combinations, combinations_with_replacement
from itertools import permutations
from itertools import product
prod = product([1, 2], [3, 4])
print(list(prod))
prod = product([1... |
2afbb2e3d68d60668d19af39aba1c00baab2d541 | Cakaliman/Algoritmos_e_Logica_de_Programacao-Python | /FuncoesEx6.py | 173 | 3.890625 | 4 | def tamanho(n):
ac = 1
while n>10:
n = n//10
ac = ac + 1
print(ac)
x = int(input('Digite um númmero: '))
tamanho(x)
print('--FIM--')
|
275fc48665d0c016dd4dbc9342fee28c5b6c92bc | KoveKim/Python-Practice | /Try-Except Block Practice.py | 368 | 4.0625 | 4 | # Try/Except Block practice
try:
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print(err) # Print the error itself
except ValueError:
print("Invalid input, numbers only")
# "Except" will catch ANY error in "try" under the sun and is too broad
# It's best to specify... |
8ff5e08b3589a7c23af68f941d7129482cba7faf | patbonecrusher/codewars | /multiples-of-3-or-5/solution.py | 280 | 3.90625 | 4 | def solution4(number):
l = [x for x in range(number) if not x%3 or not x%5]
return sum(l)
def solution(number):
return sum(x for x in range(number) if not x%3 or not x%5)
print(solution(4))
print(solution(6))
print(solution(16))
print(solution(3))
print(solution(5)) |
3590a258521b3442cfa392fe3a84bdbec9f9bfa6 | mptrepanier/coding-cookbook | /python/python-practice-master/practice/FindEmail.py | 327 | 3.515625 | 4 | import re
class FindEmail:
def find_email(self, text):
words = text.split()
r = re.compile(r'([a-zA-Z0-9])+(@)([a-zA-Z0-9])+(\.)([a-zA-Z0-9])+')
def matches(x):
return bool(r.match(x))
ans = list(filter(matches, words))
print(ans)
return ans
... |
79a6856f1b63dbe94c698285faa47d67e758a667 | subreena10/moreexercise | /harshadnumber.py | 350 | 3.890625 | 4 | # number=int(input("Enter your number: "))
# num=number
# rem=0
# sum=0
# while number>0:
# rem=number%10
# sum=sum+rem
# number=number//10
# if num%sum==0:
# print("it is harshad number")
# else:
# print("no")
# num=int(input("enter your number: "))
# if "3" in num and num[1]==3 :
# print("yes... |
065a308c27db94610f9c27ee1b6921a22cb395ff | chuckwm/flask-apis-with-python | /section2/ifstatements.py | 1,453 | 4.28125 | 4 | # should_continue = True
# if should_continue: # == True: This can be left out it is assumed
# print("Hello")
#
# known_people = ["John", "Anna", "Mary"]
# person = input("Enter the person you know: ")
# if person in known_people:
# print("You know this {}".format(person))
# # print("You know this person!")... |
c458d7c466a532c54bc96d7752597c50b324de7e | curiousTauseef/Algorithms_and_solutions | /Codility/2_OddOccurrencesInArray.py | 1,830 | 4.25 | 4 | '''
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 ... |
020840d45c974b5e241a20f89d9fedc26dde6b84 | jamessuttonjr/OOP-HW | /dictionaryhw.py | 591 | 3.96875 | 4 | coursenumbers = {"CS101":["3004", "Haynes", "8:00a.m."],
"CS102":["4501", "Alvarado", "9:00a.m."],
"CS103":["6755", "Rich", "10:00a.m."],
"NT110":["1244", "Burke", "11:00a.m"],
"CM241":["1411", "Lee", "1:00p.m."]}
coursechoice = input("Please enter a... |
3a02e7b29b0f651c4efcd0ff402baaaa29dd9f39 | qbitsinfo2016/qbitsinfo | /ejer11.py | 877 | 3.890625 | 4 | var2 = float (input("ingrese el salario del empleado"))
print ("indique por si o por no si el empleado asistio todo el mes")
x = str (input(""))
print ("indique 1, 2 o 3 segun el rango horario que trabajo el empleado")
print ("1: entre 3 y 5 horas los domingos")
print ("2: entre 6 y 10 horas los domingos")
print ("3: e... |
b97f4b8e918ad2727ecb4831ac0632c5f7154f14 | hhongjoon/TIL | /HJ_AL/190328TST/1_n까지의 합.py | 100 | 3.734375 | 4 | def summ(n):
if n ==0:
return 0
return n+summ(n-1)
N = int(input())
print(summ(N))
|
aacedb6273d4c84b0d5045806020b55f276cc091 | BensonMuriithi/python | /exercises/quest1.py | 255 | 4.09375 | 4 | """Find numbers that are divisible by & and not a multiple of 5 between 2000 and 3200 (both included)
The numbers should then be printed separated by commas in a single line"""
for i in range(2000, 3201):
if (i % 7 == 0) and not (i % 5 == 0):
print i, |
a8a8b461fbc7a9df8ab8a570406dd4f5b5fc1bc6 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Hash/PrintVertical.py | 1,042 | 4.4375 | 4 | from GeeksForGeeks.Tree.BinaryTree import BinaryTree
"""
Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method)
Given a binary tree, print it vertically. The following example illustrates vertical order traversal.
1
/ \
2 3
/ \ / \
4 5 6 7
... |
b431b4cb661331e0464857991193abe167803616 | Jinmin-Goh/LeetCode | /Solved/0215/0215_mergeSort.py | 934 | 3.578125 | 4 | # Problem No.: 215
# Solver: Jinmin Goh
# Date: 20200206
# URL: https://leetcode.com/problems/kth-largest-element-in-an-array/
import sys
# time: O(n log n) / memory: O(1)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums = self.mergeSort(nums) # also able to use d... |
5e46736ee0b05d95dc66d086ba589380401faef9 | andyRon/note-exercise | /Python/Web_Scraping_with_Python/1.4_crawling_2.py | 462 | 3.578125 | 4 | import urllib2
def download(url, num_re = 2):
print "Downloading:", url
try:
html = urllib2.urlopen(url).read()
except urllib2.URLError as e:
print "Download error.", e.reason
html = None
if num_re > 0 and hasattr(e, 'code') and 500 <= e.code < 600:
return down... |
34dd5647804cc2e786fd793e1c793da3d079a15d | ShafiqurRahman-886/ZeroToHero | /Input.py | 367 | 4.09375 | 4 | x = input()
print(x)
# by default input take string value
# inpute() -- This method for taking input
# to take integer input
y = int(input('age \n'))
print((y))
# we can convert str(age) into string and viceversa
# for x=x+3 we can use x+=3 same for others operators
#walrus operator #/
print(num := input('na... |
6b0fd17576c293759c02c54a12acefa18b8120f2 | jonaro00/ProgrammeringsOlympiaden | /skolkval18/uppg4.py | 1,245 | 3.640625 | 4 | def swap(brickor, i, d):
temp = inverted([brickor.pop(i) for _ in range(2)])
return brickor + temp if d else temp + brickor
def unswap(brickor, i, d):
for b in reversed(inverted([brickor.pop(p if d else 0) for p in range(-2, 0)])):
brickor.insert(i, b)
return brickor
def inverted(r):
return ... |
462068248a0577c25df5c1d3cf7b82cc1aca790c | drw72/Programming-for-Everybody-Python | /assignment 5_2.py | 1,273 | 4.03125 | 4 | '''
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered,
print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try
/except and put out an appropriate message and ignore the number. ... |
854a2476fe1d99bff45bd7abd876b71d57f4c628 | zero-big/Python-Basic | /Data/7. structed_text.py | 8,035 | 3.515625 | 4 | ''' 구조화된 텍스트 파일 형식
- CSV : 탭('\t'), 콤마(','), 수직바('|')와 같은 문자를 구분자(분리자)로 사용
- XML & HTML : 태그('<', '>')
- JSON : 구두점
- YAML : 들여쓰기
'''
''' 1. CSV '''
import csv
villains = [
['Doctor', 'No'],
['Rosa', 'Klebb'],
['Mister', 'Big'],
['Auric', 'Goldfinger'],
['Ernst', 'Blofeld'],
]
# 파일 쓰기(cs... |
f38c576ebba2f8d553316df117823e2065aa5133 | Brian2008/PythonTesting | /words.py | 309 | 4.0625 | 4 | intro=input("Enter your Introduction->")
charaterCount=0
wordCount=1
for i in intro:
charaterCount=charaterCount+1
if(i==' '):
wordCount=wordCount+1
print("number of words in the string are ")
print(wordCount)
print("number of charaters in the string are ")
print(charaterCount)
|
1e6dceec770e63d93b4d64b9dde390412ecad34f | joriskortekaas/Vulmachiiin | /scripts/robot/readyForRPI/encryptor.py | 451 | 3.578125 | 4 | from Crypto.Cipher import AES
class Encryptor:
key = b'2r5u7x!A%D*G-KaP'
iv = b'This is an IV456'
print(key, iv)
cipher = AES.new(key, AES.MODE_CBC, iv)
print('thats alot of cipher')
# Encrypts message
def encrypt(self, _string):
return self.ciph... |
3d680d54156c71ffe87fd1c3521f118197d970c1 | jisr0703/learn-algorithm-by-writing | /Tree/binarytree.py | 1,457 | 3.71875 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def __repr__(self):
return str(self.data)
class BinaryTree:
def __init__(self):
self.__root = None
@property
def root(self):
return self.__root
def create... |
c3a6cc369bc952f0e7294fd6acd6b47e1ec9d7e3 | uclaacm/learn.py-s21 | /session-4-files-and-automation/time.py | 380 | 3.890625 | 4 | import time
t = time.time() #time since 12AM Jan 1st, 1970
readable_t = time.ctime(t) #readable time
print(t)
print(readable_t)
# print("started")
# start_time = time.time()
# time.sleep(5)
# end_time = time.time()
# print("start - end = " + str(end_time - start_time))
count = 60
while (coun... |
05ba7b28f620147d9370395a07fb9cfc922881d1 | ruozhizhang/leetcode | /problems/array/Valid_Word_Square.py | 1,736 | 4.09375 | 4 | '''
https://leetcode.com/problems/valid-word-square/
Given a sequence of words, check whether it forms a valid word square.
A sequence of words forms a valid word square if the kth row and column read the
exact same string, where 0 ≤ k < max(numRows, numColumns).
Note:
The number of words given is at least 1 and doe... |
7afc643b4883953adc1a036fe0e4c5c9f42ced0f | mathivanansoft/algorithms_and_data_structures | /data_structures/k_sorted_list.py | 2,182 | 3.5 | 4 | # In a k sorted lists, find the minimum range in which
# atleast one element belongs to every list
import os
import sys
user_path = os.environ.get("USER_PATH")
sys.path.append(user_path)
from data_structures.min_heap import MinHeap
class K_Ordered(object):
def __init__(self, data, kind, next_index):
sel... |
148c4d42cb5fd0e3417aa4c8e0b3f33061e02094 | silvafj/BBK-MSCCS-2017-19 | /POP1/worksheets/one/ex23/code.py | 314 | 4 | 4 | def draw_grid():
"""
Draws a grid with 2 rows and 2 columns.
"""
def separator():
print("+", 4 * "-", "+", 4 * "-", "+", sep="")
for r in range(2):
separator()
for _ in range(4):
print("|", 4 * " ", "|", 4 * " ", "|", sep="")
separator()
draw_grid()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.