blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1d5bc9d13b021a1430a0a5832928b5c3d9f2fd98 | sersavn/practice-hackerrank | /Python/Strings/Textalignmentbasic.py | 764 | 4.125 | 4 | #In Python, a string of text can be aligned left, right and center.
#This method returns a left aligned string of length width.
#.ljust(width)
#This method returns a left aligned string of length width.
width = 20
print('HackerRank'.ljust(width,'-'))
#.center(width)
#This method returns a centered string of lengt... |
bac7de4e1a2a2eca4feb97a73ca2082a3f3c2d44 | rebeccasedgwick/pym | /bank_account.py | 959 | 4 | 4 | class Account(object):
# Has a balance, which is held in GBP. Rate is FX rate to convert to USD.
def __init__(self, usd_rate):
self.__balance = 0
self.usd_rate = usd_rate
@property
def balance(self):
"Returns the balance property."
return self.__balance
@property
... |
c6327543b5afe023069d71f261d1297b91ab25ed | spelykh/qa-python | /python_for_qa/lesson_2-2/task_3.py | 292 | 3.546875 | 4 | __author__ = 'Stepan_Pelykh'
def dupl(a):
list1 = []
for i in a:
if a.count(i) >= 2:
continue
else:
list1.append(i)
print 'List without duplicates -', list1
if __name__ == "__main__":
a = [1, 2, 3, 4, 4, 6, 2]
print a
dupl(a) |
8f98aef2a539011f39099741ceee792c3daa2b04 | ksarthak4ever/Competitive-Programming | /Project Euler/Problem 25/prob25.py | 458 | 4.125 | 4 | from __future__ import print_function
def fibonacci(n):
if n == 1 or type(n) is not int:
return 0
elif n == 2:
return 1
else:
sequence = [0, 1]
for i in range(2, n+1):
sequence.append(sequence[i-1] + sequence[i-2])
return sequence[n]
def fibonacci_digits_index(n):
digits = 0
index = 2
while digit... |
7214b4b3071eb64501afa06be5b00eb208a4ed0b | jamesfowkes/advent-of-code-15 | /d11.py | 1,278 | 3.71875 | 4 | import sys
import string
PAIRS = ""
STRAIGHTS = ""
def increment_char(c):
if c == "z":
return "a"
else:
return chr(ord(c) + 1)
def increment_pwd(pwd):
pwd = list(pwd)
i = len(pwd) - 1
pwd[i] = increment_char(pwd[i])
while pwd[i] == 'a' and i >= 0:
i -= 1
pwd[i] = increment_char(pwd[i])
return... |
f5078e346657d6a563e69225e4e8cb4f90e80c60 | jmlapicola/Python_Puzzles | /Problem51.py | 1,475 | 3.828125 | 4 | def isPrime(n):
if n == 2 or n == 3:
return True
if n%2 == 0 or n%3 == 0 or n < 2:
return False
max = n**(1/2)
i = 5
while i <= max:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def powerSet(set0):
if len(set0) == 1:
... |
f8a88fe18eaec8bc74116d4acc96197bc2cf483b | DanielMorales9/cracking-the-code-interview | /misc/backtracking/hamiltonian_path.py | 1,499 | 4.28125 | 4 | # Hamiltonian Path in an undirected graph is a path that visits
# each vertex exactly once.
# A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path
# such that there is an edge (in the graph) from the last vertex
# to the first vertex of the Hamiltonian Path.
# Determine whether a given graph contains Hami... |
1e1076b77dbeae3220f5d9c1d255cde55c410460 | ishankkm/pythonProgs | /progs/uniqueSubstrings.py | 233 | 3.703125 | 4 | '''
Created on Nov 5, 2017
@author: ishank
'''
def uniqueSubstrings(string, length):
return sorted(list(set(string[i : i + length] for i in range(len(string) - length + 1))))
print uniqueSubstrings("aaabbc", 2)
|
03f7fbec2f4bd23f8e838af39446f4b650f9f505 | AK-1121/code_extraction | /python/python_36.py | 162 | 3.546875 | 4 | # Is there a function in python to split a word into a list?
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
|
9c65bf648b6bf414ffbd142bb22383406c00a4df | WuraolaS/OOP_bank_account | /Bank_Account.py | 1,798 | 4.28125 | 4 | #This is an OOP python project to create a Bank Account
#variables are:
#first name
#last name
#account number
#starting balance
#current balance
#Methods
#withdraw
#deposit
#interaccount transfer
# Bank Account has a checkings and savings account
# Checkings Account is a bank account - it inherits the bank accout cl... |
a39477feebba5611af851390d7b3d272e6613b0c | Arcnaboo/Breakout-Game--Csse1001-Intro-to-Programming-Assignment-3 | /assign3_support.py | 17,937 | 3.96875 | 4 | import math
import json
# The following constants (ALL CAPS) may be useful to the student.
BLOCK_WIDTH = 50
BLOCK_HEIGHT = 15
NUM_ROWS = 30
NUM_COLUMNS = 12
WIDTH = BLOCK_WIDTH * NUM_COLUMNS
HEIGHT = BLOCK_HEIGHT * NUM_ROWS - 5
PADDLE_HEIGHT = 10
TIME_STEP = 20 # 20 millisecs
BALL_INITIAL_X_SPEED = 1
BALL_INITIAL_Y... |
d8ba4068b3a831432e63f649ecb6f4655cb25d9c | Aasthaengg/IBMdataset | /Python_codes/p02546/s946166186.py | 68 | 4.03125 | 4 | word = input()
word += "s" if word[-1] != "s" else "es"
print(word) |
81bff2a6037920e223ab243f3769a4cace1d98d5 | zhoulinyuan/Python- | /Python_Projects/game/friend.py | 320 | 3.90625 | 4 | str = "frind";
# 字符串分片、索引
print(str[0] + str[1:3] + str[-4:-1]);
# /t转义字符
print('\\t\\'); # \t\\
print('\\\t\\'); # \ \
print(r'\\\t\\');
print(r'Hello, "Bart"');# r''使得''内的字符串不转义
print('''hang1
hang2
hang3'''); # 显示3行
print(not True); #boolean类型的判断
|
484539b2b92a24a27d46c35d7c1e74c7a9b8c7cb | rajtyagi2718/berkeley_cs61b | /PrimesTemp.py | 3,136 | 3.625 | 4 | def listPrimesV5(n):
if n <= 1:
return []
if n == 2:
return [2]
if n == 3:
return [2, 3]
results = []
m = math.floor(math.sqrt(n))
# print('m= ', m)
bools = [True for _ in range(3, m+1, 2)]
stop = (m - 1) // 2
for index in range(len(bools)):
if bools[i... |
2a0cfe82c615d0a0a0061dcdf2271f9fd934a357 | yoojunwoong/python_review01 | /test3_06.py | 278 | 3.59375 | 4 | # for 문 2번 사용하기...
for i in range(1,6):
for j in range(1,6):
print(i,'-',j);
print('--------------');
# while loop 2번 사용하기
a = 1;
while a < 6:
a2 = 1;
while a2 < 6:
print(a,'-',a2);
a2 += 1;
a += 1;
|
fabab0f6ce66e62ad8c907c94e3c082a62e7ec07 | TrevorStevenson/Project-Euler | /Python/Problem_16.py | 332 | 3.890625 | 4 | #!/usr/bin/env python3
#find the sum of the digits of 2^1000
def main():
power = 1
n = 2
while power < 1000:
n = n ** 2
power *= 2
while power > 1000:
n = n // 2
power -= 1
sum = 0
for i in str(n):
sum += int(i)
print(sum)
if __name__ == "__main__":... |
261a7cfbfe74cf5fb3c7e0a5015d839a28002dc0 | whisky1234/learnPython | /Function/FunctionTest.py | 559 | 3.9375 | 4 | def func(x = 5, y = 5):
return x, y
print(func(1,2))
print(func())
def calc(*numbers):
sum = 0
for n in numbers:
sum += n * n
return sum
print(calc(1,2,3))
print(calc())
nums = [1,2,3]
print(calc(*nums))
print(*nums)
def keyword(a, b, **c):
print("a", a, "b", b, "c", c)
keyword("hello","wo... |
d36a4cd588223d4d5b4e06a369de12ce466116fc | cubricmms/Leetcode-Python | /6_zigzag_conversion.py | 1,354 | 3.609375 | 4 | # Leetcode problem 6 (ZigZag Conversion): https://leetcode.com/problems/zigzag-conversion/
# Level: Medium
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows <= 1:
return s
resu... |
2ba03f37b8bdd6c130828ce5b7095da0b5ec1a86 | Ri8thik/guessing-game | /guessgame.py | 887 | 4.09375 | 4 | import random
name = input("Hello there, what is your name: ") #asking the user his/her name
secretNumber = random.randint(1, 20) #generating the random number
print('Greetings, '+name+' ,I am thinking of a number between 1 and 20.')
print('Take a guess:') #Giving the user upto 6 chances to huess the number
... |
576c40df887ebbc39d8bea50590c1415b31b6447 | sanyatishenko/PythonEDU | /function.py | 914 | 4.15625 | 4 | #######################
# Работа с функциями
#######################
# Передача параметров, позиционные параметры
def summa(x, y):
return x+y
print(summa(12,13)) # 25
# Любое число параметров
def summa2(*array):
result = 0
for i in array:
result += i
return result
pri... |
6031c5a666437a6e886dbd9bf43bd9b021cf8a56 | atulpatel991928/Hash_map_practice | /sorted_order_country_in_list.py | 222 | 3.921875 | 4 | dict = {}
dict['Newzealand']= 'wellington'
dict['India'] = 'New Delhi'
dict['France']='Peris'
dict['Russia']='Mascoo'
dict['Australia'] ='kenbera'
print(dict)
for i in sorted (dict):
print( dict[i] , end=":")
|
aec96af0d0474596b75d4a5d9bae72d8f0318be6 | wy471x/learningNote | /python/excise/basic/chapter5/5-11.py | 286 | 3.859375 | 4 | #!/usr/bin/env python
# coding=utf-8
number = ['1','2','3','4','5','6','7','8','9']
for num in number:
if num == '1':
print(num + "st")
elif num == '2':
print(num + "nd")
elif num == '3':
print(num + "rd")
else:
print(num + "th")
|
7549d27c709062703de5d4f02b832e79b87136c5 | alphatrl/IS111 | /Lab Tests/2019.1 Mock Lab 2/Solutions/q1b.py | 1,391 | 4.25 | 4 | import q1a
def count_hashtags(post_list):
'''
This function counts the number of hashtagged words in post_list
and returns a list of tuples, where each tuple is of the form (a, b)
where a is a unique hashtagged word, and b is the number of times
that a appears in post_list
'''
# ... |
56886738d40601fee312dd5d9ce271265b525634 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_206/1639.py | 1,992 | 3.90625 | 4 | import sys
def get_max_speed(distance, horses, current_time):
# print "num horses considered: " + str(len(horses))
if len(horses) == 1:
time_taken = (distance - horses[0][0]) / (horses[0][1] + 0.0)
return distance / (time_taken + current_time)
horses.sort(key=lambda tup: tup[0])
# prin... |
54ee9dc78c8477ba5ddc7f4748b53f5f2a8200fb | Shellbellz/Factorials | /factorials.py | 1,104 | 4.15625 | 4 | '''
factorial.py
This program takes user input and then prints out the factorial
'''
def main():
userNumber = userInput()
factorial(userNumber)
'''
factorial function accepts value as int type
loops through the range from one to the value inclusively
and multiplies all values together to get the factorial.... |
9a2d701dad631ca50670f44dbd50ce4393177e21 | louis8683/Matplotlib-Tutorial | /line graph/auto (for recording)/[src] 1-intro.py | 648 | 4.125 | 4 | ` 1st stage: simple plot
# 引入matplotlib函式庫裡面的pyplot,命名為plt
from matplotlib import pyplot as plt
# 手動生成一筆資料
temperature = [21, 20, 21, 23, 25, 24, 25, 25, 26, 27]
# 把資料放到圖表上
plt.plot(temperature)
# 顯示圖表
plt.show()
`
\ 2nd stage
date = ['5/1','5/2','5/3','5/4','5/5','5/6','5/7','5/8','5/9','5/10']
\ put into plt.plot(... |
9837d5949fb96a5bd5e73b8ec72a31cbbd594303 | py19912214/python_demo | /src/basic/Enum_demo.py | 298 | 3.921875 | 4 | from enum import Enum, unique
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
student=Student("pan",Gender.Male);
print(student.name)
print(student.gender.name,student.gender.value) |
bc6b45c67240612ed42f173eab639631f72f621d | BHUVANESHWARI12/py | /numeric.py | 104 | 3.59375 | 4 | a=input("enter the string")
if(b.is numeric()):
print("yes")
else:
print("no")
|
511ce4032376d8e5ee1904775a1832dc4cdca45e | MegSteg/she_codes_python | /user_input_playground.py | 377 | 3.90625 | 4 | answer = input("How are you? ")
message= f"i'm {answer} as well, thanks for asking"
print(message)
name = input ("what is your name?")
hobby = input ("What is your hobby")
print(f"This is {name}, like {hobby}")
age = input (f"Hi {name}, how old are you?")
years_until_100 = 100 - int(age)
print(f"Wow, {name}, You'll b... |
98aa1fa75d3bf2dd381e619a7518db1d6073752f | ksambaiah/python | /pythonds/chap1/numBits.py | 297 | 3.9375 | 4 | #!/usr/bin/env python3
# Given a number find no. of bits set to 1
def numBits(x):
numBitsf = 0
while x :
numBitsf += x & 1
x >>= 1
return numBitsf
if __name__ == '__main__':
x = 1024
b = numBits(x)
print("For number {0} no. of bits are {1}".format(x,b))
|
62d5ced328c02a5c24b4da55ad21431e294dd764 | dngrrng/network_EMAT10008 | /list.py | 984 | 3.53125 | 4 | import random
hublist = []
maxhubs = 20
# constants for drawing
maxXCoord = 1000
maxYCoord = 1000
centreRadius = 40
hubRadius = 20
lineWidth = 5
# Set number of hubs
maxHubs = 32
# Values for centre hub
centreHubCoords = [maxXCoord/2,maxYCoord/2]
centreHubSquareCoords = [maxXCoord/2-centreRadius,maxYCoord/2-centreR... |
ee08edf496036aeaf651d6e71122f83c4386fea7 | reroes/p-algoritmos-ce-182 | /clase3/ejercicios-python/herencia-python/modelado1/modelo.py | 1,169 | 4.09375 | 4 | """
@reroes
"""
class Persona(object):
"""
Definir la clase Persona
"""
def __init__(self):
self.nombre = ""
self.apellido = ""
self.edad = 0
def presentar_datos(self):
return "%s-%s-%s" % (self.obtener_nombre(), self.apellido, self.edad)
def agregar_no... |
781670df284485b2d02bd23ec719e1b934f2c186 | Carlzkh/CrazyPythonNotes | /8/exercise/five.py | 763 | 4.1875 | 4 | """
5. 定义 个生成器,可依次返回 2, 3, …的阶乘
"""
def test(val, step):
print('一一一-函数开始执行一- --')
cur = 1
# 遍历 val
for i in range(2, val):
# cur 添加 i*step
cur *= i * step
yield cur
print(list(test(10, 1)))
# 参考答案
def factorial_generator(n):
rvt_list = [1]
for i in range(2, n + 1):... |
65cb8fcd5648da3fc290baedf00835fcb58bb20c | kimsisingh/python_exercises | /IO_files_examples.py | 3,229 | 4.28125 | 4 | #Input/Output Files in Python
# When you read a file, you have to close it as well
# Open a file
myfile = open('myfile.txt')
# Read the contents of a file in one huge string
contents = myfile.read()
print(f"Contents of file {contents}")
myfile.seek(0) # to move the cursor back to the starting position
contents_again = ... |
03ea4c241098ef4799162545c668a28c32961634 | Sengming/leetcode_solutions | /94.binary-tree-inorder-traversal.py | 1,220 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# Iterative solution:
def inorderTraversalIterative(self, root, localList):
stack = []
result = []
... |
eed7af18a361f7b0811d8805a0d3e3976036ab0c | sanyamsxn/competetive_coding | /hackerrank/python/Python_If_Else.py | 457 | 3.734375 | 4 | n=int(input())
def rish_fn(n):
if ( n%2==0):
if (n>=2 and n<=5):
print('Not Weird')
elif (n>=6 and n<=20):
print("Weird")
else:
print("Not Weird")
else:
print("Weird")
def rish_fn2(n):
flag=0
if ( n%2==0):
if ((n>=2 and n<=5... |
10fe405e879d0f4a889474ed1bbc48e348aaae63 | MargoGrinch/Module_Control | /6.py | 866 | 3.703125 | 4 | '''
6. Створіть масив А [1..8] за допомогою генератора випадкових чисел з
елементами від -10 до 10 і виведіть його на екран. Підрахуйте кількість від’ємних
елементів масиву.
Грінченко Маргарита 122
'''
from random import randint
import numpy as np
while True:
A = np.zeros((8,1), dtype = int)
i, j,... |
eb3dc986c667654edc24bae594d8fb7b472af30a | kevzhang/project_euler | /python/0004.py | 221 | 3.625 | 4 | def isPal(arg):
string = str(arg)
return string == string[::-1]
largest = -1
for x in range(1000):
for y in range(1000):
product = x * y
if isPal(product):
largest = max(largest, product)
print largest
|
648ebaf69ff699c6e98199764bd088c67ccae7e1 | shreeji0312/learning-python | /python-Bootcamp/assignment3/listAssign2.py | 286 | 4.21875 | 4 | #Shreeji Patel
#105151171
listmonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month = int(input('Month: '))
day = int(input('Day: '))
totaldays = 0
for i in range(month-1):
totaldays += listmonth[i]
totaldays += day
print('That\'s day %d of the year' %totaldays) |
972a80cc0e55114509880fc4f75a30bb5c1e856c | TheSuc/Ejemplo_PI | /Pi.py | 197 | 3.796875 | 4 | """
Calculando PI 3.14159265358979323846
"""
sum = 0
a = 0
# Problema de Basilea****
for i in range(1,10000000):
a = 1/((i)**2)
sum = sum + a
#***********************
pi = (sum*6)**0.5
print(pi) |
9373121d306bac8e3c1c92e145e696192632ea6e | longroad41377/iteration | /addition.py | 199 | 4.09375 | 4 | # program to prompt for 8 numbers and report the total to the user
total = 0
for i in range(1, 9):
total += int(input('Enter number {} : '.format(i)))
print('The total is {0}'.format(total))
|
e5c5a5d291f8d2b9ee7f5eeab25c2956ca4f10fa | RohinBhargava/Matrix | /Week 1/Assignments/Assignment 3 (Inverse Functions)/Complete/hw0.py | 1,492 | 3.765625 | 4 | # Please fill out this stencil and submit using the provided submission script.
## Problem 1
def myFilter(L, num):
return_list = list()
for u in L:
if u % num != 0:
return_list.append(u)
return return_list
## Problem 2
def myLists(L):
return_list = list()
for u in L:
... |
ebe2455bd21233968cccb4cda7022be985698020 | JoshuaStanley308/CP1404_Practicals1 | /prac_03/name_thing.py | 438 | 4.15625 | 4 |
def main():
name = get_name()
frequency_of_letters = int(input("Frequency of letters: "))
print_name(name, frequency_of_letters)
def print_name(name, frequency_of_letters):
print(name[::frequency_of_letters])
def get_name():
name = input("Please enter your name: ")
while len(name) == 0:
... |
28036b20590b798f654927ba4a9a46338498d84a | XifeiNi/LeetCode-Traversal | /python/stack/510_maximal_rectangle.py | 1,013 | 3.5 | 4 | class Solution:
"""
@param matrix: a boolean 2D matrix
@return: an integer
"""
def maximalRectangle(self, matrix):
if not matrix:
return 0
max_rectangle = 0
heights = [0] * len(matrix[0])
for row in matrix:
for index, num in enumerate(row):
... |
4a4ee718579e280e14779c98faaa0831270e34dd | realquizm/advent-of-code | /2019/day22/python/deck.py | 1,211 | 3.78125 | 4 | import time
class Deck:
""" Class sorting the cards in the deck """
def __init__(self, file, num_cards):
""" Initialize number of cards and parse instructions """
self.file = file
self.num_cards = num_cards
self.a, self.b = self.parse(self.read_shuffle())
def read_shuffle(self):
""" Go throu... |
38247c5b302b5007912486048e61e9753326a9cc | wangxinjun919/auto_apitest | /apiAutoTest_v2/操作数据库.py | 995 | 3.625 | 4 | '''
python操作mysql需要使用pymysql这个模块
主机:120.78.128.25
port:3306
用户:future
密码:123456
'''
import pymysql
#第一步:连接到mysql数据库
con=pymysql.connect(host="120.78.128.25",user="future",password="123456",port=3306,charset="utf8")
#第二步:创建一个游标对象,看作一个鼠标
cur=con.cursor()
#第三步:执行sql语句
#1.准备sql语句
# sql="SELECT*FROM futureloan.member WHERE... |
6a63dbb96c34713b2e0c6767af05ba57efa9cea9 | mukulietlucknow/Python-Opps-Code | /absctract.py | 422 | 3.96875 | 4 | from abc import ABC,abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Sqaure(Shape):
def __init__(self,side):
self.__side = side
def area(self):
return self.__side * self.__side
def per... |
39cd42c1d69aa0216e27945a28ebd3a5579e3cec | jeremie-j/run-away-python | /Menu.py | 1,073 | 3.6875 | 4 | import os
def Question(Question,*Choix):
Running = True
while Running == True:
print(Question)
for i, Proposition in enumerate(Choix):
print(i+1,":",Proposition)
try:
Numero_Choisi = int(input("Choix : "))
if Numero_Choisi < 1 or Numero_Choisi... |
d214296188d29ba0f4089294b5428a13adc39be8 | geekhub-python/strings-Elfpkck | /10.py | 166 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = input('Enter the string: ')
first = s.split('h', 1)
second = first[1].rsplit('h', 1)
print(first[0] + second[1])
|
d968ffe452556f95eed1913ec620f04707134266 | yandrea888/ejercicios_momento2 | /Ejercicio3.py | 362 | 4 | 4 | #3. Pide números y mételos en una lista, cuando el usuario meta un 0 ya dejaremos de insertar. Por último, muestra los números ordenados de menor a mayor.
lista = []
salir = False
while(not salir):
numero = int(input("Digite un número: "))
if(numero == 0):
salir=True
else:
lista.append(... |
e088e80c9cd5a7ad60ef3974d7694ca7b6893ca6 | serge-sans-paille/pythran | /pythran/tests/rosetta/rangeexpend.py | 387 | 3.765625 | 4 | #from http://rosettacode.org/wiki/Range_expansion#Python
#pythran export rangeexpand(str)
#runas rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20')
def rangeexpand(txt):
lst = []
for r in txt.split(','):
if '-' in r[1:]:
r0, r1 = r[1:].split('-', 1)
lst += range(int(r[0] + r0), int(r1... |
dd46ae8ef0f49879091f74a54b9a60d77a9d7138 | kakaka3170/python | /jiecheng.py | 237 | 3.640625 | 4 |
def chengfa99():
'this is triangle 9X9 table';
for i in range(1,10):
for j in range(1,i+1):
print ('%2d X %2d = %2d '%(j,i,j*i),end='');
print('');
pass;
if __name__ == '__main__' :
chengfa99();
pass;
|
a5bced7f5a8de64642c4b81def773ce42cdb6dd8 | dan-garvey/the100 | /Classic Algorithms/bubble.py | 442 | 3.5625 | 4 | def sort(list):
isSorted=False
revInd=1
while not isSorted:
isSorted=True
for i in range(len(list)-revInd):
if list[i]>list[i+1]:
swap=[list[i+1],list[i]]
list[i], list[i+1] =swap
isSorted=False
revInd+=1
return list
tes... |
46fd40a1e75e547505100f197e1a40deb324f0c1 | ASRlytics/PYTHON_TRIE | /python_trie.py | 10,096 | 3.65625 | 4 | ### 转载
# @usage 字典树
# @author mw
# @date 2016年08月02日 星期二 08:56:34
# @param
# @return
#
###
class Trie:
class TrieNode:
def __init__(self,item,next = None, follows = None):
self.item = item
self.next = next
self.follows = follows
def __str... |
18978d0f4d1d5978cbc1136d2e60ec734bc80646 | hectorRperez/ejercicios-diccionarios | /ejercicio8_practica.py | 1,716 | 4.375 | 4 | """ Ejercicio 8
Escribir un programa que cree un diccionario de traducción español-inglés.
El usuario introducirá las palabras en español e inglés separadas por dos puntos,
y cada par <palabra>:<traducción> separados por comas.
El programa debe crear un diccionario con las palabras y sus traducciones.
Después ped... |
fca4cfc4a64b04e953d7ecc86d05a756ec14c610 | polszewski443/lab1.1 | /main.py | 3,860 | 3.859375 | 4 | from math import *
# Zad1.
# Napisz pierwszy skrypt,
# w którym zadeklarujesz po dwie zmienne
# każdego typu a następnie wyświetl te zmienne
print('###########ZAD1############')
a = 2
b = 3
c = 2.5
d = 2.8
e = 'Pawel'
f = 'Olszewski'
print('Integers:', a, b)
print('Floats:', c, d)
print('Strings:', e, f)
# Zad2. Stwór... |
1505e34e57b8e4270c84da9c68f95713b8e3b23f | barjinderpaul/Programming | /python/helloInsta.py | 229 | 3.640625 | 4 |
#0. Install python :)
#1. Hello Instagram, Getting started with python !
#2. '#' is used comments :)
#3. print is used for printing statements.
#4. To run python programs -> python file_name.py
print("Hello Instagram ;) ") |
02e9380fcb2c9b43d94c8e481e98dfaf679dcd17 | astanev-hub/Curso_Alura_Python | /jogos/adivinhacao.py | 298 | 3.734375 | 4 | print("***************")
print("Olá, bem-vindo!")
print("***************")
numero_secreto = 42
chute_str = input("Digite um número=> ")
chute = int(chute_str)
if(chute == numero_secreto):
print("Você acertou!! => ", chute)
else:
print("Você errou!! => ", chute)
print("Fim do Jogo") |
188e353ad6945f79fbe15e7d25f8a11fa3bf1b1d | inpho/vsm | /vsm/extensions/clustering/plotting.py | 2,537 | 3.84375 | 4 | import numpy as np
def gen_colors(clusters):
"""
Takes 'clusters' and creates a list of colors so a cluster has a color.
:param clusters: A flat list of integers where an integer represents which
cluster the information belongs to.
:type clusters: list
:returns: colorm : list
... |
a9ce213a85d5bd77d36a9fe8cffb071b9a34b361 | tjguk/pydojo-physics-s6e3 | /lookupondarkness.py | 749 | 3.5625 | 4 | #! /usr/bin/env python
import time
class Particle:
def __init__(self, gravity, particle_type, vel=[0.0], pos=[0,0]):
self.gravity = gravity
self.vel = vel
self.pos = pos
self.type = particle_type
def move(self):
self.vel[1] = self.vel[1] - self.gravity
self.pos ... |
44f0e9b2c5251787591b2b8aa548ce4679ed3a66 | YuanSuDi/python_plus | /01-装饰器/01-装饰器原理.py | 332 | 3.75 | 4 | def test(fun):
def inner():
print("--inner--")
fun()
return inner
def f1():
print("my name is f1")
def f2():
print("my name is f2")
f2 = test(f2)
f2()
# a = (x for x in range(20))
# print(next(a))
# print(next(a))
# print(next(a))
# print(next(a))
# print("-"*20)
# for x in a:
# ... |
7d873bf4e07f32a68b5d45b0ac918bbeb3c4a89d | nikhiljsk/Hangman-CLI | /helper_modules/predict_evaluate.py | 4,206 | 4.15625 | 4 | """
Goal: Predict a letter, evaluate the prediction and update key-things
"""
# Importing the required library
from collections import Counter
def most_occured_letter(rightly_guessed, dictionary):
"""
A function which returns the most-occured letter in a set of words, also keeps track that the returne... |
1bbbecf1e75f5f0e914a45ad4c9d247c32196b97 | rajeshsvv/Lenovo_Back | /1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS LENOVO/6_notes_prorams_intermediate/16_Enumerate_in_python.py | 185 | 4.1875 | 4 | # Enumerate function it iterates through the sequence extract the index postion and its corresponding value
for i,v in enumerate(["Rajesh","Suresh","Mahesh","Brajesh"]):
print(i,v) |
971f490bac120d051b6fb2f66e830429e834ce98 | MrSkorpi/Task_1 | /calc.py | 713 | 3.8125 | 4 | try:
a = float(input("Введите число:"))
while True:
oper = input("Операция над числом: ").split()
if oper[0]=="+":
a+=float(oper[1])
elif oper[0]=="-":
a-=float(oper[1])
elif oper[0]=="*":
a*=float(oper[1])
elif oper[0]=="":
... |
34a04cadbc8723d87ffb5bb8f18b809a8236b6fc | laxmi-2000/loopa | /p5.py | 745 | 3.90625 | 4 | # 11 logon ka weight input le aur fir average weight print kare. Aur fir yeh bhi
# check kare ki kya Average weight 5 ka multiple (Yaani 5 se bhaag karne par
# shesh 0 bachta hai) hai ya nahi? Note: Isme aapko input ka use karna padega.
# Aap loop ke andar raw input ka use kar ke 11 baar raw_input le sakte ho.
... |
de63dab531b2b844a146088eee338cd159d0a6a9 | JSantiago2007/cti110 | /M5HW3_Santiago.py | 994 | 4.46875 | 4 | # CTI 110
# M5HW3: Factorial
# Juan Santiago
# 10/19/2017
#The notation n! (“n-factorial”) represents the factorial of the
#non-negative integer n. The factorial of n is the product of
#all nonnegative integers from 1 to n.
#For example:
#4! = 1 * 2 * 3 * 4 = 24
#The factorial of zero (0!) is defined to be 1... |
90af5a8ca7e5dbdd6f8d0c7b3720270b7cd1b791 | henrylaih41/LeetCode | /top_100_liked/python3/next_permutation.py | 1,087 | 3.5 | 4 | class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
### find the element to swap
prev = -math.inf
for i in range(len(nums)-1, -1, -1):
if(nums[i] < prev):
prev = ... |
9ab14cffb9d77baafc4d2728769c3a63b2f22590 | JinnyCC/changepy | /changepy/costs.py | 5,171 | 3.6875 | 4 | import numpy as np
def normal_mean(data):
""" Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
... |
d3617b8308f6bd3f94708505c5cbba145a9feffc | TheSpeedX/codex | /python/problem_26.py | 812 | 3.78125 | 4 | # Sweta Snigdha Sahoo
# author-swetasahoo29
# question
# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6)
# 1/7 = 0.(142857)
# 1/8 = 0.125
# 1/9 = 0.(1)
# ... |
f6177c14f33511dcc6ccf770b5d325e4602df70e | jozsa/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 316 | 4.0625 | 4 | #!/usr/bin/python3
"""read_file(filename="")
This module has one function that
reads a file and prints it to standard
output.
"""
def read_file(filename=""):
"""
Prints a file to standard output
"""
with open(filename, mode='r+', encoding='utf-8') as a_file:
print(a_file.read(), end="")
|
45983c257dd9f21c220dea7ec0233897a7a1e0e1 | Aasthaengg/IBMdataset | /Python_codes/p03633/s183652800.py | 115 | 3.53125 | 4 | from math import gcd
n = int(input())
a = 1
for _ in range(n):
x = int(input())
a = a // gcd(a, x) * x
print(a) |
c18565cc32bb3a8297ea03602425a770ace8bf04 | untxi/ada | /Code/TPeriodica2.py | 13,416 | 3.75 | 4 | class Elemento:
""" Esta clase permite crear elementos de la
tabla periódica.
Las atributos de las instancias de esta
clase son los siguientes:
nombre : nombre del elemento
simbolo : símbolo del elemento
nAtomico : número atómic... |
1534516f34a1799fa90e5325dd01299b778c7613 | jdodinh/DCP | /completed/DCP_32.py | 3,377 | 3.75 | 4 | """
Suppose you are given a table of currency exchange rates, represented as a 2D array. Determine whether there is a
possible arbitrage: that is, whether there is some sequence of trades you can make, starting with some amount A of
any currency, so that you can end up with some amount greater than A of that currenc... |
321e42c299cd05ec2b895eb5f064e6335db6b772 | jmwalls/sudoku | /python/simanneal.py | 2,650 | 3.796875 | 4 | import numpy as np
class Simanneal (object):
"""
Basic simulated annealing optimizer---given a discrete configuration
space, we seek the optimal value via randomized local search.
Parameters
-----------
cost : user provided function that takes a configuration as an argument
and returns... |
24882295333ed8c7692c0f51e0856d31f3dbb692 | Tejaswini060/pythonlab | /duplicate string.py | 322 | 3.53125 | 4 | test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
if ele in repl_dict:
if ele in res:
test_list[idx] = repl_dict[ele]
else:
res.add(ele)
res = ' '.join(test_list)
# printing result
print("The string after replacing : " + str(res)) ... |
ed9c546f4220fce9182b540af5a47e863c67c363 | tokibito/pycon-apac-2013-bpmappers | /src/e04.py | 853 | 3.796875 | 4 | # 例4. bpmappersを使わない場合(親子関係) リファクタリング
import json
# データモデル
class Book(object):
def __init__(self, title, price, author):
self.title = title
self.price = price
self.author = author
class Author(object):
def __init__(self, name, company):
self.name = name
self.company = c... |
77a489b9166d90e9c8b532beec0f2475756ec6c4 | vsreelasya/Search-engine | /Assignment2/Part2/VallabhaneniSreelasya.Assignment02-2.py | 1,324 | 4.3125 | 4 | ##Name: VallabhaneniSreelasya.Assignment02
##ID: Assignment 02
##Question: script that counts how many words are in the main page of the course website.
##Also, display the vocabularyof the page in alphabetical order showing for each word its frequency in the page.
##Name: Sree Lasya Vallabhaneni
##Due Date: Sept 13,... |
62f450b1e9c6c64a4c569e8645e0e8a2d0b24fc5 | JunLei-MI/PythonX | /ToolsX/leetcode/0097/0097.py | 1,127 | 3.875 | 4 | from typing import List
class Solution:
"""20190925"""
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""
交错,先来一个暴力美学
将后者依次插入前者
插入的过程想到一种思路,只要能找到后者的所有字母,就代表交错
>>> Solution().isInterleave('aabcc','dbbca','aadbbcbcac')
True
>>> Solution().isIn... |
b05ce1081b9e61a8ec93f3b99fb0a14549aca666 | HeroJeanPierre/My_Project_Euler_Solutions | /In_Progress/Problem_034.py | 493 | 4 | 4 |
print ("Working")
def fact(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
totalSum = 0
for i in range(10000000):
sum = 0
# print("i =",i)
for ch in (str(i)):
sum += fact(int(ch))
# print("Factorial of", ch, "is", fact(int(ch)))
... |
6868f82eaf916cde9da1b37ffa1edb85f25e5b54 | pppk520/miscellaneous | /ib/level_5/backtracking/combination_sum.py | 760 | 3.640625 | 4 | '''
Example,
Given candidate set 2,3,6,7 and target 7,
A solution set is:
[2, 2, 3]
[7]
'''
class Solution:
# @param A : list of integers
# @param B : integer
# @return a list of list of integers
def combinationSum(self, A, B):
self.result = []
self.recur(sorted(set(A)), [], B)
... |
e08922081b7283c64a44028f8430dbca862163c8 | jungleQi/leetcode | /greedy/1094. Car Pooling.py | 427 | 3.8125 | 4 | def carPooling(trips, capacity):
pairs = []
for trip in trips:
pairs += [trip[1],trip[0]],
pairs += [trip[2], -trip[0]],
pairs = sorted(pairs, key=lambda x:(x[0],x[1]))
total = 0
for item in pairs:
total += item[1]
if total > capacity:
return False
r... |
f38a520be83771a050665c20c5fc62ff0fe4aef2 | maxkashyap41/pythonDSA | /LeetCode/Find_TownJudge.py | 1,530 | 3.71875 | 4 | # In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
# If the town judge exists, then:
# The town judge trusts nobody.
# Everybody (except for the town judge) trusts the town judge.
# There is exactly one person that satisfies properties 1 and 2.... |
67c9f2760bb8a9627c9ca5824fe38455aa85c343 | HackBulgaria/Programming101-3 | /week2-OOP-Problems/materials/panda.py | 1,189 | 3.953125 | 4 | # клас и инстанции
# dunder
# Duck Typing
class Panda:
def __init__(self, name):
self.age = 0
self.weight = 30
self.name = name
# Мутиращи методи
def grow_up(self):
self.age += 1
def eat(self, amount):
self.weight += amount // 2
def sleep(self):
... |
f1a4f2887ee7527d12f4c071c2c8742d54b5c2b5 | zishan21/Data-Programming_Assignment-2 | /Data Programming_Assignment 2/Chapter 2_Exercise 3.py | 207 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
hours = input("Enter hours: ");
hours=int(hours);
rate = input("Enter rate: ");
rate= float(rate);
pay = hours*rate;
print("Pay: ", pay);
# In[ ]:
|
d307f1979cf7f9d905e7778aa74807587e071b2e | huckphin/euler | /05-largest-divisible-to-x.py | 879 | 4.1875 | 4 | #! /usr/bin/env python3
def find_smallest_divisible_1_to_x(x):
loop_count = 1
while True:
# Has to be divisible by both, so both are factors
# Using the largest numbers to skip as many possibilities
known_factor = x * (x-1)
x_candidate = known_factor * loop_count
divisible_by_all = True
... |
a4f118c9806b9b0b5a53fd9fbf5b057cf4aff6d7 | SoyeonHH/Algorithm_Python | /LeetCode/125.py | 373 | 3.703125 | 4 | import re
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
# alphanumeric을 제외한 문자 정규필터링
s = re.sub('[^a-z0-9]','',s)
return s==s[::-1] # 슬라이싱으로 문자열 뒤집기
instance = Solution()
s = "A man, a plan, a canal: Panama"
print(Solution.isPalindrome(instance... |
ae8359e5986fc98b1d90f75a8008a42db6923b48 | apignata/StockingUp | /Bank.py | 7,028 | 3.53125 | 4 | import random
from tabulate import tabulate
import pyautogui
class BankAccount():
def __setinfo(self, firstName, pin, balance = 7500, credit = 7500, stock = None ):
self.fName = firstName
self.balance = balance
self.cred = credit
self.pin = pin
if stock is None:
... |
ce845d0cc2852e0df89cdcea3bc008815c37c15d | AnniePawl/web-security | /Cryptography_Encryption/steganography.py | 1,898 | 3.59375 | 4 | """
Deliverables:
1. All TODOs in this file.
2. Decoded sample image with secret text revealed
3. Your own image encoded with hidden secret text!
"""
# Secret image hidden in LSB of red channel pixels. Value of LSB of each red pixel is 1 if hidden image was 1 at that location, and 0 if hidden image was also... |
712f416a8a247ee77ecb6e4c1f5564960cbbc3a3 | erachlin/Chess_AI | /make_legal_moves.py | 76,466 | 3.671875 | 4 | class game():
def __init__(self, in_possible_moves, in_state):
self.state = in_state
self.possible_moves = in_possible_moves
self.check = False
self.wK_pos = 'e1'
self.bK_pos = 'e8'
self.wK_moved = False
self.wKR_moved = False
self.wQR_moved = False
... |
970d6bc82cfad8a40837f76a4a3aa07b459213f0 | LewickiMaciej/twitterFollowers | /secondLineFollowers/twitterFollowers.py | 1,207 | 3.734375 | 4 | from twitter import Api
class TwitterFollowers:
def __init__(self, api):
self.api = api
def getFollowers(self, screen_name):
first_line_followers = set()
followers = self.api.GetFollowers(screen_name=screen_name)
for follower in followers:
first_line_followers.add(follower.screen_name)
return first... |
02ee60cd5e0eee27860dfb99376933a215ad2988 | daviz888/python_works | /rollercoater.py | 220 | 4.0625 | 4 | import screen
screen.clear()
height = int(input("How tall are you, in inches? "))
if height >= 36:
print("\nYour're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a littler older.")
|
797da5d4216356c05291c66980bc0f3afaa2e9f1 | harrylee0810/TIL | /swexpert/python01/6218.py | 383 | 3.609375 | 4 | # 다음의 결과와 같이 임의의 양의 정수를 입력받아 그 정수의 모든 약수를 구하십시오
# 입력: 9
# 출력:
# 1(은)는 9의 약수입니다.
# 3(은)는 9의 약수입니다.
# 9(은)는 9의 약수입니다.
init_num = int(input())
for i in range(1,init_num+1):
if init_num % i == 0:
print(f'{i}(은)는 {init_num}의 약수입니다.') |
43476aec2db099317e63369c4a8c4d9e39a63658 | jasmine2018jixun/leetcode2020 | /leetcode2019/leetcode113_路径优化2.py | 750 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import numpy as np
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
res ... |
db75be34a5ddf8f1cf860c1bf05c9ce8edbd72d2 | blakeli119/blakeli1109 | /HW2/merge_sort_06170222.py | 772 | 3.59375 | 4 | class Solution(object):
def merge_sort(self, nums):
result = []
if len(nums) < 2:
return nums
mid = int(len(nums)/2)
y = self.merge_sort(nums[:mid])
z = self.merge_sort(nums[mid:])
while (len(y) > 0) or (len(z) > 0):
if len(y) > 0 and len(z) > ... |
e286339dde8e34e1b5ca7e2e46e981776f9467ed | fdur1234/driving- | /driving.py | 415 | 3.84375 | 4 | #行車年齡的程式(課程例子)
country = input('請問你是哪一國人?')
age = input('請輪入年齡:')
age = int(age)
if country == '香港':
if age >= 18:
print('你可以考車牌')
else:
print('你還不可以揸車')
elif country == '美國':
if age >= 16:
print('你可以考車牌')
else:
print('你還不可以揸車')
else:
print('只可以輸入香港或美國啊,傻尻') |
379c2d2bc430865552b8728cb472bead42f92077 | anilkarela/PYTHON-PROJECTS | /Word Attack Game/main.py | 1,997 | 3.71875 | 4 | from classes.game import person, bcolors
magic=[{"name": "Fire", "cost": 10, "dmg": 100},
{"name": "Thunder", "cost": 10, "dmg": 120},
{"name": "Blizzard", "cost": 10, "dmg": 100}]
player= person(460, 65, 60, 34, magic)
enemy= person(460,65,45,25,magic)
running= True
i= 0
print(bcolors.FAIL+ bcolors.B... |
a4e653aea480af203d8a8a5a432b0b380488d530 | SREELEKSHMIPRATHAPAN/python | /python1/co1/4prblm.py | 208 | 3.9375 | 4 | string="every day is a good day.today is a good day"
a=string.split(" ")
count=0
for i in range(0,len(a)):
if (a[i])==" day" ) :
count+=1
print("the occurence times of day is :",count) |
455362f3fa8ef97f722ea6c5cf3ed0a58e4200e9 | thusyasin/aran | /hello5.py | 69 | 3.921875 | 4 | num=0
while(num<5):
print("Hello")
num=num+1
|
97a189df2628c0d7fae204a4dc081c843b9607e8 | themockingjester/leetcode-python- | /143. Reorder List.py | 1,412 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
node = h... |
95bb0c3bd2c3801de1bd3f2890f1187f5ac9b743 | ishantk/PythonNwk19 | /Session2C.py | 327 | 4.21875 | 4 | # Comparison Operators
# Result is True or False | Boolean
# >, <, >=, <=, ==, !=
partyAVoteCount = 2345141
partyBVoteCount = 2313131
print("Are Votes Equal?", partyAVoteCount == partyBVoteCount)
print("Are Votes Not Equal?", partyAVoteCount != partyBVoteCount)
print("Will PartyA Win?", partyAVoteCount > partyBVoteCo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.