blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
cea771953d2e1c6be63e6af061ff0c59dfeec3d0 | tigerpatel13/Sorts | /main.py | 423 | 4.09375 | 4 | """
The file is used to run any type of sort using this single file and its options
"""
from pigeonhole_sort import pigeonhole
def main():
item = [int(x) for x in input("Please enter a list you would like to sort using PigeonSort: ").split()]
print("Sorted order is : ", end = ' ')
pigeonhole(item)
fo... |
79b1f026ffe90884d751a18e789bc9b87591261c | elhaidi/Design_Pattern | /Builder/ComputerBuilder/computer.py | 669 | 3.625 | 4 | class Computer:
def __init__(self,case,mainboard,cpu,memory,hard_drive,video_card):
self.case=case
self.mainboard= mainboard
self.cpu=cpu
self.memory=memory
self.hard_drive=hard_drive
self.video_card=video_card
def display(self):
print("\t {:>10} : {... |
1f3baebd7e89436d3ed0397b5d823c9178b32d6d | Bals-0010/Leet-Code-and-Edabit | /Leet Code/Remove Vowels from a String.py | 288 | 4.03125 | 4 | # instructions pending
def testing(string):
vowels_list = ['a','e','i','o','u','A','E','I','O','U']
str_list = [i for i in string if i not in vowels_list]
final_list = "".join(str_list)
return final_list
print(testing("thisi is a string example")) |
30aaffce13d69354705ccb9e3c9c46e565a3b6d2 | Bals-0010/Leet-Code-and-Edabit | /Edabit/Identity matrix.py | 1,664 | 4.28125 | 4 | """
Identity Matrix
An identity matrix is defined as a square matrix with 1s running from the top left of the square to the bottom right. The rest are 0s. The identity matrix has applications ranging from machine learning to the general theory of relativity.
Create a function that takes an integer n and returns th... |
10915b56f39c9f8315f0ed3e8176baccc33f418a | radhikar408/Assignments_Python | /assignment13/ques2.py | 232 | 3.71875 | 4 | # Q.2- Name and handle the exception occurred in the following program:
# l=[1,2,3]
# print(l[3])
#name of the error--list index out of range
#handling the error
try:
li=[1,2,3]
print(li[3])
except Exception as e:
print(e)
|
80c382f2fb68f717d9bc66b4617de4aad1987527 | radhikar408/Assignments_Python | /assignment4/ques5.py | 182 | 4.125 | 4 | #create a dictionary
d={}
name=""
marks=""
for i in range(3):
name=input("enter your name ")
marks=(int(input("enter your marks ")))
d[name]=marks
print("dictionary is ")
print(d) |
d07e252bff50c58d9cf0d612edbdfd78f9a7b7a7 | radhikar408/Assignments_Python | /assignment17/ques1.py | 349 | 4.3125 | 4 | #Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.
import tkinter
from tkinter import *
import sys
root=Tk()
def show():
print("hello world")
b=Button(root,text="Hello",width=25,command=show)
b2=Button(root,text="exit",width=25, command=exit)
b.pac... |
9f466238d87b0ed85803359c885a72a033bfac95 | radhikar408/Assignments_Python | /assignment14/ques1.py | 268 | 4.0625 | 4 | #Q.1- Write a Python program to read last n lines of a file
f=open('new.txt','r')
#print(f.tell())
#a=f.tell()
content=f.readlines()
print(content)
n=int(input("enter a number : "))
# for l in range(len(content)-n,len(content)):
for i in range():
print(content[l]) |
93cb8ecf50c9f28524f1764ec62c5a9c2b6c4766 | radhikar408/Assignments_Python | /assignment4/ques6.py | 231 | 3.875 | 4 | d={}
name=""
marks=""
li=[]
for i in range(10):
name=input("enter your name ")
marks=(int(input("enter your marks ")))
d[name]=marks
li.append(marks)
d[name]=marks
print("dictionary is ")
print(d)
print(li)
li.sort()
print(li) |
eeaddb667703e9d83352cb5fad07709334d861bc | v1rals/python | /module2/guess_the_number.py | 464 | 3.828125 | 4 | #! /usr/bin/python3
import random
rnd = random.randrange(1, 100)
print("Я загадал число, может быть это", rnd ,",а может и нет")
while True:
guess = int(input('Попробуй угадать число: '))
if guess > rnd:
print("Переборщил")
continue
if guess < rnd:
print("Недоборщил")
continu... |
c1e110c59311af1c81fc95f67368f46acd9d9fcd | cosmonautd/ED | /Trabalho Extra/Questão 3/project_selection_solution.py | 5,630 | 3.703125 | 4 | import numpy
import string
import matplotlib.pyplot as plt
# V: A verba liberada pelo governo
V = 300
# N: A quantidade de projetos submetidos
# c: Os custos de cada projeto (em milhões)
# q: A estimativa da quantidade de pessoas beneficiadas por cada projeto (em milhões)
N = numpy.random.randint(20, 30)
c = list(num... |
40607f14fdd0e1dc4c002e9f9d14d12371970c76 | ucookie/share | /01_python高并发优化思路/multi_threads.py | 1,233 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import time
import threading
QUEUE = list()
def fibonacci(n):
'''斐波拉数列'''
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def init_queue():
'''初始化队列'''
global QUEUE
QUEUE =... |
4a2b683168580f13091d2d79038faff0098849cb | LucvandenBrand/OperatorGraph | /auto_tuner/ParseUtils.py | 679 | 3.734375 | 4 | def try_to_parse_int(value, defaultValue=0):
try:
return int(value)
except ValueError:
return defaultValue
def try_to_parse_bool(value):
value = value.lower()
if value == "false" or value == "0":
return False
else:
return True
def try_to_parse_int_list(value, delimi... |
42db780779436ef37aac6cc39b040bfff2d14833 | brandon-hill/CS50 | /bleep.py | 1,222 | 3.796875 | 4 | # Censors certain specified words in a given string
from cs50 import get_string
from sys import argv
def main():
text = get_text("What message would you like to censor?\n")
dictionary = open(argv[1])
banned = make_banned(dictionary)
censor_text(text, banned)
dictionary.close()
# Pro... |
6c34aad1342424ae8a1def0a6cefa8c4797b6a00 | purvitrivedi/get-next-cron-schedule | /application.py | 1,347 | 3.625 | 4 | #!/usr/bin/env python3
import sys
import select
from time_calc import validate_time_format
from crontab_parser import parse_config, next_crontab_time
def main():
try:
if len(sys.argv) != 2:
raise IndexError
if not select.select([sys.stdin, ], [], [], 0.0)[0]:
raise Inde... |
caa63eaa8c432be6f44075d6cb702d7ca7ede6fd | EZForever/pytrickz | /pytrickz/iterables.py | 4,153 | 4.15625 | 4 | '''
Defines several handy `Iterable` classes.
```
from pytrickz.iterables import iterate
print(iterate(lambda x: x * 3, 1).stream().take(5)) # (1, 3, 9, 27, 81)
```
'''
from typing import Callable, Generic, Iterable, Iterator
from .stream import stream
from .typevars import *
cla... |
42fef2a758d2df6e05b7d5db3ecbd4e2d01b058b | scline96/my-exercism | /isogram/isogram.py | 187 | 3.90625 | 4 | def is_isogram(string):
letters = []
for letter in string:
if letter in letters:
return False
break
letters.append(letter)
return True
|
ef4a19480ad8d3012972ff69f314283332c89728 | lightningC00kie/binary_addition | /script.py | 1,049 | 3.859375 | 4 |
def binary_addition(n, a1, a2):
carry = []
answer = []
for i in range(n-1, -1, -1):
a = a1[i]
b = a2[i]
if len(carry) == 0:
if a == 0 and b == 0:
c = 0
if a == 1 and b == 1:
c = 0
carry.append(1)
... |
6a64bc653a10658506193c61804230571db73621 | jacksonsr45/python_calculator | /app/src/app_calculator.py | 2,978 | 3.625 | 4 | __author__ = "jacksonsr45@gmail.com"
import tkinter
class Calculator:
def __init__(self,root):
self.root = root
self.root.title("Calculator")
x = (self.root.winfo_screenwidth() // 2) - (550 // 2)
y = (self.root.winfo_screenheight() // 2) - (600 // 2)
self.root.geometry("550... |
be71c571a73736a4d7fabf61a407ec2a492bdcbe | cooperbarth/texterize | /texterize/helpers/build_block.py | 835 | 3.6875 | 4 | import numpy as np, math
#converts a string into a 2D numpy array of text the same shape as the image to be texterized
def buildBlock(text, dimensions):
'''
params:
-text: a string to be split into a block
-dimensions: the numpy shape of the input image
return:
A 2D numpy array of characters i... |
d863a4f7a2235052c3f32222fb3cf70809d0ae94 | NullPrimer/Exercise_App | /ExerciseApp.py | 830 | 4.03125 | 4 | # Array's
import random
Day_of_the_week =("Wednesday")
print("This is your exercise for " + Day_of_the_week)
if Day_of_the_week == "Monday":
print(random.choice(("Bench", "Flys", "Dumbell_Raise")))
elif Day_of_the_week == "Tuesday":
print(random.choice(("Shoulder Press", "Lat_Raises", "Face_Pull")))
eli... |
cae03ccf21b45ea7bc0dcc9b1fcf154192dee6f1 | tmlrnc/axn_ml_2 | /axn/ml/predict/predictor/algorithm/kmedian_VL.py | 12,339 | 3.640625 | 4 | """
trains the scikit-learn python machine learning algorithm library function
https://scikit-learn.org
then passes the trained algorithm the features set and returns the
predicted y test values form, the function
then compares the y_test values from scikit-learn predicted to
y_test values passed in
then ret... |
6def63af02c7b610414cb91a43bdddf2411325ab | kiri182/Self-Taught-Programmer | /page116.py | 815 | 3.640625 | 4 |
def listprint():
list_a = ['ウォーキング・デッド', 'アントラージュ', 'ザ・ソプラノズ', 'ヴァンパイア・ダイアリーズ']
for x in list_a:
print(x)
def count():
for i in list(range(25, 51, 1)):
print(i)
def loop():
n = 0
question = ['Who are you', 'Where are you from', "What's that"]
while True:
print("Hey.... |
443f7d7779ccff1e1dfc7e1f0a2cbefc98bc97d5 | kiri182/Self-Taught-Programmer | /page69c1-3.py | 311 | 3.734375 | 4 | def square(x):
return x ** 2
def strings(x):
print(x)
def func(x, y, z, i=10, j=2):
print(x)
print(y)
print(z)
if i > 1:
print(i)
else:
print(j)
i = input("what number do you like?: ")
print(square(int(i)))
strings('Btw, how are you?')
func('a', 'b', 'c', 5)
|
dd579fcf0c2dde41709cc6a552777d799a5240f2 | MattSokol79/Python_Introduction | /python_variables.py | 1,289 | 4.5625 | 5 | # How to create a variable
# If you want to comment out more than one line, highlight it all and CTRL + /
name = "Matt" # String
# Creating a variable called name to store user name
age = 22 # Int
# Creating a variable called age to store age of user
hourly_wage = 10 # Int
# Creating a variable called hourly_wage to... |
d7ee9dfcd9573db8b914dc96bff65c61753aceec | fadhilmulyono/CP1401 | /CP1401Lab6/CP1401_Fadhil_Lab6_2.py | 373 | 4.25 | 4 | '''
The formula to convert temperature in Fahrenheit to centigrade is as follows:
c = (f-32)*5/9;
Write a program that has input in Fahrenheit and displays the temperature in Centigrade.
'''
def main():
f = float (input("Enter the temperature in Fahrenheit: "))
c = (f - 32) * 5 / 9
print("The temp... |
db9eddc3ae20c784684b86d39aa675cd8764739f | fadhilmulyono/CP1401 | /Prac05/CP1401_Fadhil_Prac5_3.py | 292 | 4.40625 | 4 | '''
Get height
Get weight
Calculate BMI (BMI = weight/(height^2 ))
Show BMI
'''
def main():
height = float(input("Enter your height (m): "))
weight = float(input("Enter your weight (kg): "))
BMI = weight / (height ** 2)
print("Your BMI is " + str(BMI))
main()
|
d3e53df801c4e65d76e275b9414312bdb2f618e5 | fadhilmulyono/CP1401 | /Prac08/CP1401_Fadhil_Prac8_3.py | 607 | 4.3125 | 4 | '''
Write a program that will display all numbers from 1 to 50 on separate lines.
For numbers that are divisible by 3 print "Fizz" instead of the number.
For numbers divisible by 5 print the word "Buzz".
For numbers that are divisible by both 3 and 5 print "FizzBuzz".
'''
def main():
number = 0
... |
676f49df4e8c42e84026f7772ffa08d7d9fd35a0 | oldpride/tpsup | /python3/examples/test_class_new_attr.py | 823 | 3.703125 | 4 | #!/usr/bin/env python3
# https://stackoverflow.com/questions/54358665/python-set-attributes-during-object-creation-in-new
# test set attr in __new__
class TestClass(object):
def __new__(cls, test_val):
obj = object().__new__(cls) # cant pass custom attrs
object.__setattr__(obj, 'customAttr', tes... |
99340807f1f60f51cd4ddd83af753df01b947a89 | oldpride/tpsup | /python3/examples/test_copilot_vscode.py | 232 | 4.28125 | 4 | #!/usr/bin/env python3
import datetime
# get days between two dates
def get_days_between_dates(date1, date2):
return (date2 - date1).days + 1
print(get_days_between_dates(datetime.date(2018, 1, 1), datetime.date(2018, 1, 3))) |
3d696720d0a36e1fe9628a2ead7826e2908f0fd1 | oldpride/tpsup | /python3/examples/test_redefine_function.py | 194 | 3.953125 | 4 | #!/usr/bin/env python3
b=100
def temp(a):
return a+1
plus1=temp
print(f'plus1={plus1(b)}')
def temp(a):
return a+2
plus2=temp
print(f'plus2={plus2(b)}')
print(f'plus1={plus1(b)}') |
1550ef200015ae11c213f5b0762e33a1ae24315c | oldpride/tpsup | /python3/examples/test_nested_dict.py | 210 | 4.40625 | 4 | #!/usr/bin/env python3
import pprint
dict1 = {}
dict2 = {'a': 1, 'b': 2}
dict1['c'] = dict2
print('before, dict1 = ')
pprint.pprint(dict1)
dict2['a'] = 3
print('after, dict1 = ')
pprint.pprint(dict1)
|
081dc3fac24a114892ee3fecc8212df7fb14aadd | oldpride/tpsup | /python3/examples/test_assign.py | 688 | 3.984375 | 4 | #!/usr/bin/env python
for row in [
[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
]:
# note,
# 1. use '+' to concatenate two lists
# 2. use '*' to repeat a list
# 3. use 'None' to fill up the list
# 4. repeat 'None' twice to fill up the list
arg1, arg2, *rest = row +... |
997b83c89aa3c7039ab9ddc10b78f73334192d42 | oldpride/tpsup | /python3/examples/test_attribute_vs_property_selector.py | 1,661 | 3.515625 | 4 | #!/usr/bin/env python
# https://stackoverflow.com/questions/43627340
# An attribute is a static attribute of a given DOM node,
# a property is a computed property of the DOM node object.
# example
# a property would be the checked state of a checkbox, or value or an input field.
# an attribute would be href of... |
34cd01dce906e6351e603ddd68b2b5cea5c124b9 | Horacio23/python-class | /strings/string.py | 243 | 3.546875 | 4 | def stringJoin():
s = ';'.join(['pal','ineed','haro'])
print(s)
def concatinate():
s = ['pal','ind','rome']
res = ''.join(s)
print(res)
def main():
stringJoin()
concatinate()
if __name__=='__main__':
main()
|
25bed37f4bdf2b62b3bcc74324ab69a68aa53fb6 | rezaasdin/Tkinter-Traffic-Light | /traffic_light_console.py | 2,224 | 3.515625 | 4 | class TrafficLight():
def __init__(self):
self.green_state = GreenState(self)
self.yellow_state = YellowState(self)
self.red_state = RedState(self)
self.state = self.red_state
def change_state(self):
self.state.handle_request()
def get_green_light_state(sel... |
9cdd048dffa47e47ed7a9da8352c13832d6c3b96 | wmoura12/materiais_apoio_cursos | /Palestras/202106 - Observatorio Social/arquivos_apoio/Aula02_Ex02_Print.py | 425 | 3.96875 | 4 | import time
print('iniciando o código')
segundos = 5
for i in range (segundos):
print("Aguarde",segundos - i,"segundos")
time.sleep(1)
# Entrada de informações
b = float(input('digite a largura: '))
h = float(input('digite a altura: '))
print("OK, vou calcular para você!\nAguarde 5 segundos")
time.sleep(5)
... |
f540701887da1465a0479f586df7b36fd7c224b8 | caryt/utensils | /date/tests.py | 9,108 | 3.53125 | 4 | """Date tests.
"""
from unittest import TestCase
from date import *
class Test_Weekday(TestCase):
"""Weekdays enumerate Sun..Sat."""
def test_weekday(self):
d = 15-Jan-2013
self.assertEqual(d.weekday, Tue)
self.assertEqual(str(d.weekday), 'Tue')
class Test_Date(TestCase):
... |
22dd50b91824ebec9b5bfb02589409947e0f07df | caryt/utensils | /lookup/lookup.py | 1,445 | 3.609375 | 4 | """Lookup
=========
"""
from bisect import bisect_left, bisect_right
from null import null
class Over(object):
"""A High Value, useful for the final entry in Lookup tables."""
def __repr__(self): return 'Over'
def __gt__(self, other): return True
def __eq__(self, other): return other is... |
8b632f931537ba4098cb27359bb4d9e9af7dc135 | ahalbert/python-euler | /euler41.py | 324 | 3.5 | 4 | __author__ = 'ahalbert'
from euler7 import findPrimes
def isPandigital(n):
digits = "123456789"
n = str(n)
digits = digits[:len(n)]
for i in digits:
if i not in n:
return False
return True
def euler41():
largest = 0
for i in findPrimes(9999999):
if isPandigital(i):
print i
largest = i
return lar... |
382700c11c43f4aa36ccdac6076a6b3685243c66 | jasigrace/guess-the-number-game | /main.py | 812 | 4.1875 | 4 | import random
from art import logo
print(logo)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
number = random.randint(1, 100)
def guess_the_number(number_of_attempts):
while number_of_attempts > 0:
print(f"You have {number_of_attempts} remaining to guess the n... |
a8b2bce1a136602fbc22a90e772875bc773eab0b | JiaEn182445u/OSPhyton | /algorithm/FCFSOptimization.py | 2,239 | 3.546875 | 4 | from algorithm import FCFSParameter
class FCFSOptimization:
def __init__(self):
self.dp = FCFSParameter.FCFSParameter("disk.ini")
self.generateAnalysis()
def printSequence(self, name, location):
curr = 0 #current starting point
prev = self.dp.getCurrent() #previous p... |
38090603adca96a2605d8feb0ea655130bc346e5 | michaelb-01/asset_IO | /examples/drawing_pen.py | 1,706 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PySide tutorial
In this example, we select a colour value
from the QtGui.QColorDialog and change the background
colour of a QtGui.QFrame widget.
author: Jan Bodnar
website: zetcode.com
last edited: August 2011
"""
# drag text from input onto the button to cha... |
54d9bd0b8590541debfc20a7dc977baf0e3a46c8 | dhhyey-desai/Palindrome_checker | /main.py | 805 | 3.59375 | 4 | import pymongo
from pymongo import MongoClient
data = MongoClient()
db = data.palindrome_checker
users = db.users
while True:
word = input("Please enter a word\n")
rev = word[::-1]
if word == rev:
print("This word is a palindrome")
user1 = ({"Palindrome": word})
... |
0491cafe80f3a348b0581ee93d03b8ba8f277e08 | srsman/spider-college | /SpiderForCollege/bean/College.py | 2,552 | 3.953125 | 4 | """
大学类
name:高校名
city:高校所在城市
department:高校归属哪个部门管理
levels:高校层次
url:高校官网
"""
class College(object):
def __init__(self, name='', icon='', city='', type='', department='', levels='', character='', url='', score=''):
self._name = name
self._icon = icon
self._city = city
self._type = ... |
cf0840aa10ba03a6bf786fdda6c05bcf72d8bf6d | issoni/twitter-bot | /mytwitterbot.py | 2,481 | 3.609375 | 4 | import sys
import time
import simple_twit
from datetime import date, datetime
def main():
# This call to simple_twit.create_api will create the api object that
# Tweepy needs in order to make authenticated requests to Twitter's API.
# Do not remove or change this function call.
# Pass the variable "ap... |
6dc95bab528b1bbd09521ddfdc3533caa83af8e5 | TristanWedderburn/leetcode | /missingNumber.py | 430 | 3.5625 | 4 | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# nums.sort()
# for i in xrange(len(nums)):
# if nums[i]!=i:
# return i
# return i+1
expectedSum = len(nums)*(len(nums)+1)/2 #... |
a67c9e5495b2c3b8079385bf20f6cb535e07cee1 | TristanWedderburn/leetcode | /letterCombinationsOfAPhoneNumber.py | 993 | 3.5625 | 4 | class Solution(object):
def __init__(self):
self.combos = []
self.keypad = {
'2':['a','b','c'],
'3':['d','e','f'],
'4':['g','h','i'],
'5':['j','k','l'],
'6':['m','n','o'],
'7':['p','q','r','s'],
'8':['t','u','v'... |
ef2407f29cd0990d9a09faa8e8ee636272ca862c | TristanWedderburn/leetcode | /maxDepthOfBinaryTree.py | 912 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
... |
3654c6e6941304f8e95e428b490f68e7b6bb4227 | randy-wittorp/ex | /ex39.py~ | 2,518 | 4.125 | 4 | # create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksongille'
}
# add some m... |
8db7d4ab1fc4d119e8c48f61821fae3dce188ea6 | ernur1/thinking-recursively | /Chapter-3/exercise-3.5.py | 748 | 4.0625 | 4 | #==============================================================================
# function to find the different arrangements possible using smaller number of letters
#==============================================================================
def permutations(letters, wordLength):
if(wordLength < letters):... |
48c2d231d58a0b04c6c91e529ee98bf985988857 | ernur1/thinking-recursively | /Chapter-3/3.2-factorial.py | 392 | 4.28125 | 4 | #===============================================================================
# find the factorial of the given integer
#===============================================================================
def factorial(num):
if (num == 0):
return 1
else:
return num * factorial(num-1)
if __name_... |
752eb476bdcfb40289559b662245786b635c1766 | ellen-yan/self-learning | /LearnPythonHardWay/ex33.py | 362 | 4.15625 | 4 | def print_num(highest, increment):
i = 0
numbers = []
while i < highest:
print "At the top i is %d" % i
numbers.append(i)
i = i + increment
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
print "The numbers: "
numbers = print_nu... |
1ce6ad0a83e82ade475c75c40d9cf5c8fb4cac43 | ellen-yan/self-learning | /LearnPythonHardWay/ex5.py | 1,363 | 4.34375 | 4 | my_name = 'Ellen X. Yan'
my_age = 23 # not a lie
my_height = 65 # inches
my_weight = 135 # lbs
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print "Let's talk about %s." % my_name
print "She's %d inches tall." % my_height
print "She's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print ... |
2a82f285d4c8f81e6a6511639631cba702e5874b | Satish-baradiya/Python-Scripts | /DSA/Sorting Algorithms/shell_sort.py | 438 | 3.734375 | 4 | def shellSort(input_list):
gap = len(input_list)//2
while gap >0:
for i in range(gap,len(input_list)):
temp = input_list[i]
j=i
#Sort the sub list for this gap
while j>=gap and input_list[j-gap]>temp:
input_list[j] = input_list[j-gap]
j = j-gap
input_list[j] = temp
#R... |
9ac717872b1c1a54206dfc4546d41d91f54d661f | Satish-baradiya/Python-Scripts | /Web Scrapping/link_scrapper.py | 337 | 3.65625 | 4 | #This scripts gets all the links from a webpage and stores it into a list.
#Getting title of wikipedia article using web scrapping.
import requests
import bs4
import lxml
result = requests.get("https://en.wikipedia.org/wiki/Elon_Musk")
result
soup = bs4.BeautifulSoup(result.text,"lxml")
res = list(soup.sele... |
abde85964ab7bf0622c04f25c675f00991cc377b | NachalnikKamchatki/PDFRenamer | /corr_file_name.py | 976 | 4.03125 | 4 | # Сhecks the character string (for example, file name) for correctness (absence of forbidden characters)
def is_correct_filename(name: str, forbidden: list):
'''
Are there any prohibited characters?
'''
for c in name:
if c in forbidden:
return False
return True
def make_c... |
dfde62bcbc398265306822174373661091c08316 | aldermartinezc/test_github | /graph_counts.py | 3,628 | 3.578125 | 4 | import matplotlib.pyplot as plt
def graph_counts(state, dataframe, column, hasSubset, subset_Col, subset_Value, graphType, isPercentage, numShow, savePDF, savePNG):
'''
Visualize particular columns in dataframe.
Parameters:
----------
state: takes a strin... |
265cfd59fe4dc187e6a1eddcac6f441d18cbe1e8 | SokolnikSergey/VkPoster | /model/VkAuthorizationModel/ReadWriteToken.py | 1,242 | 3.578125 | 4 | import os,struct
class ReadWriteToken:
"""This is class for search token to authorization on the site
to achieve your aim in future without any questions about authorization
(if your are entering not first time) write and read file with token """
@staticmethod
# This method allows to search... |
55c200066898a1ea3928796c088fc672b2520af4 | mlukasik/spines | /classification/postprocess_matrix.py | 947 | 3.71875 | 4 | '''
Created on Jan 16, 2013
@author: mlukasik
'''
def choose_most_changing_least_changing(data_matrix, most_chg, least_chg):
'''
Converts class value from real to boolean.
We choose most_chg most changing values as positives and
least_chg least changing values as negatives.
'''
inddiff = []
... |
63a5a714b9616501455bc4d7739d307009a84cde | Lopeze/Prim-s-Bio-Interactome | /io_utils.py | 3,680 | 3.546875 | 4 | '''
I/O functions
-cgraph(file)-> nodes, edges, weighted(optional)
-adj_ls(nodes, edges, directed/undirected(optional)
-adj_matrix(nodes, edges, directed/undirected(optional)
I have created some optional boolean values that you can use to make the
function work on undirected or directed graphs, and whether the graph ... |
f175f9d3d2aaad0d6cc52f30c59099466f4cb785 | ArretVice/algorithms-and-data-structures | /recursion.py | 1,473 | 3.640625 | 4 | import numpy as np
array = list(np.random.randint(0, 100, 10))
print(f'Initial array: {array}\nSum = {sum(array)}\nLength = {len(array)}\nMax = {max(array)}')
# recursive sum
def rec_sum(array):
if len(array) == 1:
return array[0]
else:
return array.pop(0) + rec_sum(array)
pri... |
fe7c55558bc6bc0f6fe216ab207abd3ad2719ad2 | meier3/wallbreakers | /week2/DistributeCandies.py | 490 | 3.625 | 4 | class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
# compile set of candy kinds
kinds = set()
for c in candies:
kinds.add(c)
# collect values
numKinds = len(kinds)
nu... |
178a37ed5f2501fc33aad24d2acaaf2978dca33f | anluxi/game | /game.py | 1,714 | 3.875 | 4 | print("hallo lovely")
print("游戏\t恋爱\t猜数字")
print("""欢迎来到千华月的小家
我是这里的主人千华月
请不要搞错,华月是姓千是名""")
import random#导入伪随机库
import decimal#导入十进制库
import os#导入清屏库
three = decimal.Decimal("0.1")#将十进制状态赋值给three变量
two = random.randint(0,9)#将伪随机库内的整数随机模块赋值给two变量
love=0#好感度值初始化
one = 10#循环执行的次数初始化
game=5#好感度系统的循环次数的... |
78ff6b74d9fb98e9d27d458982c0844a79dadfd4 | zhangxw1986/python_manage | /chap_11/index_words.py | 659 | 4.09375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
def index_words(text):
result = []
if text:
result.append(0)
for index, value in enumerate(text, 1):
if value == ' ':
result.append(index)
return result
def g_index_words(text):
'print the location of every word'
if t... |
590c9de183796d943f7f27281fc1f45455713be1 | JimmySenny/demoInterview | /src/pufa/generate.py | 634 | 3.640625 | 4 | #!/usr/bin/env python3
class Solution:
# def generate(self, numRows: int) -> List[List[int]]:
def generate(self, numRows):
ret = list();
i = 0
while i < numRows:
row = list();
j = 0
while j < i+1:
if j == 0 or j == i:
... |
9d7ace0d89acca23afa3cc3ea8487347e6248b34 | JimmySenny/demoInterview | /src/pufa/reverseString.py | 642 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 切片
class Solution:
# def reverseString(self, s: List[str]) -> None:
def reverseString(self, s):
#s = s[::-1];
s[0::] = s[::-1];
def reverseString1(self,s):
left = 0
right = len(s) - 1
while left < right:
tmp ... |
b444ea4324f5f84364db4e5dc73e48b30e1b004b | JimmySenny/demoInterview | /src/pufa/repeatedSubstringPattern.py | 500 | 3.703125 | 4 | #!/usr/bin/env python3
class Solution:
# def repeatedSubstringPattern(self, s: str) -> bool:
def repeatedSubstringPattern(self, s):
ss = s + s;
if s in ss[1:-1]:
return True;
return False;
def main():
s = Solution();
print(s.repeatedSubstringPattern("abab"));
pri... |
de75840ffebcd6abc795eb59451e7da91402ea53 | deorerohan/InterviewPreparation | /Practice/HackerRank/ListComprehensions.py | 586 | 3.734375 | 4 | x = int(input()) + 1
y = int(input()) + 1
z = int(input()) + 1
n = int(input())
output = list()
def UsingForLoop(x, y, z, n):
for i in range(x):
for j in range(y):
for k in range(z):
if i + j + k == n:
continue
output.append([i, j, k])
... |
b342abed1665454940f48e69e663f3ec50ee35cb | ahmadaljanabi/CS50-s-Web-Programming-with-Python-and-JavaScript | /lambda.py | 247 | 3.90625 | 4 | people = [
{"name": "Ahmed", "house": "South"},
{"name": "Hussain", "house": "North"},
{"name": "Mohammed", "house": "West"}
]
# def f(person):
# return person["name"]
people.sort(key=lambda person: person["name"])
print(people)
|
4b2efd65c09a643a06b339ea868f63ae5ca6c76a | adibahsan/PythonProject | /lists.py | 318 | 4.0625 | 4 | #lists are mutable :D
list1 = ["ami", "tumi", "shey", 1, 420.2]
for x in list1:
print(x)
list2 = [list1, list1,list1]
print(list2)
for x in list2:
for y in x:
print(y,end=" ")
print()
for x in range (0,len(list2)):
for y in range(0,len(list2[x])):
print(list2[x][y],end=",")
print()
|
a6f237792aef743e05e0e1d0f81e510b0926bdec | nsimsofmordor/PythonProjects | /Projects/PythonPractice.org/p2_odd_or_even.py | 481 | 4.40625 | 4 | # Ask the user for a number.
# Depending on whether the number is even or odd, print out an appropriate message to the user.
# If the number is a multiple of 4, print out a different message.
# Ask for a positive number
number = int(input("Enter a positive number: "))
while number < 0:
number = int(input("Enter ... |
ee6fcba43821b771900c0ced8ca27003e6085fd0 | nsimsofmordor/PythonProjects | /Projects/PythonPractice.org/p6_sting_lists.py | 287 | 4.53125 | 5 | # Ask the user for a string and print out whether this string is a palindrome or not.
my_str = str(input("Enter a string to check if it is a palindrome or not: ").lower())
rev_str = my_str[::-1].lower()
if my_str == rev_str:
print("Palindrome!")
else:
print("Not Palindrome!") |
068905cbe2bea0582747af13f294ce98d8edf24f | nsimsofmordor/PythonProjects | /Projects/Python_Tutorials_Corey_Schafer/PPBT5 Dicts.py | 1,064 | 4.375 | 4 | # {Key:value} == {Identifier:Data}
student = {'name': 'john', 'age': '27', 'courses': ['Math', 'Science']}
print(f"student = {student}")
print(f"student[name] = {student['name']}")
print(f"student['courses'] = {student['courses']}\n")
# print(student['Phone']) # throws a KeyError, sine that key doesn't exist
print(... |
329e327ea632d3ce5e77372b78e741820fe08d87 | luismelendez94/holberton-system_engineering-devops | /0x16-api_advanced/100-count.py | 280 | 3.546875 | 4 | #!/usr/bin/python3
""" Recursive function that queries a Reddit API, parses the title of all
hot articles, and prints a sorted count of given keywords """
import requests
def count_words(subreddit, word_list):
""" Get the total of titles recursively """
return None
|
961e2bbf24a3533c2dece5b0e4cfd0e09a7fcba2 | Priyanka-Gore/INR-Exchange-Rate- | /Assignment.py | 1,816 | 3.796875 | 4 | import datetime
import matplotlib.pyplot as plt
import json
import pandas as pd
class my_dictionary(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
def common_dates(a, b):
a_set = set(a)
b_set = set(b)
if len(a_set.intersection(b_set)) > 0:
... |
a660aaac8eebb1e01e1438edee918867de197dd0 | dsalnasskhuzzzy/python | /multiDemensionalTicTacToe/nDttt.py | 2,271 | 3.5 | 4 | class board:
def __init__(self,demensions,playerCount):
#Both Player Count and Demensions must be natural numbers
self.demensions = demensions
self.marks = [[] for x in range(playerCount)]
def addMarkForPlayer(self,mark,playerID):
self.marks[playerID].append(mark)
def checkIfValidMark(self,mark):
if(len... |
14325d0779ae0aa4b96b89daddcaef7448493106 | msossoman/coderin90 | /calculator.py | 1,165 | 4.125 | 4 | def add (a, b):
c = a + b
print "The answer is: {0} + {1} = {2}".format(a, b, c)
def subtract (a, b):
c = a - b
print "The answer is {0} - {1} = {2}".format(a, b, c)
def multiply (a, b):
c = a * b
print "The answer is {0} * {1} = {2}".format(a, b, c)
def divide (a, b):
c = a / b
print "The answer is {0} / {1... |
0d7f49adb8e1057abdd0ef528636cdf2489ad2f8 | Mcgrupp34/microbit | /code_assignment1_temp.py | 691 | 3.75 | 4 | from microbit import *
#calibrate the compass when the program starts
compass.calibrate
#main loop
while True:
#Read temperature and place in variable
temp = temperature()
#Read compass heading and place in variable
direction = compass.heading()
#Display temp converted to Fahrenheit... |
483b5885c773d07ac670547100c67bd5f97e249f | EmilyLaforte/learning | /python/test.py | 248 | 3.578125 | 4 | import turtle
t = turtle.Turtle()
t.pencolor("pink")
t.speed(0)
for i in range(5):
t.fd(50)
t.lt(123) # Let's go counterclockwise this time
t.pencolor("turquoise")
for i in range(5):
t.fd(100)
t.lt(123)
turtle.done()
|
cc556397a64793e5087523f19f4e6ce73b06ea82 | jeffysam6/April-Leetcoding-Challenge | /search-in-rotated-sorted-array-week-3.py | 906 | 3.53125 | 4 | class Solution:
def search(self, arr: List[int], target: int) -> int:
if(len(arr) == 0):
return -1
left = 0
right = len(arr) -1
while(left < right):
mid = left + (right - left)//2
if(arr[mid] > arr[right]):
le... |
6cdff0ab5ee938a1ad0371041a12875817b9c65e | captflint/dndscripts | /deathsim.py | 763 | 3.6875 | 4 | import random
trials = 0
survived = 0
died = 0
turnavg = 0
longest = 0
while trials != 1000000000:
strikes = 0
turn = 0
while strikes < 3:
roll = random.randint(1, 20)
turn += 1
if roll == 20:
strikes = 10
elif roll < 10:
strikes += 1
else:
... |
e7b1564b9ca22fb1186ce66e261e9dd213a3c776 | lffelmann/coincount | /coincount_lib.py | 7,911 | 3.6875 | 4 | """Library with all the functions for CoinCount!"""
import csv
import pickle
from math import pi, sqrt
from typing import Any
import cv2
import numpy as np
def contour(image: Any, blur: int = 3, threshold: int = 110) -> list:
"""
Returns the contours of object in a image.
Parameters:
image: Ima... |
6ad85b2a11a283923a071fb9ee5a51847da13094 | craigtmoore/secret_code | /main.py | 3,562 | 3.671875 | 4 | import argparse
import os
import string
class EncodeDecode:
def __init__(self):
alphabet = string.printable + string.whitespace
self.encodeDict = dict()
self.decodeDict = dict()
for i, character in enumerate(alphabet):
self.encodeDict[character] = i
... |
0d83a00fa33a4cc38445fca9c4b72bdb840dea18 | becodev/python-utn-frcu | /guia02python/ejercicio12.py | 440 | 3.875 | 4 | """
Dado un número de mes de 1 a 12 determinar cuántos días tiene dicho mes.
"""
# No se contempla año bisiesto
mes = int(input("Ingrese numero de mes (1 a 12): "))
if(mes >= 1 and mes <= 12):
if mes in [4, 6, 9, 11]:
print("El mes ingresado tiene 30 dias.")
elif(mes == 2):
print("El mes ingre... |
a72228600b760a27521c4731693dce52c9fb1d8f | becodev/python-utn-frcu | /guia02python/ejercicio15.py | 676 | 4.09375 | 4 | """
Dado el valor numérico de la temperatura ambiente y su escala representada con una
carácter (C Celsius y F Fahrenheit), convertirla a la otra escala aplicando las siguientes
fórmulas según correspondan:
a. de F a C: (temp_f - 32) * 5/9
b. de C a F: (temp_c * 5/9) + 32
"""
temp = float(input("Ingrese temperatura: "... |
c53d4eaa499f6920318a8fdd0b506511428c74b9 | becodev/python-utn-frcu | /guia02python/ejercicio4.py | 500 | 3.921875 | 4 | """
Dada las tres notas obtenidas por un alumno en los distintos parciales, determinar si el
mismo está aprobado o desaprobado.
"""
parcial1 = float(input("Ingrese nota primer parcial: "))
parcial2 = float(input("Ingrese nota segundo parcial: "))
parcial3 = float(input("Ingrese nota tercer parcial: "))
promedio = rou... |
39cd0ae1ddb47e458d2137fab8f08575aaa81569 | becodev/python-utn-frcu | /guia01python/ejercicio12.py | 590 | 3.8125 | 4 | """
Una empresa distribuidora de energía le cobrar a sus abonados el consumo de kW por
hora, pero además debe sumarle el 0,21 % de impuesto, pero actualmente todos los
cliente están dentro de un plan de promoción que les descuenta el 3,7 % del monto total a
pagar.
"""
consumo = float(input("Ingrese consumo en KW: "))
... |
508d6c36ad2d7ebdddf2cd856d58195c952bbf9e | becodev/python-utn-frcu | /guia02pythonCiclos/ejercicio6.py | 261 | 3.609375 | 4 | """
Dado 15 números indicar cuál es el mayor.
"""
numeros = [11, 33, 4, 5, 12, 56, 21, 34, 625, 76, 78, 12, 123, 54, 69]
i = 0
mayor = 0
while i < 15:
if(numeros[i] > mayor):
mayor = numeros[i]
i += 1
print("El numero mayor es %s" % mayor)
|
4293eb83b348924bd3db9c8ecb9f0dac2d5b5717 | becodev/python-utn-frcu | /guia01python/ejercicio18.py | 424 | 3.5625 | 4 | """
Dada las tres mediciones que se realizó un pluviómetro en un día, cada vez que el mismo
se vacía, determinar cuántos milímetros llovió ese día.
"""
medicion1 = float(input("Ingrese primera medicion: "))
medicion2 = float(input("Ingrese segunda medicion: "))
medicion3 = float(input("Ingrese tercera medicion: "))
m... |
76d0d1452b34e6f66f282a7b07302ebd3a835159 | saiswethak/swetha | /66.py | 170 | 3.609375 | 4 | m=int(input())
count=0
for i in range(1,m):
if(m % i) == 0:
count+=1
if(count == 2):
print("no")
break
else:
print("yes")
|
334c8954b4b2e25721c95443caac224b89d74e9f | kenkitts/advent_of_code | /day10/day10p1.py | 501 | 3.515625 | 4 |
def p1():
data = sorted([int(line.strip()) for line in open('input.txt','rt')])
previous_value, one_jolt_adapters, three_jolt_adapters = 0,0,0
for idx,val in enumerate(data):
if val - previous_value == 1:
one_jolt_adapters += 1
elif val - previous_value == 3:
three_j... |
160fa4ec6f60422e90267d51ffaaf7549e4cf229 | realtalishaw/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/3-print_alphabt.py | 118 | 3.796875 | 4 | #!/usr/bin/python3
for i in range(26):
if i != 4 and i != 16:
print('{}'.format(chr(ord('a')+i)), end='')
|
1b26680c89752d77a1f78e231a9165c4a25a004c | Ashok-Mishra/python-samples | /python exercises/dek_program054.py | 864 | 4.4375 | 4 | # !/user/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# Define a class named Shape and its subclass Square. The Square class has
# an init function which takes a length as argument. Both classes have a
# area function which can print the area of the shape where Shape's area
# is 0 by default... |
40746a8b06658c8d7935e4238f69e17e1d7d9315 | Ashok-Mishra/python-samples | /python exercises/dek_program068.py | 970 | 4.40625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# program068:
# Please write a program using generator to print the even numbers between
# 0 and n in comma separated form while n is input by console.
# Example:
# If the following n is given as input to the program:
# 10
# The... |
e260d508fca7871b4955a4d44eded3503d532c18 | Ashok-Mishra/python-samples | /python exercises/dek_program062.py | 482 | 4.40625 | 4 | # !/user/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# Write a program to read an ASCII string and to convert it to a unicode
# string encoded by utf - 8.
# Hints:
# Use unicode() function to convert.
def do(sentence):
# print ord('as')
unicodeString = unicode(sentence, "... |
047481cff2b6856af271cecf82fbeb71e1e68ad3 | Ashok-Mishra/python-samples | /python exercises/dek_program071.py | 571 | 4.40625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# program071:
# Please write a program which accepts basic mathematic expression from
# console and print the evaluation result.
# Example:
# If the following string is given as input to the program:
# 35+3
# Then, the output of... |
a3a5dc9698f22d9a7f8b66735894af658fffbc05 | Ashok-Mishra/python-samples | /python exercises/dek_program011.py | 1,214 | 4.03125 | 4 | #!/user/bin/python
# -*- coding: utf-8 -*-
# Author : (DEK) Devendra Kavthekar
# program# : Name
# =>
# Write a program which accepts a sequence of comma separated
# 4 digit binary numbers as its input and then check whether
# they are divisible by 5 or not. The numbers that are divisible
# by 5 are to be printed in ... |
d502383264e8d290050e3b1384916f7888c07677 | Ashok-Mishra/python-samples | /python exercises/dek_program045.py | 694 | 4.375 | 4 | # !/user/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# Write a program which can filter even numbers in a list by using filter
# function. The list is:
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
# Hints:
# Use filter() to filter some elements in a list.
# Use lambda to define anonymous functio... |
9ffade93e2d1f84246df872596c06ba4fd3262cd | Ashok-Mishra/python-samples | /python exercises/dek_program005.py | 905 | 4.0625 | 4 | #!/user/bin/python
# -*- coding: utf-8 -*-
# Author : (DEK) Devendra Kavthekar
# program005 : Name
# =>
# Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
# Also please include simple test function to test the class metho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.