blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
419e9c5cbb652df0abccd13ca68273bc18327cd9
|
jadugnap/python-problem-solving
|
/Task4-predict-telemarketers.py
| 1,300
| 4.15625
| 4
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
text.csv columns: sending number (string), receiving number (string), message timestamp (string).
call.csv columns: calling number (string), receiving number (string), start timestamp (string), duration in seconds (string)
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
text_senders = set([t[0] for t in texts])
text_receivers = set([t[1] for t in texts])
call_receivers = set([c[1] for c in calls])
whitelist = call_receivers.union(text_senders, text_receivers)
# print("\n".join(sorted(whitelist)))
callers = sorted(set([c[0] for c in calls if c[0] not in whitelist]))
print("These numbers could be telemarketers: ")
print("\n".join(callers))
| true
|
a4b024fe5edf1f5da39078c8d52034ba303a98cc
|
schirrecker/Math
|
/Math with Python.py
| 397
| 4.15625
| 4
|
from fractions import Fraction
try:
a = Fraction(input("Enter a fraction: "))
b = Fraction(input("Enter another fraction: "))
except ValueError:
print ("You entered an invalid number")
except ZeroDivisionError:
print ("You can't divide by zero")
else:
print (a+b)
def is_factor (a, b):
if b % a == 0:
return True
else:
return False
| true
|
9fa0e009c15e00016bfae128e68515f6aaa87e5d
|
rohanyadav030/cp_practice
|
/is-digit-present.py
| 865
| 4.1875
| 4
|
# Python program to print the number which
# contain the digit d from 0 to n
# Returns true if d is present as digit
# in number x.
def isDigitPresent(x, d):
# Breal loop if d is present as digit
if (x > 0):
if (x % 10 == d):
return(True)
else:
return(False)
else:
return(False)
# function to display the values
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n+1):
# checking for digit
if (i == d or isDigitPresent(i, d)):
print(i,end=" ")
# Driver code
n = 20
d = 5
print("n is",n)
print("d is",d)
print("The number of values are")
printNumbers(n, d)
'''
******************* output **********************
n is 47
d is 7
The number of values are
7 17 27 37 47
n is 20
d is 5
The number of values are
5 15
'''
| true
|
18bde0bbb7b8f371cbbab5d3a73310f823fa3570
|
amrutha1352/4040
|
/regularpolygon.py
| 280
| 4.28125
| 4
|
In [46]:
X= float(input("Enter the length of any side: "))
Y= int(input("Enter the number of sides in the regular polygon: "))
import math
numerator= math.pow(X,2)*Y
denominator= 4*(math.tan(math.pi/Y))
area= numerator/denominator
print("The area of the regular polygon is:",area)
| true
|
34c467f6bcb628d403321d30b29644d35af003f3
|
jonesm1663/cti110
|
/cti 110/P3HW2.py
| 543
| 4.28125
| 4
|
# CTI-110
# P3HW2 - Shipping Charges
# Michael Jones
# 12/2/18
#write a program tha asks the user to enter the weight of a package
#then display shipping charges
weightofpackage = int(input("Please enter the weight of the package:"))
if weightofpackage<= 2:
shippingcharges = 1.50
elif weightofpackage < 7:
shippingcharges = 3.00
elif weightofpackage < 11:
shippingcharges = 4.00
else:shippingcharges = 4.75
print("package weighs"+str(weightofpackage)+", you pay"+ \
format(shippingcharges,",.2f"))
| true
|
619ebd59a6875ca0c6feb9a2074ba5412215c4ae
|
jonesm1663/cti110
|
/cti 110/P3HW1.py
| 820
| 4.4375
| 4
|
# CTI-110
# P3HW1 - Roman Numerals
# Michael Jones
# 12/2/18
#Write a program that prompts the user to enter a number within the range of 1-10
#The program should display the Roman numeral version of that number.
#If the number is outside the range of 1-10, the program should display as error message.
userNumber = int(input("Please enter a number"))
if userNumber ==1:
print("1")
elif userNumber ==2:
print("II")
elif userNumber ==3:
print("III")
elif userNumber ==4:
print("IV")
elif userNumber ==5:
print("V")
elif userNumber ==6:
print("VI")
elif userNumber ==7:
print("VII")
elif userNumber ==8:
print("VIII")
elif userNumber ==9:
print("IX")
elif userNumber ==10:
print("X")
else:
print("Error: Please enter a number between 1 and 10.")
| true
|
698b8212c16b1a11a5fb9d63af5db687d404039f
|
beyzakilickol/week1Friday
|
/algorithms.py
| 953
| 4.1875
| 4
|
#Write a program which will remove duplicates from the array.
arr = ['Beyza', 'Emre', 'John', 'Emre', 'Mark', 'Beyza']
arr = set(arr)
arr = list(arr)
print(arr)
#-------Second way------------------------
remove_dups = []
for i in range(0, len(arr)):
if arr[i] not in remove_dups:
remove_dups.append(arr[i])
print(remove_dups)
#-------------Assignment 2-------------------------
#Write a program which finds the largest element in the array
arr = [3,5,7,8,9,14,24,105]
print(max(arr))
#-------------Assignment 3--------------------------------
#Write a program which finds the smallest element in the array
print(min(arr))
# stringArr = ['beyza', 'cem', 'ramazan', 'ak', 'ghrmhffjhfd', 'yep']
# print(min(stringArr)) # returns ak in alphabetical order
#------------Assigment 4----------------------------------
#Write a program to display a pyramid
string = "*"
for i in range(1, 18 , 2):
print('{:^50}'.format(i * string))
| true
|
32f05d2f45e3bad3e2014e1ba768a6b92d4e67b6
|
soumyadc/myLearning
|
/python/statement/loop-generator.py
| 575
| 4.3125
| 4
|
#!/usr/bin/python
# A Generator:
# helps to generate a iterator object by adding 1-by-1 elements in iterator.
#A generator is a function that produces or yields a sequence of values using yield method.
def fibonacci(n): #define the generator function
a, b, counter = 0, 1, 0 # a=0, b=1, counter=0
while True:
if(counter > n):
return
yield a
a=b
b=a+b
counter += 1
it=fibonacci(5) # it is out iterator object here
while True:
try:
print (next(it))
except:
break
print("GoodBye")
| true
|
7400c080f5ce15b3a5537f436e3458772b42d801
|
soumyadc/myLearning
|
/python/tkinter-gui/hello.py
| 737
| 4.21875
| 4
|
#!/usr/bin/python
from Tkinter import *
import tkMessageBox
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
# Code to add widgets will go here...
# Tk root widget, which is a window with a title bar and other decoration provided by the window manager.
# The root widget has to be created before any other widgets and there can only be one root widget.
top = Tk()
L1= Label(top, text="Hello World")
L1.pack(side=LEFT)
# Button, when clicked it calls helloCallBack() function
B1=Button(top, text="Hello", command=helloCallBack)
B1.pack(side=RIGHT)
# The window won't appear until we enter the Tkinter event loop
# Our script will remain in the event loop until we close the window
top.mainloop()
| true
|
29c1733f39888ca54099d2e15a762d8d748c06f9
|
opiroi/sololearn_python
|
/assistant/python_iterators_and_generators.py
| 1,556
| 4.5
| 4
|
def iteration_over_list():
"""Iteration over list elements.
:return: None
"""
print("##### ##### iteration_over_list ##### #####")
for i in [1, 2, 3, 4]:
print(i)
# prints:
# 1
# 2
# 3
# 4
def iteration_over_string():
"""Iteration over string characters.
:return: None
"""
print("##### ##### iteration_over_string ##### #####")
for i in "python":
print(i)
# prints:
# p
# y
# t
# h
# o
# n
def iteration_over_dictionary():
"""Iteration over dictionary elements.
:return: None
"""
print("##### ##### iteration_over_dictionary ##### #####")
for i in {"x": 1, "y": 2, "z": 3}:
print(i)
# prints:
# z
# y
# x
def iteration_over_file_line():
"""Iteration over file lines.
:return: None
"""
print("##### ##### iteration_over_file_line ##### #####")
for line in open("a.txt"):
print(line)
# prints:
# first line
# second line
def iteration_practical_usage():
"""Efficient usage examples of iterations.
1. list join
2. dictionary join
3. string list
4. dictionary list
:return: None
"""
print("##### ##### iteration_practical_usage ##### #####")
print(",".join(["a", "b", "c"]))
# prints as string: 'a,b,c'
print(",".join({"x": 1, "y": 2}))
# prints as string: 'y,x'
print(list("python"))
# prints as list: ['p', 'y', 't', 'h', 'o', 'n']
list({"x": 1, "y": 2})
# prints as list: ['y', 'x']
| false
|
7b3a4e66395735192270abc17f1c77bc8d5ee5bd
|
newjoseph/Python
|
/Kakao/String/parentheses.py
| 2,587
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
# parentheses example
def solution(p):
#print("solution called, p is: " + p + "\n" )
answer = ""
#strings and substrings
#w = ""
u = ""
v = ""
temp_str = ""
rev_str = ""
#number of parentheses
left = 0
right = 0
count = 0
# flag
correct = True;
#step 1
#if p is an empty string, return p;
if len(p) == 0:
#print("empty string!")
return p
# step 2
#count the number of parentheses
for i in range(0, len(p)):
if p[i] == "(" :
left += 1
else:
right += 1
# this is the first case the number of left and right are the same
if left == right:
u = p[0: 2*left]
v = p[2*left:]
#print("u: " + u)
#print("v: " + v)
break
# check this is the correct parenthese ()
for i in range(0, len(u)):
#count the number of "("
if u[i] == "(":
count += 1
# find ")"
else:
# if the first element is not "("
if count == 0 and i == 0 :
#print("u: "+ u +" change to false")
correct = False
break
# reduce the number of counter
count -= 1
if count < 0:
correct = False
break;
else:
continue
"""
for j in range(1, count + 1):
print("i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count) + " lenth of u is " + "{}".format(len(u)))
#
#if u[i+j] == "(" :
if count < 0:
print( " change to false " + "i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count))
correct = False
break
else:
continue
"""
# reset the counter
count = 0
#print( "u: " + u + " v: " + v)
#if the string u is correct
if correct == True:
temp = u + solution(v)
#print(" u is " + u +" CORRECT! and return: " + temp)
return temp
# if the string u is not correct
else:
#print(" u is " + u +" INCORRECT!")
#print("check: " + check)
temp_str = "(" + solution(v) + ")"
# remove the first and the last character
temp_u = u[1:len(u)-1]
# change parentheses from ( to ) and ) to (
for i in range(len(temp_u)):
if temp_u[i] == "(":
rev_str += ")"
else:
rev_str += "("
#print("temp_str: " + temp_str + " rev_str: " + rev_str)
answer = temp_str + rev_str
#print("end! \n")
return answer
| true
|
40834ff71cc6200a7028bd1d8a7cacf42c9f886e
|
nicolaetiut/PLPNick
|
/checkpoint1/sort.py
| 2,480
| 4.25
| 4
|
"""Sort list of dictionaries from file based on the dictionary keys.
The rule for comparing dictionaries between them is:
- if the value of the dictionary with the lowest alphabetic key
is lower than the value of the other dictionary with the lowest
alphabetic key, then the first dictionary is smaller than the
second.
- if the two values specified in the previous rule are equal
reapply the algorithm ignoring the current key.
"""
import sys
def quicksort(l):
"""Quicksort implementation using list comprehensions
>>> quicksort([1, 2, 3])
[1, 2, 3]
>>> quicksort('bac')
['a', 'b', 'c']
>>> quicksort([{'bb': 1, 'aa': 2}, {'ba': 1, 'ab': 2}, {'aa': 1, 'ac': 2}])
[{'aa': 1, 'ac': 2}, {'aa': 2, 'bb': 1}, {'ab': 2, 'ba': 1}]
>>> quicksort([])
[]
"""
if l == []:
return []
else:
pivot = l[0]
sub_list = [list_element for list_element in l[1:]
if list_element < pivot]
lesser = quicksort(sub_list)
sub_list = [list_element for list_element in l[1:]
if list_element >= pivot]
greater = quicksort(sub_list)
return lesser + [pivot] + greater
def sortListFromFile(fileName, outputFileName):
"""Sort list of dictionaries from file. The input is a file containing
the list of dictionaries. Each dictionary key value is specified on
the same line in the form <key> <whitespace> <value>. Each list item
is split by an empty row. The output is a file containing a list of
integers specifying the dictionary list in sorted order. Each integer
identifies a dictionary in the order they were received in the input
file.
>>> sortListFromFile('nonexistentfile','output.txt')
Traceback (most recent call last):
...
IOError: [Errno 2] No such file or directory: 'nonexistentfile'
"""
l = []
with open(fileName, 'r') as f:
elem = {}
for line in f:
if line.strip():
line = line.split()
elem[line[0]] = line[1]
else:
l.append(elem)
elem = {}
l.append(elem)
f.closed
with open(outputFileName, 'w+') as f:
for list_elem in quicksort(l):
f.write(str(l.index(list_elem)) + '\n')
f.closed
if __name__ == "__main__":
if (len(sys.argv) > 1):
sortListFromFile(sys.argv[1], 'output.txt')
else:
print "Please provide an input file as argument."
| true
|
4fe12c2ab9d4892088c5270beb6e2ce5d96debb1
|
chapman-cs510-2016f/cw-03-datapanthers
|
/test_sequences.py
| 915
| 4.3125
| 4
|
#!/usr/bin/env python
import sequences
# this function imports the sequences.py and tests the fibonacci function to check if it returns the expected list.
def test_fibonacci():
fib_list=sequences.fibonacci(5)
test_list=[1,1,2,3,5]
assert fib_list == test_list
#
### INSTRUCTOR COMMENT:
# It is better to have each assert run in a separate test function. They are really separate tests that way.
# Also, it may be more clear in this case to skip defining so many intermediate variables:
# assert sequences.fibonacci(1) == [1]
#
fib_list=sequences.fibonacci(1)
test_list=[1]
assert fib_list == test_list
fib_list=sequences.fibonacci(10)
test_list=[1,1,2,3,5,8,13,21,34,55]
assert fib_list == test_list
# test to make sure negative input works
fib_list=sequences.fibonacci(-5)
test_list=[1,1,2,3,5]
assert fib_list == test_list
| true
|
bd7938eb01d3dc51b4c5a29b68d9f4518163cc92
|
jguarni/Python-Labs-Project
|
/Lab 5/prob2test.py
| 721
| 4.125
| 4
|
from cisc106 import *
def tuple_avg_rec(aList,index):
"""
This function will take a list of non-empty tuples with integers
as elements and return a list with the averages of the elements
in each tuple using recursion.
aList - List of Numbers
return - List with Floating Numbers
"""
newList = []
if len(aList) == 0:
return 0
if (len(aList) != index):
newList.append((sum(aList[index])/len(aList[index])))
newList.extend((sum(aList[index])/len(aList[index])))
print(aList[index])
tuple_avg_rec(aList, index+1)
return newList
assertEqual(tuple_avg_rec(([(4,5,6),(1,2,3),(7,8,9)]),0),[5.0, 2.0, 8.0])
| true
|
8656ff504d98876c89ead36e7dd4cc73c3d2249e
|
jlopezmx/community-resources
|
/careercup.com/exercises/04-Detect-Strings-Are-Anagrams.py
| 2,923
| 4.21875
| 4
|
# Jaziel Lopez <juan.jaziel@gmail.com>
# Software Developer
# http://jlopez.mx
words = {'left': "secured", 'right': "rescued"}
def anagram(left="", right=""):
"""
Compare left and right strings
Determine if strings are anagram
:param left:
:param right:
:return:
"""
# anagram: left and right strings have been reduced to empty strings
if not len(left) and not len(right):
print("Anagram!")
return True
# anagram not possible on asymetric strings
if not len(left) == len(right):
print("Impossible Anagram: asymetric strings `{}`({}) - `{}`({})".format(left, len(left), right, len(right)))
return False
# get first char from left string
# it should exist on right regardless char position
# if first char from left does not exist at all in right string
# anagram is not possible
char = left[0]
if not has_char(right, char):
print("Impossible Anagram: char `{}` in `{}` not exists in `{}`".format(char, left, right))
return False
left = reduce(left, char)
right = reduce(right, char)
if len(left) and len(right):
print("After eliminating char `{}`\n `{}` - `{}`\n".format(char, left, right))
else:
print("Both strings have been reduced\n")
# keep reducing left and right strings until empty strings
# anagram is possible when left and right strings are reduced to empty strings
anagram(left, right)
def has_char(haystack, char):
"""
Determine if a given char exists in a string regardless of the position
:param haystack:
:param char:
:return:
"""
char_in_string = False
for i in range(0, len(haystack)):
if haystack[i] == char:
char_in_string = True
break
return char_in_string
def reduce(haystack, char):
"""
Return a reduced string after eliminating `char` from original haystack
:param haystack:
:param char:
:return:
"""
output = ""
char_times_string = 0
for i in range(0, len(haystack)):
if haystack[i] == char:
char_times_string += 1
if haystack[i] == char and char_times_string > 1:
output += haystack[i]
if haystack[i] != char:
output += haystack[i]
return output
print("\nAre `{}` and `{}` anagrams?\n".format(words['left'], words['right']))
anagram(words['left'], words['right'])
# How to use:
# $ python3 04-Detect-Strings-Are-Anagrams.py
#
# Are `secured` and `rescued` anagrams?
#
# After eliminating char `s`
# `ecured` - `recued`
#
# After eliminating char `e`
# `cured` - `rcued`
#
# After eliminating char `c`
# `ured` - `rued`
#
# After eliminating char `u`
# `red` - `red`
#
# After eliminating char `r`
# `ed` - `ed`
#
# After eliminating char `e`
# `d` - `d`
#
# Both strings have been reduced
#
# Anagram!
#
# Process finished with exit code 0
| true
|
846cc6cd0915328b64f83d50883167e0d0910f6a
|
Teju-28/321810304018-Python-assignment-4
|
/321810304018-Python assignment 4.py
| 1,839
| 4.46875
| 4
|
#!/usr/bin/env python
# coding: utf-8
# ## 1.Write a python function to find max of three numbers.
# In[5]:
def max():
a=int(input("Enter num1:"))
b=int(input("Enter num2:"))
c=int(input("Enter num3:"))
if a==b==c:
print("All are equal.No maximum number")
elif (a>b and a>c):
print("Maximum number is:",a)
elif (b>c and b>a):
print("Maximum number is:",b)
else:
print("Maximum number is:",c)
max()
# ## 2.Write a python program to reverse a string.
# In[6]:
def reverse_string():
A=str(input("Enter the string:"))
return A[::-1]
reverse_string()
# ## 3.write a python function to check whether the number is prime or not.
# In[13]:
def prime():
num=int(input("Enter any number:"))
if num>1:
for i in range(2,num):
if (num%i==0):
print(num ,"is not a prime number")
break
else:
print(num ,"is a prime number")
else:
print(num ,"is not a prime number")
prime()
# ## 4.Use try,except,else and finally block to check whether the number is palindrome or not.
# In[25]:
def palindrome():
try:
num=int(input("Enter a number"))
except Exception as ValueError:
print("Invalid input enter a integer")
else:
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome")
else:
print("Not a palindrome")
finally:
print("program executed")
palindrome()
# ## 5.Write a python function to find sum of squares of first n natural numbers
# In[27]:
def sum_of_squares():
n=int(input("Enter the number"))
return (n*(n+1)*(2*n+1))/6
sum_of_squares()
| true
|
22b5a162408555fa5aea974ebafc6dbd56ea8f18
|
BercziSandor/pythonCourse_2020_09
|
/DataTransfer/json_1.py
| 1,153
| 4.21875
| 4
|
# https://www.w3schools.com/python/python_json.asp
# https://www.youtube.com/watch?v=9N6a-VLBa2I Python Tutorial: Working with JSON Data using the json Module (Corey Schaefer)
# https://lornajane.net/posts/2013/pretty-printing-json-with-pythons-json-tool
# http://jsoneditoronline.org/ JSON online editor
###################
# JSON: JavaScript Object Notation. Adatcseréhez, konfigurációs fájlokhoz használják,
# a legtöbb nyelvben van illesztő egység hozzá.
# loads: Sztringből beolvasás.
import json
str_1 = '{"name": "John", "age":30.5, "cities": ["New York", "Budapest"]}'
x = json.loads(str_1)
print(x) # {'name':'John', 'age':30.5, 'cities': ['New York', 'Budapest']}
# A sztringeknél idézőjelet kell használni, aposztrofot nem fogad el.
str_1 = '{'name': "John"}'
x = json.loads(str_1) # SyntaxError
# A dict kulcsoknak sztringeknek kell lenniük.
# tuple-t, set-et nem ismer.
###################
# dumps: sztringbe írás.
import json
lst_1 = ['John', 30.5, ['New York', 'Budapest']]
str_1 = json.dumps(lst_1)
print(str_1, type(str_1)) # ["John", 30.5, ["New York", "Budapest"]] <class 'str'>
###################
| false
|
f81b9e4fdf5b0d1dc28194beb061bd140d6996b9
|
BercziSandor/pythonCourse_2020_09
|
/Functions/scope_2.py
| 2,977
| 4.21875
| 4
|
# Változók hatásköre 2.
# Egymásba ágyazott, belső függvények
# global kontra nonlocal
# https://realpython.com/inner-functions-what-are-they-good-for/
# Függvényen belül is lehet definiálni függvényt. Ezt sok hasznos dologra fogjuk tudni használni.
# Első előny: információrejtés. Ha a belső függvény csak segédművelet, amit kívül nem
# használunk, akkor jobb, ha a függvényen kívül nem is látszik.
# A változót belülről kifelé haladva keresi a futtató rendszer.
def func():
def inner():
x = 'x inner' # x itt definiálódott
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x inner
######################################
def func():
def inner():
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x func local
######################################
def func():
def inner():
print(x)
inner()
x = 'x global'
func() # x global
######################################
def func():
def inner():
print(x) # itt használom
x = 'x inner' # de csak itt definiálom
inner()
x = 'x global'
func() # hiba, először használom, aztán definiálom
######################################
def func():
def inner():
global x
print(x)
x = 'x inner'
inner()
x = 'x global'
func() # x global
print('x func() után:', x) # x func() után: x inner
######################################
# A global-nak deklarált változókat a tartalmazó függvényben NEM keresi.
def func():
def inner():
global x
print(x)
x = 'x func local' # nem ezt találja meg
inner()
x = 'x global'
func() # x global
######################################
# A nonlocal-nak deklarált változókat a legkülső függvényen kívül (modul szinten) nem keresi.
# Ez rendben van:
def func():
def inner():
nonlocal x
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x func local
# De ez nem működik:
def func():
def inner():
nonlocal x
print(x) # itt használná
inner()
x = 'x global'
func() # hiba
# x hiába van modul-szinten definiálva, ott már nem keresi.
# Ez sem működik:
def func():
def inner():
nonlocal x
print(x) # itt használná
inner()
x = 'x func local' # de csak itt definiálódik
x = 'x global'
func() # hiba
# A felhasználáskor még nem volt definiálva x.
######################################
# A belső függvény a tartalmazó függvénynek a bemenő paramétereit is látja.
def func(outerParam):
def inner():
print('inner:',outerParam)
inner()
x = 'x global'
func('func parameter') # func parameter
# Ezt sok helyen fogjuk használni.
##################
| false
|
a9169a0606ef75c17087acce0c610bb5aa8e1660
|
vivek28111992/DailyCoding
|
/problem_#99.py
| 624
| 4.1875
| 4
|
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
def largestElem(arr):
s = set(arr)
m = 0
for i in range(len(arr)):
if arr[i]+1 in s:
j = arr[i]
m1 = 0
while j in s:
j += 1
m1 += 1
m = max(m, m1)
print(m)
return m
if __name__ == "__main__":
largestElem([100, 4, 200, 1, 3, 2])
| true
|
f96e8a52c38e140ecf3863d1ea138e15b78c7aa8
|
vivek28111992/DailyCoding
|
/problem_#28_15032019.py
| 1,687
| 4.125
| 4
|
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified.
More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left.
If you can only fit one word on a line, then you should pad the right-hand side with spaces.
Each word is guaranteed not to be longer than k.
For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following:
["the quick brown", # 1 extra space on the left
"fox jumps over", # 2 extra spaces distributed evenly
"the lazy dog"] # 4 extra spaces distributed evenly
https://leetcode.com/problems/text-justification/discuss/24891/Concise-python-solution-10-lines.
"""
def fulljustify(words, maxWidth):
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
res.append(''.join(cur))
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]
words = ["the quick brown",
"fox jumps over",
"the lazy dog"]
print(fulljustify(words, 16))
| true
|
c80b26a41d86ec4f2f702aab0922b86eec368e84
|
Brucehanyf/python_tutorial
|
/file_and_exception/file_reader.py
| 917
| 4.15625
| 4
|
# 读取圆周率
# 读取整个文件
# with open('pi_digits.txt') as file_object:
# contents = file_object.read()
# print(contents)
# file_path = 'pi_digits.txt';
# \f要转义
# 按行读取
file_path = "D:\PycharmProjects\practise\\file_and_exception\pi_digits.txt";
# with open(file_path) as file_object:
# for line in file_object:
# print(line)
# file_object.readlines()
# with open(file_path) as file_object:
# lines = file_object.readlines()
# for line in lines:
# print(line)
# 使用文件中的内容
with open(file_path) as file_object:
lines = file_object.readlines()
result = '';
for line in lines:
result += line.strip()
print(result)
print(result[:10]+'......')
print(len(result))
birthday = input('请输入您的生日')
if birthday in result:
print("your birthday appears in pai digits")
else:
print("your birthday does not appears in pai digits")
| true
|
62bd9b81b6ace8f9bab84fb293710c50ca0bcf29
|
thekevinsmith/project_euler_python
|
/4/largest_palindrome_product.py
| 1,778
| 4.125
| 4
|
# Problem 4 : Statement:
# 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 main():
largest = 0
for i in range(0, 1000, 1):
count = 0
Num = i
while Num > 0:
Num = Num//10
count += 1
if count == 3:
prodNum.append(i)
for p in range(len(prodNum)):
for n in range(len(prodNum)):
result = prodNum[p] * prodNum[n]
test = result
count = 0
while test > 0:
test = test // 10
count += 1
if count == 6:
sixNum.append(result)
if (result // 10 ** 5 % 10) == (result // 10 ** 0 % 10):
if (result // 10 ** 4 % 10) == (result // 10 ** 1 % 10):
if (result // 10 ** 3 % 10) == (result // 10 ** 2 % 10):
palindromeNum.append(result) # all that fit criteria
if result > largest:
largest = result
print("Largest palindromic: %d" % largest)
if __name__ == '__main__':
palindromeNum = []
prodNum = []
sixNum = []
main()
# Dynamic attempt: Technically its possible but very difficult as we need to
# consider set points if a for or while is used to do verification
# Think on this...
# largest = 0
# count = 6
# result = 994009
# for c in range(0, count // 2, 1):
# if (result // 10 ** (count - 1 - c) % 10) == (result // 10 ** (c) % 10):
# if result > largest:
# largest = result
# print(result)
| true
|
e604fb50261893929a57a9377d7e7b0e11a9b851
|
georgeyjm/Sorting-Tests
|
/sort.py
| 2,686
| 4.34375
| 4
|
def someSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i+1,length):
comparisons += 1
if array[i] > array[j]:
accesses += 1
array[i], array[j] = array[j], array[i]
return array, comparisons, accesses
def insertionSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i):
comparisons += 1
if array[j] > array[i]:
accesses += 1
array.insert(j,array[i])
del array[i+1]
return array, comparisons, accesses
def selectionSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length-1):
min = i
for j in range(i+1,length):
comparisons += 1
if array[j] < array[min]:
accesses += 1
min = j
array[i], array[min] = array[min], array[i]
return array, comparisons, accesses
def bubbleSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length-1):
for j in range(length-1,i,-1):
comparisons += 1
if array[j] < array[j-1]:
accesses += 1
array[j], array[j-1] = array[j-1], array[j]
return array, comparisons, accesses
def mergeSort(array,comparisons=0,accesses=0):
'''Or is it quick sort??'''
if len(array) == 1: return array, comparisons, accesses
result = []
middle = len(array) // 2
left, comparisons, accesses = mergeSort(array[:middle],comparisons,accesses)
right, comparisons, accesses = mergeSort(array[middle:],comparisons,accesses)
leftIndex, rightIndex = 0,0
while leftIndex < len(left) and rightIndex < len(right):
comparisons += 1
if left[leftIndex] > right[rightIndex]:
result.append(right[rightIndex])
rightIndex += 1
else:
result.append(left[leftIndex])
leftIndex += 1
result += left[leftIndex:] + right[rightIndex:]
return result, comparisons, accesses
def bogoSort(array):
'''Time Complexity: O(1) (best), O(∞) (worst)'''
from random import shuffle
comparisons, accesses = 0,0
while True:
for i in range(1, len(array)):
comparisons += 1
if array[i] < array[i-1]: break
else:
break
shuffle(array)
accesses += 1
return array, comparisons, accesses
| true
|
a82eb08a4de5bab1c90099a414eda670219aeb95
|
eliaskousk/example-code-2e
|
/21-async/mojifinder/charindex.py
| 2,445
| 4.15625
| 4
|
#!/usr/bin/env python
"""
Class ``InvertedIndex`` builds an inverted index mapping each word to
the set of Unicode characters which contain that word in their names.
Optional arguments to the constructor are ``first`` and ``last+1``
character codes to index, to make testing easier. In the examples
below, only the ASCII range was indexed.
The `entries` attribute is a `defaultdict` with uppercased single
words as keys::
>>> idx = InvertedIndex(32, 128)
>>> idx.entries['DOLLAR']
{'$'}
>>> sorted(idx.entries['SIGN'])
['#', '$', '%', '+', '<', '=', '>']
>>> idx.entries['A'] & idx.entries['SMALL']
{'a'}
>>> idx.entries['BRILLIG']
set()
The `.search()` method takes a string, uppercases it, splits it into
words, and returns the intersection of the entries for each word::
>>> idx.search('capital a')
{'A'}
"""
import sys
import unicodedata
from collections import defaultdict
from collections.abc import Iterator
STOP_CODE: int = sys.maxunicode + 1
Char = str
Index = defaultdict[str, set[Char]]
def tokenize(text: str) -> Iterator[str]:
"""return iterator of uppercased words"""
for word in text.upper().replace('-', ' ').split():
yield word
class InvertedIndex:
entries: Index
def __init__(self, start: int = 32, stop: int = STOP_CODE):
entries: Index = defaultdict(set)
for char in (chr(i) for i in range(start, stop)):
name = unicodedata.name(char, '')
if name:
for word in tokenize(name):
entries[word].add(char)
self.entries = entries
def search(self, query: str) -> set[Char]:
if words := list(tokenize(query)):
found = self.entries[words[0]]
return found.intersection(*(self.entries[w] for w in words[1:]))
else:
return set()
def format_results(chars: set[Char]) -> Iterator[str]:
for char in sorted(chars):
name = unicodedata.name(char)
code = ord(char)
yield f'U+{code:04X}\t{char}\t{name}'
def main(words: list[str]) -> None:
if not words:
print('Please give one or more words to search.')
sys.exit(2) # command line usage error
index = InvertedIndex()
chars = index.search(' '.join(words))
for line in format_results(chars):
print(line)
print('─' * 66, f'{len(chars)} found')
if __name__ == '__main__':
main(sys.argv[1:])
| true
|
639d50d4d0579ee239adf72a08d7b4d78d9b91b6
|
blaise594/PythonPuzzles
|
/weightConverter.py
| 424
| 4.21875
| 4
|
#The purpose of this program is to convert weight in pounds to weight in kilos
#Get user input
#Convert pounds to kilograms
#Display result in kilograms rounded to one decimal place
#Get user weight in pounds
weightInPounds=float(input('Enter your weight in pounds. '))
#One pound equals 2.2046226218 kilograms
weightInKilos=weightInPounds/2.2046226218
print('Your weight in kilograms is: '+format(weightInKilos, '.1f'))
| true
|
c3a23f4391d29250c7ff9ee4fa0ad9cd133abbe7
|
priancho/nlp100
|
/05.py
| 900
| 4.3125
| 4
|
#usage example:
#python3 05.py 2 "This is a pen."
import re
import sys
# extract character n-grams and calculate n-gram frequency
def char_n_gram(n, str):
ngramList = {}
n=int(n)
str = str.lower()
wordList=re.findall("[a-z]+",str)
for word in wordList:
if len(word) >= n:
for i in range(len(word)-n+1):
if word[i:i+n] in ngramList:
ngramList[word[i:i+n]]+=1
else:
ngramList[word[i:i+n]]=1
return ngramList
# extract character n-grams and calculate n-gram frequency
def word_n_gram(n, str):
next
if __name__ == '__main__':
if len(sys.argv) != 3:
print "Usage: %s <n> <sentence>" % (sys.argv[0])
print " <n>: n for n-gram."
print " <sentence>: input sentence to generate n-grams"
print ""
print " e.g., %s 2 \"This is a pen.\"" % (sys.argv[0])
exit(1)
print (char_n_gram(sys.argv[1],sys.argv[2]))
print (word_n_gram(sys.argv[1],sys.argv[2]))
| false
|
8a56d576c3c6be23f5fdbb3ad70965befbac04f7
|
juancebarberis/algo1
|
/practica/7-10.py
| 898
| 4.3125
| 4
|
#Ejercicio 7.10. Matrices.
#a) Escribir una función que reciba dos matrices y devuelva la suma.
#b) Escribir una función que reciba dos matrices y devuelva el producto.
#c) ⋆ Escribir una función que opere sobre una matriz y mediante eliminación gaussiana de-
#vuelva una matriz triangular superior.
#d) ⋆ Escribir una función que indique si un grupo de vectores, recibidos mediante una
#lista, son linealmente independientes o no.
A = [(2,1), (4,1)]
B = [(4,0), (2,8)]
def sumarMatrices(A, B):
""""""
resultado = []
for i in range(len(A)):
nuevaFila = []
for e in range(len(A[i])):
nuevaFila.append(A[i][e] + B[i][e])
resultado.append(nuevaFila)
return resultado
print('A')
for fila in A:
print(fila)
print('B')
for fila in B:
print(fila)
print('Resultado!:')
res = sumarMatrices(A, B)
print(f"{res[0]}")
print(f"{res[1]}")
| false
|
04dcc88ad0fb461fa9aafe3e290ab9addb03c08e
|
juancebarberis/algo1
|
/practica/5-4.py
| 1,135
| 4.125
| 4
|
#Ejercicio 5.4. Utilizando la función randrange del módulo random , escribir un programa que
#obtenga un número aleatorio secreto, y luego permita al usuario ingresar números y le indique
#si son menores o mayores que el número a adivinar, hasta que el usuario ingrese el número
#correcto.
from random import randrange
def adivinarNumeroAleatorio():
""""""
numeroSecreto = randrange(start= 0, stop=100)
print('Adivine el número entre 0 y 100.')
while True:
entrada = input('Ingrese el candidato:')
if not entrada.isnumeric():
print('Por favor, ingrese un número válido.')
continue
else:
entrada = int(entrada)
if entrada == numeroSecreto:
break
if entrada > numeroSecreto:
print(f'El número {entrada} es mayor que el número a adivinar.')
continue
if entrada < numeroSecreto:
print(f'El número {entrada} es menor que el número a adivinar.')
continue
print('¡Genial, adivinaste! El número era ' + str(numeroSecreto))
adivinarNumeroAleatorio()
| false
|
e08f787de4a2297aa6884dbb013e92f612423cc5
|
juancebarberis/algo1
|
/practica/7-7.py
| 877
| 4.21875
| 4
|
#Ejercicio 7.7. Escribir una función que reciba una lista de tuplas (Apellido, Nombre, Ini-
#cial_segundo_nombre) y devuelva una lista de cadenas donde cada una contenga primero el
#nombre, luego la inicial con un punto, y luego el apellido.
data = [
('Viviana', 'Tupac', 'R'),
('Francisco', 'Tupac', 'M'),
('Raquel', 'Barquez', 'H'),
('Mocca', 'Tupac Barquez', 'D'),
('Lara', 'Tupac Barquez', 'P')
]
def tuplaACadena(lista):
"""
Esta función recibe una lista de tuplas con (Nombre, Apellido, Inicial segundo nombre)
y devuelve una lista con cadenas, donde cada una representa "Nombre Inicial. Apellido).
"""
resultante = []
for persona in lista:
cadenaIndividual = ""
cadenaIndividual += f"{persona[1]} {persona[2]}. {persona[0]}"
resultante.append(cadenaIndividual)
return resultante
print(tuplaACadena(data))
| false
|
53439bc9fed95069408cec769fddd8fc2fc9376d
|
BryCant/Intro-to-Programming-MSMS-
|
/Chapter13.py
| 2,435
| 4.34375
| 4
|
# Exception Handling
# encapsulation take all data associated with an object and put it in one class
# data hiding
# inheritance
# polymorphism ; function that syntactically looks same is different based on how you use it
"""
# basic syntax
try:
# Your normal code goes here.
# Your code should include function calls which might raise exceptions.
except:
# If any exception was raised, then execute this code block
# catching specific exceptions
try:
# Your normal code goes here.
# Your code should include function calls which might raise exceptions.
except ExceptionName:
# If ExceptionName was raise, then execute this block
# catching multiple specific exceptions
try:
# Your normal code goes here.
# Your code should include function calls which might raise exceptions.
except Exception_one:
# If Exception_one was raised, then execute this block
except Exception_two:
# If Exception_two was raised, then execute this block
else:
# If there was no exception, then execute this block
# clean-up after exceptions (if you have code that you want to be executed even if exceptions occur)
try:
# Your normal code goes here.
# Your code might include functions which might raise exceptions.
# If an exception is raised, some of these statements might not be executed
finally:
# This block of code WILL ALWAYS execute, even if there are exceptions raised
"""
# example with some file I/O (great place to include exception handling
try:
# the outer try:except: block takes care of a missing file or the fact that the file can't be opened for writing
f = open("my_file.txt", "w")
try:
# the inner: except: block protects against output errors, such as trying to write to a device that is full
f.write("Writing some data to the file")
finally:
# the finally code guarantees that the file is closed properly, even if there are errors during writing
f.close()
except IOError:
print("Error: my_file.txt does not exist or it can't be opened for output.")
# as long as a function that is capable of handling an exception exists above where the exception is raised in the stack
# the exception can be handled
def main()
A()
def A():
B()
def B():
C()
def C():
# processes
try:
if condition:
raise MyException
except MyException:
# what to do if this exception occurs
| true
|
2679e524fb70ea8bc6a8801a3a9149ee258d9090
|
daviscuen/Astro-119-hw-1
|
/check_in_solution.py
| 818
| 4.125
| 4
|
#this imports numpy
import numpy as np
#this step creates a function called main
def main():
i = 0 #sets a variable i equal to 0
x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?)
for i in range(120): #starting at i, add one everytime the program gets to the end of the for loop
if (i%2) == 0: #if the value of i divided by 2 is exactly 0, then do the below part
x += 3.0 #resets the variable x to 3 more than it was before
else: # if the above condition is not true, do what is below
x -= 5.0 #resets the variable x to 5 less than it was before
s = "%3.2e" % x #puts it in sci notation (need help with why)
print(s) #prints the above string s
if __name__ == "__main__":
main()
| true
|
0d4aad51ef559c9bf11cd905cf14de63a6011457
|
mvinovivek/BA_Python
|
/Class_3/8_functions_with_return.py
| 982
| 4.375
| 4
|
#Function can return a value
#Defining the function
def cbrt(X):
"""
This is called as docstring short form of Document String
This is useful to give information about the function.
For example,
This function computes the cube root of the given number
"""
cuberoot=X**(1/3)
return cuberoot #This is returning value to the place where function is called
print(cbrt(27))
#calling using a variable
number=64
print("Cube root of {} is {}".format(number,cbrt(number)))
#Mentioning Type of the arguments
#Defining the function
def cbrt(X: float) -> float:
cuberoot=X**(1/3)
return cuberoot #This is returning value to the place where function is called
print(cbrt(50))
#Mutiple returns
def calculation(X):
sqrt=X**0.5
cbrt=X**(1/3)
return sqrt,cbrt
# print(calculation(9))
# values=calculation(9)
# print(values)
# values=calculation(9)
# print(values[0])
# sqrt,cbrt=calculation(9)
# print(sqrt,cbrt)
| true
|
53cee6f939c97b0d84be910eee64b6e7f515b12f
|
mvinovivek/BA_Python
|
/Class_3/7_functions_with_default.py
| 680
| 4.1875
| 4
|
# We can set some default values for the function arguments
#Passing Multiple Arguments
def greet(name, message="How are you!"):
print("Hi {}".format(name))
print(message)
greet("Bellatrix", "You are Awesome!")
greet("Bellatrix")
#NOTE Default arguments must come at the last. All arguments before default are called positional arguments
def greet(message="How are you!", name): #This will Throw error
print("Hi {}".format(name))
print(message)
#You can mix the positional values when using their name
#Passing Multiple Arguments
def greet(name, message):
print("Hi {}".format(name))
print(message)
greet( message="You are Awesome!",name="Bellatrix")
| true
|
3cb1bc2560b5771e4c9ec69d429fcfd9c0eadd2c
|
mvinovivek/BA_Python
|
/Class_2/7_for_loop_2.py
| 1,009
| 4.625
| 5
|
#In case if we want to loop over several lists in one go, or need to access corresponding
#values of any list pairs, we can make use of the range method
#
# range is a method when called will create an array of integers upto the given value
# for example range(3) will return an array with elements [0,1,2]
#now we can see that this is an array which can act as control variables
#Combining this with the len function, we can iterate over any number of lists
#Simple range example
numbers=[1,2,3,4,6,6,7,8,9,10]
squares=[]
cubes=[]
for number in numbers:
squares.append(number**2)
cubes.append(number**3)
for i in range(len(numbers)):
print("The Square of {} is {}".format(numbers[i], squares[i]))
for i in range(len(numbers)):
print("The Cube of {} is {}".format(numbers[i], cubes[i]))
#Finding sum of numbers upto a given number
number = 5
sum_value=0
for i in range(number + 1):
sum_value = sum_value + i
print("The sum of numbers upto {} is {}".format(number,sum_value))
| true
|
c9a6c2f6b8f0655b3e417057f7e52015794d26d6
|
316126510004/ostlab04
|
/scramble.py
| 1,456
| 4.40625
| 4
|
def scramble(word, stop):
'''
scramble(word, stop)
word -> the text to be scrambled
stop -> The last index it can extract word from
returns a scrambled version of the word.
This function takes a word as input and returns a scrambled version of it.
However, the letters in the beginning and ending do not change.
'''
import random
pre, suf = word[0], word[stop:]
word = list(word)
mid_word = word[1:stop]
random.shuffle(mid_word)
word = pre + ''.join(mid_word) + suf
return word
def unpack_and_scramble(words):
'''
unpack_and_scramble(words)
words -> a list of words to be scrambled.
returns a list of scrambled strings
This function unpacks all the words and checks if len(word) < 3
If true then it scrambles the word
Now, it will be appended to a new list
'''
words = words.split()
scrambled_words = []
for word in words:
if len(word) <3:
scrambled_words.append(word)
continue
if word.endswith((',', '?', '.', ';', '!')):
stop = -2
else:
stop = -3
scrambled_word = scramble(word, stop)
scrambled_words.append(scrambled_word)
return ' '.join(scrambled_words)
file_name = input('Enter file name:')
try:
file = open(file_name, 'r')
new_file = file.name + 'Scrambled'
words = file.read()
file.close()
scrambed_words = unpack_and_scramble(words)
file_name = open(new_file, 'w')
file_name.write(scrambed_words)
file_name.close()
except OSError as ose:
print('Please enter file name properly')
| true
|
d24514f8bed4e72aaaee68ae96076ec3921f5898
|
ChanghaoWang/py4e
|
/Chapter9_Dictionaries/TwoIterationVariable.py
| 429
| 4.375
| 4
|
# Two iteration varibales
# We can have multiple itertion variables in a for loop
name = {'first name':'Changhao','middle name':None,'last name':'Wang'}
keys = list(name.keys())
values = list(name.values())
items = list(name.items())
print("Keys of the dict:",keys)
print("Values of the dict:",values)
print("Items of the dict:",items)
for key,value in items: # Two Itertion Values
print('Keys and Values of the dict:',key)
| true
|
6d325039a3caa4c331ecc6fa6bb058ff431218f8
|
ChanghaoWang/py4e
|
/Chapter8_Lists/note.py
| 921
| 4.21875
| 4
|
# Chapter 8 Lists Page 97
a = ['Changhao','Wang','scores',[100,200],'points','.']
# method: append & extend
a.append('Yeah!') #Note, the method returns None. it is different with str
a.extend(['He','is','so','clever','!'])
# method : sort (arranges the elements of the list from low to high)
b= ['He','is','clever','!']
b.sort()
print(b)
# method : delete (pop) retrus the element we removed.
c = ['a',1,'c']
x = c.pop(0)
print('After remove:',c)
print('What we removed is:',x)
# method : del
c = ['a',1,'c']
del c[0]
print(c)
# method : remove attention: it can only remove one element
c = ['a',1,'c',1]
c.remove(1)
print(c)
# convert string to List
d = 'Changhao'
e = list(d)
print(e)
f = 'Changhao Wang'
g = f.split()
print(g)
# string method : split()
s = 'spam-spam-spam'
s_new = s.split('-')
print(s_new)
# convert lists to string
t = ['pining','for','the','fjords']
delimiter = ' '
t_str = delimiter.join(t)
print(t_str)
| true
|
d593ffafc59015480c713c213b59f6304914d660
|
Ayush10/python-programs
|
/vowel_or_consonant.py
| 1,451
| 4.40625
| 4
|
# Program to check if the given alphabet is vowel or consonant
# Taking user input
alphabet = input("Enter any alphabet: ")
# Function to check if the given alphabet is vowel or consonant
def check_alphabets(letter):
lower_case_letter = letter.lower()
if lower_case_letter == 'a' or lower_case_letter == 'e' or lower_case_letter == 'i' or lower_case_letter == 'o' \
or lower_case_letter == 'u':
# or lower_case_letter == 'A' or lower_case_letter == 'E' or lower_case_letter == \
# 'I' or lower_case_letter == 'U':
return "vowel"
else:
return "consonant"
# Checking if the first character is an alphabet or not:
if 65 <= ord(alphabet[0]) <= 90 or 97 <= ord(alphabet[0]) <= 122:
# Checking if there are more than 1 characters in the given string.
if len(alphabet) > 1:
print("Please enter only one character!")
print("The first character {0} of the given string {1} is {2}.".format(alphabet[0], alphabet,
check_alphabets(alphabet[0])))
# If only one character in the given string.
else:
print("The given character {0} is {1}.".format(alphabet, check_alphabets(alphabet)))
# If the condition is not satisfied then returning the error to the user without calculation.
else:
print("Please enter a valid alphabet. The character {0} is not an alphabet.".format(alphabet[0]))
| true
|
2676477d211e0702d1c44802f9295e8457df21a8
|
Ayush10/python-programs
|
/greatest_of_three_numbers.py
| 492
| 4.3125
| 4
|
# Program to find greatest among three numbers
# Taking user input
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
# Comparison Algorithm and displaying result
if a > b > c:
print("%d is the greatest number among %d, %d and %d." % (a, a, b, c))
elif b > a > c:
print("%d is the greatest number among %d, %d and %d." % (b, a, b, c))
else:
print("%d is the greatest number among %d, %d and %d." % (c, a, b, c))
| true
|
e50f8e37210054df2e5c54eb55e7dee381a91aff
|
super468/leetcode
|
/python/src/BestMeetingPoint.py
| 1,219
| 4.15625
| 4
|
class Solution:
def minTotalDistance(self, grid):
"""
the point is that median can minimize the total distance of different points.
the math explanation is https://leetcode.com/problems/best-meeting-point/discuss/74217/The-theory-behind-(why-the-median-works)
the more human language version is that there are two groups of people, it will decrease the distance if you put the point
closer to the group with more people. At end of the day, the two sides will be equal.
:type grid: List[List[int]]
:rtype: int
"""
list_y = []
list_x = []
for row in range(0, len(grid)):
for col in range(0, len(grid[row])):
if grid[row][col] == 1:
list_y.append(row)
list_x.append(col)
list_y.sort()
list_x.sort()
median_y = list_y[int(len(list_y) / 2)]
median_x = list_x[int(len(list_x) / 2)]
sum_y = 0
for y in list_y:
sum_y += median_y - y if median_y > y else y - median_y
sum_x = 0
for x in list_x:
sum_x += median_x - x if median_x > x else x - median_x
return sum_x + sum_y
| true
|
63825db8fd9cd5e9e6aaa551ef7bfec29713a925
|
Rohit439/pythonLab-file
|
/lab 9 .py
| 1,686
| 4.28125
| 4
|
#!/usr/bin/env python
# coding: utf-8
# ### q1
# In[2]:
class Triangle:
def _init_(self):
self.a=0
self.b=0
self.c=0
def create_triangle(self):
self.a=int(input("enter the first side"))
self.b=int(input("enter the second side"))
self.c=int(input("enter the third side"))
def print_sides(self):
print("first side:",self.a,"second side:",self.b,"third side",self.c)
x=Triangle()
x.create_triangle()
x.print_sides()
# ### q2
# In[4]:
class String():
def _init_(self):
self.str1=""
def inputstr(self):
self.str1=input("enter the string")
def printstr(self):
print(self.str1)
x=String()
x.inputstr()
x.printstr()
# ### q3
# In[4]:
class Rectangle:
length=0.0
width=0.0
per=0.0
def rect_values(self,l,w):
self.length=l
self.width=w
def perimeter(self):
self.per=2*self.length+self.width
return(self.per)
r1=Rectangle()
r1.rect_values(10,20)
k=r1.perimeter()
print("the perimeter of rectangle is",k)
# ### q4
# In[6]:
class Circle:
radius=0.0
area=0.0
peri=0.0
def _init_(self,radius):
self.radius=radius
def area(self):
self.area=3.14*self.radius*self.radius
return(self.area)
def perimeter(self):
self.peri=2*3.14*self.radius
return(self.peri)
c1=Circle()
c1._init_(4)
a=c1.area()
p=c1.perimeter()
print("the area and perimeter of circle are:",a,p)
# ### q5
# In[7]:
class Class2:
pass
class Class3:
def m(self):
print("in class3")
class Class4(Class2,Class3):
pass
obj=Class4()
obj.m()
# In[ ]:
| true
|
69b848ed2eeae8f3090a9c35b2cdf12bc4dd29e5
|
Rita626/HK
|
/Leetcode/237_刪除鏈表中的節點_05170229.py
| 1,671
| 4.21875
| 4
|
#題目:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = None
#直觀的認為可以直接刪除
#結果:答案錯誤,只是將要刪除的值變為None而已
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = None
#改為以下一節點取代要刪除的值,並將(想像中)重複的下一個節點刪除
#結果:答案錯誤,題目要求的值卻時刪除了,但也將後面的值刪掉了
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
#同樣以下一節點取代要刪除的值,並將後面節點整個前移
#結果:通過,用時28ms,內存消耗13MB
| false
|
2991c345efe646cedda8aeaeeebe06b2a4cc6842
|
drmason13/euler-dream-team
|
/euler1.py
| 778
| 4.34375
| 4
|
def main():
"""
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.
"""
test()
print(do_the_thing(1000))
def do_the_thing(target):
numbers = range(1, target)
answer = []
for i in numbers:
#print(i)
if is_multiple_of(i, 3) or is_multiple_of(i, 5):
answer.append(i)
#ends here => i won't be a thing after this
return(sum(answer))
def test():
result = do_the_thing(10)
if result == 23:
print("success")
print(result)
else:
print("check again pinhead")
print(result)
def is_multiple_of(num, multiple):
#print("is_multiple_of")
return num % multiple == 0
main()
| true
|
6f1aa43d0614cd211b0c92a48b182cf662e230fa
|
nmaswood/Random-Walk-Through-Computer-Science
|
/lessons/day4/exercises.py
| 720
| 4.25
| 4
|
def fib_recursion(n):
"""
return the nth element in the fibonacci sequence using recursion
"""
return 0
def fib_not_recursion(n):
"""
return the nth element in the fibonacci sequence using not recursion
"""
return 0
def sequence_1(n):
"""
return the nth element in the sequence
S_n = S_{n-1} * 2 + 1
"""
return 0
def factorial_recursive(n):
"""
Calculate the factorial of n using recursion
"""
return 0
class LinkedList():
def __init__(self, val):
self.val = val
self.next = None
"""
Use the LinkedList Data Type
Create a linked list with the elements
"fee" -> "fi" -> "foo" -> "fum" and print it backwards
"""
| true
|
42d3e9a30261a005a547a0957c4e53d2a19d5911
|
jfernand196/Ejercicios-Python
|
/examen_makeitreal.py
| 610
| 4.21875
| 4
|
# Temperaturas
# Escribe una función llamada `temperaturas` que reciba un arreglo (que representan temperaturas) y
# retorne `true` si todas las temperaturas están en el rango normal (entre 18 y 30 grados) o `false` de
# lo contrario.
# temperaturas([30, 19, 21, 18]) -> true
# temperaturas([28, 45, 17, 21, 17, 70]) -> false
def temperaturas(x):
r= []
for i in x:
o=0
if i>= 18 and i<=30:
r.append(i)
return r
print(temperaturas([30, 19, 21, 18])) #-> true
print(temperaturas([28, 45, 17, 21, 17, 70])) #-> false
| false
|
42bb3d5df47e7eb91425f7a92e19872ed16e3483
|
piranna/asi-iesenlaces
|
/0708/repeticiones/ej109.py
| 861
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
$Id$
Calcula el factorial de un número entero positivo que pedimos por teclado
Si tienes dudas de lo que es el factorial, consulta http://es.wikipedia.org/wiki/Factorial
"""
# Presentación
print "*" * 50
print "Programa que calcula el factorial de un número"
print "*" * 50
# Petición del número positivo
numero = int(raw_input("Introduzca un número positivo "))
while numero < 0: # Aseguramos que el número es positivo
numero = int(raw_input("Introduzca un número positivo "))
# Por defecto: factorial de 0 es 1
factorial = 1
for n in range(1, numero + 1): # +1 porque si no range llegaría sólo hasta numero-1
# n va tomando los valores desde 1 hasta numero
factorial = factorial * n
print "El factorial del número", numero, "es", factorial
# Sugerencia: programa el bucle con un while y compara
| false
|
b976f86e302748c97bcd5033499a0f2a928bcbdc
|
taddes/python-blockchain
|
/data_structures_assignment.py
| 1,053
| 4.40625
| 4
|
# 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want.
person = [{'name': 'Taddes', 'age': 30, 'hobbies': ['bass', 'coding', 'reading', 'exercise']},
{'name': 'Sarah', 'age': 30, 'hobbies': ['exercise', 'writing', 'crafting']},
{'name': 'Pepper', 'age': 5, 'hobbies': ['hunting', 'eating plants', 'napping']}]
# 2) Use a list comprehension to convert this list of persons into a list of names (of the persons).
name_list = [name['name'] for name in person ]
print(name_list)
# 3) Use a list comprehension to check whether all persons are older than 20.
age_check = all([age['age'] > 20 for age in person ])
print(age_check)
# 4) Copy the person list such that you can safely edit the name of the first person (without changing the original list).
copied_person = person[:]
print(copied_person)
print(person)
# 5) Unpack the persons of the original list into different variables and output these variables.
name, age, hobbies = person
print(name)
print(age)
| true
|
e1ddd1d2897462bc6d6831993acdd9b9257554b2
|
changfenxia/gb-python
|
/lesson_1/ex_2.py
| 503
| 4.3125
| 4
|
'''
2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
'''
time_seconds = int(input("Enter time in seconds: "))
hours = time_seconds // 3600
minutes = (time_seconds % 3600) // 60
seconds = time_seconds - (hours * 3600) - (minutes * 60)
print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
| false
|
7cdaebe77cfb044dfc16e01576311244caae283f
|
roshna1924/Python
|
/ICP1/Source Code/operations.py
| 590
| 4.125
| 4
|
num1 = int(input("Enter first number: "))
num2 = int(input("Enter Second number: "))
operation = int(input("Enter 1 for addition\n" "Enter 2 for Subtraction\n" "Enter 3 for multiplication\n" "Enter 4 for division\n"))
def arithmeticOperations(op):
switcher = {
1: "Result of addition : " + str(num1 + num2),
2: "Result of Subtraction : " + str(abs(num1 - num2)),
3: "Result of multiplication : " + str(num1 * num2),
4: "Result of division : " + str(num1 / num2)
}
print(switcher.get(op, "invalid operation\n"))
arithmeticOperations(operation)
| true
|
26cf949e46bd2bb958eca1241fe25beef76bbb1d
|
kamadforge/ranking
|
/algorithms/binary_tree.py
| 1,273
| 4.25
| 4
|
class Tree:
def __init__(self):
self.root=None
def insert(self, data):
if not self.root:
self.root=Node(data)
else:
self.root.insert(data)
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Use the insert method to add nodes
# root = Node(12)
# root.insert(6)
# root.insert(14)
# root.insert(3)
# root.PrintTree()
#second way
tree=Tree()
tree.insert(3)
tree.insert(10)
tree.insert(12)
tree.insert(5)
tree.insert(6)
tree.insert(11)
tree.root.PrintTree()
| false
|
2185999943f7891d33a7519159d3d08feba8e14d
|
tim-jackson/euler-python
|
/Problem1/multiples.py
| 356
| 4.125
| 4
|
"""multiples.py: Exercise 1 of project Euler.
Calculates the sum of the multiples of 3 or 5, below 1000. """
if __name__ == "__main__":
TOTAL = 0
for num in xrange(0, 1000):
if num % 5 == 0 or num % 3 == 0:
TOTAL += num
print "The sum of the multiples between 3 and 5, " \
"below 1000 is: " + str(TOTAL)
| true
|
ac4244195cf8ecf1330621bd31773f3b211f4d5c
|
HaNuNa42/pythonDersleri
|
/python dersleri/tipDonusumleri.py
| 1,286
| 4.1875
| 4
|
#string to int
x = input("1.sayı: ")
y = input("2 sayı: ")
print(type(x))
print(type(y))
toplam = x + y
print(toplam) # ekrana yazdirirken string ifade olarak algiladigindan dolayı sayilari toplamadi yanyana yazdi bu yuzden sonuc yanlis oldu. bu durumu duzeltmek için string'ten int' veri tipine donusturmemiz gerek
print("doğrusu şöyle olmalı")
toplam = int(x) + int(y)
print(toplam)
print("---------------")
a = 10
b = 4.1
isim = "hatice"
ogrenciMi = True
print(type(a))
print(type(b))
print(type(isim))
print(type(ogrenciMi))
print("---------------")
#int to float
a = float(a) # int olan a degiskeni floata donusturduk
print(a)
print(type(a)) # donusup donusmedigini kontrol edelim
print("---------------")
#float to int
a = int(b) # float olan a degiskeni inte donusturduk
print(b)
print(type(b))
print("---------------")
# bool to string
ogrenciMi = str(ogrenciMi) # bool olan a degiskeni stringe donusturduk
print(ogrenciMi)
print(type(ogrenciMi))
print("---------------")
#bool to int
ogrenciMi = int(ogrenciMi) # bool olan a degiskeni inte donusturduk
print(ogrenciMi)
print(type(ogrenciMi))
| false
|
68372dfabb4a768815176fd77acbab0dca4cfd68
|
AngelLiang/python3-stduy-notes-book-one
|
/ch02/memory.py
| 635
| 4.28125
| 4
|
"""内存
对于常用的小数字,解释器会在初始化时进行预缓存。
以Python36为例,其预缓存范围是[-5,256]。
>>> a = -5
>>> b = -5
>>> a is b
True
>>> a = 256
>>> b = 256
>>> a is b
True
# 如果超出缓存范围,那么每次都要新建对象。
>>> a = -6
>>> b = -6
>>> a is b
False
>>> a = 257
>>> b = 257
>>> a is b
False
>>> import psutil
>>> def res():
... m = psutil.Process().memory_info()
... print(m.rss >> 20, 'MB')
...
>>> res()
17 MB
>>> x = list(range(10000000))
>>> res()
403 MB
>>> del x
>>> res()
17 MB
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| false
|
78b2dadaa067264258ed93da5a4e13ebf692ec6a
|
klq/euler_project
|
/euler41.py
| 2,391
| 4.25
| 4
|
import itertools
import math
def is_prime(n):
"""returns True if n is a prime number"""
if n < 2:
return False
if n in [2,3]:
return True
if n % 2 == 0:
return False
for factor in range(3, int(math.sqrt(n))+1, 2):
if n % factor == 0:
return False
return True
def get_primes(maxi):
"""return a list of Booleans is_prime in which is_prime[i] is True if i is a prime number for every i <= maxi"""
is_prime = [True] * (maxi + 1)
is_prime[0] = False
is_prime[1] = False
# is_prime[2] = True and all other even numbers are not prime
for i in range(2,maxi+1):
if is_prime[i]: # if current is prime, set multiples to current not prime
for j in range(2*i, maxi+1, i):
is_prime[j] = False
return is_prime
def get_all_permutations(l):
# returns n-length iterable object, n = len(l)
# in lexical order (which means if input is [5,4,3,2,1], output will be in strictly decreasing order)
return itertools.permutations(l)
def list2num(l):
s = ''.join(map(str, l))
return int(s)
def get_sorted_pandigital(m):
"""returns a (reversed) sorted list of all pandigital numbers given m digits"""
perms = get_all_permutations(range(m,0,-1))
for perm in perms:
# per is a m-length tuple
perm = list2num(perm)
yield perm
def euler41():
"""https://projecteuler.net/problem=41
Pandigital Prime
What is the largest n-digit pandigital prime that exists?
"""
# Method 1: -----Turns out 1.1 itself is too costly
# 1. Get all the primes
# 2. Get all the pandigital numbers (sorted)
# 3. Test if prime from largest to smallest, stop when first one found
# is_prime = get_primes(987654321) taking too long
# Method 2: ----
# 1. Get all the pandigital numbers (sorted)
# 2. Test if prime from largest to smallest, stop when first one found
# !!! There will not be 8-digit or 9-digit pandigital prime numbers
# !!! Because they are all divisible by 3!
# !!! Only check 7-digit and 4-digit pandigital numbers
for m in [7,4]:
for pd in get_sorted_pandigital(m):
if is_prime(pd):
print pd
return
# Answer is:
# 7652413
def main():
euler41()
if __name__ == '__main__':
main()
| true
|
1ba8cda2d2376bd93a169031caa473825b3912da
|
QaisZainon/Learning-Coding
|
/Practice Python/Exercise_02.py
| 795
| 4.375
| 4
|
'''
Ask the user for a number
Check for even or odd
Print out a message for the user
Extras:
1. If number is a multiple of 4, print a different message.
2. Ask the users for two numbers, check if it is divisible, then
print message according to the answer.
'''
def even_odd():
num = int(input('Enter a number\n'))
if num % 4 == 0:
print('This number is divisible by 4')
if num % 2 == 0:
print('This is an even number')
elif num % 2 == 1:
print('This is an odd number')
print('Give me two numbers,the first to check and the second to divide')
check = int(input('Check number'))
divide = int(input('Divider'))
if num / divide == check:
print('Correct!')
else:
print('Incorrect!')
even_odd()
| true
|
6426ac00f17c7d1c5879ddf994938cfa0a412e62
|
ChienSien1990/Python_collection
|
/Ecryption/Encrpytion(applycoder).py
| 655
| 4.375
| 4
|
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers, and spaces.
shift: 0 <= int < 26
returns: dict
"""
### TODO
myDict={}
for i in string.ascii_lowercase:
if((ord(i)+shift)>122):
myDict[i] = chr(ord(i)+shift-26)
else:
myDict[i] = chr(ord(i)+shift)
for i in string.ascii_uppercase:
if((ord(i)+shift)>90):
myDict[i] = chr(ord(i)+shift-26)
else:
myDict[i] = chr(ord(i)+shift)
return myDict
| true
|
1105fd4cb3e9b95294e5e918b0017e7f109d1aac
|
sujit4/problems
|
/interviewQs/InterviewCake/ReverseChars.py
| 1,023
| 4.25
| 4
|
# Write a function that takes a list of characters and reverses the letters in place.
import unittest
def reverse(list_of_chars):
left_index = 0
right_index = len(list_of_chars) - 1
while left_index < right_index:
list_of_chars[left_index], list_of_chars[right_index] = list_of_chars[right_index], list_of_chars[left_index]
left_index += 1
right_index -= 1
# Tests
class Test(unittest.TestCase):
def test_empty_string(self):
list_of_chars = []
reverse(list_of_chars)
expected = []
self.assertEqual(list_of_chars, expected)
def test_single_character_string(self):
list_of_chars = ['A']
reverse(list_of_chars)
expected = ['A']
self.assertEqual(list_of_chars, expected)
def test_longer_string(self):
list_of_chars = ['A', 'B', 'C', 'D', 'E']
reverse(list_of_chars)
expected = ['E', 'D', 'C', 'B', 'A']
self.assertEqual(list_of_chars, expected)
unittest.main(verbosity=2)
| true
|
934bdc157134659f5fc834ea4bce96bd6df629a2
|
JuanSebastianOG/Analisis-Numerico
|
/Talleres/PrimerCorte/PrimerTaller/Algoritmos/Metodo_Newton.py
| 1,285
| 4.25
| 4
|
#Implementación del método de Newton para encontrar las raices de una función dada
from matplotlib import pyplot
import numpy
import math
def f( x ):
return math.e ** x - math.pi * x
def fd( x ):
return math.e ** x - math.pi
def newton( a, b ):
x = (a + b) / 2
it = 0
tol = 10e-8
errorX = []
errorY = []
raiz = x - ( f(x) / fd(x) )
while abs( raiz - x ) > tol:
if it > 0:
errorX.append( abs( raiz - x ) )
it = it + 1
x = raiz
raiz = x - ( f(x) / fd(x) )
if it > 1:
errorY.append( abs( raiz - x ) )
print("La raiz que se encuentra en el intervalo ", a, ", ", b, " es aproximadamente: ", raiz )
print("El numero de iteraciones que se obtuvieron: ", it )
pol = numpy.polyfit(errorX, errorY, 2)
pol2 = numpy.poly1d( pol )
cX = numpy.linspace( errorX[0], errorX[len(errorX) - 1], 50 )
cY = pol2( cX )
pyplot.plot( cX, cY )
pyplot.xlabel("Errores X ")
pyplot.ylabel("Errores Y ")
pyplot.title("Metodo de Newton: \n Errores en X vs. Errores en Y")
pyplot.grid()
pyplot.show()
#------------------------MAIN------------------------------------------
if __name__ == "__main__":
newton( 0, 1 )
newton( 1, 2 )
| false
|
72f12e63fbac4561a74211964ab031f5ffb29212
|
derick-droid/pythonbasics
|
/files.py
| 905
| 4.125
| 4
|
# checking files in python
open("employee.txt", "r") # to read the existing file
open("employee.txt", "a") # to append information into a file
employee = open("employee.txt", "r")
# employee.close() # after opening a file we close the file
print(employee.readable()) # this is to check if the file is readable
print(employee.readline()) # this helps read the first line
print(employee.readline()) # this helps to read the second line after the first line
print(employee.readline()[0]) # accessing specific data from the array
# looping through a file in python
for employees in employee.readline():
print(employee)
# adding information into a file
employee = open("employee.txt", "a")
print(employee.write("\n derrick -- for ICT department"))
employee.close()
# re writing a new file or overwriting a file
employee = open("employee1.txt", "w")
employee.write("kelly -- new manager")
| true
|
95a9f725607b5acc0f023b0a0af2551bec253afd
|
derick-droid/pythonbasics
|
/dictexer.py
| 677
| 4.90625
| 5
|
# 6-5. Rivers: Make a dictionary containing three major rivers and the country
# each river runs through. One key-value pair might be 'nile': 'egypt'.
# • Use a loop to print a sentence about each river, such as The Nile runs
# through Egypt.
# • Use a loop to print the name of each river included in the dictionary.
# • Use a loop to print the name of each country included in the dictionary.
rivers = {
"Nile": "Egypt",
"Amazon": "America",
"Tana": "Kenya"
}
for river, country in rivers.items():
print(river + " runs through " + country)
print()
for river in rivers.keys():
print(river)
print()
for country in rivers.values():
print(country)
| true
|
935e0579d7cbb2da005c6c6b1ab7f548a6694a86
|
derick-droid/pythonbasics
|
/slicelst.py
| 2,312
| 4.875
| 5
|
# 4-10. Slices: Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that program’s list.
# • Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# • Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
numbers = [1, 3, 2, 4, 5, 6, 7, 8, 9]
slice1 = numbers[:3]
slice2 = numbers[4:]
slice3 = numbers[-3:]
print(f"The first three items in the list are:{slice1}")
print(f"The items from the middle of the list are:{slice2}")
print(f"The last three items in the list are:{slice3}")
print()
# 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1
# (page 60). Make a copy of the list of pizzas, and call it friend_pizzas .
# Then, do the following:
# • Add a new pizza to the original list.
# • Add a different pizza to the list friend_pizzas .
# • Prove that you have two separate lists. Print the message, My favorite
# pizzas are:, and then use a for loop to print the first list. Print the message,
# My friend’s favorite pizzas are:, and then use a for loop to print the sec-
# ond list. Make sure each new pizza is stored in the appropriate list.
print()
pizzas = ["chicago pizza", "new york_style pizza", "greek pizza", "neapolitans pizza"]
friends_pizza = pizzas[:]
pizzas.append("sicilian pizza")
friends_pizza.append("Detroit pizza")
print(f"my favourite pizzas are:{pizzas}")
print()
print(f"my friend favourite pizzas are:{friends_pizza}")
print()
print("my favourite pizzas are: ")
for pizza in pizzas:
print(pizza)
print()
print("my favourite pizzas are: ")
for items in friends_pizza:
print(items)
print()
#
# 4-12. More Loops: All versions of foods.py in this section have avoided using
# for loops when printing to save space. Choose a version of foods.py, and
# write two for loops to print each list of foods.
food_stuff = ["cake", "rice", "meat", "ice cream", "banana"]
food = ["goat meat", "pilau", "egg stew", "fried", "meat stew"]
for foodz in food_stuff:
print(foodz)
print()
for itemz in food:
print(itemz)
| true
|
5a827e2d5036414682f468fac5915502a784f486
|
derick-droid/pythonbasics
|
/exerdic.py
| 2,972
| 4.5
| 4
|
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the
# name of a pet. In each dictionary, include the kind of animal and the owner’s
# name. Store these dictionaries in a list called pets . Next, loop through your list
# and as you do print everything you know about each print it
rex = {
"name" : "rex",
"kind": "dog",
"owner's name" : "joe"
}
pop = {
"name" :"pop",
"kind" : "pig",
"owner's name": "vincent"
}
dough = {
"name": "dough",
"kind" : "cat",
"owner's name" : "pamna"
}
pets = [rex, pop, dough ]
for item in pets:
print(item)
print()
# 6-9. Favorite Places: Make a dictionary called favorite_places . Think of three
# names to use as keys in the dictionary, and store one to three favorite places
# for each person. To make this exercise a bit more interesting, ask some friends
# to name a few of their favorite places. Loop through the dictionary, and print
# each person’s name and their favorite places.
favorite_places = {
"derrick": {
"nairobi", "mombasa", "kisumu"
},
"dennis":{
"denmark", "thika", "roman"
},
"john": {
"zambia", "kajiado", "suna"
}
}
for name, places in favorite_places.items(): # looping through the dictionary and printing only the name variable
print(f"{name} 's favorite places are :")
for place in places: # looping through the places variable to come up with each value in the variable
print(f"-{place}")
print()
# 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so
# each person can have more than one favorite number. Then print each person’s
# name along with their favorite numbers.
favorite_number = {
"derrick" : [1, 2, 3],
"don" : [3, 5, 7],
"jazzy" : [7, 8, 9]
}
for name, fav_number in favorite_number.items():
print(f"{name} favorite numbers are: ")
for number in fav_number:
print(f"-{number}")
# 6-11. Cities: Make a dictionary called cities . Use the names of three cities as
# keys in your dictionary. Create a dictionary of information about each city and
# include the country that the city is in, its approximate population, and one fact
# about that city. The keys for each city’s dictionary should be something like
# country , population , and fact . Print the name of each city and all of the infor-
# mation you have stored about it.
cities = {
"Nairobi" : {
"population" : "1400000",
"country" : "kenya",
"facts" : "largest city in East Africa"
},
"Dar-es-salaam" : {
"population" : "5000000",
"country" : "tanzania",
"facts" : "largest city in Tanzania"
},
"Kampala" : {
"population" : "1000000",
"country" : "Uganda",
"facts" : "The largest city in Uganda"
}
}
for city, information in cities.items():
print(f"{city}:")
for fact,facts in information.items():
print(f"-{fact}: {facts}")
| true
|
d65f32a065cc87e5de526a718aeea6d601e1ac06
|
derick-droid/pythonbasics
|
/iflsttry.py
| 2,930
| 4.5
| 4
|
# 5-8. Hello Admin: Make a list of five or more usernames, including the name
# 'admin' . Imagine you are writing code that will print a greeting to each user
# after they log in to a website. Loop through the list, and print a greeting to
# each user:
# • If the username is 'admin' , print a special greeting, such as Hello admin,
# would you like to see a status report?
# • Otherwise, print a generic greeting, such as Hello Eric, thank you for log-
# ging in again.
usernames = ["derick-admin", "Erick", "charles", "yusuf"]
for name in usernames:
if name == "derick-admin":
print(f"Hello admin , would you like to see status report")
else:
print(f"Hello {name} , thank you for logging in again")
#
# 5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is
# not empty.
# • If the list is empty, print the message We need to find some users!
# • Remove all of the usernames from your list, and make sure the correct
# message is printed.
users = ["deno", "geogre", "mulla", "naomi"]
users.clear()
if users:
for item in users:
print(f"hello {item}")
else:
print("we need at least one user")
print()
#
# 5-10. Checking Usernames: Do the following to create a program that simulates
# how websites ensure that everyone has a unique username.
# • Make a list of five or more usernames called current_users .
# • Make another list of five usernames called new_users . Make sure one or
# two of the new usernames are also in the current_users list.
# • Loop through the new_users list to see if each new username has already
# been used. If it has, print a message that the person will need to enter a
# new username. If a username has not been used, print a message saying
# that the username is available.
# •
# Make sure your comparison is case insensitive. If 'John' has been used,
# 'JOHN' should not be accepted.
web_users = ["derrick", "moses", "Raila", "john", "ojwang", "enock"]
new_users = ["derrick", "moses", "babu", "vicky", "dave", "denver"]
for user_name in new_users:
if user_name in web_users:
print("please enter a new user name ")
else:
print("the name already registered ")
print()
# 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such
# as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
# • Store the numbers 1 through 9 in a list.
# • Loop through the list.
# • Use an if - elif - else chain inside the loop to print the proper ordinal end-
# ing for each number. Your output should read "1st 2nd 3rd 4th 5th 6th
# 7th 8th 9th" , and each result should be on a separate line
ordinary_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in ordinary_numbers:
if number == 1:
print(f'{number}st')
elif number == 2:
print(f"{number}nd")
elif number == 3:
print(f"{number}rd")
else:
print(f"{number}th")
| true
|
0ed70af907f37229379d7b38b7aaae938a7fc31a
|
adamkozuch/scratches
|
/scratch_4.py
| 584
| 4.15625
| 4
|
def get_longest_sequence(arr):
if len(arr) < 3:
return len(arr)
first = 0
second = None
length = 0
for i in range(1, len(arr)):
if arr[first] == arr[i] or (second and arr[second]== arr[i]):
continue
if not second:
second = i
continue
if i - first > length:
length = i - first
first = second
second = i
if len(arr) - first > length:
length = len(arr) - first
return length
print(get_longest_sequence([1]))
print(get_longest_sequence([5,1,2,1,2,5]))
| true
|
228c27b3406c45f10f3df2588de29e1d4ad5bfcb
|
AjayHao/helloPy
|
/demos/basic/list.py
| 684
| 4.21875
| 4
|
#!/usr/bin/python3
# 元祖
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7, 8]
# 随机读取
print ("list1[0]: ", list1[0])
print ("list1[-2]: ", list1[-2])
print ("list2[1:3]: ", list2[1:3])
print ("list2[2:]: ", list2[2:])
# 更新
list1[2] = '123'
print ("[update] list1: ", list1)
# 删除
del list1[2]
print ("[del] list1: ", list1)
# 操作符
print ("[len()] list1: ", len(list1))
print ("list1 + list2: ", list1 + list2)
print ("list1 * 2: ", list1 * 2)
print ("2000 in list1: ", 2000 in list1)
for x in list1: print(x, end=" ")
print()
print(1 not in list2)
# 列表数组转换
tuple = tuple(list2)
print(tuple)
| false
|
0b303dde589390cf6795a2fc79ca473349c5e190
|
SeanLau/leetcode
|
/problem_104.py
| 1,203
| 4.125
| 4
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 此题可以先序遍历二叉树,找到最长的即可
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
if not root:
return depth
result = []
def preOrder(root, depth):
# return root
depth += 1
if root.left:
preOrder(root.left, depth)
if root.right:
preOrder(root.right, depth)
# yield depth
if not (root.left and root.right):
print("## depth in ===>", depth)
result.append(depth)
preOrder(root, depth)
return max(result)
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(3)
root.right.left = TreeNode(4)
so = Solution()
print(so.maxDepth(root))
| true
|
e3fc26f817596ff52cf7a97933ea0c192c5cef42
|
dsintsov/python
|
/labs/lab1/lab1-1_7.py
| 989
| 4.125
| 4
|
# № 7: В переменную Y ввести номер года. Определить, является ли год високосным.
"""
wiki: год, номер которого кратен 400, — високосный;
остальные годы, номер которых кратен 100, — невисокосные (например, годы 1700, 1800, 1900, 2100, 2200, 2300);
остальные годы, номер которых кратен 4, — високосные
"""
# Checking the user input
while True:
Y = input("Enter a year: ")
try:
if int(Y) > 0:
break # input is INT and greater than 0
else:
raise TypeError() # just call an exception
except:
print("ERR: \"{0}\" - it\'s NOT a valid year number, try again!".format(str(Y)))
Y = int(Y)
print(str(Y), end='')
if Y % 400 == 0 or Y % 4 == 0 and Y % 100 != 0:
print(" - is a leap year")
else:
print(" - isn't a leap year")
exit(0)
| false
|
24ef3ae3700fb03f7376673ee39067c362eee76a
|
billdonghp/Python
|
/stringDemo.py
| 877
| 4.25
| 4
|
'''
字符串操作符 + *
字符串的长度 len
比较字符串大小
字符串截取 [:] [0:]
判断有无子串 in not in
查找子串出现的位置 find() index() 不存在的话报错
encode,decode
replace(old,new,count)、count(sub,start,end)
isdigit()、startswith
split、join '-'.join('我爱你中国')
隔位截取str1[::2] = str1[0:-1:2] start 和end不写时为全部;step=2 如果 step为负数时,倒序截取;
'''
str1 = 'hello'
a = 'a'
b = 'b'
def stringEncode(str):
myBytes = str.encode(encoding='utf-8')
return myBytes
if __name__ == "__main__":
print(len(str1))
print(a < b)
print('中国' < '美国') #utf-8中 美比中大
print(str1[2:])
print(str1.upper())
sEncode = stringEncode('我爱你中国')
print(sEncode.decode(encoding='utf-8'))
print(str1.find('7'))
print(str1[::-1])
pass
| false
|
144aadab9b2167c896838ae99747d606b91834a3
|
skad00sh/algorithms-specialization
|
/Divide and Conquer, Sorting and Searching, and Randomized Algorithms/0.4 week1 - bubble-sort.py
| 691
| 4.21875
| 4
|
def bubble_sort(lst):
"""
------ Pseudocode Steps -----
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
------ Doctests -----
>>> unsorted_list = [8,4,3,7,87,5,64,6,73]
>>> sorted_list = insertion_sort(unsorted_list)
>>> sorted_list
[3, 4, 5, 6, 7, 8, 64, 73, 87]
"""
for h in range(len(lst)):
for i in range(len(lst)-h-1):
if lst[i] > lst[i+1]:
lst[i], lst[i+1] = lst[i+1], lst[i]
return lst
| false
|
60cff1227d0866a558d88df56dad871a8d189d9e
|
mac912/python
|
/calender.py
| 1,021
| 4.3125
| 4
|
# program to print calender of the month given by month number
# Assumptions: Leap year not considered when inputed is for February(2). Month doesn't start with specific day
mon = int(input("Enter the month number :"))
def calender():
if mon <=7:
if mon%2==0 and mon!=2:
for j in range(1,31):
print(j, end=' ')
if j%7==0:
print()
elif mon==2:
for j in range(1,29):
print(j, end=' ')
if j%7==0:
print()
elif mon<=7 and mon%2!=0:
for j in range(1,32):
print(j, end=' ')
if j%7==0:
print()
elif mon>7 and mon%2==0:
for j in range(1,32):
print(j, end=' ')
if j%7==0:
print()
elif mon>7 and mon%2!=0:
for j in range(1,31):
print(j, end=' ')
if j%7==0:
print()
calender()
| false
|
773d9211d4e6037aff180f87f135d11e0f660d7e
|
dr2moscow/GeekBrains_Education
|
/I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_3.py
| 696
| 4.15625
| 4
|
'''
Задание # 3
Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
возвращает сумму наибольших двух аргументов.
'''
def f_max_2_from_3(var_1, var_2, var_3):
return var_1 + var_2 + var_3 - min(var_1, var_2, var_3)
my_vars = []
for count in range(3):
try:
var = float(input(f'Введите число # {count+1}: '))
except ValueError:
print('Должно быть число! По умолчанию подставлена 1')
var = 1
my_vars.append(var)
print(f'{f_max_2_from_3(my_vars[0], my_vars[1], my_vars[2])}')
| false
|
a3c81c5b91daffbd7de1fbe55e2fce7eac26cd80
|
dr2moscow/GeekBrains_Education
|
/I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_4.py
| 1,434
| 4.125
| 4
|
'''
Задание # 3
Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
возвращает сумму наибольших двух аргументов.
'''
def f_my_power(base, power):
base__power = 1
for count in range(power*(-1)):
base__power *= base
return 1 / base__power
try:
var_1 = float(input('Введите действительное положительное: '))
except ValueError:
print('Должно быть число! По умолчанию подставлена 1')
var_1 = 1
try:
var_2 = int(input('Введите целое отрицательное число: '))
if var_2 > 0:
print('Число должно быть отрицательным. Поставим минус за Вас')
var_2 = 0 - var_2
elif var_2 == 0:
print('0 не подходит. Подставим -1')
var_2 = -1
except ValueError:
print('целое отрицательное число. А вы ввели что-то друге. Подставим вместо Вас -1')
var_2 = -1
print(f'Результат работы моей функции: {f_my_power(var_1, var_2)}')
print(f'Результат работы системной функции python: {var_1**var_2}. Для визуальной проверки результата')
| false
|
ef1ebb2ba1f95a2d8c09f3dc32af9d2ffec17499
|
CyberTaoFlow/Snowman
|
/Source/server/web/exceptions.py
| 402
| 4.3125
| 4
|
class InvalidValueError(Exception):
"""Exception thrown if an invalid value is encountered.
Example: checking if A.type == "type1" || A.type == "type2"
A.type is actually "type3" which is not expected => throw this exception.
Throw with custom message: InvalidValueError("I did not expect that value!")"""
def __init__(self, message):
Exception.__init__(self, message)
| true
|
c61d5128252a279d1f6c2b6f054e8ea1ead7b2af
|
rup3sh/python_expr
|
/general/trie
| 2,217
| 4.28125
| 4
|
#!/bin/python3
import json
class Trie:
def __init__(self):
self._root = {}
def insertWord(self, string):
''' Inserts word by iterating thru char by char and adding '*"
to mark end of word and store complete word there for easy search'''
node = self._root
for c in string:
if c not in node:
node[c] = {}
node = node[c]
node['*'] = string
def printTrie(self):
node = self._root
print(json.dumps(self._root, indent=2))
##Utility methods
def isWord(self, word):
''' check if word exists in trie'''
node = self._root
for c in word:
if c not in node:
return False
node = node[c]
# All chars were seen
return True
#EPIP, Question 24.20
def shortestUniquePrefix(self, string):
'''shortest unique prefix not in the trie'''
prefix = []
node = self._root
for c in string:
prefix.append(c)
if c not in node:
return ''.join(prefix)
node = node[c]
return ''
def startsWithPrefix(self, prefix):
''' return suffixes that start with given prefix '''
# Simulating DFS
def _dfs(node):
stack = []
stack.append(node)
temp = []
while stack:
n = stack.pop()
for c in n.keys():
if c == '*': #Word end found
temp.append(n[c])
else: #Keep searching
stack.append(n[c])
return temp
##Position node to the end of prefix list
node = self._root
for c in prefix:
if c not in node:
break
node = node[c]
return _dfs(node)
def main():
t_list = "mon mony mont monty monday mondays tea ted teddy tom tony tori tomas tomi todd"
words = t_list.split()
trie = Trie()
for word in words:
trie.insertWord(word)
#trie.printTrie()
#Utility method test
target = 'teal'
#print(target, "Is in tree?", trie.isWord(target))
target = 'teddy'
#print(target, "Is in tree?", trie.isWord(target))
target = 'temporary'
#shortest_unique_not_in_trie = trie.shortestUniquePrefix(target)
#print("shortest_unique_not_in_trie is :", shortest_unique_not_in_trie)
suffixes = trie.startsWithPrefix('mon')
print("Words starting with prefix:", suffixes)
if __name__=="__main__":main()
| true
|
23f20f17dc25cc3771922706260d43751f2584c5
|
rup3sh/python_expr
|
/generators/generator
| 1,446
| 4.34375
| 4
|
#!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
generatorDemo()
def list_of_even(n):
for i in range(0,n+1):
if i%2 == 0:
yield i
def generatorDemo():
try:
x = list_of_even(10)
print(type(x))
for i in x:
print("EVEN:" + str(i))
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
#Print the reverse list
print(the_list[::-1])
#list comprehension
new_list = [ item.upper() for item in the_list ]
print("NEWLIST:" + str(new_list))
#generator expression
gen_object = (item.upper() for item in the_list)
#You can also call next() on this generator object
# Generator would call a StopIteration Execepton if you cannot call next anymore
print(type(gen_object))
##This yields the items one by one toa list
newlist = list(gen_object)
print("YET ANOTHER NEWLIST:" + str(new_list))
# As you can see, generator objects cannot be reused
# So this would be empty
one_more_list = list(gen_object)
print("ONE MORE LIST:" + str(one_more_list))
# Capitalizes the word and reverses the word in one step
ultimate_gen = (item[::-1] for item in (item.upper() for item in the_list))
print("ULTIMATE LIST:" + str(list(ultimate_gen)))
except Exception as e:
sys.stderr.write("Exception:{}".format(str(e)))
if __name__ == "__main__":main(sys.argv[0:])
| true
|
8fe1986f84ccd0f906095b651aa98ba62b2928b8
|
rup3sh/python_expr
|
/listsItersEtc/listComp
| 1,981
| 4.1875
| 4
|
#!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
listComp()
def listComp():
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
print(the_list[0:len(the_list)])
#Slicing
#the_list[2:] = "paz"
#['stanley', 'ave', 'p', 'a', 'z'] # This replaces everything from indexs 2 onwards
#Everything except the last one
#print(str(the_list[:-1]))
#Prints 2, 3 only
#print(str(the_list[2:4]))
#Prints reverse -N onwards, but counting from 1 "los angeles", "istanbul", "moscow", "korea"]
#print(str(the_list[-4:]))
#Prints from start except last 4 ["stanley", "ave", "fremont",
#print(str(the_list[:-4]))
#Prints from start, skips odd positions ['ave', 'los angeles', 'moscow']
#print(str(the_list[1::2]))
#Prints from reverse at 1, skips odd positions (only 'ave')
#print(str(the_list[1::-2]))
#the_list[3:3] = "California"
#['stanley', 'ave', 'fremont', 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a', 'los angeles', 'istanbul', 'moscow', 'korea']
#Insert new list at a position
#the_list[3:3] = ["California"]
#['stanley', 'ave', 'fremont', 'California', 'los angeles', 'istanbul', 'moscow', 'korea']
# Modifies list to ['stanley', 'ave', 'fremont', 'California', 'moscow', 'korea']
#the_list[3:5] = ["California"]
# Delete middle of the list ['stanley', 'ave', 'fremont','moscow', 'korea']
#the_list[3:5] = []
##Add list to another list
add_this = ["africa", "asia", "antarctica"]
the_list.extend(add_this)
#Insert in the list
the_list.insert(4, 'alameda')
#Delete an element by index
x = the_list.pop(3)
#Delete an element by name
the_list.remove('moscow')
print(str(the_list))
#In-place reversal
the_list.reverse()
print(str(the_list))
print("Index of africa is: "+ str(the_list.index('africa')))
# Count occurrence
print(str(the_list.count('fremont')))
if __name__ == "__main__":main(sys.argv[0:])
| true
|
3b597cae9208d703e6479525625da55ddc18b976
|
DahlitzFlorian/python-zero-calculator
|
/tests/test_tokenize.py
| 1,196
| 4.1875
| 4
|
from calculator.helper import tokenize
def test_tokenize_simple():
"""
Tokenize a very simple function and tests if it's done correctly.
"""
func = "2 * x - 2"
solution = ["2", "*", "x", "-", "2"]
assert tokenize.tokenize(func) == solution
def test_tokenize_complex():
"""
Tokenize a more complex function with different whitespaces and
operators. It also includes functions like sin() and con().
"""
func = "x*x- 3 /sin( x +3* x) + cos(9*x)"
solution = [
"x",
"*",
"x",
"-",
"3",
"/",
"sin",
"(",
"x",
"+",
"3",
"*",
"x",
")",
"+",
"cos",
"(",
"9",
"*",
"x",
")",
]
assert tokenize.tokenize(func) == solution
def test_tokenize_exponential_operator():
"""
Test if tokenizing a function including the exponential operator **
works as expected and that it does not add two times the multiplication
operator to the final list.
"""
func = "2 ** 3 * 18"
solution = ["2", "**", "3", "*", "18"]
assert tokenize.tokenize(func) == solution
| true
|
4b7dbbf640d118514fa306ca39a5ee336852aa05
|
francoischalifour/ju-python-labs
|
/lab9/exercises.py
| 1,777
| 4.25
| 4
|
#!/usr/bin/env python3
# coding: utf-8
# Lab 9 - Functional Programming
# François Chalifour
from functools import reduce
def product_between(a=0, b=0):
"""Returns the product of the integers between these two numbers"""
return reduce(lambda a, b: a * b, range(a, b + 1), 1)
def sum_of_numbers(numbers):
"""Returns the sum of all the numbers in the list"""
return reduce(lambda a, b: a + b, numbers, 0)
def is_in_list(x, numbers):
"""Returns True if the list contains the number, otherwise False"""
return any(filter(lambda n: n == x, numbers))
def count(numbers, x):
"""Returns the number of time the number occurs in the list"""
return len(filter(lambda n: n == x, numbers))
def test(got, expected):
"""Prints the actual result and the expected"""
prefix = '[OK]' if got == expected else '[X]'
print('{:5} got: {!r}'.format(prefix, got))
print(' expected: {!r}'.format(expected))
def main():
"""Tests all the functions"""
print('''
======================
LAB 9
======================
''')
print('1. Multiplying values')
test(product_between(0, 1), 0)
test(product_between(1, 3), 6)
test(product_between(10, 10), 10)
test(product_between(5, 7), 210)
print('\n2. Summarizing numbers in lists')
test(sum_of_numbers([]), 0)
test(sum_of_numbers([1, 1, 1]), 3)
test(sum_of_numbers([3, 1, 2]), 6)
print('\n3. Searching for a value in a list')
test(is_in_list(1, []), False)
test(is_in_list(3, [1, 2, 3, 4, 5]), True)
test(is_in_list(7, [1, 2, 1, 2]), False)
print('\n4. Counting elements in lists')
test(count([], 4), 0)
test(count([1, 2, 3, 4, 5], 3), 1)
test(count([1, 1, 1], 1), 3)
if __name__ == '__main__':
main()
| true
|
ba5bce618d68b7570c397bc50d6f96766b600fd9
|
francoischalifour/ju-python-labs
|
/lab4/exercises.py
| 1,024
| 4.1875
| 4
|
#!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Dictionaries
# François Chalifour
def sums(numbers):
"""Returns a dictionary where the key "odd" contains the sum of all the odd
integers in the list, the key "even" contains the sum of all the even
integers, and the key "all" contains the sum of all integers"""
sums = {'odd': 0, 'even': 0, 'all': 0}
for x in numbers:
if x % 2 == 0:
sums['even'] += x
else:
sums['odd'] += x
sums['all'] += x
return sums
def test(got, expected):
"""Prints the actual result and the expected"""
prefix = '[OK]' if got == expected else '[X]'
print('{:5} got: {!r}'.format(prefix, got))
print(' expected: {!r}'.format(expected))
def main():
"""Tests all the functions"""
print('''
======================
LAB 4
======================
''')
print('1. Computing sums')
test(sums([1, 2, 3, 4, 5]), {"odd": 9, "even": 6, "all": 15})
if __name__ == '__main__':
main()
| true
|
a81ce65a4df9304e652af161f5a00534b35cc844
|
Abuubkar/python
|
/code_samples/p4_if_with_in.py
| 1,501
| 4.25
| 4
|
# IF STATEMENT
# Python does not require an else block at the end of an if-elif chain.
# Unlike C++ or Java
cars = ['audi', 'bmw', 'subaru', 'toyota']
if not cars:
print('Empty Car List')
if cars == []:
print('Empty Car List')
for car in cars:
if car == 'bmw':
print(car.upper())
elif cars == []: # this condition wont run as if empty FOR LOOP won't run
print('No car present')
else:
print(car.title())
age_0 = 10
age_1 = 12
if(age_0 > 1 and age_0 < age_1):
print("\nYoung")
if(age_1 > age_0 or age_1 >= 11):
print("Elder")
# Check presence in list
car = 'bmw'
print("\nAudi is presend in cars:- " + str('audi' in cars))
print(car.title()+" is presend in cars:- " + str(car in cars)+"\n")
# Another way
car = 'Suzuki'
if car in cars:
print(car+' is present')
if car not in cars:
print(car+' is not present\n')
# it does not check presence in 'for loop' as output of cars is
# overwritten by for loop
# for car in cars :
# print (car)
# Checking Multiple List
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
| true
|
b583554675d3ec46b424ac0e808a8281a339de67
|
NandanSatheesh/Daily-Coding-Problems
|
/Codes/2.py
| 602
| 4.21875
| 4
|
# This problem was asked by Uber.
#
# Given an array of integers,
# return a new array such that each element at index i of the
# new array is the product of all the numbers in the original array
# except the one at i.
#
# For example,
# if our input was [1, 2, 3, 4, 5],
# the expected output would be [120, 60, 40, 30, 24].
# If our input was [3, 2, 1], the expected output would be [2, 3, 6].
def getList(l):
product = 1
for i in l:
product *= i
newlist = [product/i for i in l ]
print(newList)
return newList
l = [1,2,3,4,5]
getList(l)
getList([3,2,1])
| true
|
e08d5430b054d56ae0ac12b818ad476158cfa51f
|
susoooo/IFCT06092019C3
|
/elvis/python/bucle5.py
| 645
| 4.125
| 4
|
# Escriba un programa que pregunte cuántos números se van a introducir, pida esos números
# y escriba cuántos negativos ha introducido.
print("NÚMEROS NEGATIVOS")
numero = int(input("¿Cuántos valores va a introducir? "))
if numero < 0:
print("¡Imposible!")
else:
contador = 0
for i in range(1, numero + 1):
valor = float(input(f"Escriba el número {i}: "))
if valor < 0:
contador = contador + 1
if contador == 0:
print("No ha escrito ningún número negativo.")
elif contador == 1:
print("Ha escrito 1 número negativo.")
else:
print(f"Ha escrito {contador} números negativos.")
| false
|
16ec073e55924a91de34557320e539c750f377a3
|
susoooo/IFCT06092019C3
|
/jesusp/phyton/Divisor.py
| 215
| 4.125
| 4
|
print("Introduzca un número")
num = int(input())
if(num > 0):
for num1 in range(1, num+1):
if(num % num1 == 0):
print("Divisible por: ", num1)
else:
print("Distinto de cero o positivo")
| false
|
b2ba8e45c360ae96a08209172ba05811dd3a3b96
|
susoooo/IFCT06092019C3
|
/jesusp/phyton/Decimal.py
| 201
| 4.15625
| 4
|
print("Introduzca un número")
num = int(input())
print("Introduzca otro número")
num1 = int(input())
while(num > num1):
print("Introduzca un numero decimal: ")
num1= float(input())
| false
|
19bfe557a5e0d351be9215b2f8ea501587337fda
|
Chelton-dev/ICTPRG-Python
|
/except_div_zero.py
| 242
| 4.1875
| 4
|
num1 = int (input("Enter num1: "))
num2 = int (input("Enter num2: "))
# Problem:
# num3 = 0/0
try:
result = num1/num2
print(num1,"divided by", num2, "is ", result)
except ZeroDivisionError:
print("division by zero has occured")
| false
|
371ed66d667edb14d59347994462ddf30dde6a84
|
Liraz-Benbenishti/Python-Code-I-Wrote
|
/hangman/hangman/hangman-unit7/hangman-ex7.3.1.py
| 836
| 4.25
| 4
|
def show_hidden_word(secret_word, old_letters_guessed):
"""
:param secret_word: represent the hidden word the player need to guess.
:param old_letters_guessed: the list that contain the letters the player guessed by now.
:type secret_word: string
:type old_letters_guessed: list
:return: string that comprised of the letters and underscores. Shows the letter from the list that contained in the secret word in their location.
rtype: string
"""
new_word = []
for letter in secret_word:
if (letter in old_letters_guessed):
new_word.append(letter)
else:
new_word.append("_")
return " ".join(new_word)
def main():
secret_word = "mammals"
old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k']
print(show_hidden_word(secret_word, old_letters_guessed))
if __name__ == "__main__":
main()
| true
|
fda16aa729c019888cb2305fcfb00d782e620db6
|
cnulenka/Coffee-Machine
|
/models/Beverage.py
| 1,434
| 4.34375
| 4
|
class Beverage:
"""
Beverage class represents a beverage, which has a name
and is made up of a list of ingredients.
self._composition is a python dict with ingredient name as
key and ingredient quantity as value
"""
def __init__(self, beverage_name: str, beverage_composition: dict):
self._name: str = beverage_name
self._composition: dict = beverage_composition
def get_name(self):
return self._name
def get_composition(self):
return self._composition
"""
CANDIDATE NOTE:
one other idea here was to make a abstract Beverage class and inherit and
create child classes of hot_coffee, black_coffee, hot_tea etc where each of
them over ride get_composition and store the composition info with in class.
So orders will be a list of Beverage objects having child class instances.
But this would hard code the composition and types of Beverages, hence extensibility
will be affected, but may be we can have a custom child class also where user
can create any beverage object by setting name and composition.
Same approach can be followed for Ingredients Class. I don't have a Ingredients class
though. Each ingredient can have a different warning limit, hence get_warning_limit
will be implemented differently. For example water is most used resource so that
can have a warning limit of 50% may be.
-Shakti Prasad Lenka
"""
| true
|
7762d9a8c0b8ebb97551f2071f9377fe896b686f
|
itstooloud/boring_stuff
|
/chapter_3/global_local_scope.py
| 922
| 4.1875
| 4
|
##
####def spam():
#### global eggs
#### eggs = 'spam'
####
####eggs = 'global'
####spam()
####print(eggs)
##
####using the word global inside the def means that when you refer to that variable within
####the function, you are referring to the global variable and can change it.
##
####def spam():
#### global eggs
#### eggs = 'spam' #this is a the global
####
####def bacon():
#### eggs = 'bacon' #this is a local variable
####
####def ham():
#### print(eggs) #this is the global
####
####eggs = 42 #this is the global
####spam()
####print(eggs)
##
#### if you try to use a global variable inside a function without assigning a value to it, you'll get an error
##
##def spam():
## print(eggs) #this will give an error
## ## eggs = 'spam local'
##
##eggs = 'global'
##
##spam()
##
#### it only throws the error because the function assigns a value to eggs. Commenting it out should remove the error
| true
|
46c128c433288c3eed04ecb148693e52828c6975
|
itstooloud/boring_stuff
|
/hello_age.py
| 358
| 4.15625
| 4
|
#if/elif will exit as soon as one condition is met
print('Hello! What is your name?')
my_name = input()
if my_name == "Chris":
print('Hello Chris! Youre me!')
print('Your age?')
my_age = input()
my_age = int(my_age)
if my_age > 20:
print("you're old")
elif my_age <= 10:
print("you're young")
else:
print('you are a spring chicken!')
| false
|
f85f89d07de9f394d7f95646c0a490232bc3b7bc
|
whoismaruf/usermanager
|
/app.py
| 2,605
| 4.15625
| 4
|
from scripts.user import User
print('\nWelcome to user management CLI application')
user_list = {}
def create_account():
name = input('\nSay your name: ')
while True:
email = input('\nEnter email: ')
if '@' in email:
temp = [i for i in email[email.find('@'):]]
if '.' in temp:
user = User(name, email)
break
else:
print("\nInvalid Email address! Please enter the correct one.")
continue
else:
print("\nInvalid Email address! Please enter the correct one.")
continue
uname = user.set_username()
current_user = {
'name': name,
'email': email
}
while True:
if uname in user_list:
new_uname = input(f'\nSorry your username "{uname}" has been taken, choose another one: ')
uname = new_uname.replace(" ", '')
else:
break
user_list[f'{uname}'] = current_user
print(f"\nHello, {name}! Your account has been created as {uname}.\n\nChoose what to do next - ")
while True:
user_input = input('''
A --> Create account
S --> Show account info
Q --> Quit
''')
if user_input == 'A' or user_input == 'a':
create_account()
elif user_input == 'S' or user_input == 's':
if len(user_list) == 0:
print("\nThere is no account, please create one")
continue
else:
while True:
search = input('\nEnter username: ')
if search not in user_list:
print(f"\nYour searched '{search}' user not found.")
pop = input('''
S --> Search again
M --> Back to main menu
''')
if pop == 'S' or pop == 's':
continue
elif pop == 'M' or pop == 'm':
break
else:
print('Bad input')
break
else:
res = user_list[search]
print(f'''
Account information for {search}
Name: {res['name']}
Email: {res['email']}
''')
break
elif user_input == 'Q' or user_input == 'q':
break
elif user_input == '':
print('Please input something')
continue
else:
print('\nBad input, try again\n')
| true
|
4da19128caf20616ecbd36b297022b1d3ccb92ce
|
PraneshASP/LeetCode-Solutions-2
|
/234 - Palindrome Linked List.py
| 1,548
| 4.1875
| 4
|
# Solution: The idea is that we can reverse the first half of the LinkedList, and then
# compare the first half with the second half to see if it's a palindrome.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
slow = head
fast = head
# Move through the list with fast and slow pointers,
# when fast reaches the end, slow will be in the middle
# Trick #1: At the same time we can also reverse the first half of the list
tmp = slow.next
while fast is not None and fast.next is not None:
fast = fast.next.next
prev = slow
slow = tmp
tmp = slow.next
slow.next = prev
head.next = None
# Trick #2: If fast is None, the string is even length
evenCheck = (fast is None)
if evenCheck:
if slow.val != slow.next.val:
return False
slow = slow.next.next
else:
slow = slow.next
# Check that the reversed first half matches the second half
while slow is not None:
if tmp is None or slow.val != tmp.val:
return False
slow = slow.next
tmp = tmp.next
return True
| true
|
869edf4c975e41ccdee0eacfbda1a636576578fc
|
jigarshah2811/Python-Programming
|
/Matrix_Print_Spiral.py
| 1,741
| 4.6875
| 5
|
"""
http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
Print a given matrix in spiral form
Given a 2D array, print it in spiral form. See the following examples.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
spiral-matrix
"""
def print_spiral(matrix):
'''matrix is a list of list -- a 2-d matrix.'''
first_row = 0
last_row = len(matrix) - 1
first_column = 0
last_column = len(matrix[0]) - 1
while True:
# Print first row
for col_idx in range(first_column, last_column + 1):
print(matrix[first_row][col_idx])
first_row += 1
if first_row > last_row:
return
# Print last column
for row_idx in range(first_row, last_row + 1):
print(matrix[row_idx][last_column])
last_column -= 1
if last_column < first_column:
return
# Print last row, in reverse
for col_idx in reversed(range(first_column, last_column + 1)):
print(matrix[last_row][col_idx])
last_row -= 1
if last_row < first_row:
return
# Print first column, bottom to top
for row_idx in reversed(range(first_row, last_row + 1)):
print(matrix[row_idx][first_column])
first_column += 1
if first_column > last_column:
return
if __name__ == '__main__':
mat = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
print_spiral(mat)
| true
|
4a5fc85b209138408683797ef784cbd59dd978fe
|
jigarshah2811/Python-Programming
|
/LL_MergeSort.py
| 2,556
| 4.625
| 5
|
# Python3 program merge two sorted linked
# in third linked list using recursive.
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Constructor to initialize the node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Method to print linked list
def printList(self):
temp = self.head
while temp:
print temp.data
temp = temp.next
# Function to add of node at the end.
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def splitList(head):
slow = fast = head
while fast:
fast = fast.next
if fast is not None:
fast = fast.next
slow = slow.next
# Now, Fast is at End and Slow is at Middle
A = head
B = slow
slow.next = None
return A, B
def mergeSort(head):
if head is None or head.next is None:
return head
# Split unsorted list into A and B
A, B = splitList(head)
# Indivudally sort A and B
mergeSort(A)
mergeSort(B)
# Now we have 2 sorted lists, A & B, merge them
return mergeLists(A, B)
# Function to merge two sorted linked list.
def mergeLists(A, B):
tail = None
if A is None:
return B
if B is None:
return A
if A.data < B.data:
tail = A
tail.next = mergeLists(A.next, B)
else:
tail = B
tail.next = mergeLists(A, B.next)
return tail
# Driver Function
if __name__ == '__main__':
# Create linked list :
# 10->20->30->40->50
list1 = LinkedList()
list1.append(3)
list1.append(5)
list1.append(7)
# Create linked list 2 :
# 5->15->18->35->60
list2 = LinkedList()
list2.append(1)
list2.append(2)
list2.append(4)
list2.append(6)
# Create linked list 3
list3 = LinkedList()
# Merging linked list 1 and linked list 2
# in linked list 3
list3.head = mergeLists(list1.head, list2.head)
print(" Merged Linked List is : ")
list3.printList()
print "Testing MergeSort"
# Create linked list 4 :
# 5->2->1->4->3
list3 = LinkedList()
list3.append(5)
list3.append(2)
list3.append(1)
list3.append(4)
list3.append(3)
sortedList = mergeSort(list3.head)
sortedList.printList()
| true
|
f9e0bf6998f5ee9065ca8b27e56baa95907cb486
|
jigarshah2811/Python-Programming
|
/Advance-OOP-Threading/OOP/ClassObject.py
| 1,422
| 4.53125
| 5
|
"""
This is valid, self takes up the arg!
"""
# class Robot:
# def introduce(self):
# print("My name is {}".format(self.name))
#
# r1 = Robot()
# r1.name = "Krups"
# #r1.namee = "Krups" # Error: Because now self.name wouldn't be defined!
# r1.introduce()
#
# r2 = Robot()
# r2.name = "Pasi"
# r2.introduce()
""" OOP
Class constructor
"""
class Robot:
def __init__(self, name, color, weight):
self.name, self.color, self.weight = name, color, weight
def introduce(self):
print("My name: {}, color: {}, weight: {}".format(self.name, self.color, self.weight))
r1 = Robot(name="Google", color="Pink", weight=10)
r2 = Robot(name="Alexa", color="Purple", weight=60)
r1.introduce()
r2.introduce()
class Person:
def __init__(self, name, personality, isSitting=True):
self.name, self.personality, self.isSitting = name, personality, isSitting
def introduce(self):
print("Person name: {}, personality: {}, isSitting: {}".format(self.name, self.personality, self.isSitting))
krups = Person(name="Krups", personality="Talkative", isSitting=False)
pasi = Person(name="pasi", personality="Singing", isSitting=True)
""" OOP: Relationship between objects
"""
krups.robot_owned = r1 # A class member can be defined "Run-Time"!. This will be self.robot_owned in "krups" object
pasi.robot_owned = r2
krups.robot_owned.introduce()
pasi.robot_owned.introduce()
| false
|
28a8e6ee2b125056cfe0c3056d6e3a92ba5e4a65
|
sabeeh99/Batch-2
|
/fathima_ashref.py
| 289
| 4.28125
| 4
|
# FathimaAshref-2-HelloWorldAnimation
import time
def animation(word):
"""this function takes the input and displays it
character by character with a delay of 1 second"""
for i in word:
time.sleep(1)
print(i, end="")
animation("Hello World")
| true
|
d2f96447565c188fcc5fb24a24254dc68a2f5b60
|
hanucane/dojo
|
/Online_Academy/python-intro/datatypes.py
| 763
| 4.3125
| 4
|
# 4 basic data types
# print "hello world" # Strings
# print 4 - 3 # Integers
# print True, False # Booleans
# print 4.2 # Floats
# print type("hello world") # Identify data type
# print type(1)
# print type(True)
# print type(4.2)
# Variables
name = "eric"
# print name
myFavoriteInt = 8
myBool = True
myFloat = 4.2
# print myFavoriteInt
# print myBool
# print myFloat
# Objects
# list => array (referred to as list in Python)
# len() shows the length of the variable / object
myList = [
name,
myFavoriteInt,
myBool,
myFloat,
[myBool, myFavoriteInt, myFloat]
]
print len(myList)
# Dictionary
myDictionary = {
"name": "Eric",
"title": "Entrepenuer",
"hasCar": True,
"favoriteNumber": 8
}
print myDictionary["name"]
| true
|
eb392b54023303e56d23b76a464539b70f8ee6e8
|
shamim-ahmed/udemy-python-masterclass
|
/section-4/examples/guessinggame6.py
| 507
| 4.1875
| 4
|
#!/usr/bin/env python
import random
highest = 10
answer = random.randint(1, highest)
is_done = False
while not is_done:
# obtain user input
guess = int(input("Please enter a number between 1 and {}: ".format(highest)))
if guess == answer:
is_done = True
print("Well done! The correct answer is {}".format(answer))
else:
suggestion = "Please guess higher" if guess < answer else "Please guess lower"
print(f"Sorry, your guess is incorrect. {suggestion}")
| true
|
3d1946247a3518c4bd2128786609946be2ae768c
|
shamim-ahmed/udemy-python-masterclass
|
/section-4/exercises/exercise11.py
| 638
| 4.21875
| 4
|
#!/usr/bin/env python3
def print_option_menu(options):
print("Please choose your option from the list below:\n")
for i, option in enumerate(options):
print("{}. {}".format(i, option))
print()
if __name__ == "__main__":
options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have dinner", "Go to bed"]
print_option_menu(options)
done = False
while not done:
choice = int(input())
if choice == 0:
done = True
elif 0 < choice < len(options):
print("You have entered {}".format(choice))
else:
print_option_menu(options)
| true
|
bcd6ddba72d2fe2c22112c11f6dbea95fe536d37
|
shamim-ahmed/udemy-python-masterclass
|
/section-12/examples/example_kwargs.py
| 323
| 4.3125
| 4
|
#!/usr/bin/env python
def print_keyworded_arguments(arg1, **kwargs):
print("arg1 = {}".format(arg1))
for key, value in kwargs.items():
print("{} = {}".format(key, value))
# you can mix keyworded args with non-keyworded args
print_keyworded_arguments("Hello", fruit="Apple", number=10, planet="Jupiter")
| false
|
047b6808f400db0906409e22fb7e3897f9bda51a
|
kirillrssu/pythonintask
|
/PMIa/2014/Samovarov/task_3_17.py
| 810
| 4.1875
| 4
|
#Задача №3, Вариант 7
#Напишите программу, которая выводит имя "Симона Руссель", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Samovarov K.
#25.05.2016
print("Герой нашей сегодняшней программы - Симона Руссель")
psev=input("Под каким же именем мы знаем этого человека? Ваш ответ:")
if (psev)==("Мишель Морган"):
print ("Все верно: Симона Руссель - "+psev)
else:
print("Вы ошиблись, это не его псевдоним.")
input(" Нажмите Enter для выхода")
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.