blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
b1868ddb16d474b647edabf6aa4d8233a6d6fde4
|
yshshadow/Leetcode
|
/101-150/103.py
| 1,115
| 4.15625
| 4
|
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level order traversal as:
# [
# [3],
# [20,9],
# [15,7]
# ]
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.zigzag(root, res, 1)
for x in range(len(res)):
if x % 2 != 0:
res[x].reverse()
return res
def zigzag(self, root, res, level):
if not root:
return
if len(res) < level:
res.append([])
res[level - 1].append(root.val)
self.zigzag(root.left, res, level + 1)
self.zigzag(root.right, res, level + 1)
| true
|
584b822e45b7cb26ccb8e5cacc66cdb8eae399a4
|
yshshadow/Leetcode
|
/251-300/261.py
| 1,396
| 4.125
| 4
|
# Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
#
# Example 1:
#
# Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
# Output: true
# Example 2:
#
# Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
# Output: false
# Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
#
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
m = [[0 for _ in range(n)] for _ in range(n)]
for i, j in edges:
m[i][j] = 1
# m[j][i] = 1
visited = set()
visited.add(0)
def dfs(m, i):
for j, e in enumerate(m[i]):
if e == 0:
continue
if j in visited:
return False
visited.add(j)
if not dfs(m, j):
return False
return True
if not dfs(m, 0):
return False
if len(visited) != n:
return False
return True
s = Solution()
print(s.validTree(5,
[[0, 1], [0, 2], [0, 3], [1, 4]]))
| true
|
ee7a31838dbba2216f509bfd2a764b6d825cbe4a
|
jamiezeminzhang/Leetcode_Python
|
/_Google/282_OO_Expression_Add_Operators.py
| 1,717
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 10:57:57 2016
282. Expression Add Operators
Total Accepted: 7924 Total Submissions: 33827 Difficulty: Hard
Given a string that contains only digits 0-9 and a target value, return all possibilities
to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
*** My answer didn't consider the case of
"105", 5 -> ["1*0+5","10-5"]
that 105 could be regarded as 10 and 5
should not transcript into stack first
注意:包含前导0的运算数是无效的。
例如,通过"00+9"获得目标值9是不正确的。
@author: zzhang04
"""
class Solution(object):
def addOperators(self, num, target):
res, self.target = [], target
for i in range(1,len(num)+1):
if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
self.dfs(num[i:], num[:i], int(num[:i]), int(num[:i]), res) # this step put first number in the string
return res
def dfs(self, num, temp, cur, last, res):
if not num:
if cur == self.target:
res.append(temp)
return
for i in range(1, len(num)+1):
val = num[:i]
if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
self.dfs(num[i:], temp + "+" + val, cur+int(val), int(val), res)
self.dfs(num[i:], temp + "-" + val, cur-int(val), -int(val), res)
self.dfs(num[i:], temp + "*" + val, cur-last+last*int(val), last*int(val), res)
| true
|
f791001ef212e94de7adbf9df8df4812bc198622
|
jamiezeminzhang/Leetcode_Python
|
/others/073_Set_Matrix_Zeroes.py
| 1,863
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 28 10:55:49 2016
73. Set Matrix Zeroes
Total Accepted: 69165 Total Submissions: 204537 Difficulty: Medium
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
**** Constant space solution *******
class Solution(object):
def setZeroes(self, matrix):
m, n, first_row_has_zero = len(matrix), len(matrix[0]), not all(matrix[0])
for i in range(1,m):
for j in range(n):
if matrix[i][j] == 0:
matrix[i][0]=0
matrix[0][j]=0
for i in range(1,m):
for j in range(n-1,-1,-1):
# 这里希望最后再算第一列。如果0,0是0,那么希望第一列最后也变成0.
if matrix[i][0]==0 or matrix[0][j]==0:
matrix[i][j] = 0
if first_row_has_zero:
matrix[0] = [0]*n
@author: zeminzhang
"""
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m,n = len(matrix), len(matrix[0])
row,col = [],[]
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row.append(i)
col.append(j)
for i in row:
for j in range(n):
matrix[i][j] = 0
for i in col:
for j in range(m):
matrix[j][i] = 0
| true
|
3cf7f0e66b8c81c56c8b362fc05f000c243e9249
|
HimNG/CrackingTheCodeInterview
|
/2.2/2.2/_2.2.py
| 1,480
| 4.15625
| 4
|
class Node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist :
#count=0
def __init__(self):
self.head=None
def insert_at_begin(self,data):
node=Node(data)
node.next=self.head
self.head=node
# kth last element with recursive method
def kth_last_element_recursive(self,current,k):
if current.next==None :
return 1
else:
count=self.kth_last_element_recursive(current.next,k) + 1
if count==k :
print(current.data)
return count
# kth last element with non-recursive method
def kth_last_element_non_recursive(self,k):
temp1,temp2,count=self.head,self.head,1
while count<k :
temp2=temp2.next
count=count+1
while temp2.next :
temp1=temp1.next
temp2=temp2.next
print(temp1.data)
#print all elements
def print_ll(self):
ll=self.head
while ll!=None :
print(ll.data,end=" ")
ll=ll.next
print("")
if __name__ == '__main__' :
llist=linkedlist()
llist.insert_at_begin(10)
llist.insert_at_begin(14)
llist.insert_at_begin(15)
llist.insert_at_begin(1)
llist.insert_at_begin(6)
llist.print_ll()
llist.kth_last_element_recursive(llist.head,3)
llist.kth_last_element_non_recursive(4)
| false
|
442531f67bbcb62c307af612b26aa1d4d12d5bcf
|
gkalidas/Python
|
/practice/censor.py
| 658
| 4.3125
| 4
|
#Write a function called censor that takes two strings, text and word, as input.
#It should return the text with the word you chose replaced with asterisks.
#For example:
#censor("this hack is wack hack", "hack")
#should return:
#"this **** is wack ****"
#Assume your input strings won't contain punctuation or upper case letters.
#The number of asterisks you put should correspond to the number of letters in the censored word.
def censor(text,word):
text = text.split(" ")
for char in range(0,len(text)):
if text[char]==word:
text[char] = len(text[char]) * "*"
else:
text[char]=text[char]
text = " ".join(text)
return text
| true
|
6ae7d434d182efebea2ee20dd122860f6bafde8b
|
TamaraJBabij/ReMiPy
|
/dictOps.py
| 550
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
# Applies a function to each value in a dict and returns a new dict with the results
def mapDict(d, fn):
return {k: fn(v) for k,v in d.items()}
# Applies a function to each matching pair of values from 2 dicts
def mapDicts(a, b, fn):
return {k: fn(a[k], b[k]) for k in a.keys()}
# Adds matching values from 2 dicts with the same keys
def addDicts(a,b):
return mapDicts(a, b, lambda x, y: x + y)
# Multiply all values in a dict by the same constant
def multiplyDict(d, c):
return mapDict(d, lambda x: x * c)
| true
|
d6dffc62229cbd1851ed4bfd7b3244313576eb59
|
elim168/study
|
/python/basic/function/09.partial_test.py
| 404
| 4.15625
| 4
|
# 测试partial函数
# functools的partial函数可以把一个函数的某些参数固定住,然后返回新的函数。比如下面把int函数的base参数固定为2返回new_int函数,之后new_int都以二进制对字符串进行整数转换。
import functools
new_int = functools.partial(int, base=2)
print(new_int('111')) # 7
print(new_int('1110')) # 14
print(new_int('1110101')) # 117
| false
|
dccdeed268be18dba9142290de732b5e20ad30c8
|
elim168/study
|
/python/basic/numpy/test02_array.py
| 498
| 4.125
| 4
|
import numpy
# 创建一维的数组,基于一维的列表
ndarray = numpy.array([1, 2, 3, 4, 5, 6])
print(ndarray)
print(type(ndarray)) # <class 'numpy.ndarray'>
# 创建二维的数组,基于二维的列表。三维/四维等也是类似的道理
ndarray = numpy.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]])
print(ndarray)
# 通过ndmin指定最小维度
ndarray = numpy.array([1, 2, 3], ndmin=5) # 指定创建的数组最小为5维
print(ndarray) # [[[[[1 2 3]]]]]
| false
|
085f60472146523cbf36d36e75ba002cba379e10
|
nachoba/python
|
/introducing-python/003-py-filling.py
| 2,302
| 4.59375
| 5
|
# Chapter 3 : Py Filling: Lists, Tuples, Dictionaries, and Sets
# ------------------------------------------------------------------------------
# Before started with Python's basic data types: booleans, integers, floats, and
# strings. If you thinks of those as atoms, the data structures in this chapter
# are like molecules. That's, we combine those basic types in more complex ways.
# Lists and Tuples
# ----------------
# Most computer languages can represent a sequence of items indexed by their in-
# teger position: first, second, and so on down to the last.Python's strings are
# sequences, sequences of characters.
# Python has two other sequence structures: tuples and lists. These contain zero
# or more elments. Unlike strings, the elements can be of different types.
# In fact, each element can be any Python object. This lets you create struc-
# tures as deep and complex as you like.
# The difference between lists and tuples is that tuples are immutable; when you
# assign elements to a tuple, they can't be changed.
# Lists are mutable, meaning you can insert and delete elements.
# Lists
# -----
# Lists are good for keeping track of things by their order, especially when the
# order and contents might change. Unlike strings, lists are mutable.You can add
# delete, and remove elements.
# Create with [] and list()
# -------------------------
# A list is made from zero or more elements, separated by commas, and surrounded
# by square brackets:
empty_list = [ ]
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
big_birds = ['emu', 'ostrich', 'cassowary']
first_names = ['Graham', 'John', 'Terry', 'Terry', 'Michael']
# You can also make an empty list with the "list()" function:
another_empty_list = list()
# In a list values do not need to be unique. If you know you only want to keep
# track of unique values and do not care about order, a Python "set" might be a
# better choice than a list.
print(weekdays)
print(another_empty_list)
# Conver other Data Types to Lists with list()
# --------------------------------------------
# Python's "list()" function, converts other data types to lists:
cat_list = list('cat')
print(cat_list)
# This example converts a tuple to a list:
a_tuple = ('ready', 'fire', 'aim')
print(list(a_tuple))
| true
|
37eb9929352029c4ae42099cda1d8b29103a9f9d
|
myke-oliveira/curso-em-video-python3
|
/desafio22.py
| 734
| 4.40625
| 4
|
''' Crie um programa que leia o nome completo de uma pessoa e mostre:
O nome com todas as letras maiúsculas.
O nome con todas minusculas.
Quantas letras ao todo (sem considerar espaços).
Quantas letras tem o primeiro nome.'''
print('Digite o nome completo da pessoa: ')
nome = input().strip()
print()
print('O nome com todas as letras maiúsculas:')
print(nome.upper())
print()
print('O nome com todas as letras minúsculas: ')
print(nome.lower())
print()
print('Quantas letras ao todo (sem considerar os pespaços): {}'.format(len(nome.replace(' ', ''))))
# len(nome) - nome.count(' ')
print()
print('Quantas letras tem o primeiro nome: {}'.format(len(nome.split()[0])))
# Método Guanabara
# nome.find(' ')
| false
|
209d380eeb75040a3911371e2b1297f210c66adb
|
berketuna/py_scripts
|
/reverse.py
| 253
| 4.40625
| 4
|
def reverse(text):
rev_str = ""
for i in range(len(text)):
rev_str += text[-1-i]
return rev_str
while True:
word = raw_input("Enter a word: ")
if word == "exit":
break
reversed = reverse(word)
print reversed
| true
|
e1752393679416438c2c0c1f1d4015d3cc776f58
|
Jaredbartley123/Lab-4
|
/Lab 4.1.3.8.py
| 783
| 4.21875
| 4
|
#lab 3
def isYearLeap(year):
if year < 1582:
return False
elif year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
def daysInMonth(year, month):
leap = isYearLeap(year)
if leap and month == 2:
return 29
elif month == 2:
return 28
elif month == 4 or month == 6 or month == 9 or month == 11:
return 30
else:
return 31
def dayOfYear(year, month, day):
dayInYear = 0
for days in range (month - 1):
dayInYear += daysInMonth(year, days+1)
dayInYear += day
return(dayInYear)
print(dayOfYear(2000, 12, 31))
| true
|
a8d29b3e2247885d8dd9648343f7b0ba27b83a4f
|
sathappan1989/Pythonlearning
|
/Empty.py
| 579
| 4.34375
| 4
|
#Starting From Empty
#Print a statement that tells us what the last career you thought of was.
#Create the list you ended up with in Working List, but this time start your file with an empty list and fill it up using append() statements.
jobs=[]
jobs.append('qa')
jobs.append('dev')
jobs.append('sm')
jobs.append('po')
print(jobs)
#Print a statement that tells us what the first career you thought of was.
print('first carrer '+ jobs[0].upper()+'!')
#Print a statement that tells us what the last career you thought of was.
print('first carrer '+ jobs[-1].upper()+'!')
| true
|
f04c7247ba0b372240ef2bc0f118f340b0c9054b
|
angela-andrews/learning-python
|
/ex9.py
| 565
| 4.28125
| 4
|
# printing
# Here's some new strange stuff, remember type it exactly.
# print the string on the same line
days = "Mon Tue Wed Thu Fri Sat Sun"
# print Jan on the same line as and the remaining months on new lines
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days: ", days)
print("Here are the months: ", months)
# this allows you to break your string up over multiple lines.
print("""
There's something going on here.
With the the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
| true
|
c73358f413572fdfa0e1f309c4d0e762e50c5ef2
|
angela-andrews/learning-python
|
/ex33.py
| 1,268
| 4.40625
| 4
|
# while loops
i = 0
numbers = []
while i < 6:
print(f"At the top is {i}")
numbers.append(i)
i = i + 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
# convert while-loop to a function
def test_loop(x):
i = 0
numbers = []
while i < x:
print(f"At the top is {i}")
numbers.append(i)
i = i + 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
test_loop(11)
#===============================================
def test_loop2(x, y):
i = 0
numbers = []
while i < x:
print(f"At the top is {i}")
numbers.append(i)
i = i + y
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
test_loop2(29,5)
#======================================
# testing out turning a while into a for using a range
def test_loop3(y):
numbers = []
numbers = list(range(y))
print(numbers)
for i in numbers:
print(f"Range made it easy to create a list of numbers: {i}")
test_loop3(26)
| true
|
49bb1b18646aa0aad8ec823f7206ccb08709e36a
|
rojit1/python_assignment
|
/q9.py
| 247
| 4.375
| 4
|
# 9. Write a Python program to change a given string to a new string where the first
# and last chars have been exchanged.
def exchange_first_and_last(s):
new_s = s[-1]+s[1:-1]+s[0]
return new_s
print(exchange_first_and_last('apple'))
| true
|
62ed4994bb2ff26ee717f135a50eddff151e0643
|
rojit1/python_assignment
|
/q27.py
| 298
| 4.21875
| 4
|
# 27. Write a Python program to replace the last element in a list with another list.
# Sample data : [1, 3, 5, 7, 9, 10], [2, 4, 6, 8]
# Expected Output: [1, 3, 5, 7, 9, 2, 4, 6, 8]
def replace_last(lst1, lst2):
return lst1[:-1]+lst2
print(replace_last([1, 3, 5, 7, 9, 10], [2, 4, 6, 8]))
| true
|
4f9ff83562f99c636dee253b7bfdbac93f46facc
|
rojit1/python_assignment
|
/functions/q3.py
| 263
| 4.46875
| 4
|
# 3. Write a Python function to multiply all the numbers in a list.
# Sample List : (8, 2, 3, -1, 7)
# Expected Output : -336
def multiply_elements(lst):
ans = 1
for i in lst:
ans *= i
return ans
print(multiply_elements([8, 2, 3, -1, 7]))
| true
|
7b0614ad3f05e76bb8ca6400bc9e230f130c3d5e
|
xala3pa/Introduction-to-Computer-Science-and-Programming-with-python
|
/week4/Problems/L6PROBLEM2.py
| 960
| 4.1875
| 4
|
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
ans = ()
index = 1
for c in aTup:
if index % 2 != 0:
ans += (c,)
index += 1
return ans
def oddTuples2(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
# a placeholder to gather our response
rTup = ()
index = 0
# Idea: Iterate over the elements in aTup, counting by 2
# (every other element) and adding that element to
# the result
while index < len(aTup):
rTup += (aTup[index],)
index += 2
return rTup
def oddTuples3(aTup):
'''
Another way to solve the problem.
aTup: a tuple
returns: tuple, every other element of aTup.
'''
# Here is another solution to the problem that uses tuple
# slicing by 2 to achieve the same result
return aTup[::2]
| true
|
6b588b64560ceacfba4cbe1676eae2d565a28358
|
bshep23/Animation-lab
|
/Animation.py
| 1,388
| 4.15625
| 4
|
# -------------------------------------------------
# Name: Blake Shepherd and Lilana Linan
# Filename: Animation.py
# Date: July 31th, 2019
#
# Description: Praticing with animation
#
# -------------------------------------------------
from graphics import *
import random
class Fish:
"""Definition for a fish with a body, eye, and tail"""
def __init__(self, win, position):
"""constructs a fish made of 1 oval centered at `position`,
a second oval for the tail, and a circle for the eye"""
red = random.randint(0,255)
green = random.randint(0,255)
blue = random.randint(0,255)
# body
p1 = Point(position.getX()-40, position.getY()-20)
p2 = Point(position.getX()+40, position.getY()+20)
self.body = Oval( p1, p2 )
self.body.setFill(color_rgb(red, green, blue))
# tail
p1 = Point(position.getX()+30, position.getY()-30)
p2 = Point(position.getX()+50, position.getY()+30)
self.tail = Oval( p1, p2 )
self.tail.setFill( "black" )
# eye
center2 = Point( position.getX()-15, position.getY()-5 )
self.eye = Circle( center2, 5 )
self.eye.setFill( "black" )
def draw( self, win ):
"""draw the fish to the window"""
self.body.draw( win )
self.tail.draw( win )
self.eye.draw( win )
x = GraphWin("Hello", 600 , 400)
Bob = Fish(x, Point(300,200))
Bob.draw(x)
| true
|
baefdc82a2d2af26940678bd040c871350cc6a77
|
swang2017/python-factorial-application
|
/factorial.py
| 390
| 4.15625
| 4
|
try:
input_number = int(raw_input("please enter an integer\n"))
except ValueError:
print("Hey you cannot enter alphabets")
except FileNotFound:
print("File not found")
else:
print("no exceptions to be reported")
# result = 1
# for index in range (1, input_number+1):
# result = result * index
#
# print("The factorial of " + str(input_number) + " is " + str(result))
| true
|
2b7470c9569abd1a45a8ab79b20e9f82418dc941
|
savithande/Python
|
/strings1.py
| 1,290
| 4.4375
| 4
|
# single quote character
str = 'Python'
print(str)
# fine the type of variable
print(type(str))
print("\n")
# double quote character
str = "Python"
print(str)
# fine the type of variable
print(type(str))
print("\n")
# triple quote example
str = """Python"""
print(str)
# fine the type of variable
print(type(str))
print("\n")
# methods of string
# 1) finding the index value
string = "Python"
print("Python".index("t"))
print("Python_programing_language".index("_"))
print ("\n")
# join the list of strings by using join condition
combine_string = "%".join(["1","2","3"])
print(combine_string)
print("\n")
# split the string based on the condition by using the split()
print("1:2:3:4".split(":"))
print("1 2 3 4".split(" "))
print("1,2,3,4,5,6".split(","))
print("\n")
# accessing the individual character in the string
# by using the index values of the given string
# the python index value stating with "0"
string = "Python"
print(string[4])
print(string[0])
print("\n")
# formatting methods usage examples
print("hii, my name is %s" % ("Python"))
print("%s is a one of the %s language" % ("Python","scripting"))
print("\n")
# truth value testing of string using boolean(bool) keyword
print(bool("")) # '0' argument method
print(bool("Python")) # with argument method
| true
|
5cd3edd9cbce8aa65769a8dd142828c072390537
|
jovian34/j34_simple_probs
|
/elementary/07mult_table/mult_table.py
| 372
| 4.1875
| 4
|
# http://adriann.github.io/programming_problems.html
# Write a program that prints a multiplication table for numbers up to 12.
multi_table_12 = []
for x in range(1, 13):
multi_table_row = []
for y in range(1, 13):
multi_table_row.append(x * y)
multi_table_12.append(multi_table_row)
for i in range(len(multi_table_12)):
print(multi_table_12[i])
| false
|
a2fb730cc784a3720dc845069b9a0e1a4821adbe
|
jovian34/j34_simple_probs
|
/elementary/05sum_multiples/sum_of_multiples.py
| 1,239
| 4.1875
| 4
|
# http://adriann.github.io/programming_problems.html
# Write a program that asks the user for a number n and prints
# the sum of the numbers 1 to n
# Modify the previous program such that only multiples of three or
# five are considered
# in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
def get_number_from_user():
print('Enter a number: ', end='')
return input()
def sum_range(number):
sum_total = 0
for i in range(1, number + 1):
print(i, end='')
sum_total = sum_total + i
print('...{}'.format(sum_total))
return sum_total
def sum_range_of_multiples(number):
sum_total = 0
for i in range(1, number + 1):
if i % 3 == 0 or i % 5 == 0:
sum_total = sum_total + i
print('{} ... {}'.format(i, sum_total))
return sum_total
def main():
user_number = get_number_from_user()
try:
user_number = int(user_number)
except:
print('This program only works on integer values.')
print('Please try again')
return main()
sum_num = sum_range_of_multiples(user_number)
print('The sum of the multiple of 3 and 5 from 1 to '
'{} is {}.'.format(user_number, sum_num))
if __name__ == '__main__':
main()
| true
|
b29e7eba5620eb7d8c54715543b62cae65aaeee4
|
yashgugale/Python-Programming-Data-Structures-and-Algorithms
|
/NPTEL Course/Concept Practices/inplace_scope_exception2.py
| 1,222
| 4.1875
| 4
|
L1 = [10, 20 ,30]
print("Global list L: ", L1)
def f1():
L1[2] = 500
print("L1 from function on in place change is is: ", L1)
print("\nShallow copy of L1 to L2")
L2 = L1
L2.append(600)
print("Lists L1 and L2 are: L1:", L1, "L2: ", L2)
print("\nDeep copy of L1 to L3")
L3 = L1.copy()
L3.append(700)
print("Lists L1 and L3 are: L1:", L1, "L3: ", L3)
f1()
print("\nGlobally L1 after all the changes is: ", L1)
# how can we, from a local function without using a 'global' or a 'nonlocal'
# change the value of a LIST used globally?
# It is true for both dimensions of mutability: 1. in place change 2. grow/shrink, so,
# is this property applicable to all mutable data types? List, Dict, Set?
S = { 10, 20, 30}
print("\nThe global value of set S", S)
def f2():
S.add(400)
print("The values of set S are: ", S)
f2()
print("The value of set S after function f2 is: ", S)
D = { 'a' : 10, 'b' : 20, 'c' : 30}
print("\nThe dictionary is: ", D)
def f3():
D.update({'d' : 40})
print("The value of dict D is: ", D)
f3()
print("The value of dict D after function f3 is: ", D)
# as we can see, we are able to do do without using 'global' or 'nonlocal'
# why does this work?
| true
|
bcae10b007172a57dac0121a7a84feff564c60d6
|
nguyeti/mooc_python_10_app
|
/date_time.py
| 790
| 4.34375
| 4
|
from datetime import datetime, timedelta
import time
# Basic date operation
now = datetime.now()
yesterday = now - timedelta(days=1)
lastYear = datetime(2016,3,8,0,0,0,0) # create a datime object with (year, month, day, hour, minute, seconds, milliseconds)
print(str(now))
print(str(yesterday) + ' ***** \n')
# convert a date string into an datetime object
datestr = "2017-03-07"
date = datetime.strptime(datestr,"%Y-%m-%d")
print(str(date) + ' ***** \n')
def create_file(filename):
"""Create an empty file with datetime as filename"""
with open(filename.strftime('%Y%m%d_%H-%M-%S.%f') + ".txt","w") as file:
file.write('')
#create_file(now)
#use of time object
list =[]
for i in range(3):
list.append(datetime.now())
time.sleep(1)
for i in list:
print(i)
| false
|
9e750b872b0d154f74f64353e71b0bdeb7e4f122
|
nguyeti/mooc_python_10_app
|
/OOP/example.py
| 1,880
| 4.21875
| 4
|
class Machine:
def __init__(self):
print("I am a Machine")
class DrivingMachine(Machine):
def __init__(self):
print("I am a DrivingMachine")
def start(self):
print("Machine starts")
class Bike(DrivingMachine):
def __init__(self, brand, color):
self.brand = brand # __attrName > makes it private
self.color = color
print("I am a Bike")
def start(self):
print("Override : Bike starts")
def getattr(self, name):
return self.name
class Car(DrivingMachine):
def __init__(self, brand, color):
self.__color = color # __attrName > makes it private Can't be seen and accessed from outside
self._brand = brand # _A > makes it protected Like a public member, but they shouldn't be directly accessed from outside.
print("I am a Car")
def start(self):
print("Override : car starts")
def changeColor(self, color):
self.__color = color
# machine = Machine()
# d = DrivingMachine()
# bike = Bike("Suzuki", "red")
# car = Car("Toyota", "black")
# d.start() # calls the parent's start() method
# bike.start()
# car.start()
#
# print("Bike : " + bike.brand + " : " + bike.color)
# print("Bike : " + getattr(bike,"brand") + " : " + getattr(bike,"color"))
# print(hasattr(bike, "color"))
# setattr(bike, "color", "yellow")
# print("Bike : " + getattr(bike,"brand") + " : " + getattr(bike,"color"))
# # print(issubclass(Bike,Machine))
# # print(issubclass(Bike,DrivingMachine))
# # print(isinstance(bike,Machine))
# # print(isinstance(bike,DrivingMachine))
#
# # print("Car : " + car.brand + " : " + car.color) # AttributeError: 'Car' object has no attribute 'brand'
# # print("Car : " + getattr(car, "brand") + " : " + car.color) # pareil fonctionne pas
# print("Car :" + car._Car__color)
# car._Car__color ="purple"
# print("Car :" + car._Car__color)
| true
|
eb2b71845ab019e7fa8131669bf3777e6d93c3d5
|
nguyeti/mooc_python_10_app
|
/ex1_c_to_f.py
| 541
| 4.1875
| 4
|
"""
This script converts C temp into F temp
"""
# def celsiusToFahrenheit(temperatureC):
# if temperatureC < -273.15:
# print("That temperature doesn't make sense!")
# else:
# f = temperatureC * (9/5) + 32
# return f
temperatures = [10, -20, -289, 100]
def writer(temperatures):
"""This is the function to convert C into F"""
with open("example.txt",'w') as file:
for c in temperatures:
if c > -273.15:
f = c * (9/5) + 32
file.write(str(f) + "\n")
| true
|
1f90807c81934fd38d38dd8bd5e42102813efa86
|
c18441084/Python
|
/Labtest1.py
| 1,056
| 4.375
| 4
|
#Function to use Pascal's Formula
def make_new_row(old_row, limit):
new_row = []
new_list = []
L=[]
i=0
new_row = old_row[:]
while i < limit:
new_row.append(1)
long = len(new_row) - 1
j=0
h=0
if i ==0:
new_list = new_row[:]
#Print list of lists
print("Printing list of lists, one list at a time: ")
print(old_row)
#Formula for Pascal Triangle
for j in range(new_row[0], long):
new_row[j]= new_list[h] + new_list[h+1]
j = j+1
h = h+1
new_list = new_row[:]
#Printing lists
print(new_row)
#Adding list into whole lists
L.append(new_row)
i=i+1
print("Print whole list of lists: ")
print(L)
#Asking user for height of triangle
ans = input("Enter the desired height of Pascal's triangle: ")
lim = int(ans)
old_row = [1,1]
#Sending the row and limit to the function
make_new_row(old_row, lim)
| true
|
d0092057d615ba0067f48a07be80c37e423b0cd9
|
bachns/LearningPython
|
/exercise24.py
| 278
| 4.3125
| 4
|
# Write a Python program to test whether a passed letter is a vowel or not.
def isVowel(v):
vowels = ("u", "e", "o", "a", "i")
return v in vowels
vowel = input("Enter a letter: ")
if isVowel(vowel):
print("This is a vowel")
else:
print("This isn't a vowel")
| true
|
ece0d3f409b258a7a098917b0a865f2569c8eb10
|
bachns/LearningPython
|
/exercise27.py
| 255
| 4.15625
| 4
|
# Write a Python program to concatenate all elements in a list into
# a string and return it
def concatenate(list):
conc_str = ""
for number in list:
conc_str += str(number)
return conc_str
print(concatenate([3, 4, 1000, 23, 2]))
| true
|
60fe76e0b3bd43e87dde6e7e7d77ad4d5108c326
|
bachns/LearningPython
|
/exercise7.py
| 315
| 4.25
| 4
|
# Write a Python program to accept a filename from the user and print
# the extension of that.
# Sample filename : abc.java
# Output : java
filename = input("Enter file name: ")
parts = filename.rsplit(".", 1)
print("Extension:" + parts[-1])
index = filename.rfind(".") + 1
print("Extension:" + filename[index:])
| true
|
c3a0e29d457803d6bbae306b86c2ed98e476d77d
|
bachns/LearningPython
|
/exercise21.py
| 334
| 4.25
| 4
|
# Write a Python program to find whether a given number (accept from the user)
# is even or odd, print out an appropriate message to the user
def check_number(number):
if number % 2:
return "This is an odd number"
return "This is an even number"
number = int(input("Enter a number: "))
print(check_number(number))
| true
|
a2bc4a35e26f590c738178bdaffac36e42b56993
|
hitendrapratapsingh/python_basic
|
/user_input.py
| 229
| 4.28125
| 4
|
# input function
#user input function
name = input("type your name")
print("hello " + name)
#input function type alwase value in string for example
age = input("what is your age") #because herae age is string
print("age: " + age)
| true
|
750900f9be03aac96ec39601a667b6c3948c0ad3
|
injoon5/C3coding-python
|
/2020/04/22/02.py
| 388
| 4.125
| 4
|
height =int(input("your height : "))
if height<110:
print("Do not enter!")
if height>= 110:
print("have a nice time!")
if height == 110:
print("perfect!")
if height != 110:
print("Not 110.")
if 100 <= height <110:
print("Next year~")
print("Booltype = ", height< 110,height >= 110, height == 110)
print("Booltype =", height != 110, 100 <= height < 110)
| true
|
c1a3c8305447e8ef79212e07731b4744759074f7
|
shakibaSHS/pythonclass
|
/s3h_1_BMI.py
| 245
| 4.15625
| 4
|
weight = int(input('input your weight in kg\n weight='))
height = float(input('input your height in meter\n height='))
def BMI(weight , height):
B = weight / (height ** 2)
return B
print(f'Your BMI is= {BMI(weight , height)}')
| true
|
b2b54b45e806acff0d0d7efee18c0bf5b6b4d0b0
|
abhishek5135/Python_Projects
|
/snakewatergun.py
| 1,550
| 4.125
| 4
|
import time
import random
def turn(num):
player_1=0
player_2=0
listcomputer=['snake','water','gun']
computer=random.choice(listcomputer)
num2=0
while(num2!=num):
print("snake","water","gun")
players_inpu = input("Player 1 Enter your choice from above ")
print(f"computer choice {computer}")
if(computer=='snake' and players_inpu=='water'):
player_2+=1
elif (computer=='gun' and players_inpu=='water'):
player_1+=1
elif(computer=='water' and players_inpu=='water'):
print("Turn draw")
elif(computer=='gun' and players_inpu=='snake'):
player_2+=1
elif (computer=='water' and players_inpu=='snake'):
player_1+=1
elif(computer=='snake' and players_inpu=='snake'):
print("Turn draw")
elif(computer=='snake' and players_inpu=='gun'):
player_1+=1
elif (computer=='water' and players_inpu=='gun'):
player_2+=1
elif(computer=='gun' and players_inpu=='gun'):
print("Turn draw")
num2+=1
if(player_1>player_2):
print("You are winner of This game ")
elif (player_2>player_1):
print("You lose the game")
print("Better luck next time")
if __name__ == "__main__":
start=time.time()
num3=int(input("Enter how Turns you want to play "))
turn(num3)
end=time.time()
print(f"Runtime of the program is {end - start}")
| true
|
16cf1423d8a7840f49b7ad206f0f8b9f5104a514
|
meet29in/Sp2018-Accelerated
|
/students/mathewcm/lesson04/trigrams.py
| 1,217
| 4.125
| 4
|
#!/usr/bin/env Python
"""
trigrams:
solutions to trigrams
"""
sample = """Now is the time for all good men to come to the aid of the country"""
import sys
import random
words = sample.split()
print(words)
def parse_file(filename)
"""
parse text file to makelist of words
"""
with open(filename) as infile:
words = []
for line in infile:
print(line)
wrds = line.strip().split()
# print(wrds)
words.extend(wrds)
return words
def build_trigram(words):
tris = {}
for i in range(len(words) - 2):
first = words[i]
second = words[i + 1]
third = words[i + 2]
# print(first, second, third)
tris[(first, second)] = [third]
# print(tris)
return tris
def make_new_text(trigram)
pair = random.choice(list(trigram.keys()))
sentence = []
sentence.extend(pair)
for i in range(10):
followers = trigram[pair]
sentence.append(random.choice(followers))
pair = tuple(sentence[-2])
print(pair)
return sentence
if __name__ == "__main__"
words = parse_file("sherlock_small.txt")
print(words)
# trigram = build_trigram(words)
| true
|
3580488590a479d85b7e0bce53567e00608b2d61
|
ShadowStorm0/College-Python-Programs
|
/day_Of_The_Week.py
| 824
| 4.34375
| 4
|
#Day of Week List
Week = ['I can only accept a number between 1 and 7. Please try again.', 'Sunday', 'Monday', 'Tuesday', 'Wedensday', 'Thursday', 'Friday' ,'Saturday']
#Introduce User to Program
print('Day of the Week Exercise')
print('Enter a number for the day of the week you want displayed.')
#Input prompt / Input Validation
while True:
try:
#User Input
userInput = int(input("(Days are numbered sequentially from 1 - 7, starting with Sunday.): "))
#Check if Number
except ValueError:
print("I can only accept a number between 1 and 7. Please try again.\n")
continue
else:
#Check if in Range
if (userInput < 0 or userInput > 7):
print("I can only accept a number between 1 and 7. Please try again.\n")
continue
break
#Output
print(Week[userInput])
| true
|
4dcaabf16d2a0e0354d9954ee3b05306f19d1591
|
goonming/Programing
|
/5_9.py
| 504
| 4.40625
| 4
|
#creating and accessing and modifying a dict
#ereate and print Dict
emptyDict={}
print "the value of emptyDict is :", emptyDict
#creat and print Dict with initial values
Dict={'Name':'chenming','age':100}
print "this is chen ming: ", Dict
#accessing and modifying the Dict
age_2= raw_input("please input a age: ")
Dict['age']=int(age_2)
print Dict
print "delete///"
del Dict['age']
print "the Dict after deleting: ", Dict
print "add////"
Dict['height']= 190
print "the Dict after adding is : ", Dict
| false
|
1eb61779347687b166f28a48fb2a69747482c8fe
|
LuckyLub/crashcourse
|
/test_cc_20190305.py
| 2,316
| 4.3125
| 4
|
'''11-1. City, Country: Write a function that accepts two parameters: a city name
and a country name. The function should return a single string of the form
City, Country , such as Santiago, Chile . Store the function in a module called
city _functions.py.
Create a file called test_cities.py that tests the function you just wrote
(remember that you need to import unittest and the function you want to test).
Write a method called test_city_country() to verify that calling your function
with values such as 'santiago' and 'chile' results in the correct string. Run
test_cities.py, and make sure test_city_country() passes.
11-2. Population: Modify your function so it requires a third parameter,
population . It should now return a single string of the form City, Country –
population xxx , such as Santiago, Chile – population 5000000 . Run
test_cities.py again. Make sure test_city_country() fails this time.
Modify the function so the population parameter is optional. Run
test_cities.py again, and make sure test_city_country() passes again.
Write a second test called test_city_country_population() that veri-
fies you can call your function with the values 'santiago' , 'chile' , and
'population=5000000' . Run test_cities.py again, and make sure this new test
passes.
'''
import unittest
import cc_20190305
class TestPlace(unittest.TestCase):
def setUp(self):
self.employee1 = cc_20190305.Employee("Mark", "Moerman", "100000")
def test_if_2_strings_are_joined_together(self):
self.assertEqual(cc_20190305.place("Santiago","Chile"),"Santiago, Chile")
def test_if_population_can_be_added_to_description(self):
self.assertEqual(cc_20190305.place("Santiago", "Chile", 5000000), "Santiago, Chile - population 5000000")
def test_if_raise_method_adds_5000_to_annual_salary(self):
expected_outcome = self.employee1.annual_salary + 5000
self.employee1.give_raise()
self.assertEqual(self.employee1.annual_salary, expected_outcome)
def test_if_raise_method_adds_user_defined_raise_to_annual_salary(self):
user_defined_raise = 30000
expected_outcome = self.employee1.annual_salary + user_defined_raise
self.employee1.give_raise(user_defined_raise)
self.assertEqual(self.employee1.annual_salary, expected_outcome)
| true
|
c4a6190da0cdbfc05b981df0e3db311bc1ca8ec7
|
yashsf08/project-iNeuron
|
/Assignment2-python/program-one.py
| 481
| 4.1875
| 4
|
"""
1. Create the below pattern using nested for loop in Python.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
from math import ceil
def draw_pattern(data):
upper_limit = ceil(data/2)
print(upper_limit)
lower_limit = 0
for i in range(upper_limit):
print('*'*(i+1))
for i in range(upper_limit-1,0,-1):
print('*'*i)
number = int(input("Dear User, provide number of lines for you wish to draw pattern: " ))
draw_pattern(number)
| true
|
251975745094bce828e72eb2571e38a470aae3a1
|
vladskakun/TAQCPY
|
/tests/TestQuestion12.py
| 595
| 4.125
| 4
|
"""
12. Concatenate Variable Number of Input Lists
Create a function that concatenates n input lists, where n is variable.
Examples
concat([1, 2, 3], [4, 5], [6, 7]) ➞ [1, 2, 3, 4, 5, 6, 7]
concat([1], [2], [3], [4], [5], [6], [7]) ➞ [1, 2, 3, 4, 5, 6, 7]
concat([1, 2], [3, 4]) ➞ [1, 2, 3, 4]
concat([4, 4, 4, 4, 4]) ➞ [4, 4, 4, 4, 4]
Notes
Lists should be concatenated in order of the arguments.
"""
def concat(*lists):
summ = []
for list1 in lists:
summ = summ + list1
return summ
a=[1,3,5]
b=[2,4,6]
c=[0,-1]
#print(concat(a,b,c))
| true
|
604eb41c794380ba4cc3b4542518b7246889f582
|
vladskakun/TAQCPY
|
/tests/TestQuestion19.py
| 918
| 4.5
| 4
|
"""
19. Oddish vs. Evenish
Create a function that determines whether a number is Oddish or Evenish. A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the sum of all of its digits is even. If a number is Oddish, return "Oddish". Otherwise, return "Evenish".
For example, oddish_or_evenish(121) should return "Evenish", since 1 + 2 + 1 = 4. oddish_or_evenish(41) should return "Oddish", since 4 + 1 = 5.
Examples
oddish_or_evenish(43) ➞ "Oddish"
oddish_or_evenish(373) ➞ "Oddish"
oddish_or_evenish(4433) ➞ "Evenish"
"""
def oddish_or_evenish(num_num):
numbers_of_num = []
for i in range(0, len(str(num_num))):
numbers_of_num.append(num_num % 10)
num_num=num_num // 10
summ = 0
for number in numbers_of_num:
summ = summ + number
if summ % 2 == 0:
return 'Evenish'
else:
return 'Oddish'
| true
|
c86585ae6baf8cd8772c752f335e161ce6382f38
|
vladskakun/TAQCPY
|
/tests/TestQuestion24.py
| 753
| 4.15625
| 4
|
"""
24. Buggy Uppercase Counting
In the Code tab is a function which is meant to return how many uppercase letters there are in a list of various words. Fix the list comprehension so that the code functions normally!
Examples
count_uppercase(['SOLO', 'hello', 'Tea', 'wHat']) ➞ 6
count_uppercase(['little', 'lower', 'down']) ➞ 0
count_uppercase(['EDAbit', 'Educate', 'Coding']) ➞ 5
"""
def count_uppercase(data_list):
i = 0
rez = 0
while(i < len(data_list)):
j = 0
while(j < len(data_list[i])):
if data_list[i][j].isupper():
rez += 1
j += 1
i += 1
return rez
print(count_uppercase(['EDAbit', 'Educate', 'Coding']))
| true
|
bef9c39d7a11dbedc7633555a0b6c370384d737f
|
HakimZiani/Dijkstra-s-algorithm
|
/dijkstra.py
| 2,356
| 4.28125
| 4
|
#----------------------------------------------------------------------
# Implementation of the Dijkstra's Algorithm
# This program requires no libraries like pandas, numpy...
# and the graph DataStructure is a dictionary of dictionaries
#
# Created by [HakimZiani - zianianakim@gmail.com]
#----------------------------------------------------------------------
# the key in the graph dic is the node and the value is its neighbors
graph = {'A':{'B':1,'D':7},
'B':{'A':1,'C':3,'E':1},
'C':{'B':3,'D':2,'E':8},
'D':{'A':7,'C':2,'E':1},
'E':{'D':1,'E':8,'B':1},
}
def printGraph(graph):
for x , y in graph.items():
print(x + " in relation with : " + str(y))
printGraph(graph)
# Initialize the Start and End node
StartNode = input("Enter Start Node : ")
EndNode = input("Enter End Node : ")
# initList function for crating the queues of unvesited nodes
# and data
# The Structure is : {'node':[Distance,'prev-node']}
def initList(graph,StartNode,EndNOde):
d={}
for x in graph.keys():
if x == StartNode:
d[x] = [0,'']
else:
d[x] =[99999,'']
return d
# getMinimalValue function to return the label of the node that
# has the minimal value
def getMinimalValue(d):
min = 999999
a = 'ERROR' # to see if the value don't change
for x,y in d.items():
if y[0] < min:
a = x
min = y[0]
return a
d= initList(graph,StartNode,EndNode)
unvisited = initList(graph,StartNode,EndNode)
while(True):
#get the node to work with
focus = getMinimalValue(unvisited)
# Break if it's the destination
if focus == EndNode:
break
# Setting the Data queue
for x,y in graph[focus].items():
if d[x][0] > d[focus][0]+y:
d[x][0] = d[focus][0]+y
d[x][1] = focus
try:
unvisited[x][0] = unvisited[focus][0]+y
unvisited[x][1] = focus
except:
pass
del unvisited[focus]
road = []
node= EndNode
# d now contains the final data queue we need
# All we have to do is getting the right path from the EndNode
# to the StartNode using the prev states stored in d
while (node != StartNode):
road.append(node)
node = d[node][1]
road.append(StartNode)
# Showing the result
print("The shortest road is : "+"-->".join(reversed(road)))
| true
|
faa19462725653c83f971c0ca8717b085e16973d
|
eishk/Udacity-Data-Structures-and-Algorithms-Course
|
/P0/Task4.py
| 1,188
| 4.3125
| 4
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
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)
calls_caller = set()
calls_called = set()
texts_texter = set()
texts_texted = set()
for text in texts:
texts_texter.add(text[0])
texts_texted.add(text[1])
for call in calls:
calls_caller.add(call[0])
calls_called.add(call[1])
list = []
for call in calls_caller:
if (call not in calls_called and call not in texts_texted and call not in texts_texter):
list.append(call)
list.sort()
print("These numbers could be telemarketers: ")
for l in list:
print(l)
"""
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.
"""
| true
|
8318d4a5b9e442193b267dd7e045f60adabfe243
|
ramendra-singh/Practice
|
/DataStructure/Strings/secondMostChar.py
| 1,400
| 4.1875
| 4
|
'''
Program to find second most frequent character
Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string.
Examples:
Input: str = "aabababa";
Output: Second most frequent character is 'b'
Input: str = "geeksforgeeks";
Output: Second most frequent character is 'g'
Input: str = "geeksquiz";
Output: Second most frequent character is 'g'
The output can also be any other character with
count 1 like 'z', 'i'.
Input: str = "abcd";
Output: No Second most frequent character
A simple solution is to start from the first character, count its occurrences, then second character and so on. While counting these occurrence keep track of max and second max. Time complexity of this solution is O(n2).
We can solve this problem in O(n) time using a count array with size equal to 256 (Assuming characters are stored in ASCII format).
'''
def secondMostChar(input):
count = [0] * 256
for i in input:
count[ord(i)] += 1
max = -1
first = 0
second = 0
for i in range(256):
if count[i] > count[first]:
second = first
first = i
elif count[i] > count[second] and count[i] != count[first]:
second = i
for i in input:
if count[ord(i)] == count[second]:
print i
break
input = "aabababa"
secondMostChar(input)
| true
|
29791d166ecc57376e54f0ae83edebaae75acc2b
|
haema5/python_algorithms_and_structures
|
/hw07_01.py
| 932
| 4.125
| 4
|
# -*- coding: utf-8 -*-
# 1. Отсортировать по убыванию методом «пузырька» одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100). Вывести на экран исходный
# и отсортированный массивы.
from random import randint
MIN = -100
MAX = 99
ARRAY_LEN = 10
def bubble_sort(array):
n = 1
trigger = True
while trigger:
trigger = False
for i in range(len(array) - n):
if array[i] < array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
trigger = True
n += 1
return array
init_array = [randint(MIN, MAX) for _ in range(ARRAY_LEN)]
print(f'Исходный массив:\n\t{init_array} \nОтсортированный массив:\n\t{bubble_sort(init_array)}')
| false
|
be9b32579e460a7b44864ba89cd6161fbf03eff5
|
bmosc/Mindtree_TechFest_2015
|
/fractals/koch snow flake curve.py
| 879
| 4.125
| 4
|
#!/usr/bin/python
from turtle import *
def draw_fractal(length, angle, level, initial_state, target, replacement, target2, replacement2):
state = initial_state
for counter in range(level):
state2 = ''
for character in state:
if character == target:
state2 += replacement
elif character == target2:
state2 += replacement2
else:
state2 += character
state = state2
# draw
for character in state:
if character == 'F':
forward(length)
elif character == '+':
right(angle)
elif character == '-':
left(angle)
speed(0)
delay(0)
hideturtle()
# Lindenmayer Notation
# Koch Flake
up(); goto(-180, 60); down();
setup(1.0, 1.0)
draw_fractal(1, 60, 5, 'X++X++X', 'X', 'FX-FX++XF-XF', '', '')
exitonclick()
| true
|
ac68226a997c7c29a695f8a7f980010eeb5c2ae8
|
satyam4853/PythonProgram
|
/Functional-Programs/Quadratic.py
| 613
| 4.15625
| 4
|
"""
* Author - Satyam Vaishnav
* Date - 21-SEP-2021
* Time - 10:30 PM
* Title - Quadratic
"""
#cmath module using to compute the math function for complex numbers
import cmath
#initalize the variables taking from UserInput.
a=float(input("Enter the value of a: "))
b=float(input("Enter the value of b: "))
c=float(input("Enter the value of c: "))
#Math Formula for Quadratic Equation
delta= (b*b-(4*a*c))
#To finding Roots of equation
root1 = (-b+(cmath.sqrt(delta)))/(2*a)
root2 = (-b-(cmath.sqrt(delta)))/(2*a)
#Getting the vale of roots
print("Root1 of x is : ",root1)
print("Root2 of x is : ",root2)
| true
|
2c6536e36c175fde978191d7041a56f0320d8d15
|
WOWOStudio/Python_test
|
/Xin/game/maze_game/tortoise.py
| 1,531
| 4.1875
| 4
|
#小乌龟模型
from turtle import Turtle
class Tortoise(Turtle):
def __init__(self,maze_list,start_m,start_n,end_m,end_n):
Turtle.__init__(self)
self.maze_list = maze_list
self.m = start_m
self.n = start_n
self.end_m = end_m
self.end_n = end_n
self.hideturtle()
self.speed(0)
self.penup()
self.goto(self.n*20-120,120-self.m*20)
self.shape('turtle')
self.color('#28bea0')
self.setheading(270)
self.showturtle()
screen = self.getscreen()
screen.addshape('tortoise.gif')
def reach_exit(self, m, n):
if m == self.end_m and n == self.end_n:
self.shape('tortoise.gif')
def move(self,m,n):
self.m = m
self.n = n
self.goto(self.n*20-120,120-self.m*20)
self.reach_exit(m,n)
def go_up(self):
if self.canmove(self.m-1,self.n):
self.setheading(90)
self.move(self.m-1,self.n)
def go_down(self):
if self.canmove(self.m+1,self.n):
self.setheading(270)
self.move(self.m+1,self.n)
def go_left(self):
if self.canmove(self.m,self.n-1):
self.setheading(180)
self.move(self.m,self.n-1)
def go_right(self):
if self.canmove(self.m,self.n+1):
self.setheading(0)
self.move(self.m,self.n+1)
def canmove(self,m,n):
return self.maze_list[m][n] == 0
| false
|
e2c667ae64facebd8546107afb9b1774a9576914
|
Mayym/learnPython
|
/1-OOP/03.py
| 1,772
| 4.21875
| 4
|
class Student():
name = "May"
age = 20
def say(self):
self.name = "zym"
self.age = 22
print("My name is {0}.".format(self.name))
print("My age is {0}.".format(self.age))
def say_again(s):
print("My name is {0}.".format(s.name))
print("My age is {0}.".format(s.age))
may = Student()
may.say()
may.say_again()
print("*" * 20)
class Teacher():
name = "ym"
age = 23
def say(self):
self.name = "may"
self.age = 20
print("My name is {0}.".format(self.name))
print("My age is {0}.".format(self.age))
# 调用类的成员变量需要用__class__
print("My age is {0}.".format(__class__.age))
def say_again():
print(__class__.name)
print(__class__.age)
print("Hello, nice to see you again.")
t = Teacher()
t.say()
# t.say_again()报错,因为方法say_again()没有参数传入,但是该句会将实例t直接传入导致出错
# 调用绑定类函数时应使用类名
Teacher.say_again()
print("-" * 30)
# 关于self的案例
class A():
name = "Tom"
age = 18
def __init__(self):
self.name = "Max"
self.age = 20
def say(self):
print(self.name)
print(self.age)
class B():
name = "Bob"
age = 19
a = A()
# 此时,系统会默认把a作为第一个参数传入函数
a.say()
# A.say()会报错,因为A为类实例,系统无法默认将A作为参数传入__init__构造函数
# 此时,手动传入参数,self被a替换
A.say(a)
# 同样可以把A作为参数传入,此时打印的是类的属性
A.say(A)
# 此时,传入的是类实例B,因为B具有name和age属性,所以不会报错
A.say(B)
# 以上代码,利用了鸭子模型
| false
|
3b24e2a04e23058ab07b84286471a9fcb5df678e
|
luzonimrod/PythonProjects
|
/Lessons/MiddleEX1.py
| 250
| 4.125
| 4
|
#Write a Python program to display the current date and time. Sample Output :
#Current date and time :
#14:34:14 2014-07-05
from datetime import date
today=date.today()
ti=today.strftime("%d/%m/%Y %H:%M:%S")
print("current date and time :\n " + ti)
| true
|
7683518c723464172d103ab63ba4d1264c95ec4e
|
bipinaghimire/lab4_continue
|
/dictionary/fourtytwo.py
| 227
| 4.5625
| 5
|
'''
.Write a Python program to iterate over dictionaries using for loops.
'''
dict={1:'cow',2:'tiger',3:'lion',4:'monkey'}
for i in dict:
print(i)
for j in dict.values():
print(j)
for k in dict.items():
print(k)
| false
|
f8551faa26b591b1ee0d4325d236a87da3e5ad6e
|
imshawan/ProblemSolving-Hackerrank
|
/30Days-OfCode/Dictionaries and Maps.py
| 469
| 4.125
| 4
|
# Day 8: Dictionaries and Maps
# Key-Value pair mappings using a Map or Dictionary data structure
# Enter your code here. Read input from STDIN. Print output to STDOUT
N=int(input())
phoneBook={}
for _ in range(N):
name,contact=input().split()
phoneBook[name]=contact
try:
while(True):
check=str(input())
if check in phoneBook:
print(check+"="+phoneBook[check])
else:
print('Not found')
except:
pass
| true
|
50ac0dc6dfbe3a6dff8fb85eb0788936e75e9845
|
hericlysdlarii/Respostas-lista-de-Exercicio
|
/Questao4.py
| 266
| 4.15625
| 4
|
# Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
letra = str(input("Digite uma letra: "))
if ((letra == 'a') or (letra == 'e') or (letra == 'i') or (letra == 'o') or (letra == 'u')):
print("Vogal")
else:
print("Consoante")
| false
|
5fddff1509c6cdd53ecf20c4230f1db35f769544
|
tawrahim/Taaye_Kahinde
|
/Kahinde/chp6/tryitout (2).py
| 1,912
| 4.125
| 4
|
print "First Question:"
firstname="Kahinde"
lastname="Giwa"
print "Hello,my name is,",firstname,lastname
print "\n\n\n"
print "**************************\n"
firstname=raw_input("Enter your first name please:")
lastname=raw_input("Now enter your lastname:")
print "You entered",firstname,"for your firstname,"
print "And you entered",lastname,"for your lastname"
print "Hello,",firstname,lastname,".How do you do?"
print "\n\n\n"
print "**************************\n"
print """Tell me the dimensions of a rectangular room
and I will give you the amount of carpet you need for that room."""
length=int(raw_input("What is the length?"))
width=int(raw_input("Now what is the width?"))
print "You entered,",length,"for the length."
print "And you entered,",width,"for the width."
answer=length*width
print "The answer is,",answer
print "So that's the amount of carpet you need for your floor",answer
print "\n\n\n"
print "**************************\n"
print """Tell me the demensions of a rectangular room and I will give
you the amount of money you need for that room in yards and feet"""
length=float(raw_input("What is the length?"))
width=float(raw_input("Now what is the width?"))
money=float(raw_input("What is the amount of money for each sq. yd."))
area_ft=length*width
yards=area_ft/9.0
cost=float(area_ft*money)
print "The area is," ,int(area_ft),"in feet."
print "The area is,",yards,"in yards."
print "The cost is,",cost
print "\n\n\n"
print "**************************\n"
print "I will ask you to give me your change so I can add it up for you."
quarter=int(raw_input("Enter in how many quarters:"))*25
dime=int(raw_input("Enter in how many dimes:"))*10
nickel=int(raw_input("Enter in how many nickels:"))*5
penny=int(raw_input("Enter in how many pennies:"))*1
formula=quarter+dime+nickel+penny
print "For change,you have",formula,"cents"
| true
|
77ef1a85e93549c28e6eeef9fdeeeab5a1365350
|
tawrahim/Taaye_Kahinde
|
/Taaye/chp4/dec-int.py
| 1,346
| 4.625
| 5
|
print "Question #1, Try it out"
print"\n"
print'This is a way to change a string to a float'
string1=12.34
string="'12.34'"
print 'The string is,',string
point= '12.34'
formula= float(string1)
print "And the float is,",point
print 'We use this formala to change a string into a float, the formula is,', formula
print 'So then you get,'
print formula
print "\n"
print 'Question #2, try it out'
print "\n"
formula= "int(56.78)"
working=int(56.78)
decimal=56.78
print 'We are going to change the decimal,',decimal,'to an integer(number)'
print 'To do that we must use the formula,',formula
print 'Ten once once you type it in, you get the answer.......'
print working
print 'That is how you do it.'
print '\n\n'
print 'Question #3, try it out'
print '\n'
string="'1234.56'"
string1=1234.56
formula=int(string1)
formula2= "('1234.56')"
print 'To make the string,',string,'into an integer, we must use the formula , int ().'
print 'But since you can not put quotations inside the perantheses,' ,formula2,'or it will not work.'
print 'We have to assign,',string,'to a variable, any variable for example I will do number.'
print 'Number=',string,'so now we can do, int(number).'
print 'Then, once you type that in, you get............'
print formula
print 'That is how you do it'
print 'Done by Taaye'
| true
|
07566268fa1ca3f0e66a41f8fc4d6f758fdaa9d0
|
tawrahim/Taaye_Kahinde
|
/Kahinde/chp8/looper_tio.py
| 1,077
| 4.125
| 4
|
#Kainde's work,Chapter 8,tryitout,question1
number=int(raw_input("Hello, what table should I display? Type in a number:"))
print "Here is your table:"
for looper in range(number):
print looper, "*",number,"=",looper*number
print "\n*************************************"
#Chapter 8,tryitout,question2
number=int(raw_input("Hello, what table should I display? Type in a number:"))
print "Here is your table:"
j=0
while (j<5):
print j,"*",number,"=",j*number
j=j+1
print "\n**************************************"
#Chapter 8,tryitout,question3
number=int(raw_input("Which multiplication table would you like?"))
number1=int(raw_input("How high do you want to go?"))
for looper in range(number1):
print looper, "*",number,"=",looper*number
if looper==number1:
break
print "\n**************************************"
number=int(raw_input("Which multiplication table do you want?"))
number1=int(raw_input("How high do you want to go?"))
k=0
while k<number1:
print number,"*",k,"=",number*k
k+=1
| true
|
89ba7658b45e09a370813e75845e4009e9d4fa28
|
TrinityChristiana/py-classes
|
/main.py
| 882
| 4.15625
| 4
|
# **************************** Challenge: Urban Planner II ****************************
"""
Author: Trinity Terry
pyrun: python main.py
"""
from building import Building
from city import City
from random_names import random_name
# Create a new city instance and add your building instances to it. Once all buildings are in the city, iterate the city's building collection and output the information about each building in the city.
megalopolis = City("Megalopolis", "Trinity", "2020")
buildings = [Building("333 Commerce Street", 33), Building("Strada General Traian Moșoiu 24", 5), Building(
"5 Avenue Anatole France", 276), Building("1600 Pennsylvania Ave NW", 6), Building("48009 Bilbo", 3)]
for building in buildings:
person = random_name()
building.purchase(person)
building.construct()
megalopolis.add_building(building)
megalopolis.print_building_details()
| true
|
a2ca245925c0c9fd9408ba5d5ca109c655d9af56
|
rashmitallam/PythonBasics
|
/tables_2_to_n.py
| 271
| 4.25
| 4
|
#WAP to accept an integer 'n' from user and print tables from 2 to n
n=input('Enter an integer:')
for x in range(2,n+1):
print("Table of "+str(x)+":\n")
for y in range(1,11):
z = x*y
print(str(x)+"*"+str(y)+"="+str(z))
print('\n')
| false
|
a2e72fc8db97045e7b33c13ec8d40eb9dcb37ca6
|
lokeshom1/python
|
/datetransformer.py
| 682
| 4.21875
| 4
|
month = eval(input('Please enter the month as a number(1-12): '))
day = eval(input('Please enter the day of the month : '))
if month == 1:
print('January', end='')
elif month == 2:
print('February', end='')
elif month == 3:
print('March', end='')
elif month == 4:
print('April', end='')
elif month == 5:
print('May',end='')
elif month == 6:
print('June',end='')
elif month == 7:
print('July',end='')
elif month == 8:
print('August',end='')
elif month == 9:
print('September',end='')
elif month == 10:
print('October',end='')
elif month == 11:
print('November',end='')
elif month == 12:
print('December',end='')
print(day)
| true
|
311ab08d466143062b58036743236330b0c92f57
|
khamosh-nigahen/linked_list_interview_practice
|
/Insertion_SLL.py
| 1,692
| 4.5625
| 5
|
# Three types of insertion in Single Linked List
# ->insert node at front
# ->insert Node after a given node
# ->insert Node at the tail
class Node(object):
def __init__(self, data):
self.data = data
self.nextNode = None
class singleLinkedList(object):
def __init__(self):
self.head = None
def printLinkedlist(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.nextNode
def pushAtBegining(self, data):
new_node = Node(data)
new_node.nextNode = self.head
self.head = new_node
def insertAfterNode(self, data, prev_node):
if prev_node is None:
print("Please provide Node which exits in the linked list")
else:
new_node = Node(data)
new_node.nextNode = prev_node.nextNode
prev_node.nextNode = new_node
def pushAttail(self, data):
new_node = Node(4)
temp = self.head
while(temp.nextNode != None):
temp = temp.nextNode
temp.nextNode = new_node
new_node.nextNode = None
if __name__ == "__main__":
sllist = singleLinkedList()
# creating 3 nodes of the linked list
first = Node(1)
second = Node(2)
third = Node(3)
third.nextNode = None
sllist.head = first
first.nextNode = second
second.nextNode = third
#inserting the node at head
sllist.pushAtBegining(0)
#insert after particular Node
sllist.insertAfterNode(2.5, second)
#insert after tail
sllist.pushAttail(4)
#print the linked list
sllist.printLinkedlist()
| true
|
a157d4775a860a6be525c7308aed0773f5dd926b
|
eugenialuzzi/UADE
|
/PROGRA1_TP1_ej6.py
| 842
| 4.125
| 4
|
#Escribir dos funciones para imprimir por pantalla cada uno de los siguientes patrones
#de asteriscos.
def ImprimirCuadrado(n):
"""Imprime un cuadrado de asteriscos. Recibe la cantidad de filas y columnas nxn,
e imprime el cuadrado de asteriscos"""
for i in range(n):
for j in range(n):
print("*", end="")
print()
def ImprimirTriangulo(num):
"""Imprime un triangulo de asteriscos, comenzando de 2 asteriszoa. Recibe la
cantidad de filas y columnas nxn, e imprime el cuadrado de asteriscos"""
for k in range(2,num+1):
print("*"*k)
def main():
numero = int(input("Ingrese a cantidad asterizcos que desea imprimir: "))
rectangulo = ImprimirCuadrado(numero)
print()
triangulo = ImprimirTriangulo(numero)
#Programa Principal
main()
| false
|
2f69c84b0517375ad6e4591ca8ad4dab9279d708
|
AkashKadam75/Kaggle-Python-Course
|
/Boolean.py
| 716
| 4.125
| 4
|
val = True;
print(type(val))
def can_run_for_president(age):
"""Can someone of the given age run for president in the US?"""
# The US Constitution says you must "have attained to the Age of thirty-five Years"
return age >= 35
print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))
print(3.0 == 3)
print(type('3'))
print('3' == 3.0)
def is_odd(n):
return (n % 2) == 1
print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))
print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
| true
|
ef8b9904bbaf95f0ee8e7b53ecff67ae4b2593c9
|
huboa/xuexi
|
/oldboy-python18/day04-函数嵌套-装饰器-生成器/00-study/00-day4/生成器/生成器.py
| 1,807
| 4.28125
| 4
|
#生成器:在函数内部包含yield关键,那么该函数执行的结果是生成器
#生成器就是迭代器
#yield的功能:
# 1 把函数的结果做生迭代器(以一种优雅的方式封装好__iter__,__next__)
# 2 函数暂停与再继续运行的状态是由yield
# def func():
# print('first')
# yield 11111111
# print('second')
# yield 2222222
# print('third')
# yield 33333333
# print('fourth')
#
#
# g=func()
# print(g)
# from collections import Iterator
# print(isinstance(g,Iterator))
# print(next(g))
# print('======>')
# print(next(g))
# print('======>')
# print(next(g))
# print('======>')
# print(next(g))
# for i in g: #i=iter(g)
# print(i)
# def func(n):
# print('我开动啦')
# while True:
# yield n
# n+=1
#
# g=func(0)
#
# # print(next(g))
# # print(next(g))
# # print(next(g))
# for i in g:
# print(i)
#
# for i in range(10000):
# print(i)
# def my_range(start,stop):
# while True:
# if start == stop:
# raise StopIteration
# yield start #2
# start+=1 #3
#
# g=my_range(1,3)
# #
# print(next(g))
# print(next(g))
# print(next(g))
#
#
# for i in my_range(1,3):
# print(i)
#yield与return的比较?
#相同:都有返回值的功能
#不同:return只能返回一次值,而yield可以返回多次值
# python3 02--tail.py -f access.log | grep 'error'
import time
def tail(filepath):
with open(filepath, 'r') as f:
f.seek(0, 2)
while True:
line = f.readline()
if line:
yield line
else:
time.sleep(0.2)
def grep(pattern,lines):
for line in lines:
if pattern in line:
print(line,end='')
grep('error',tail('access.log'))
| false
|
8c4f19f7f6a830f31d76d64251ee6bcc0c46366d
|
huboa/xuexi
|
/oldboy-python18/day07-模块补充-面向对象/self/05-继承/组合.py
| 1,585
| 4.25
| 4
|
class OldboyPeople:
school = 'oldboy'
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def eat(self):
print('is eating')
class OldboyStudent(OldboyPeople):
def __init__(self,name,age,sex):
OldboyPeople.__init__(self,name,age,sex)
self.course=[]
def learn(self):
print('%s is learning' %self.name)
class OldboyTeacher(OldboyPeople):
def __init__(self,name,age,sex,salary,title):
OldboyPeople.__init__(self,name,age,sex)
self.salary=salary
self.title=title
self.course=[]
def teach(self):
print('%s is teaching' %self.name)
class Course:
def __init__(self,course_name,course_period,course_price):
self.course_name=course_name
self.course_period=course_period
self.course_price=course_price
def tell_info(self):
print('<课程名:%s 周期:%s 价格:%s>' %(self.course_name,self.course_period,self.course_price))
python=Course('Python','6mons',3000)
linux=Course('Lnux','3mons',2000)
bigdata=Course('BigData','1mons',1000)
# python.tell_info()
egon_obj=OldboyTeacher('egon',18,'male',3.1,'沙河霸道金牌讲师')
#
# egon_obj.course.append(python)
# egon_obj.course.append(linux)
#
# for obj in egon_obj.course:
# obj.tell_info()
yl_obj=OldboyStudent('yanglei',28,'female')
yl_obj.course.append(python,bigdata)
for i in yl_obj.course:
# print(i.course_name,i.course_period,i.course_price)
i.tell_info()
| false
|
86eb98601768f42b58559422e47e2b3d516d3bdd
|
huboa/xuexi
|
/oldboy-python18/day07-模块补充-面向对象/00-tt/day7/继承/继承.py
| 2,485
| 4.53125
| 5
|
#继承的基本形式
# class ParentClass1(object): #定义父类
# pass
#
# class ParentClass2: #定义父类
# pass
#
# class SubClass1(ParentClass1): #单继承,基类是ParentClass1,派生类是SubClass
# pass
#
# class SubClass2(ParentClass1,ParentClass2): #python支持多继承,用逗号分隔开多个继承的类
# pass
#
#
#
#
# print(SubClass1.__bases__)
# print(SubClass2.__bases__)
# print(ParentClass1.__bases__)
#经典类与新式类的区别
# class Animal:
# x=1
# def __init__(self,name,age,sex):
# self.name=name
# self.age=age
# self.sex=sex
# # print('Animal.__init__')
# def eat(self):
# print('%s eat' %self.name)
#
# def talk(self):
# print('%s say' %self.name)
#
# class People(Animal):
# x=10
# def __init__(self,name,age,sex,education):
# Animal.__init__(self,name,age,sex)
# self.education=education
# # print('People.__init__')
#
# def talk(self):
# Animal.talk(self)
# print('这是人在说话')
#
# class Dog(Animal):
# pass
# class Pig(Animal):
# pass
#
#
# peo1=People('alex',18,'male','小学肄业')
# print(peo1.__dict__)
# peo1.talk()
# print(peo1.x)
# dog1=Dog('yuanhao',28,'male')
# pig1=Pig('wupeiqi',18,'male')
#
#
# print(peo1.name)
# print(dog1.name)
# print(pig1.name)
class OldboyPeople:
school = 'oldboy'
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def eat(self):
print('is eating')
class OldboyStudent(OldboyPeople):
def learn(self):
print('%s is learning' %self.name)
class OldboyTeacher(OldboyPeople):
def __init__(self,name,age,sex,salary,title):
OldboyPeople.__init__(self,name,age,sex)
self.salary=salary
self.title=title
def teach(self):
print('%s is teaching' %self.name)
yl_obj=OldboyStudent('yanglei',28,'female')
egon_obj=OldboyTeacher('egon',18,'male',3.1,'沙河霸道金牌讲师')
#
# yl_obj.learn()
# yl_obj.eat()
print(egon_obj.__dict__)
'''
总结:
1 继承的功能之一:解决类与类之间的代码重复问题
2 继承是类与类之间的关系,是一种,什么是什么的关系
3 在子类派生出的新的属性,已自己的为准
4 在子类派生出的新的方法内重用父类的功能的方式:指名道姓法
OldboyPeople.__init__
这种调用方式本身与继承是没有关系
'''
| false
|
fe0628d501eaa9391b229991a3dfaf1940ff0751
|
huboa/xuexi
|
/oldboy-python18/day03-函数-file/00-day3/函数参数.py
| 2,026
| 4.3125
| 4
|
#形参:在定义函数时,括号内的参数成为形参
#特点:形参就是变量名
# def foo(x,y): #x=1,y=2
# print(x)
# print(y)
#实参:在调用函数时,括号内的参数成为实参
#特点:实参就是变量值
# foo(1,2)
#在调用阶段实参(变量值)才会绑定形参(变量名)
#调用结束后,解除绑定
#参数的分类
#位置参数:按照从左到右的顺序依次定义的参数
#位置形参:必须被传值,并且多一个不行,少一个也不行
#位置实参:与形参按照位置一一对应
# def foo(x,y):
# print(x)
# print(y)
#
# foo('egon',1,2)
#关键字实参:指的是按照name=value的形式,指名道姓地给name传值
# def foo(name,age):
# print(name)
# print(age)
# foo('egon',18)
# foo(age=18,name='egon')
#关键字实参需要注意的问题是:
# def foo(name,age,sex):
# print(name)
# print(age)
# print(sex)
# foo('egon',18,'male')
# print('======>')
# foo(sex='male',age=18,name='egon')
# foo('egon',sex='male',age=18)
#问题一:语法规定位置实参必须在关键字实参的前面
# foo('egon',sex='male',age=18)
#问题二:一定不要对同一个形参传多次值
# foo('egon',sex='male',age=18,name='egon1')
# foo('male',age=18,name='egon1')
#默认形参:在定义阶段,就已经为形参赋值,意味在调用阶段可以不用传值
# def foo(x,y=1111111):
# print(x)
# print(y)
#
#
# foo(1,'a')
#
# def register(name,age,sex='male'):
# print(name,age,sex)
#
#
# register('asb',73)
# register('wsb',38)
# register('ysb',84)
# register('yaya',28,'female')
#默认参数需要注意的问题
#问题一:默认参数必须放在位置参数之后
# def foo(y=1,x):
# print(x,y)
#问题二:默认参数只在定义阶段赋值一次,而且仅一次
# x=100
# def foo(a,b=x):
# print(a,b)
#
# x=111111111111111111111111111111
# foo('egon')
#问题三:默认参数的值应该定义成不可变类型
| false
|
2fa86da40002d7a92e3dd06c3643c3cf76d8f91c
|
huboa/xuexi
|
/oldboy-python18/day08-接口-网络/00-day8/封装.py
| 2,931
| 4.15625
| 4
|
#先看如何隐藏
class Foo:
__N=111111 #_Foo__N
def __init__(self,name):
self.__Name=name #self._Foo__Name=name
def __f1(self): #_Foo__f1
print('f1')
def f2(self):
self.__f1() #self._Foo__f1()
f=Foo('egon')
# print(f.__N)
# f.__f1()
# f.__Name
# f.f2()
#这种隐藏需要注意的问题:
#1:这种隐藏只是一种语法上变形操作,并不会将属性真正隐藏起来
# print(Foo.__dict__)
# print(f.__dict__)
# print(f._Foo__Name)
# print(f._Foo__N)
#2:这种语法级别的变形,是在类定义阶段发生的,并且只在类定义阶段发生
# Foo.__x=123123123123123123123123123123123123123123
# print(Foo.__dict__)
# print(Foo.__x)
# f.__x=123123123
# print(f.__dict__)
# print(f.__x)
#3:在子类定义的__x不会覆盖在父类定义的__x,因为子类中变形成了:_子类名__x,而父类中变形成了:_父类名__x,即双下滑线开头的属性在继承给子类时,子类是无法覆盖的。
class Foo:
def __f1(self): #_Foo__f1
print('Foo.f1')
def f2(self):
self.__f1() #self._Foo_f1
class Bar(Foo):
def __f1(self): #_Bar__f1
print('Bar.f1')
# b=Bar()
# b.f2()
#封装不是单纯意义的隐藏
#1:封装数据属性:将属性隐藏起来,然后对外提供访问属性的接口,关键是我们在接口内定制一些控制逻辑从而严格控制使用对数据属性的使用
class People:
def __init__(self,name,age):
if not isinstance(name,str):
raise TypeError('%s must be str' %name)
if not isinstance(age,int):
raise TypeError('%s must be int' %age)
self.__Name=name
self.__Age=age
def tell_info(self):
print('<名字:%s 年龄:%s>' %(self.__Name,self.__Age))
def set_info(self,x,y):
if not isinstance(x,str):
raise TypeError('%s must be str' %x)
if not isinstance(y,int):
raise TypeError('%s must be int' %y)
self.__Name=x
self.__Age=y
# p=People('egon',18)
# p.tell_info()
#
# # p.set_info('Egon','19')
# p.set_info('Egon',19)
# p.tell_info()
#2:封装函数属性:为了隔离复杂度
#取款是功能,而这个功能有很多功能组成:插卡、密码认证、输入金额、打印账单、取钱
#对使用者来说,只需要知道取款这个功能即可,其余功能我们都可以隐藏起来,很明显这么做
#隔离了复杂度,同时也提升了安全性
class ATM:
def __card(self):
print('插卡')
def __auth(self):
print('用户认证')
def __input(self):
print('输入取款金额')
def __print_bill(self):
print('打印账单')
def __take_money(self):
print('取款')
def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
self.__take_money()
a=ATM()
a.withdraw()
# _x=123
| false
|
052744e05cac11301014d1c33f8bc99e41c023c0
|
huboa/xuexi
|
/oldboy-python18/day03-函数-file/00-day3/可变长参数.py
| 2,575
| 4.15625
| 4
|
#可变长参数指的是实参的个数多了
#实参无非位置实参和关键字实参两种
#形参必须要两种机制来分别处理按照位置定义的实参溢出的情况:*
#跟按照关键字定义的实参溢出的情况:**
# def foo(x,y,*args): #nums=(3,4,5,6,7)
# print(x)
# print(y)
# print(args)
# foo(1,2,3,4,5,6,7) #*
# foo(1,2) #*
#*args的扩展用法
# def foo(x,y,*args): #*args=*(3,4,5,6,7)
# print(x)
# print(y)
# print(args)
#
# # foo(1,2,3,4,5,6,7) #*
#
#
# foo(1,2,*(3,4,5,6,7)) #foo(1,2,3,4,5,6,7)
# def foo(x,y=1,*args): #
# print(x)
# print(y)
# print(args)
#
# # foo('a','b',*(1,2,3,4,5,6,7)) #foo('a','b',1,2,3,4,5,6,7)
# # foo('egon',10,2,3,4,5,6,9,y=2) #报错
# foo('egon',10,2,3,4,5,6,9)
# def foo(x,y,**kwargs): #nums={'z':3,'b':2,'a':1}
# print(x)
# print(y)
# print(kwargs)
# foo(1,2,z=3,a=1,b=2) #**
# def foo(x,y,**kwargs): #kwargs={'z':3,'b':2,'a':1}
# print(x)
# print(y)
# print(kwargs)
#
# foo(1,2,**{'z':3,'b':2,'a':1}) #foo(1,2,a=1,z=3,b=2)
# def foo(x, y): #
# print(x)
# print(y)
#
# foo(**{'y':1,'x':2}) # foo(y=1,x=2)
# def foo(x,*args,**kwargs):#args=(2,3,4,5) kwargs={'b':1,'a':2}
# print(x)
# print(args)
# print(kwargs)
#
#
# foo(1,2,3,4,5,b=1,a=2)
#这俩东西*args,**kwargs干甚用???
def register(name,age,sex='male'):
print(name)
print(age)
print(sex)
# def wrapper(*args,**kwargs): #args=(1,2,3) kwargs={'a':1,'b':2}
# # print(args)
# # print(kwargs)
# register(*args,**kwargs)
# # register(*(1, 2, 3),**{'a': 1, 'b': 2})
# # register(1, 2, 3,a=1,b=2)
#
#
# wrapper(1,2,3,a=1,b=2)
import time
# def register(name,age,sex='male'):
# # start_time=time.time()
# print(name)
# print(age)
# print(sex)
# time.sleep(3)
# stop_time=time.time()
# print('run time is %s' %(stop_time-start_time))
# def wrapper(*args, **kwargs): #args=('egon',) kwargs={'age':18}
# start_time=time.time()
# register(*args, **kwargs)
# stop_time=time.time()
# print('run time is %s' %(stop_time-start_time))
#
#
# wrapper('egon',age=18)
# register('egon',18)
#命名关键字参数: 在*后面定义的形参称为命名关键字参数,必须是被以关键字实参的形式传值
# def foo(name,age,*args,sex='male',group):
# print(name)
# print(age)
# print(args)
# print(sex)
# print(group)
#
# foo('alex',18,19,20,300,group='group1')
def foo(name,age=18,*args,sex='male',group,**kwargs):
pass
| false
|
3a5ba0d910522c04787252d6a8afc8e8cae27952
|
AdamsGeeky/basics
|
/04 - Classes-inheritance-oops/51-classes-descriptor-magic-methods.py
| 2,230
| 4.25
| 4
|
# HEAD
# Classes - Magic Methods - Building Descriptor Objects
# DESCRIPTION
# Describes the magic methods of classes
# __get__, __set__, __delete__
# RESOURCES
#
# https://rszalski.github.io/magicmethods/
# Building Descriptor Objects
# Descriptors are classes which, when accessed through either getting, setting, or deleting, can also alter other objects. Descriptors aren't meant to stand alone; rather, they're meant to be held by an owner class. Descriptors can be useful when building object-oriented databases or classes that have attributes whose values are dependent on each other. Descriptors are particularly useful when representing attributes in several different units of measurement or representing computed attributes (like distance from the origin in a class to represent a point on a grid).
# To be a descriptor, a class must have at least one of __get__, __set__, and __delete__ implemented. Let's take a look at those magic methods:
# __get__(self, instance, owner)
# Define behavior for when the descriptor's value is retrieved. instance is the instance of the owner object. owner is the owner class itself.
# __set__(self, instance, value)
# Define behavior for when the descriptor's value is changed. instance is the instance of the owner class and value is the value to set the descriptor to.
# __delete__(self, instance)
# Define behavior for when the descriptor's value is deleted. instance is the instance of the owner object.
# Now, an example of a useful application of descriptors: unit conversions.
# class Meter(object):
# '''Descriptor for a meter.'''
# def __init__(self, value=0.0):
# self.value = float(value)
# def __get__(self, instance, owner):
# return self.value
# def __set__(self, instance, value):
# self.value = float(value)
# class Foot(object):
# '''Descriptor for a foot.'''
# def __get__(self, instance, owner):
# return instance.meter * 3.2808
# def __set__(self, instance, value):
# instance.meter = float(value) / 3.2808
# class Distance(object):
# '''Class to represent distance holding two descriptors for feet and
# meters.'''
# meter = Meter()
# foot = Foot()
| true
|
2b4ee967304815ea875dfc6e943a298df143ef48
|
AdamsGeeky/basics
|
/04 - Classes-inheritance-oops/05-classes-getters-setters.py
| 784
| 4.34375
| 4
|
# HEAD
# Classes - Getters and Setters
# DESCRIPTION
# Describes how to create getters and setters for attributes
# RESOURCES
#
# Creating a custom class
# Class name - GetterSetter
class GetterSetter():
# An class attribute with a getter method is a Property
attr = "Value"
# GETTER - gets values for attr
def get_attr(self):
return self.attr
# SETTER - sets values for attr
def set_attr(self, val):
self.attr = val
obj = GetterSetter()
# Print Values before using setter and direct attribute access
print("obj.get_attr()", obj.get_attr())
print("obj.attr", obj.attr)
# Use a setter
obj.set_attr(10)
# Print Values again using setter and direct attribute access
print("obj.get_attr()", obj.get_attr())
print("obj.attr", obj.attr)
| true
|
6f45acaeec134b92f051c4b43d100eeb45533be4
|
AdamsGeeky/basics
|
/02 - Operators/10-membership-operators.py
| 1,363
| 4.59375
| 5
|
# HEAD
# Membership Operators
# DESCRIPTION
# Describe the usage of membership operators
# RESOURCES
#
# 'in' operator checks if an item is a part of
# a sequence or iterator
# 'not in' operator checks if an item is not
# a part of a sequence or iterator
lists = [1, 2, 3, 4, 5]
dictions = {"key": "value", "a": "b", "c": "d"}
# Usage with lists for
# 'not in' AND 'in'
# 'in' checks for item in sequence
if (1 in lists):
print("in operator - 1 in lists:", (1 in lists))
# 'in' checks for absence of item in sequence
if (1 not in lists):
print("not in operator - 1 not in lists:", (1 not in lists))
# 'in' checks for absence of item in sequence
if ("b" not in lists):
print("not in operator - 'b' not in lists:", ("b" not in lists))
# Usage with dictions for
# 'not in' AND 'in'
# 'in' checks for item in sequence
# diction.keys() return a sequence
if ("key" in dictions.keys()):
print("in operator - 'key' in dictions.keys():", ("key" in dictions.keys()))
# 'not in' checks for absence of item in sequence
# diction.keys() return a sequence
if ("key" not in dictions.keys()):
print("not in operator - 'key' in dictions.keys():",
("key" not in dictions.keys()))
if ("somekey" not in dictions.keys()):
print("not in operator - 'somekey' in dictions.keys():",
("somekey" not in dictions.keys()))
| true
|
57e6b0b5cbb90562a02251739653f405b8237114
|
AdamsGeeky/basics
|
/03 - Types/3.1 - InbuiltTypes-String-Integer/05-integer-intro.py
| 952
| 4.15625
| 4
|
# HEAD
# DataType - Integer Introduction
# DESCRIPTION
# Describes what is a integer and it details
# RESOURCES
#
# int() is a function that converts a
# integer like characters or float to a integer
# float() is a function that converts a
# integer or float like characters or integer to a float
# Working with integer
# Assigning integer values in different ways
integer1 = 1
# Working with int() inbuilt function to create float
integer2 = int("2")
integer3 = int("3")
integer4 = int(4)
print(integer1)
print(integer2)
print(integer3)
print(integer4)
# Working with float
# Assigning float values in different ways
# Direct assignation
float1 = 1.234
# Working with float() inbuilt function to create float
# float() function can also be used to convert an
# integer or float like string type to float
float2 = float("5")
float3 = float("6.789")
float4 = float(1)
print(float1)
print(float2)
print(float3)
print(float4)
| true
|
b04ae7f2eea4a5301c9439e4403403599358a05f
|
AdamsGeeky/basics
|
/04 - Classes-inheritance-oops/54-classes-overwriting.py
| 1,525
| 4.375
| 4
|
# Classes
# Overriding
# Vehicle
class Vehicle():
maneuver = "Steering"
body = "Open Top"
seats = 4
wheels = 4
start = 0
end = 0
def __init__(self, maneuver, body, seats, wheels):
self.maneuver = maneuver
self.body = body
self.seats = seats
self.wheels = wheels
print("Vehicle Instantiated")
def move(self, end):
self.end = end
print("Vehicle moved from {} to {}".format(self.start, self.end))
# Following is not polymorphism
# v = Vehicle()
# print(v.body, v.maneuver, v.seats, v.wheels, v.start, v.end)
# v = Vehicle("Bike", "Handle", 2, 2)
# print(v.body, v.maneuver, v.seats, v.wheels, v.start, v.end)
class Bike(Vehicle):
# overriding - Parent-Child scope
# maneuver = None
def __init__(self, body, seats, wheels, maneuver= "Handle"):
# declare => runs automatically when instantiating class
# defining or assigning value to new
# attribute is like defining it in class
# Use same names in child like parent
# overriding => parent:child scoping
self.maneuver = maneuver
self.body = body
self.seats = seats
self.wheels = wheels
print("Bike Instantiated")
# overriding - Parent-Child scope
def move(self, end, name):
self.end = end
print("{} moved from {} to {}".format(name, self.start, self.end))
b = Bike("Yamaha", 2, 2)
print(b.body, b.maneuver, b.seats, b.wheels, b.start, b.end)
| true
|
a0f7967a83d0876a37cc74dd8c3c3dc8e1f2eaf3
|
AdamsGeeky/basics
|
/01 - Basics/33-error-handling-try-except-intro.py
| 1,137
| 4.1875
| 4
|
# HEAD
# Python Error Handling - UnNamed Excepts
# DESCRIPTION
# Describes using of Error Handling of code in python
# try...except is used for error handling
#
# RESOURCES
#
# 'try' block will be be executed by default
# If an error occurs then the specific or
# related 'except' block will be trigered
# depending on whether the 'except' block
# has named error or not
# 'except' can use a named error and have multiple errors
# 'except' without name will handle and
# execute if any error occurs
# You can have any number of 'except' blocks
def obj(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
except (TypeError, NameError):
print('Error: Multiple Error Block.')
except:
print('Error: Invalid argument.')
print(obj(2))
print(obj(12))
# Will throw ZeroDivisionError and will be
# captured triggering respective except block
print(obj(0))
print(obj(1))
# # Error Handling using ImportError
# try:
# # Non-existent module
# import def
# except ImportError:
# print('Module not found')
| true
|
a30f5ca5fac728d808ef78763f16ca54290765f6
|
AdamsGeeky/basics
|
/01 - Basics/11-flowcontrol-for-enumerate-loops.py
| 1,129
| 4.78125
| 5
|
# HEAD
# Python FlowControl - for loop
# DESCRIPTION
# Describes usage of for loop in different ways
# for different usages
#
# 'for' loop can iterate over iterable (sequence like) or sequence objects
# Result provided during every loop is an index and the relative item
#
# RESOURCES
#
# # USAGE
# 1
# # for item in iterator:
# # execution block
# # Based on total number of items in the list
ls = [2, 3, 4, 5, 6, 7, 8]
# Using iterator to get
# a item which is iterated
for item in ls:
print("Provides item of the iterator")
print('for item in ls ' + str(item))
# Usage of enumerate() function:
# enumerate(list)
# using enumerate(iterator) function to get
# a tuple of (index, value) which can be destructured
for item in enumerate(ls):
print("Provides index and its item of the iterator")
print("enumerate(list) usage: for item with first item as idx& second as item in enumerate(ls): ", item[0], item[1])
for idx, item in enumerate(ls):
print("Provides index and its item of the iterator")
print("enumerate(list) usage: for idx, item in enumerate(ls): ", idx, item)
| true
|
0640d7d0149ef291a99d472edcaf9e6d6c80ebe4
|
AdamsGeeky/basics
|
/01 - Basics/50-datatypes-type-conversion.py
| 2,961
| 4.5625
| 5
|
# HEAD
# Python Basics - Conversion of Data Types
# DESCRIPTION
# Type Conversion
# DESCRIPTION
# Describes type conversion methods (inter-conversion) available in python
#
# RESOURCES
#
# These function can also be used to declare specific types
# When appropriate object is used, these functions can be
# used to convert one type to another
# Example: list <-> tuple
# Example: list <-> str
# Example: dict <-> sequence of key value tuples
# Other functions also exist like
# list(), dict(), tuple(), set(), frozenset(), etc
# repr() function and str() function both provide
# the string representation of variable value
# As per documetation repr() provides more
# precise representation than str()
import sys
# STRING TYPE CONVERSION
# str() converts to string
sStr1 = str("Testing String")
print('str1', sStr1)
sStr2 = str(12)
print('str2', sStr2)
sStr3 = str(1.2345678901234567890)
print('str3', sStr3)
# repr() gives more precision while conversion to string
sRepr1 = repr("Testing String")
print('repr1', sRepr1)
sRepr2 = repr(12)
print('repr2', sRepr2)
sRepr3 = repr(1.2345678901234567890)
print('repr3', sRepr3)
# NUMBER TYPE CONVERSION AND MEMORY USAGE
# Type int(x) to convert x to a plain integer
cint = int(1.12345678901234567890)
print(cint)
# Type long(x) to convert x to a long integer - Python 2
# clong = long(1.12345678901234567890)
# print(clong)
# Type float(x) to convert x to a floating-point number.
cfloat = float(1.12345678901234567890)
print(cfloat)
# Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
# Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y.
# x and y are numeric expressions
ccomplex = complex(1.12345678901234567890)
print(ccomplex)
# (1.1234567890123457+0j)
ccomplexs = complex(1, 1.12345678901234567890)
print(ccomplexs)
# (1+1.1234567890123457j)
print("\nByte size of each of following:\n")
print("cint:", cint, "bytes", sys.getsizeof(cint))
# print("clong:", clong, "bytes", sys.getsizeof(clong))
print("cfloat:", cfloat, "bytes", sys.getsizeof(cfloat))
print("ccomplex:", ccomplex, "bytes", sys.getsizeof(ccomplex))
print("ccomplexs:", ccomplexs, "bytes", sys.getsizeof(ccomplexs))
# LIST TUPLE TYPE CONVERSIONS
# Convert sequence of numbers to a list
ls = list(,1,2,3,4)
# Convert list to a tuple
tpl = tuple(ls)
# Convert tuple to a list
ls = list(tpl)
# Convert list to a set
st = set(ls)
# Convert tuple to a set
st = set(tpl)
# Convert set to a list
ls = list(st)
# Convert set to a tpl
tpl = tuple(st)
# Create a dictionary using a Key:Value
dc = dict({"st": "new", "s": 10})
# Convert list to dictionary
ds = dict(ls)
# Convert tuple to dictionary
ds = dict(tpl)
# Convert set to a dictionary
ds = set(dc)
# Convert dictionary to a list
ls = list(dc)
# Convert dictionary to a tuple
tpl = tuple(dc)
# Convert dictionary to a set
st = set(dc)
| true
|
ee34a13657d64a8f3300fdf73e34362ad5a49206
|
AdamsGeeky/basics
|
/04 - Classes-inheritance-oops/17-classes-inheritance-setters-shallow.py
| 1,030
| 4.46875
| 4
|
# HEAD
# Classes - Setters are shallow
# DESCRIPTION
# Describes how setting of inherited attributes and values function
# RESOURCES
#
# Creating Parent class
class Parent():
par_cent = "parent"
# Parent Init method
def __init__(self, val):
self.par_cent = val
print("Parent Instantiated with ", self.par_cent)
# Creating ParentTwo class
class Child(Parent):
# Child Init method
def __init__(self, val_two):
print("Child Instantiated with ", val_two)
# Explicit Instantiation of parent init
# Instantiate parent once and passing args
# Parent assigns value storing it in object to access
# Parent default value remains
self.p = super()
self.p.__init__(val_two)
obj = Child(10)
print("""
Value of par_cent is assigned &
fetched from Child class &
default refs of parent remains
""")
print("obj.par_cent", obj.par_cent)
print("obj.p.par_cent, id(obj.p), id(obj)", obj.p.par_cent, id(obj.p), id(obj))
| true
|
f96d6651e41ca733e06d7b0346137a65688cd20a
|
RAVURISREESAIHARIKRISHNA/Python-2.7.12-3.5.2-
|
/Reading_list_INTs_Exception.py
| 816
| 4.21875
| 4
|
def Assign(n):
try:
return(int(n))
except ValueError: # Managing Inputs Like 's'
print("Illegal Entery\nRetry..")
n=input() # Asking User to Re-entry
Assign(n) # Calling the Same function,I correct input entered..Integer will be Returned,Else..Calling Recursively
return(int(n)) #Returning the Appropriate Int value
except SyntaxError: # Managing Inputs like '5a'
print("Illegal Entry\nRetr..") # -do-copy-
n=input() # -do-copy-
Assign(n) # -do-copy-
return(int(n)) # -do-copy-
List=[]
print("Enter Size of the List:")
temp=input()
size=Assign(temp)
print("Size is {}".format(str(size)))
for i in range(1,size+1):
print("Enter element {} :".format(str(i)))
temp=input()
List.append(Assign(temp))
print("The List is:")
print(List)
| true
|
da0158c1a20f3cf8a521b342fd4315bb5672100d
|
curiosubermensch/python-autodidacta
|
/wily.py
| 290
| 4.125
| 4
|
#while es un ciclo indefinido
def whily():
n=int(input("ing numero positivo:"))
while n<0:
print("error de ingreso")
n=int(input("ing numero positivo:"))
print("el numero positivo ing es: ",n)
def whilyBreak():
n=int(input("ing numero positivo:"))
if n<0:
break
print()
| false
|
d673103b6d9361916427652b337b9fbbf1fe7eae
|
cnkarz/Other
|
/Investing/Python/dateCreator.py
| 1,743
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
This script writes an array of dates of weekdays as YYYYMMDD
in a csv file. It starts with user's input,
which must be a monday in the same format
Created on Wed Jan 25 07:36:22 2017
@author: cenka
"""
import csv
def displayDate(year, month, day):
date = "%d%02d%02d" % (year, month, day)
return date
monthLength = {"01":[31, 31], "02":[28, 29], "03":[31, 31],
"04":[30, 30], "05":[31, 31], "06":[30, 30],
"07":[31, 31], "08":[31, 31], "09":[30, 30],
"10":[31, 31], "11":[30, 30], "12":[31, 31]}
leapYears = [2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060]
firstDay = raw_input("Please enter the starting date: ")
lastDay = int(raw_input("Please enter the ending date: "))
year = int(firstDay[:4])
month = int(firstDay[4:6])
day = int(firstDay[6:])
intFirstDay = int(firstDay)
count = 1
listIndex = 0
listOfDates = list()
listOfDates.append(intFirstDay)
while intFirstDay < lastDay :
day += 1
count += 1
for key in monthLength :
if year not in leapYears :
if int(key) == month and monthLength[key][0] +1 == day :
month += 1
day = 1
else :
if int(key) == month and monthLength[key][1] + 1 == day :
month += 1
day = 1
if month == 13 :
year += 1
month = 1
if count == 6 or count == 7:
continue
elif count == 8 :
count = 1
listIndex += 1
firstDay = displayDate(year, month, day)
intFirstDay = int(firstDay)
listOfDates.append(intFirstDay)
with open("dates.csv", "wb") as datecsv:
datewr = csv.writer(datecsv)
for k in range(len(listOfDates)):
datewr.writerow([listOfDates[k]])
datecsv.close()
| true
|
b3ee3c37efe6d97d32869f14d6e5bba5e9e8fc91
|
bglogowski/IntroPython2016a
|
/students/Boundb3/Session05/cigar_party.py
| 594
| 4.125
| 4
|
#!/usr/bin/env python
"""
When squirrels get together for a party, they like to have cigars.
A squirrel party is successful when the number of cigars is between
40 and 60, inclusive. Unless it is the weekend, in which case there
is no upper bound on the number of cigars.
Return True if the party with the given values is successful,
or False otherwise.
"""
print ("this is a test")
def cigar_party(cigars, is_weekend):
print(cigars,is_weekend, "made it to the def cigar_party function")
return (cigars*2)
cigar = 40
is_weekend = False
x = cigar_party(cigar, is_weekend)
print(x)
| true
|
c81670473d618bdb663d88d94f54980e3f0b563c
|
rohitgupta29/Python_projects
|
/Data_Structures/4.Hexadecimal_output.py
| 337
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 16:46:47 2020
@author: infom
"""
def hex_output():
decnum = 0
hexnum = input('Enter a hex number to convert: ')
for power, digit in enumerate (reversed(hexnum)):
decnum += int(digit,16) * (16 ** power)
print(decnum)
hex_output()
| false
|
73a241b1ba5d6337a93fe53fdfdb85815953d13e
|
AaryaVora/Python-Level-1-2
|
/hw3.py
| 266
| 4.125
| 4
|
fnum = int(input("Please enter a number: "))
snum = int(input("Please enter a number: "))
if fnum == snum :
print("Both numbers are equal")
elif fnum < snum:
print("Second number is greater")
else:
print("First number is greater than the second number")
| true
|
e61e0925cb261ff53f4a3ce9cf90314a3d9c4ed9
|
Harrison-Z1000/IntroProgramming-Labs
|
/labs/lab_03/pi.py
| 1,077
| 4.34375
| 4
|
# Introduction to Programming
# Author: Harrison Zheng
# Date: 09/25/19
# This program approximates the value of pi based on user input.
import math
def main():
print("This program approximates the value of pi.")
n = int(input("Enter the number of terms to be summed: "))
piApproximation = approximate(n) # Calls the approximate method, passing n as the argument
print("The sum of the first", n, "terms of this series is", piApproximation)
difference = math.pi - piApproximation # Finds the difference between the approximated value and actual value of pi
print("The difference between the approximation and the actual value of pi is", difference)
def approximate(n):
total = 0.0
for i in range(n):
total = total + (-1.0) ** i / (2.0 * i + 1.0) # The sign of each term in the sequence is always the opposite
# of the last. The denominator of every term is odd and is two more than that of the previous term.
return 4 * total # The numerator of every term is 4 so multiply total by 4 to get the approximation of pi
main()
| true
|
1b2dea794f55fab9398ec2fcbf258df7007f0f90
|
yash95shah/Leetcode
|
/swapnotemp.py
| 284
| 4.28125
| 4
|
'''
know swapping works on python without actually using temps
'''
def swap(x, y):
x = x ^ y
y = x ^ y
x = x ^ y
return (x, y)
x = int(input("Enter the value of x: "))
y = int(input("Enter the value of y: "))
print("New value of x and y: " + str(swap(x, y)))
| true
|
ca312b4e02650221b6bb5f34871ef12f45ad98d9
|
yash95shah/Leetcode
|
/sumwithoutarith.py
| 411
| 4.3125
| 4
|
'''
Sum of two integers without actually using the arithmetic operators
'''
def sum_without_arith(num1, num2):
temp_sum = num1 ^ num2
and_sum = num1 & num2 << 1
if and_sum:
temp_sum = sum_without_arith(temp_sum, and_sum)
return temp_sum
n1 = int(input("Enter your 1st number: "))
n2 = int(input("Enter your 2nd number: "))
print("Their sum is: " + str(sum_without_arith(n1, n2)))
| true
|
3962ed28f3ccc7d4689d73f5839bc6d016e43736
|
Juhkim90/Multiplication-Game-v.1
|
/main.py
| 980
| 4.15625
| 4
|
# To Run this program,
# Press Command + Enter
import random
import time
print ("Welcome to the Multiplication Game")
print ("Two Numbers are randomly picked between 0 and 12")
print ("Try to Answer ASAP. If you do not answer in 3 seconds, You FAIL!")
score = 0
ready = input("\n\nAre you ready? (y/n): ")
while (ready == 'y'):
first = random.randint(0,12)
second = random.randint(0,12)
for x in range(3,0,-1):
print(x)
time.sleep(1)
print("\nQuestion: ")
time1 = time.time()
question = int(input(str(first) + " x " + str(second) + " = "))
time2 = time.time()
if (question == first * second and time2 - time1 < 3):
print ("You got it!")
score += 1
else:
if (time2 - time1 >= 3):
print ("You did not get it in time.")
else:
print ("Wrong Answer.")
print ("Score: " + str(score))
ready = input("\n\nAre you ready? (y/n): ")
else:
print ("Alright. Prepare yourself")
print ("Total Score: " + str(score))
| true
|
442554266ce87af7740511669163b8c575a96950
|
OliviaParamour/AdventofCode2020
|
/day2.py
| 1,553
| 4.25
| 4
|
import re
def load_file(file_name: str) -> list:
"""Loads and parses the input for use in the challenge."""
input = []
with open(file_name) as file:
for line in file:
parts = re.match(r"^(\d+)-(\d+) ([a-z]): (\w+)$", line)
input.append((int(parts.group(1)), int(parts.group(2)),
parts.group(3), parts.group(4)) )
return input
def is_password_valid(case: tuple) -> bool:
"""Checks if a password is valid based on provided criteria:
Includes number of letters between low and high, inclusive.
"""
low, high, letter, password = case[0], case[1], case[2], case[3]
return low <= password.count(letter) <= high
def is_password_valid_two(case: tuple) -> bool:
"""Checks if a password is valid based on provided criteria:
Must contain a letter in either position 1 or 2 but not both.
"""
first, second, criteria, password = case[0]-1, case[1]-1, case[2], case[3]
return (password[first] == criteria) ^ (password[second] == criteria)
def main() -> None:
"""The main function for day 2. Answers question 1 and 2."""
passwords = load_file("day2.txt")
schema_1 = sum([is_password_valid(password) for password in passwords])
schema_2 = sum([is_password_valid_two(password) for password in passwords])
print(f"Total Passwords: {len(passwords)}")
print( f"Number of valid passwords for schema 1: {schema_1}" )
print(f"Number of valid passwords for schema 2: {schema_2}" )
if __name__ == "__main__":
main()
| true
|
1b120b65333495c5bd98f63e0e016942b419a708
|
DarshAsawa/ML-and-Computer-vision-using-Python
|
/Python_Basics/Roll_Dice.py
| 413
| 4.28125
| 4
|
import random
no_of_dices=int(input("how many dice you want :"))
end_count=no_of_dices*6
print("Since you are rolling %d dice or dices, you will get numbers between 1 and %d" % (no_of_dices,end_count))
count=1
while count==1 :
user_inp=input("Do you want to roll a dice : ")
if user_inp=="yes" or user_inp=="y" or user_inp=="Y":
print("Your number is : %d" % random.randrange(1,end_count,1))
else :
break
| true
|
f1d228b0afac00ffc567698775fc594b8e2b1069
|
nischalshk/pythonProject2
|
/3.py
| 385
| 4.3125
| 4
|
""" 3. Write code that will print out the anagrams (words that use the same
letters) from a paragraph of text."""
print("Question 3")
string1 = input("Enter First String: ")
string2 = input("Enter Second String: ")
sort_string1 = sorted(string1.lower())
sort_string2 = sorted(string2.lower())
if sort_string1 == sort_string2:
print("Anagram")
else:
print("Not Anagram")
| true
|
e838332cbe89a89c11746c421c6b284c0c05af94
|
jkfer/LeetCode
|
/Find_Largest_Value_in_Each_Tree_Row.py
| 1,117
| 4.15625
| 4
|
"""
You need to find the largest value in each row of a binary tree.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(1)
root.left = TreeNode(3)
root.right = TreeNode(2)
root.left.left = TreeNode(5)
root.left.right = TreeNode(3)
root.right.right = TreeNode(9)
class Solution:
def largestValues(self, root):
result = []
ROOT = [root]
def eval(root):
result.append(max(root))
def traverse(ROOT):
values = []
next_ROOT = []
for root in ROOT:
if root:
values.append(root.val)
next_ROOT.append(root.left)
next_ROOT.append(root.right)
eval(values)
if any(i != None for i in next_ROOT):
traverse(next_ROOT)
else:
return
if root:
traverse(ROOT)
return result
S = Solution()
x = S.largestValues(root)
print(x)
| true
|
1d79865e5d1a2ce727eff4c55c8ddd8cd22dee65
|
liyaozr/project
|
/base/day6/02while的使用.py
| 1,598
| 4.21875
| 4
|
"""
============================
Author:柠檬班-木森
Time:2020/1/6 20:47
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
需求:打印100白hello python
"""
# 定义一个变量来计数,记录打印了多少遍hello python
i = 0
while i < 100:
i = i + 1
print("这是第{}遍打印:hello python".format(i))
# -------------------------------死循环-------------------------:
# 循环条件始终成立的循环称之为死循环
# while True:
# print("hello python")
# i = 0
# while i < 100:
# print("这是第{}遍打印:hello python".format(i))
# ---------------------------break-----------------------------
# 如果终止循环(包括死循环):break(只能用在循环里面)
# break的作用:终止循环,
# 需求 当打印到第50遍的时候,循环结束
# i = 0
# while i < 100:
# i = i + 1
# print("这是第{}遍打印:hello python".format(i))
# if i == 50:
# break
# print('-----------end:{}-----------'.format(i))
#
# print("---------循环体之外的代码-------------")
# ---------------------------continue:-----------------------------
# continue:中止当前本轮循环,进行下一轮循环的条件判断(执行到continue之后,会直接回到while后面进行添加判读)
# i = 0
# while i < 100:
# i = i + 1
# print("这是第{}遍打印:hello python".format(i))
# if i == 50:
# continue
# print('-----------end:{}-----------'.format(i))
#
# print("---------循环体之外的代码-------------")
| false
|
ee1f838de3652e533b1600bce3fa33f59ad8d26d
|
Yasune/Python-Review
|
/Files.py
| 665
| 4.28125
| 4
|
#Opening and writing files with python
#Files are objects form the class _io.TEXTIOWRAPPER
#Opening and reading a file
myfile=open('faketext.txt','r')
#opening options :
#'r' ouverture en lecture
#'w' ouverture en ecriture
#'a' ouverture en mode append
#'b' ouverture en mode binaire
print type(myfile)
content=myfile.read()
print(content)
myfile.close() #close a file
# myfile=open('faketext.txt','a')
# myfile.write('SkillCorner is a badass company ')
# myfile.close()
#the right way to open a file
with open('faketext.txt','r') as dumbtext:
dumbcontent=dumbtext.read()
print dumbcontent
print myfile.closed #verify if file named myfile is closed
| true
|
688c1740371fdc204941281724563f4c813b2ab7
|
Introduction-to-Programming-OSOWSKI/2-9-factorial-beccakosey22
|
/main.py
| 208
| 4.21875
| 4
|
#Create a function called factorial() that returns the factorial of a given variable x.
def factorial(x):
y = 1
for i in range (1, x + 1):
y = y*i
return y
print(factorial(5))
| true
|
27c08ed8c4d0b80c7039144a170f6375b6daba3f
|
Spuntininki/Aulas-Python-Guanabara
|
/ex0060.py
| 493
| 4.15625
| 4
|
#Programa que lê um numero inteiro positivo qualquer e mostra seu fatorial
from math import factorial
n = int(input('Digite um número: '))
f = factorial(n)
print('O fatorial de {} é {} '.format(n, f))
'''c = n
fator1 = n
resultado = n * (n-1)
for c in range(1, n-1):
n -= 1
resultado = resultado * (n-1)
print('O fatorial de {} resulta em {}'.format(fator1, resultado))'''
'''while c != 1:
n = n * (c-1)
c -= 1
print('O fatorial de {} resulta em {}'.format(fator1, n))'''
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.