blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
696e979eadffb26bac50a562fd62c0dc6de655b4 | AvanindraC/Python | /histogram.py | 332 | 4.15625 | 4 | # Write a Python program to create a histogram from a given list of integers
def histogram(data):
for item in data:
print('.' * item)
data = []
num_data = int(input("Enter number of entries: "))
for item in range(0, num_data):
user_input = int(input())
data.append(user_input)
res = histogram(data... | true |
8b0c933fc0179f1a072ff79403e64ad979e69ca0 | AvanindraC/Python | /reverse.py | 262 | 4.28125 | 4 | # Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them
first = str(input("Enter first name: "))
last = str(input("Enter last name: "))
result = first[::-1] + " " + last[::-1]
print(result) | true |
02bd5ed48d7d512b30aa1b0938c87ef26629351d | JeganKunniya/practice-python-exercises | /16-PasswordGenerator.py | 1,094 | 4.125 | 4 | # Exercise 16 - Password Generator
import random
import string
STRONG = 1
MEDIUM = 2
WEAK = 3
def generate_password(password_complexity):
"""
Generates the password based on the complexity requested by the user.
:param password_complexity: could be Strong, Medium, Weak
:return: generated password b... | true |
9446bb68742d2f789534219c702c2be0c303f373 | mathivanansoft/algorithms_and_data_structures | /algorithms/divide_and_conquer/sorted_rotated_arr.py | 877 | 4.125 | 4 | # search an element in sorted rotated array
def search_in_sorted_rotated_arr(arr, key, start, end):
if start > end:
return -1
else:
mid = start + (end - start) // 2
if arr[mid] == key:
return mid
elif arr[mid] < arr[end]:
if key > arr[mid] and key <= ar... | false |
c6ce638e8b2ac21aa1971d76f27d50aab98ca958 | cleviane/CampinasTechTalentes-Python | /Aula_006/condicionaiscomnumeros.py | 365 | 4.28125 | 4 | # num_um = 1
# num_dois = 2
numero = int(input("Coloque o seu número: "))
if numero >= 0 and numero <= 3:
print(f"Os números {numero} está entre 0 e 3")
elif numero >= 3 and numero <= 4:
print(f"O número {numero} está entre 3 e 4")
elif numero >= 5 and numero <= 10:
print(f"O número ... | false |
dd75bef404b684e89eea27671c8e5adb78a35ab8 | dannyjew/Data22 | /HangMan/main.py | 2,460 | 4.28125 | 4 | word_to_guess = input("Please pick a word to guess...") # user inputs a word to guess
max_lives = 5 # max lives that the guesser has
wrong_counter = 1 # tracks the number of times the guesser guesses wrong
underscores = "________________________________________________________________________" # this is used to... | true |
94c4e796a3ab358f9c73df69be968aedcb7182e4 | EWilcox811/UdemyPython | /LambdaMap.py | 988 | 4.125 | 4 | def square(num):
return num**2
my_nums = [1,2,3,4,5]
for item in map(square, my_nums):
print(item)
list(map(square,my_nums))
def splicer(mystring):
if len(mystring)%2 == 0:
return 'EVEN'
else:
return mystring[0]
name = ['Andy','Eve','Sally']
list(map(splicer,name))
# When using the map... | true |
89fd8e1721a761ac8db70bd29590bc7d1b1ae6d3 | lingxueli/CodingBook | /Python/decorator/decorator.py | 1,223 | 4.28125 | 4 | def hello():
print('helloooooo')
greet = hello()
print(greet) # hello
greet = hello
print(greet) # function object
del hello
# hello is the pointer to the function
# this deletes the pointer not the function itself
greet() # still executed
# @decorator
# def hello():
# pass
# decorator add extra features t... | true |
fd4dfabeda6c4267eb8b57cd33c0aa95be45701d | lingxueli/CodingBook | /Python/Basics/range.py | 283 | 4.125 | 4 | # range creates an object that you can iterate over
print(range(0,100))
# obj: range(0,100)
for number in range(0,100):
print(number)
# when you don't need the variable
# send emails 100 times
for _ in range(0,100):
print('email email list')
print(_) # print 1,2,...
| true |
ef4fcfc933daf2bd296b07ec620f32af92ccd248 | lingxueli/CodingBook | /Python/Error handling/errorhandling4.py | 537 | 4.1875 | 4 | # stop the program from an error: raise
while True:
try:
age = int(input('what s your age? '))
10/age
# this stops the program
raise ValueError('hey cut it out')
# alternative: stop from any type of error
raise Exception('hey cut it out')
# remove the except part
... | true |
c25a1bb60e229ce1e9041427dadb3addc4429d56 | haodayitoutou/Algorithms | /LC50/lc24.py | 1,239 | 4.125 | 4 | """
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
"""
from util import ListNode, create_node_li... | true |
926fd5942e965801e9a0483c7ad67d0bfb33e77c | Bushraafsar/Alien-Dictionary | /alien.py | 2,532 | 4.40625 | 4 | # PYTHON ASSIGNMENT:
#ALIEN TASK:
# Python Program that display meaning of word said by alien in English Language:
# Python Program that display meaning of word said by human in alien language:
import json
print("==================== ENGLISH / ALIEN TRANSLATOR=========================")
while True:
print... | true |
4558a55e7d002e971aa7472aba0983160b90926e | ZanyeEast/ISAT252 | /lec9.py | 615 | 4.4375 | 4 | """
Lecture 9 Classes
Self method should be the first argument
"""
class car: # car is the class name
maker = 'toyota' #attribute
def __init__(self,input_model):
self.model = input_model
def report(self):
#return the attribute of the instance
return self.maker,sel... | true |
17bb66f503fee20354db38815f5ec7e094c3059c | ZanyeEast/ISAT252 | /lec8.py | 1,220 | 4.46875 | 4 | """
Lecture 8 Functions
return function should always be the last command in function
"""
#positional argument
def my_function(a, b):
result = a + b
print('a is',a)
print('b is',b)
return result
print(my_function(2, 1))
def my_function(a, b=0):
result = a + b
print('a is',a)
print('b is'... | true |
00e625639340092f82a32dedf9bdabcf3be4c28a | DrGMark7/CodingProblem | /Circle Test.py | 461 | 4.15625 | 4 | from math import sqrt
print('*'*30)
print('*********About Circle*********')
print('*'*30)
r = float(input('Input radius: '))
pi = 3.141592653589793
area = (pi*(r*r))
circ = (2*pi*r)
print('Radius is',r)
print('Circumference is', round(circ,4))
print('Area is', round(area,2) )
y = float(input('Enter y for fin... | false |
dc8df2ff35639fe143f5173aae56413e33ab125b | karinasamohvalova/OneMonth_python | /tip.py | 551 | 4.15625 | 4 | # We ask client's name and his bill
name = input("What is your name? ")
original_bill = int(input("What is your bill? "))
# We count three types if tips
tip_one = original_bill * 0.15
tip_two = original_bill * 0.18
tip_three = original_bill * 0.20
# We make an offer to the person. It includes 3 choices.
pri... | true |
2a45b8f146c70af9967b203c4cc587a0bdc801a2 | nakayamaqs/PythonModule | /Learning/func_return.py | 1,354 | 4.3125 | 4 | # from :http://docs.python.org/3.3/faq/programming.html#what-is-the-difference-between-arguments-and-parameters
# By returning a tuple of the results:
def func2(a, b):
a = 'new-value' # a and b are local names
b = b + 1 # assigned to new objects
return a, b # return new value... | true |
0b4b0a0299125f12419c24828b4e3699b8708226 | nakayamaqs/PythonModule | /Learning/find.py | 1,670 | 4.125 | 4 | #!/usr/bin/env python
# encoding: utf-8 #
# Simple imitation of the Unix find command, which search sub-tree
# for a named file, both of which are specified as arguments.
# Because python is a scripting language, and because python
# offers such fantastic support for file system navigation and
# regular expressions, py... | true |
9b16cc21ec0857141c7c359bf9a9ed5d8f72868a | ravgeetdhillon/hackerrank-algo-ds | /Extract_Number.py | 341 | 4.375 | 4 | numbers=['0','1','2','3','4','5','6','7','8','9']
print('***PROGRAM : To extract the valid phone number from the string***')
a=str(input('Input your string : '))
p=''
for char in a:
if char in numbers:
p=p+char
if len(p)==10:
print('The phone number is',p)
else:
print("Your input doesn't contain a v... | true |
75febbcc0d60df375dd9990b256fb1f35f330aa1 | balaprasanna/Trie-DataStructure | /trie.py | 2,254 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class trieNode:
""" leaf to indicates end of string """
def __init__(self):
self.next = {}
self.leaf = False
"""function to add a string to trie"""
def add_item(self, item):
i = 0
while i < len(item):
k = item[i]... | true |
0fa387eb77e0e0143b6390cec53c0edc123bc670 | soumyax1das/soumyax1das | /string_format.py | 434 | 4.1875 | 4 | """
This function shows how to use format method in different ways
Author :: Soumya Das
"""
import math
def string_format(str):
print(str.format('val1','val2','val3'))
def string_format_import_math_library(str):
print(str.format(m=math))
if __name__ == '__main__':
string_format('parm1={} parm2={} parm3={... | false |
d7bc082d5a94cd74332333f1b94beac9264711fb | soumyax1das/soumyax1das | /list_index_and_slicing.py | 420 | 4.125 | 4 | #!/usr/bin/env python3
def string_index_example(lst,indx):
print('Actual String is -',lst)
print('Value at index',indx,'is',lst[indx])
def string_slice(lst):
print(lst[-2:-1])
print(lst[-2:])
if __name__ == '__main__':
str="Hello this is Soumya Das"
###Create a list from a string###
lst=... | false |
7c19c4a9425947694aa49fcdd30ff905e044df7d | soumyax1das/soumyax1das | /simpleWhile.py | 320 | 4.15625 | 4 | """
This is a simple program to demonstarte the while loop in Python
"""
def create_pyramid(height):
i=1
while(i<=height):
i=i+1
print('i is',i)
if i == 4:
#continue
pass
print('+'*i)
print('*'*i)
if __name__ == '__main__':
create_pyramid(5)
| true |
8e2059b1be305f600cf4f0c1db5addd0da218cbe | yang-official/LC | /Python/4_Trees_and_Graphs/2_Graph_Traversal/207_course_schedule.py | 2,170 | 4.125 | 4 | # https://leetcode.com/problems/course-schedule/
# 207. Course Schedule
# There are a total of n courses you have to take, labeled from 0 to n-1.
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
# Given the total number of courses a... | true |
7e83e498e6841fa9db31c32c9591dfe5da8112ad | theknewkid/knewkidcalculator | /backend-code/calculations.py | 1,206 | 4.46875 | 4 | #Let's set up functions for the different calculations here. We'll create a float from the user's input.
hey = "Welcome to my very elementary calculator!"
print(hey)
def addition():
'''This is a function for adding.'''
a = float(input("Enter a number. "))
b = float(input("Enter another number. "))
pr... | true |
bfdcaf2efb90c0318c26a74d1e4c18ace6a781a2 | Liu-YanP/DataStructure | /DoubleQueue.py | 1,262 | 4.53125 | 5 | #双端队列
'''
双端队列(deque,全名double-ended queue),是一种具有队列和栈的性质的数据结构。
双端队列中的元素可以从两端弹出,其限定插入和删除操作在表的两端进行。
双端队列可以在队列任意一端入队和出队。
操作
Deque() 创建一个空的双端队列
add_front(item) 从队头加入一个item元素
add_rear(item) 从队尾加入一个item元素
remove_front() 从队头删除一个item元素
remove_rear() 从队尾删除一个item元素
is_empty() 判断双端队列是否为空
size() 返回队列的大小
'''
class Deque(object):
... | false |
fc7dc9c3c7f6999c57faf2a49dd43bb0a316bc65 | Liu-YanP/DataStructure | /Queue.py | 730 | 4.375 | 4 | #队列的实现
'''
同栈一样,队列也可以用顺序表或者链表实现。
操作
Queue() 创建一个空的队列
enqueue(item) 往队列中添加一个item元素
dequeue() 从队列头部删除一个元素
is_empty() 判断一个队列是否为空
size() 返回队列的大小
'''
class Queue(object):
"""队列"""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self,item):
self.items.insert(0,item... | false |
f1d80ec4d8de02adbb016bbf7a094ed24d1b9fbe | swathiswaminathan/guessing-game | /game.py | 1,640 | 4.21875 | 4 | """A number-guessing game."""
# Put your code here
import random
print "Welcome to the game!"
name = raw_input("What's your name? ")
print"Choose a random number, %s" % (name)
# secret_num = random.randint(1, 100)
#print " the secret number is %d" % (secret_num)
# guess = None
# too_high = 100
# too_low = 0
# coun... | true |
b0d5c7e842af58cd8d159e137f94a6eab79e5428 | sfGit2Hub/PythonLearn | /PythonDemo/static/max_cost_assignment.py | 1,058 | 4.40625 | 4 | import dlib
# So in this example, let's imagine we have 3 people and 3 jobs. We represent
# the amount of money each person will produce at each job with a cost matrix.
# Each row corresponds to a person and each column corresponds to a job. So for
# example, below we are saying that person 0 will make $1 at job 0, $2... | true |
3a167a50a74c630eaa197f4188b3baffb20eeced | ua114/py4e | /week1.py | 1,221 | 4.1875 | 4 | # Using strong functions
# fruit = 'banana'
# print(len(fruit)) #Lengh of the string
# fruit = 'mango'
# count = 0
# while count < len(fruit):
# print(count, fruit[count])
# count = count +1
# print('Done')
#
# for letter in 'banana':
# print(letter)
# word = 'abrasion'
# count = 0
# a_count = 0
#
# for ... | true |
0961deb46fd0ad1a27f842950979a5cb87188a74 | anjan111/python_8pm | /002_Built-in-function/003_built-in/004_unput_raw_float.py | 464 | 4.15625 | 4 | # raw_input vs input
'''
===>> rawinput is resultant datatype is str for any data
===>> input is resultant datatype is based data
'''
a = raw_input("enter float by raw : ")
print "data in a " ,a
print(type(a))
print "memory : ",id(a)
a = bool(a)
print "data in a " ,a
print(type(a))
print "memory : ",id... | false |
625b9dc82f0deea1a6a81f5496679a6ab30dbbbf | khyathipurushotham/python_2 | /matrix_subraction.py | 884 | 4.1875 | 4 | row = int(input("enter the row numbers:"))
col = int(input("enter the col number:"))
print("enter the elements for matrix1:")
matrix1 = [[int(input()) for i in range (col)] for j in range(row)]
print("matrix1:")
for i in range (row):
for j in range (col):
print(format(matrix1[i][j],"<3"),end="")
... | false |
f940e67265df7b83165a5aed6a153bd311b2d35a | yufang2802/CS1010E | /checkOrder.py | 338 | 4.375 | 4 | integer = input("Enter positive integer ")
def check_order(integer):
previous = 0
while (integer > 0 and integer > previous):
previous = integer
integer = int(input("Enter positive integer "))
if integer == 0:
print("Data are in increasing order.")
else:
print("Data are not in increasing order.")
check_o... | true |
2008f04cd95611d3f205817998af5534a1624bae | yufang2802/CS1010E | /factorial.py | 376 | 4.125 | 4 | #using recursion
def getFactorial(n):
if n < 2:
return 1
else:
return n * getFactorial(n-1)
#using iteration (loops)
def getFactorial2(n):
if n > 2:
factorial = 1
for i in range(1, n+1):
factorial *= i
return factorial
number = int(input("Enter n: "))
... | false |
4e6e1082fa4cd3c3b102eec8cdbc7de38673004e | TutorialDoctor/Scripts-for-Kids | /Python/math_basic.py | 661 | 4.1875 | 4 | # Get the sum of two numbers a and b
def sum(a,b):
return a+b
# Get the difference of two numbers a and b
def difference(a,b):
return a-b
# Get the quotient of two numbers a and b where b cannot equal 0
# You have to use a float somewhere in your dividion so that the answer comes out as a float
# A float is a num... | true |
0cf6a75530b43c968ab95fd2e2623369bbd9b5d9 | siraom15/coffee-to-code | /Python/SmilealniS.py | 219 | 4.125 | 4 | # coffee = input()
coffee = "coffee"
code = ""
words = coffee.split(' ')
for word in words:
if word == 'coffee':
code += 'code'
else:
code += word
code += ' '
code = code.rstrip()
print(code) | false |
acec8f27e351ee18087d6abb276a695dc95180a9 | Rhylan2333/Python35_work | /精品试卷 - 10/基本操作题 3:字典交换.py | 417 | 4.4375 | 4 | #在......上填写一段代码
def reverse_dict(dic):
out_dic = {}
## print(dic.items())
for key, value in dic.items():
## print(key, value)
out_dic[value] = key
keys = sorted(out_dic.keys(), reverse = True) # 返回一个列表
## print(keys)
for key in keys:
print(key, out_dic[key])
return out... | false |
34e739f02434bd9530cafc88adb65a6efe3bc4ec | sinvalfelisberto/python_curso_video | /aula10/exercicio/aula10_02.py | 315 | 4.375 | 4 | # estruturas condicionais
valor = int(input('Quantos anos tem seu carro?: '))
if valor <= 3:
print('Seu carro ainda está novo!')
else:
print('Seu carro está velho')
print('--- Fim ---')
# outra forma de fazer uma condicional
print('Seu carro ainda está novo!' if valor <=3 else 'Seu carro está velho!')
| false |
33703def35ae0f6298b06ca4e49c2f3a49d2ba4f | Dishvater/sda_pycharm_python | /python podstawy d2/d2/python_basic/python_basic/zad/z03_leap_year.py | 787 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def is_leap_year(year: str):
if not int(year) % 4 and not year.endswith('00'):
return True
elif not int(year) % 400 and year.endswith('00'):
return True
else:
return False
def is_leap_year_2(year: str):
if year.endswith('00'):
... | false |
c5e9594da3c8e46845d7428ec06c6cbac40b4499 | saisurajpydi/Python | /Python/Lists.py | 1,040 | 4.5625 | 5 | fruits = ["apple","banana","orange","kiwi"]
fruits.append("cherry")# to add element at last
print(fruits)
fruits.insert(2,"watermelon") # to add at index 2
print(fruits)
print(fruits[1]) # to get the element at index 1
print(fruits[1:4]) # to get the element from 1-3
# print using for loop
for i in fruits:
print(i)... | false |
732cb6de8566d69a84813850a25d426d862944f8 | Shailendre/simplilearn-python-training | /section1 - basic python/lesson6.5.py | 1,233 | 4.28125 | 4 | # tuple and list
# tuple: immutable
# sicnce tuple is immutable its fast in traversal and other operations
def example():
# this is called sequence packing
return 13,13
# this is sequence unpacking
a,b = example()
print(a)
# list
ll = [2,4,1,7,3,9,3,8,6,4,0]
# list size
print ("original length:", len(ll))
#... | true |
da06aa6567f4495284792a7196f01af46ecacb19 | zahranorozzadeh/tamarin4 | /tamrin4-3.py | 255 | 4.5 | 4 | # Python Program to print table
# of a number upto 10
def table(n):
for i in range (1, 11):
# multiples from 1 to 10
print (n, i, n * i)
# number for which table is evaluated
n = 5
table(n)
# This article is contributed by Shubham Rana
| true |
f1938f6cdb52543c85729a355584a25fd52ab9c4 | smspillaz/fair-technical-interview-questions | /python/default.py | 303 | 4.28125 | 4 | #!/usr/bin/env python
#
# This code *should* print [1], [2] but does something different. Can
# you explain why and how you would fix the problem?
def append(element, array=[]):
"""Return element as appended to array."""
array.append(element)
return array
print(append(1))
print(append(2)) | true |
fad067e667888ea23e5903f5b76eab36192ca521 | ZeyadAl/small-python-programs | /balance.py | 473 | 4.375 | 4 | '''
we are given 3 variablees
1) balance
2) annual interest rate
3) monthly min rate
first calculate monthly interest rate
'''
balance= float(input('Balance '))
annual= float(input('Annual interest rate '))
minrate= float(input('monthly Min rate '))
paid=0
mint= annual/12
for i in range(12):
balance= balance*(mi... | true |
ac86491af11e13ad77e3f266aba3e241a72f6476 | deesaw/PythonD-03 | /Databases/sqlite3Ex/selectTable.py | 618 | 4.25 | 4 | import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
sql = "SELECT * FROM cars"
print ("listing of all the records in the table:")
for row in cursor.execute(sql):
print (row)
print ("Results...")
cursor.execute(sql)
print(len(cursor.fetchmany(3)))
for id,carname,price in cursor.fetchal... | true |
768615562d1ba0d17b4e7a473ee8819bfd02da13 | deesaw/PythonD-03 | /Data Structures/7_dictionary.py | 750 | 4.28125 | 4 | #dictionary
marks={'Maths':97,'Science':98,'History':78}
print(marks)
print(type(marks))
print(len(marks))
print(sum(marks.values()))
print(max(marks.values()))
print(min(marks.values()))
print(marks.keys()) #prints keys from the dictionary
print(marks.valu... | true |
b5017c4fce9992d652e6cbd57056ab8ab36e3c5c | kingkongmok/kingkongmok.github.com | /bin/test/python/ex42.py | 1,852 | 4.40625 | 4 | #!/usr/bin/python
# http://learnpythonthehardway.org/book/ex42.html
# Is-A, Has-A, Objects, and Classes
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a Animal, has a function named __init__ that taks self, name parameters.
class Dog(Animal):
def ... | true |
0d55bfc50430c186b8c46fa816a23b27838f2aab | thuaung23/elementary-sortings | /main.py | 2,511 | 4.125 | 4 | # This program uses elementary sorts, such as selection, insertion and bubble.
# This program is written in object oriented programming.
# Written by: Thu Aung
# Written on: Oct 11,2020
"""
These elementary sorting algorithms are good for only smaller input sizes
because the time complexity of them is quadratic, O(N^2... | true |
52fed17125980a152cc0c90ef0a0cd21fa87c10b | caffwin/rev-string | /reverse-string.py | 2,816 | 4.375 | 4 | from pprint import pprint
# Reverse a string in place
# Input: string
# Output: string
# Strings are immutable in python, so use a list
# "hello" > "olleh"
# h e l l o
# 0 1 2 3 4
# 0 <-> 4
# or.. 0 <-> -1
# 1 <-> 3
# or.. 1 <-> -2
# 2 stays in place (no work done)
# h e l l o o
# 0 1 2 3 4 5
# ^ ^
# 0 ... | true |
218350fa2a2e5fb0ac0226a9ff64a9bf29ffa935 | samrana1996/python-code | /Grocery_shop.py | 1,735 | 4.125 | 4 |
print(" Hello Friends! ")
print(" What Item do you want to buy ?")
print(" You may Check our Product_List")
product = ["Rice", "Cereal", "Soap", "Biscuit", "Chips"]
catagory = ({"Basmati Rice": 90,
"Gouri": 85,
"Gobindovog": 79,
"Golden Silky Rice": 26,
... | false |
2c655db1e97429eeb8bc525cbc9d5408f6edeaf9 | appleboy919/python_DS_ALG | /ch4_Queue/myQueue.py | 1,147 | 4.25 | 4 | # application:
# CPU scheduling
# asynchronous data between two processes
# graph traversal algorithm
# transport, operations management
# file servers, IO buffers, printer queues
# phone calls to customer service hotlines
# !! resource is shared among multiple consumers !!
# head <-> rear (tail)
# FIFO
# head: remove ... | true |
0c9f99988ba5ce914094e28cccf2c85a008ee8b6 | GintautasButkus/20210810_Coin-Flip-Streaks | /Coin Flips.py | 2,384 | 4.34375 | 4 | # Coin Flip Streaks
# For this exercise, we’ll try doing an experiment. If you flip a coin 100 times
# and write down an “H” for each heads and “T” for each tails, you’ll create
# a list that looks like “T T T T H H H H T T.” If you ask a human to make
# up 100 random coin flips, you’ll probably end up with alternatin... | true |
791fe6d02d0a5a85f62db34d82a35e07aa72aeb7 | greenca/exercism-python | /wordy/wordy.py | 945 | 4.15625 | 4 | operators = {'plus':'+', 'minus':'-', 'multiplied':'*', 'divided':'/'}
def calculate(question):
question_words = question.split(' ')
if question_words[:2] == ['What', 'is']:
question_words = question_words[2:]
num1 = question_words.pop(0)
op = question_words.pop(0)
num2 = questi... | true |
9c895d9990c777c0ecd1310d316ad10ca69b7cf8 | vdpham326/python-data-structures | /dictionary/find_anagrams.py | 892 | 4.28125 | 4 | words = ['gallery', 'recasts', 'casters', 'marine', 'bird', 'largely', 'actress', 'remain', 'allergy']
def find_anagrams(list):
new = {}
#key should store strings from input list with letters sorted alphabetically
for word in list:
key = ''.join(sorted(word))
if key not in new:
... | true |
59aa697109d141faa171bfb00ddee85cac9e153f | vdpham326/python-data-structures | /tuple/get_values.py | 608 | 4.3125 | 4 | '''
Create a function named get_min_max_mean(numbers) that accepts a list of integer values and returns the smallest element,
the largest element, and the average value respectively – all of them in the form of a tuple.
'''
def get_min_max_mean(numbers):
smallest, largest, total = numbers[0], numbers[0], 0
for ... | true |
d7528247c450cbd739a07c58dae1d6812250c192 | hiukongDan/EulerMethod | /EulerMethod.py | 802 | 4.1875 | 4 | #!/usr/python
class EulerMethod:
def __init__(self, diffFunc, initX, initY):
self.func = diffFunc
self.init = [initX, initY]
def plot(self, stop, step):
dot = [self.init[0], self.init[1]]
while dot[0] <= stop:
print("(%f,%f)"%(dot[0],dot[1]))
... | false |
bca033e9e874316c0386fc7efc55cc3e4034ff4c | dignakr/sample_digna | /python-IDLE/item_menu_ass1.py | 1,892 | 4.25 | 4 | class ItemList:
def __init__(self, itemname, itemcode):
self.itemname = itemname
self.itemcode = itemcode
def display(self):
print '[itemname :',self.itemname,',itemcode :',self.itemcode,']'
if __name__=="__main... | true |
d76e737379f2afd92f4dce9f74ac73593d674980 | John-Ming-Ngo/Assorted-Code | /PureWeb_Submission/Shuffle.py | 2,853 | 4.4375 | 4 | import random as rand
import copy
'''
This function, given an input value N, produces a randomized list
with each value from 1 to N. Naively, this can be done by actually
simulating a real shuffle, as I did in a prior assignment, but since
we want to optimize for speed, we're going to have to be more
creative. The fir... | true |
86b243cc66970a367cf6ffacf2e9727cea200e78 | vgiabao/a-byte-of-python | /oop_objvar.py | 965 | 4.125 | 4 | class Robot:
''' Represents a robot, with a name'''
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
'''Initialise the data'''
self.name = name
print('initialise {0}'.format(self.name))
Robot.population += 1
def die(self):
... | false |
47ddd4ebe7f26b2f3a48439ac77110a69df333e6 | NotQuiteHeroes/HackerRank | /Python/Math/Triangle_Quest_2.py | 929 | 4.15625 | 4 | '''
You are given a positive integer N.
Your task is to print a palindromic triangle of size N.
For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
You can't take more than two lines. The first line (a for-statement) is already written for you.
You have to complete the code using exactly o... | true |
8f76164190b01039565d41b9c735c5dba85304dc | NotQuiteHeroes/HackerRank | /Python/Sets/Captains_Room.py | 1,359 | 4.125 | 4 | '''
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was given a separa... | true |
ddf276c6fd4b62db64141085002cc4b246e61de1 | NotQuiteHeroes/HackerRank | /Python/Basic_Data_Types/List_Comprehensions.py | 873 | 4.28125 | 4 | '''
Let's learn about list comprehensions! You are given three integers x, y, and z representing the dimensions of a cuboid along with an integer n. You have to print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k is not equal to n. Here, 0 <= i <= x, 0 <= j <= y, 0 <= k <... | true |
37da311250659eff59593188f0c3a40423d93f77 | bensontjohn/pands-problem-set | /squareroot.py | 600 | 4.15625 | 4 | # Benson Thomas John, 2019
# Program that takes a positive floating point number as input and outputs an approximation of its square root.
# import the math module
import math
# Take user input and convert to float type
user_num = float(input("Please enter a positive number: "))
# Referenced : https://docs.pyt... | true |
9cc7773a5de21e86034de5b1bea974f33d240289 | lucius1991/myedu-1904 | /day02/lianxi.py | 1,426 | 4.1875 | 4 |
#这是一个列表的数据类型,英文是list,也叫数组
alist = ['你好',10,15,20,'world']
#查询
def list_test():
print(alist[0])
print(alist[0:1])
取倒数第三位
print(alist[6:7])
print(alist[-3])
#第5个开始到后面所有
print(alist[4:])
print(alist[:4])
#删除
def list_del():
alist.pop()
print(alist)
alist.pop(4)
a = alis... | false |
4bee2818070b5910cd395c0c88e7df7657672819 | jerryperez25/ArtificialIntelligence-CS4341 | /Homework 1/CS4341_HW1_PerezJerry/PerezJerry/ex2.py | 773 | 4.125 | 4 | def isreverse(s1, s2):
# Your code here
if (len(s1) == 0 and len(s2) == 0): # if both lengths are 0 then they are both equal: only thing thats 0 is empty
return True;
if len(s1) != len(s2): # if the lengths of 2 words are not equal then there is no way they can be reversals
return False;... | true |
c4c8adf35fb920d7929e3e4ee11281ae69300d68 | androshchyk11/Colocvium-2-semester | /10.py | 896 | 4.375 | 4 | '''
Дані про температуру повітря за декаду листопада зберігаються в масиві.
Визначити, скільки разів температура опускалася нижче -10 градусів.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
temperature = [20, 14, -5, 1, 23, 5, 7, -8, -7, 0] # Ініціалізуємо масив з температурами(можна дані змінити)
answe... | false |
5f2ea39bd61ac3e2cad0d9f157be9bea78037081 | androshchyk11/Colocvium-2-semester | /22.py | 1,133 | 4.125 | 4 | '''
Знайти добуток елементів масиву, кратних 3 і 9. Розмірність масиву - 10.
Заповнення масиву здійснити випадковими числами від 5 до 500.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
import random
answer = 1 # Ініціалізуємо змінну результат
a = [random.randint(5, 500) for i in range(10)] # створюємо... | false |
faea3e3b47ef0a20cb862df7f8090c336e8f5fda | jerry1210/HWs | /HW5/3.py | 642 | 4.15625 | 4 | '''
Write a decorator called accepts that checks if a function was called with correct argument types. Usage example:
# make sure function can only be called with a float and an int
@accepts(float, int)
def pow(base, exp):
pass
# raise AssertionError
pow('x', 10)
'''
def accepts(*types):
def decorator(func):
... | true |
0d8252d254e300ae9c60ce0ed0f9db19f6242b43 | omshivpuje/Python_Basics_to_Advance | /Python primery data structures.py | 1,104 | 4.25 | 4 | """
Primary Data structures:
1. List
2. Tuple
3. Dictionary
4. Sets
"""
# List
# Lists are mutable and ordered. Also can have different, duplicate members. can be declared in [].
ranks = [1, 2, 3, 4, 5]
fruits = ["Orange", "Mango", "Pineapple", "Strawberry"]
print("ranks: {0}, fruits: {1}".format(ranks... | true |
62cefc2511642742ec4e3b31bb62de545631dd68 | StrelnikovaKarina/Coding | /21.02.19.py | 1,638 | 4.4375 | 4 | import time
counter = 3 # количество сравнений
sleep = 1 # время прирывания программы
clock_counter = 0 # количество раз когда time.clock() была точнее
time_counter = 0 # количество раз когда time.time() была точнее
# в цикле расчитывается время выполнения time.sleep(sleep) с помо... | false |
6b0f8a586f105c982592196a0c9c2a13f4515d34 | dan8919/python | /sort/String Tokenizer/stringTokenizer.py | 318 | 4.15625 | 4 | string = "1+2*(3-4)"
#숫자와 괄호를 분리 해주는 식
def stringTokenzier(string):
result = []
for char in string:
if char in ["+","-","*","/","(",")"]:
result.append(char)
result.append(char)
return result
result = stringTokenzier(string)
print("result=>",result)
| false |
860936a58673a46d8ee2733dc2ced12968e74976 | gauravk268/Competitive_Coding | /Python Competitive Program/LIST.py | 1,928 | 4.34375 | 4 | Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> ## LISTS IN PYTHON
>>>
>>> list1 = [10,20,30,"hello",2.4]
>>> list1
[10, 20, 30, 'hello', 2.4]
>>> list1[1]
20
>>> list1[-4]
20
>>> ## Accessing th... | true |
b9d676a541b0c0a52e62c39eb8b665e81f8b8c2e | gauravk268/Competitive_Coding | /Python Competitive Program/gretest element in right.py | 1,087 | 4.5625 | 5 | # Python Program to replace every element with the
# greatest element on right side
# Function to replace every element with the next greatest
# element
def nextGreatest(arr):
size = len(arr)
# Initialize the next greatest element
max_from_right = arr[size-1]
# The next greatest ele... | true |
570c0313be76ea30e28fbf796388b61987ffe7f0 | gauravk268/Competitive_Coding | /Python Competitive Program/ifelse.py | 236 | 4.3125 | 4 | #-------- Senior Citizen---------
age=float(input("Enter your age : "))
if age>0 and age<=1:
print("Infant")
elif age>1 and age<=18:
print("Child")
elif age>18 and age<=60:
print("Adult")
else:
print("Senior Citizen")
| false |
a2f503fe913e6103377a6aabca170c035b60896d | group6BCS1/BCS-2021 | /src/chapter5/excercise1.py | 485 | 4.21875 | 4 | try:
total = 0
count = 0
# the user will be able to input numbers repeatedly
while True:
x = input('enter a number')
# when done is entered, the loop will be broken
if x == 'done':
break
x = int(x)
# we are finding the total, count and average of the numbers entered
... | true |
573530cf686edbd3264ad6a2440c2809dd3c04f1 | yufanglin/Basic-Python | /sortingListsTuplesObjects.py | 1,603 | 4.21875 | 4 | '''
Sorting Lists, Tuples, and Objects
Code from following this tutorial:
https://www.youtube.com/watch?v=D3JvDWO-BY4&index=21&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU
'''
# sort
li = [9, 1, 8, 2, 7, 3, 6, 4, 5]
s_li = sorted(li)
desc_li = sorted(li, reverse=True)
print('Sorted Variable:\t', s_li)
print('Descending S... | false |
6495d47e7d6695d6c4851252bfa5c0080aef1296 | yufanglin/Basic-Python | /List.py | 2,474 | 4.46875 | 4 | '''
List practice in Python 3
'''
############################## LISTS ##############################
courses = ['History', 'Math', 'Physics', 'CompSci']
# Print the list
print(courses)
# length of the list
print(len(courses))
# Get specific values in list
print(courses[0])
# Get last value in list
print(co... | true |
181764d142ccd99845d433fbbd32e976dace9c40 | clarito2021/python-course | /11.-loops.py | 1,785 | 4.15625 | 4 | foods = ['apples', 'bread', 'cheese', 'milk',
'graves', 'vine', 'cereal', 'banana']
print('******************************************')
print("Aquí vemos la salida si imprimimos los indices especificados uno por uno")
print(foods[0])
print(foods[1])
print(foods[2])
print(foods[3])
print('*****************... | false |
12f364334a3a95711444bcd45345b834a48ff47f | tb1over/datastruct_and_algorithms | /interview/CyC2018_Interview-Notebook/剑指offer/16.py | 499 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent。求 base 的 exponent 次方。
"""
def _power(x, n):
result = 1
while n > 0:
if n & 1 == 1:
# 判断是否为奇数,如果是奇数则计算result
result *= x
n >>= 1
x *= x
return result
def power(x, n):
pn = n if n > ... | false |
d06c4e14ca6439e732ab46594b449caacf965c8b | tb1over/datastruct_and_algorithms | /number/mod_exp.py | 468 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Given three numbers x, y and p, compute (x^y) % p.
# recursive power
def power_rf(x, y):
if y == 1:
return x
return x * power(x, y-1)
# for loop
def power(x, y):
res = 1
while y > 0:
# 如果y是奇数,那么res = res * x
if y & 1:
res *= x
y >>= 1 ... | false |
c603b386c71d984b3a4771028d7a960c1957dbe7 | colinbazzano/recursive-sorting-examples | /src/lecture.py | 1,492 | 4.1875 | 4 | # *********************************************
# NEVER DO THIS, BUT... it is recursion
# def my_recursion(n):
# print(n)
# my_recursion(n+1)
# my_recursion(1)
# *********************************************
# we have now added a base case to prevent infinite recursion
def my_recursion(n):
print(n)
... | true |
baa425cca4e36d27b14c71569660ea92e6e47815 | kishorchouhan/Udacity-Intro_to_CS | /Better splitting.py | 1,370 | 4.34375 | 4 | def split_string(source,splitlist):
word_list = ['']
at_split = False
for char in source:
if char in splitlist:
at_split = True
else:
if at_split:
# We've now reached the start of the word, time to make a new element in the list
word_li... | true |
ecd06a64bd206784e741f086a8bc6f0453716786 | vimalkkumar/Basics-of-Python | /Factorial.py | 280 | 4.1875 | 4 | def main():
def factorial_number(num):
result = 1
for i in range(1, num+1):
result = i*result
print("factorial of {} is {}".format(num, result))
factorial_number(int(input("Enter a number : ")))
if __name__ == "__main__":
main()
| true |
13bb71cc08704b55facd4fbc8ba363bfe16c04ef | lf-coder/python | /01-basicLearning/13-字典.py | 353 | 4.40625 | 4 | """
1.字典是dict的实例
1.python的字典和js中的对象一模一样
2.可以使用in 和 not in判断字典中是否有该key
"""
# 创建一个字典
dict1 = {'name': 'lf', 'age': 23}
print(dict1)
dict2 = dict((('name', 'lf'), ('age', 23)))
print(dict2)
dict3 = dict(name='lf', age=23)
print(dict3)
dict3['hobby'] = 'play game'
print(dict3)
| false |
6a7aeb4b770d80379edd2380372df614b5db4d4c | saikiran335/python-projects | /contactlist.py | 2,039 | 4.28125 | 4 | contacts={}
print("--------Contacts---------")
while True:
print("\nSelect the operation")
print("1.Insert the contact")
print("2.Search for the contact")
print("3.Delete the contact")
print("4.Display all the contacts")
print("5.delete all the contacts")
print("6.edit the contact")
prin... | true |
390605ee17a9754ae7ee2f702269a61bb20908cd | Prudhvik-MSIT/cspp1-practice | /m9/Odd Tuples Exercise/odd_tuples.py | 638 | 4.40625 | 4 | '''
Author: Prudhvik Chirunomula
Date: 08-08-2018
'''
#Exercise : Odd Tuples
#Write a python function odd_tuples(a_tup) that takes a some numbers
# in the tuple as input and returns a tuple in which contains odd
# index values in the input tuple
def odd_tuples(a_tup):
'''
a_tup: a tuple
retur... | true |
fd998d3bc0b125e9d775521e37e4ad3d2fd0ad37 | zadrozny/algorithms | /find_list_duplicates.py | 1,255 | 4.125 | 4 | '''
Write a function that finds and returns
the duplicates in a list.
Write a test for this.
'''
def find_duplicates_1(lst):
duplicates = []
for element in set(lst):
if lst.count(element) > 1:
duplicates.append(element)
return duplicates
#Rewritten as a list comprehension
def find_duplicates_2(lst):
r... | true |
547984f82e245a84d8d1122553600f8fd5242f79 | zadrozny/algorithms | /matched_braces.py | 1,299 | 4.125 | 4 | '''
Challenge 2: Braces
Given an array of strings containing three types of braces: round (), square [] and curly {}
Your task is to write a function that checks whether the braces in each string are correctly matched prints 1 to standard output (stdout) if the braces in each string are matched and 0 if they're not (... | true |
74f9d1a7da0af018658e153665870d69b6259d46 | HtetoOs/Practicals | /prac_03/oddName.py | 223 | 4.125 | 4 | name = input("Enter your name!")
while len(name)<=0:
print("Name is blank! Please enter your name!")
name = input("Enter your name!")
print(name[: : 2])
for i in range(0, len(name), 2):
print(name[i], end="") | true |
d4001e7b106ceb83691eba57765097493fa4571b | arthurbragav/Curso_udemy | /Aula 23 - Estruturas logicas and or not is.py | 553 | 4.1875 | 4 | """
Estruturas lógicas and, or, not, is
Operadores unários:
- not
Operadores binários
- and, or, is
Regras de funcionamento
Para o 'and', ambos os valores precisam ser True
Para o 'or', um ou outro valor precisa ser True
Para o 'not', o valor do booleano é invertido
Para o 'is', o valor é comparado com um seg... | false |
bf721957e07df6a9ab6fad30ba99e233512a0a15 | gbanfi3/misc | /Euler/a001.py | 331 | 4.15625 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
lim = 1000
sum = 0
for i in range(1,lim):
if not i % 3:
sum +=i
continue
if not i % 5:
sum +=i... | true |
fd2d5ef7a880dc1749d489542ae72a5510f39199 | Al153/Programming | /Python/Misc/maths.py | 959 | 4.34375 | 4 | pi=3.1415926535
from math import *
n=2
operation = "go"
square = 1
circle = 2
elipse = 3
rectangle = 4
while operation != "stop":
operation = (input("which shape do you want to find the area of? "))
if operation == 1:
print("area of a square")
sidelength=float(input("side length = "))
a... | true |
0b545e74b9ec8ba6284590a38cf0f7e24f9bc7bf | Al153/Programming | /Guest/Hour of code/Heapsort.py | 2,174 | 4.25 | 4 | def heapsort(lst):
''' Heapsort. Note: this function sorts in-place (it mutates the list). '''
compare_count = 0
print "Creating heap"
for start in range((len(lst)-2)/2, -1, -1):
compare_count = siftdown(lst, start, len(lst)-1,compare_count)
print lst
print "decomposing heap"
for end in range(len(l... | true |
8a2a07ff7d19edea0d93b5dfdb65d032ad851630 | Adheethaov/InfyTQ-Python | /grade.py | 647 | 4.21875 | 4 | #A teacher in a school wants to find and display the grade of a student based on his/her percentage score.
#The criterion for grades is as given below:
#Score (both inclusive) Grade
#Between 80 and 100 A
#Between 73 and 79 B
#Between 65 and 72 C
... | true |
b026e0fa91ec048ff4a61a95902319a0e3439c4b | anishsaah/Learning-Python | /sample calculator.py | 1,221 | 4.375 | 4 | while True:
print("Options:")
print("Enter 'add' to add two numbers.")
print("Enter 'subtract' to subtract two numbers.")
print("Enter 'multiply' to multiply two numbers.")
print("Enter 'divide' to divide two numbers.")
print("Enter 'quit' to end the program.")
a = input(": ")
... | true |
fdaab6120cacaab50010d1d2c907f6ca625359a3 | SibiSagar/codekata | /problem4.py | 246 | 4.25 | 4 | #Check whether a character is an alphabet or not
alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
char=input()
if char in alphabet:
print("Alphabet")
elif char in alphabet.lower():
print("Alphabet")
else:
print("No")
| true |
ae86b88683c3f7a4a5bdb0575e7355ce4d6623f9 | MaisenRv/EjerciciosCiclo1 | /eje23_metodos_de_cadenas_caracteres.py | 1,073 | 4.15625 | 4 | from os import system
system("cls")
#miestra la letra que esta en corchetes
x = "jose maria cordoba"
print(x[2])
#mayuscula la primera letra
print(x.capitalize())
#El tecto lo pone en mayuscula
print(x.upper())
#Todo en minuscula
print(x.lower())
#centra el texto entre 25 caracteres " "
print(x.center(25,"-"))
#... | false |
5f2b3fdc2e0cedcfba66a2cdd36edf2475c2ca78 | ambergooch/dictionaries | /dictionaryOfWords.py | 828 | 4.625 | 5 |
# Create a dictionary with key value pairs to represent words (key) and its definition (value)
word_definitions = dict()
word_definitions["Awesome"] = "The feeling of students when they are learning Python"
word_definitions["Cool"] = "A descriptor word for a cucumber"
word_definitions["Chill"] = "The act of sinking ... | true |
e534b2fa2a5545f10c26be9245a37f403070c682 | chamoysvoice/p_euler | /problem4.py | 781 | 4.15625 | 4 | # coding=utf-8
from __future__ import division
from math import sqrt
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is
9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(sv):
retu... | true |
3177febbe7fdfa6e909558ecbc45a1b37d09c5a9 | hidalgowo/CC1002 | /Clases/Clase_05_modulos/ejsRecursion.py | 2,790 | 4.15625 | 4 | # potencia: num int -> num
# calcula el valor de una potencia de base elevado a exponente
# para exponentes enteros positivos
# ejemplo: potencia (4,5) debe dar 1024
def potencia(base, exponente):
if exponente == 0:
return 1
else:
return base*(potencia(base, exponente-1))
# test
assert potencia... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.