blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b0030dded25a12027a157488e9b4243d1883be85 | kt3a/GWCPython | /Lesson5.py | 1,498 | 4.25 | 4 | #loops and lists
##class demo
#lists
alist = [1,2,3,"a","b"] #lists can hold any variable type
blist = [alist,10] #you can put a list inside of a list
#print(blist)
#accessing items in a list
#print(alist[4])
#reassign items in a list
blist[0] = "Zero"
#print(blist)
#loops
for i in range(0,5): #i represents the index number in a range of numbers the loop currently deals with
# print(i)
for a in range(0,10,2): #make sure you nest the print statement and have a colon after the loop statement
#print(a)
for b in range(10,0,-1): #you can loop in reverse order if you add a third perameter
print(b)
##class activity answer key
#1: what element is at index 3 in the list
lista = ["katie",23,4.5,"A"]
print("Index 3 of lista is:",lista[3])
#2: what is the output of the following code?
for i in range(0,4):
print("hi")
#3: take the list and change index 4 to "a"
alist = [1,2,3,4,5]
alist[4] = "a"
print("The new list is:",alist)
#4: write a loop that will print out your name 5 times
my_name = "katie"
for a in range(5):
print(my_name)
#5 review: make a loop that will print out hi and your name 5 times if a user input number is between 0 and 5
my_name1 = "Katie"
x = int(input("choose a number"))
if x<=5:
print(my_name1)
else:
print(x)
#6
sum = 0
for b in range(0,5):
sum = sum + b
print(sum)
#7
clist = [2,3,4,5,6]
the_sum = 0
for i in clist:
the_sum += i
print(the_sum)
| true |
71ac86f54d3e8b1a02bc1c2441a6c0097f85e32a | kt3a/GWCPython | /Lesson10.py | 913 | 4.15625 | 4 | ## Lesson 10 Giant Review Session
aword = "marquette"
count_e = 0
for i in range(len(aword)):
if aword[i] in "e":
count_e += 1
#print(count_e)
def repeat():
while True:
x = input("What day of the week is it?")
if x == "Monday":
print("It's the first day of the week!")
elif x == "Saturday":
print("Its the weekend, yay!")
#put a statement here to stop the program
#function call here
def repeat1():
while True:
x = int(input("give me a number"))
if x > 6 and x<13 and x!=9:
print(str(x) + " is greater than 6!")
elif x >13 and x<15:
print("nice!")
continue
elif x == 9:
break
repeat1()
#how to use the number randomizer
import random
num = random.randint(1,6+1)
#print(num)
| true |
513cf425757e257990bd6c004fd9f096934f02ae | sivaneshl/pyhton-tutorials | /listcomprehension.py | 327 | 4.125 | 4 | # List Comprehension
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
# newwords = []
# for word in words:
# if word != 'the':
# newwords.append(word)
# print(newwords)
# Comprehension notation
newwords = [(word) for word in words if word != 'the']
print(newwords)
| false |
1a5652f8f52b06b740bf02d8696fde7368b493e9 | Weijun-H/cs164 | /HW/HW1/P3a.py | 1,673 | 4.15625 | 4 | # Simple template for HW1, problem #3a
import sys, re
# You may find it convenient to define shorthand to use in your solution.
# For example,
#
# LETTER = r'[a-z]'
# ALPHANUM = r'[a-z0-9]'
#
# Later, inside a regular expression in the rules section, you can concatenate
# these definitions with other things, like this:
#
# ANSWER = LETTER + ALPHANUM + "*"
ANSWER = r'REPLACE WITH YOUR SOLUTION TO THIS PROBLEM'
# Restrictions: Besides ordinary characters (which stand for themselves),
# ANSWER must use only the constructs [...], *, +, |, ^, $, (...), ?,
# and .
# To test your solution, put the inputs to be tested, one to a
# line, in some file INPUTFILE, and enter the command
#
# python P3a.py INPUTFILE
# or
#
# python P3a.py < INPUTFILE
#
# Or, just type
#
# python P3a.py
#
# and enter inputs, one per line, by hand (on Unix, use ^D to end this input,
# or ^C^D in an Emacs shell).
if len (sys.argv) > 1:
inp = open (sys.argv[1])
else:
inp = sys.stdin
# Note for Python novices: A nicer way to write the next three lines and
# the readline at the end of the loop is to use the single line
# for line inp:
# However, since the Python runtime would buffer input in that case, it
# would not work well for interactive input (it would wait until you indicated
# end-of-file).
line = inp.readline ()
while line:
line = re.sub (r'[\n\r]', '', line)
try:
if re.match (ANSWER, line):
print 'Input "%s" accepted.' % line
else:
print 'Input "%s" rejected.' % line
except:
print 'Error in regular expression:', ANSWER
sys.exit (1)
line = inp.readline ()
| true |
d4b5052cec754c95505275428f95c0a45ef0a827 | d2fzero/Hw-3 | /serius ex 1.py | 550 | 4.21875 | 4 | # Severely underweight if BMI < 16
# Underweight if BMI is between 16 and 18.5
# Normal if BMI is between 18.5 and 25
# Overweight if BMI is between 25 and 30
# Obese if BMI is more than 30
height=int(input("nhap chieu cao"))
weight=int(input("nhao can nang"))
height=height/100
bmi=weight/(height*height)
if bmi<16 :
print("severely underweight")
elif bmi>=16 and bmi<=18.5:
print("underweight")
elif bmi>18.5 and bmi<=25:
print("normal")
elif bmi>25 and bmi<=30:
print("overweight")
else :
print("obese")
| false |
d5376c34796d6f5d6555b5aefd6b299869adc91c | daliskafroyan/30-Days-Of-Python-exercise | /06_tuple/exercises.py | 902 | 4.40625 | 4 | # Create a tuple containing names of your sisters and your brothers (imaginary siblings are fine)
# Join brothers and sisters tuples and assign it to siblings
sister = ('akira', 'rikka')
brother = ('akaza', 'rakuzan')
siblings = sister + brother
print(siblings)
# How many siblings do you have?
print(len(siblings))
# Modify the siblings tuple and add the name of your father and mother and assign it to family_members
siblings_list = list(siblings)
siblings_list.extend(['papa', 'mama'])
siblings = tuple(siblings_list)
print(siblings)
# Check if an item exists in tuple:
# Check if 'Estonia' is a nordic country
# Check if 'Iceland' is a nordic country
# nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden')
nordic_countries = ('Denmark', 'Finland', 'Iceland', 'Norway', 'Sweden')
print('Estonia' in nordic_countries)
print('Iceland' in nordic_countries)
| true |
7b7b8d2ac0a4aa536ecedda9fc318d23631a6880 | JackT103226809/ICTPRG-Python | /varibles.py | 300 | 4.34375 | 4 | #Jack Thomas
#27/July/2020
#gets user input and stores it in variable 'name'
name=input("What is your name?:")
#gets user input and stores it in variable 'age'
age=2020-int(input("What is your age?:"))
#displays what the user has inputed
print("hello ",name,"! How are you? You are born ",age,"!",sep="") | true |
7a8b1b4310c7454d420720233812d8a36cb752b4 | bbeckom/Tkinter_Test | /test_files/3.py | 366 | 4.125 | 4 | import tkinter
# create main window
root = tkinter.Tk()
one = tkinter.Label(root, text="One", bg="red", fg="white")
one.pack()
two = tkinter.Label(root, text="Two", bg="green", fg="black")
two.pack(fill=tkinter.X)
three = tkinter.Label(root, text="Three", bg="blue", fg="white")
three.pack(side=tkinter.LEFT, fill=tkinter.Y)
# run window in loop
root.mainloop() | false |
6804427e9b41c1efe5497b6cc07584af5098204a | mayurmorin/PYTHON-1 | /Assignment_1.11439.py | 2,460 | 4.28125 | 4 |
# coding: utf-8
# Task 1.1: Install Jupyter Notebook and run the first program and share the output of the program.
#
# Answer: Below is attached screen shot for your reference
# 
# Task 1.2: Write a program which will find all such numbers which are divisible by 7 but are not a multiple
# of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a
# comma-separated sequence on a single line.
# In[1]:
newlst=[]
for int_i in range(2000, 3201):
if (int_i%7==0) and (int_i%5!=0):
newlst.append(str(int_i))
print(','.join(newlst))
# Task 1.3: Write a Python program to accept the user's first and last name and then getting them printed in
# the the reverse order with a space between first name and last name.
# In[2]:
firstname = input('Please enter your First Name : ')
lastname = input('Please enter your Last Name : ')
print(lastname[::-1] + ' ' + firstname[::-1])
# Task 1.4:Write a Python program to find the volume of a sphere with diameter 12 cm.
# Formula: V=4/3 * π * r3
# In[3]:
# pi value has taken as 3.141592653
pi = 3.141592653
#radius is half of diameter
r = 12/2
V = (4/3)*pi*(r**3)
print('Volume of a sphere with diameter 12 cm is :', V)
# Task 2.1: Write a program which accepts a sequence of comma-separated numbers from console and
# generate a list.
# In[4]:
commasepnum=input('Kindly enter a sequence of comma-separated numbers : ')
print("List : ",commasepnum.split(","))
# Task 2.2: Create the below pattern using nested for loop in Python.
# In[5]:
for star in range(0,5,1):
print('*' * star)
for star in range(5,0,-1):
print('*' * star)
# Task 2.3: Write a Python program to reverse a word after accepting the input from the user.
# In[6]:
inputstr = input('Kindly enter a word to reverse : ')
print('Entered reversed word is : ', inputstr[::-1])
# Task 2.4: Write a Python Program to print the given string in the format specified in the sample output.
# WE, THE PEOPLE OF INDIA, having solemnly resolved to constitute India into a
# SOVEREIGN, SOCIALIST, SECULAR, DEMOCRATIC REPUBLIC and to secure to all
# its citizens
# In[7]:
formatstring="WE, THE PEOPLE OF INDIA,{0:5} having solemnly resolved to constitute India into a SOVEREIGN,{1:5} SOCIALIST, SECULAR, DEMOCRATIC REPUBLIC {2:5} and to secure to all its citizens"
print(formatstring.format('\n','!\n\t','\n\t'))
| true |
2783fdcb56904deac29da365296740422c7e8ab0 | yanhuangxiaoguang/offer-python | /剑指offer/从头到尾打印链表.py | 1,873 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
题目描述:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解题思路(胡说):这道题如果弄懂了,什么是链表,链表的最基本结构,由值域和下一链环的地址域组成(单链表)。至于其他的什么
双向链表,循环链表,十字(交叉)链表就不在这赘述。
首先创建一个空的list:
方法一:通过python 内置方法insert(0,data)每次在list的首部(头部,前面)插入当前值。
方法二:通过list 的 append 获得顺序的list 数据域,然后通过python的list倒序方法实现,有
list(reversed(a))
sorted(a,reverse=True)
a[: :-1]
"""
'''单链表的数据结构'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if listNode == None:
return []
tmp_list = []
now_node = listNode
while now_node:
tmp_list.insert(0, now_node.val)
now_node = now_node.next
return tmp_list
def python_list_reverse(self, listNode):
if listNode == None:
return []
tmp_list = []
now_node = listNode
while now_node:
tmp_list.append(now_node.val)
now_node = now_node.next
print(list(reversed(tmp_list)))
print(sorted(tmp_list, reverse=True))
print(tmp_list[::-1])
'''用例'''
data_0 = [1, 2, 3, 4]
'''构建单链表'''
head_node = ListNode(0)
now_node = head_node
for i, e in enumerate(data_0):
tmp_node = ListNode(e)
now_node.next = tmp_node
now_node = now_node.next
'''测试'''
s = Solution()
print(s.printListFromTailToHead(head_node))
s.python_list_reverse(head_node)
| false |
93cbafcaa2c2af03d37f425ced71f7d9c4e9f77c | singhpraveen2010/experimental | /lucky.py | 1,131 | 4.375 | 4 | """
A number is called lucky a number if if all digits of the number are different.
Eg: 123
"""
"""
Example usage:
python lucky --n <To find if number is lucky or not>
python lucky --n 123
OR
DEFAULT DOES WORK
python lucky
"""
import argparse
import sys
from collections import Counter
def is_lucky(n):
str_n = str(n)
num_set = set(str_n)
return len(num_set) == len(str_n)
def find_frequency(n):
digit_frequency = Counter()
str_n = str(n)
for digit in str_n:
digit_frequency[digit] += 1
for digit in digit_frequency:
frequency = digit_frequency[digit]
if frequency > 1:
print "{} occurs {} times.".format(digit, frequency)
def main(n):
if is_lucky(n):
print("{} is a Lucky Number.".format(n))
return
print("{} is not a Lucky Number.".format(n))
find_frequency(n)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Check if number is lucky or not.')
parser.add_argument('-n', type=int,
help='Lucky.', required=True)
args = parser.parse_args()
main(args.n)
| true |
7047dbeb75160d602cf3a1af2e017ee7bb62b8c6 | TahaaFatima/PythonSamaan | /sessionTwo/classTask.py | 649 | 4.125 | 4 | firstNumber = float(input('Enter the first number : '))
secondNumber = float(input('Enter the second number : '))
operation = input('Enter the operation : add, sub, mult, div or operation symbol : ').strip()
if operation == 'add' or operation == '+':
print(f'Addition = {firstNumber + secondNumber}')
elif operation == 'sub' or operation == '-':
print(f'Subtraction = {firstNumber - secondNumber}')
elif operation == 'mult' or operation == '*':
print(f'Multiplication = {firstNumber * secondNumber}')
elif operation == 'div' or operation == '/':
print(f'Division = {firstNumber / secondNumber}')
else:
print('Operator not found') | true |
d72f510f209d8d481a758d52ab14e43f83a099d2 | akiran1234/pythondsoft | /Python-Kiran/python-tutorials/PythonPrograms/NumberProgs/03_ReverseOfNum.py | 1,789 | 4.34375 | 4 | # To print the reverse of a number
n=1234
dig=rev=0
print("Actual Number={0}".format(n))
while(n>0):
dig=n%10 # It will pull the last digit
rev=rev*10+dig
n=n//10 # It will pull the quotient after divided by 10.
print("Reverse of Number={0}".format(rev))
###########################################################################################
# To check a given number is palindrome or not
n=151
dig=rev=0
pal=n
print("Actual Number={0}".format(n))
while(n>0):
dig=n%10 # It will pull the last digit
rev=rev*10+dig
n=n//10 # It will pull the quotient after divided by 10.
if(rev==pal):
print("Number is palindrome={0}".format(pal))
else:
print("Number is not palindrome={0}".format(rev))
###########################################################################################
# To print even or odd
n=7
if n%2==0:
print('The number is even={0}'.format(n))
else:
print('The number is odd={0}'.format(n))
###############################################################################################
# Sum of numbers of a given digit.
a = 1234
sum = 0
while (a > 0):
dig = a % 10
sum = sum + dig
a = a // 10
print( sum )
################################################################################################
# Find the least divisor for a number
n = 15
a = []
for i in range( 2, n ):
if (n % i == 0):
a.append( i )
a.sort()
print( "Smallest divisor is:", a[0] )
###################################################################################################
# This will print the number which is not divisible by 2 and 3.
for i in range( 1, 50 ):
if (i % 2 != 0 and i % 3 != 0):
print( "This is not divisible by 2 or 3:", i ) | true |
3b4f0331b40b004c40ce31bae4b8ec9171b7fba1 | gauravm043/All-Codes | /Second-Sem/PYTHON/CLASS_ITEMS/17-1.py | 651 | 4.3125 | 4 | d={}
d['jan']=100 #here key is 'jan' and value is 100
#values can also be lists
d['feb']=200 #use as a regular array
print 'original d=',d
#keys must be immutable (non-modifiable) : strings,numbers etc.
#lists are unhashable as they are mutable, so cannot be used as keys
k=d.keys()
print 'array of keys:',k
k.sort()
print 'sorted keys:',k #keys are sorted now, so if we want to traverse with keys in sorted order, we can traverse k and take values
d2={}
d2=d #we have created d2 as an alias of d, so any change in d2 is reflected in d
d2['jan']=50
print 'd2=',d2
print 'd=',d
x=d2['jan']
print x
def f():
return 1
d2['mar']=f()
print 'new d2:',d2
| true |
8bf2029458910ab1fa5ac02391631f9c4ecf6fcc | yuwinzer/GB_Python_basics | /hw_to_lesson_01/2_time.py | 286 | 4.1875 | 4 | input_time = int(input("Type your time in seconds: "))
print(f"\nYou entered {input_time} seconds")
hours = input_time // 3600
minutes = input_time // 60 - hours * 60
seconds = input_time - hours * 3600 - minutes * 60
print(f"Your time will be: {hours:02d}:{minutes:02d}:{seconds:02d}") | false |
1e152e86abb225433b77ee48710409038465a037 | yuwinzer/GB_Python_basics | /hw_to_lesson_01/1_variables.py | 734 | 4.125 | 4 | number = 16
print(f"This is an integer type of number: {int(number)}")
print(f"This is a float type of number: {float(number)}")
print("Now type your numbers and text. I will print it in different types!")
user_number_1 = int(input("\nType first number here: "))
user_number_2 = int(input("Type second number: "))
user_text_1 = input("Now type some text: ")
user_text_2 = input("And type any text again: ")
print(f"This is an integer type of your numbers: {int(user_number_1)} and {int(user_number_2)}")
print(f"This is a float type of your numbers: {float(user_number_1)} and {float(user_number_2)}")
list_type = [user_number_1, user_number_2, user_text_1, user_text_2]
print(f"This is all your inputs in a list type: {list_type}")
| true |
e907f213b8a00f21d89f73b2023e08b51cbbf576 | printfoo/leetcode-python | /problems/0088/merge_sorted_array.py | 989 | 4.125 | 4 | """
Solution for Merge Sorted Array, Time O(n), Space O(1).
Idea:
From tail to head.
"""
# Solution.
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while n > 0 and m > 0:
if nums1[m - 1] < nums2[n - 1]:
nums1[m + n - 1] = nums2[n - 1] # switch value
n -= 1
else:
nums1[m + n - 1] = nums1[m - 1] # switch value
m -= 1
if m == 0: nums1[:n] = nums2[:n]
# if the nums1 move out first, replace all leading elements with the remaining of the second list
# if the nums2 list move out first, we already have the right answer
# Main.
if __name__ == "__main__":
nums1 = [0]
m = 0
nums2 = [1]
n = 1
print(Solution().merge(nums1, m, nums2, n))
| true |
382059ab1330403d60ee7fa3b3abf38e1e43fdb0 | HuJiawei1990/LeetCode | /src/463_Island_Perimeter.py | 1,701 | 4.125 | 4 | # C:\lib\Python\Python36 python.exe
# -*- coding:utf-8 -*-
"""
@file 463_Island_Perimeter.py
@project LeetCode
--------------------------------------
@author hjw
@date 2018-04-08 16:36
@version 0.0.1.20180408
--------------------------------------
463. Island Perimeter
You are given a map in form of a two-dimensional integer grid where 1 represents land
and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally).
The grid is completely surrounded by water, and there is exactly one island (
i.e., one or more connected land cells). The island doesn't have "lakes"
(water inside that isn't connected to the water around the island).
One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100.
Determine the perimeter of the island.
"""
import sys
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
num_rows = len(grid)
num_cols = len(grid[0])
ans = sum([self.computeBlocks(row) for row in grid]) + \
sum([self.computeBlocks([row[i] for row in grid]) for i in range(num_cols)])
return 2 * ans
def computeBlocks(self, l1):
last_carre = 0
blocks = 0
for carre in l1:
if (carre == 1) & (last_carre == 0):
blocks += 1
last_carre = carre
return blocks
if __name__ == "__main__":
grid = [[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]]
print(Solution().islandPerimeter(grid))
| true |
1ba86e133e2bd92b0242e29d6a07af3a36ffce52 | HuJiawei1990/LeetCode | /src/101_Symmetric_Tree.py | 2,120 | 4.375 | 4 | # C:\lib\Python\Python36 python.exe
# -*- coding:utf-8 -*-
"""
@file 101_Symmetric_Tree.py
@project LeetCode
--------------------------------------
@author hjw
@date 2018-03-20 17:48
@version 0.0.1.20180320
--------------------------------------
101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric.
Note:
Bonus points if you could solve it both recursively and iteratively.
"""
import sys
from _utils import TreeNode, list2TreeNode
class Solution(object):
def isSymmetric(self, root: TreeNode):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None: return True
return self.isMirror(root.left, root.right)
def isMirror(self, tree1: TreeNode, tree2: TreeNode):
if tree1 is None and tree2 is None: return True
if tree1 is None or tree2 is None: return False
if tree1.val != tree2.val: return False
return (self.isMirror(tree1.left, tree2.right)) and (self.isMirror(tree1.right, tree2.left))
def isSymmetric2(self, root):
"""
Iterative method.
:param root: TreeNode
:return: boolean
"""
if root is None: return True
stack = [[root.left, root.right]]
while len(stack) > 0:
pair = stack.pop(0)
left = pair[0]
right = pair[1]
if (left is None) + (right is None) == 1:
return False
if left.val == right.val:
stack.insert(0, [left.left, right.right])
stack.insert(0, [left.right, right.left])
else:
return False
return True
if __name__ == "__main__":
#list_test = [1, 2, 2, 3, 4, 4, 3]
list_test = [2, 3, 3, 4, 5, 5, 4, None, None, 8, 9, 9, 8]
tree_test = list2TreeNode(list_test)
#print(tree_test.toList())
if Solution().isSymmetric(tree_test):
print('true')
| true |
bda2cd120228442947a074e0422e92c1acb74ccd | HuJiawei1990/LeetCode | /src/662_Max_Width_of_Binary_Tree.py | 1,607 | 4.125 | 4 | # C:\lib\Python\Python36 python.exe
# -*- coding:utf-8 -*-
"""
@file 662_Max_Width_of_Binary_Tree.py
@project LeetCode
--------------------------------------
@author hjw
@date 2018-03-27 15:30
@version 0.0.1.20180327
--------------------------------------
662. Maximum Width of Binary Tree
Given a binary tree, write a function to get the maximum width of the given tree.
The width of a tree is the maximum width among all levels.
The binary tree has the same structure as a full binary tree, but some nodes are None.
The width of one level is defined as the length between the end-nodes
(the leftmost and right most non-None nodes in the level, where the None nodes
between the end-nodes are also counted into the length calculation.
"""
import sys
from _utils import TreeNode, list2TreeNode
class Solution(object):
def widthOfBinaryTree(self, root):
def dfs(node, depth=0, pos=0):
if node:
yield depth, pos
yield from dfs(node.left, depth + 1, pos * 2)
yield from dfs(node.right, depth + 1, pos * 2 + 1)
left = {}
right = {}
ans = 0
for depth, pos in dfs(root):
left[depth] = min(left.get(depth, pos), pos)
right[depth] = max(right.get(depth, pos), pos)
ans = max(ans, right[depth] - left[depth] + 1)
return ans
if __name__ == "__main__":
tree =list2TreeNode([1,1,1,1,1,1,1,None,None,None,1,None,None,None,None,2,2,2,2,2,2,2,None,2,None,None,2,None,2])
print(Solution().widthOfBinaryTree(tree))
| true |
e733c8a8334bf07325c5937b4a57494379d43da5 | DrMWalters/coding-practice | /permMissingElem.py | 1,656 | 4.15625 | 4 | '''
An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:
def solution(A)
that, given an array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5
the function should return 4, as it is the missing element.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].
'''
'''
POSSIBLE BETTER ANSWER BELOW....
int find_missing_element(vector<int> &v) { // Here +1 needs to find size of full sequence with
// the missing element
auto v_size = v.size() + 1;
// Find sum of all elements of the sequence
auto sumOfAllElements = (v_size * (1 + v_size)) / 2;
auto missing_element = sumOfAllElements -
std::accumulate(v.begin(), v.end(), 0);
return missing_element;
}
'''
def solution(A):
# write your code in Python 3.6
A.sort()
print(len(A))
for i in range(len(A)):
if i == len(A) - 1 and A[i] == len(A): return len(A) + 1
if A[i] != i + 1:
return i + 1
return 1
if __name__ == '__main__':
print('Start tests..')
assert solution([2,3,1,5]) == 4
# assert solution([]) == 0
# assert solution([0,1]) == 1
# assert solution([0, 0]) == 0
# assert solution([1,0,0,3]) == 4
print('Ok!')
| true |
650df73e10305f6861c10e7c8213b91afa54cbb3 | CyberCrypter2810/CFPython | /code202/ch_10/part_1/assign/speed.py | 705 | 4.125 | 4 | # speed.py
'''
Program creates a speed dial when called appond. It
will then display the current speed of the car.
'''
import car
# main function
def main():
# create values for car class
year_model = int(input("Enter the year model: "))
make = input("What type of car is it? ")
speed = 0
# sends data to car class
design = car.Car(year_model, make, speed)
# call the accelerate method 5 times and displays results
print()
for i in range(5):
design.accelerate(speed)
print(design)
# call the brake method 5 times and displays results
print()
for i in range(5):
design.brake(speed)
print(design)
# calling main
main()
| true |
cbc1d3ad11af60d6aa2017e82d06977515bf31aa | CyberCrypter2810/CFPython | /code102/final/hawn_final.py | 2,961 | 4.25 | 4 | # hawn_final.py
'''
Program take user input on the amout of lessons they want
to purchase and calculates the final total.
'''
# Price of each lessons
GUITAR = 29.99
PIANO = 20
FLUTE = 10
# main function
def main():
try:
# calling functions
menu()
price, number, lesson = select()
print()
fee = zoom()
print()
total(lesson, number, price, fee)
except:
print()
# menu function
def menu():
print("Lesson Menu")
print("Number \t Lesson \t Price per lesson")
print("1: \t Guitar \t $29.99")
print("2: \t Piano \t\t $20")
print("3: \t Flute \t\t $10")
print()
print("If you decide to receive your lessons over Zoom,")
print("there will be a $15 fee.")
print()
# select function
def select():
try:
lesson = int(input("Which lesson do you want to take? "))
# error loop
while lesson < 1 or lesson > 3:
print("ERROR, No option exist, please choose again.")
lesson = int(input("Which lesson do you want to take? "))
number = int(input("How many are you going to take? "))
# error loop
while number < 1:
print("ERROR, You cannot have no less than 1 lesson.")
number = int(input("How many are you going to take? "))
# providing prise for input
if lesson == 1:
price = GUITAR * number
elif lesson == 2:
price = PIANO * number
else:
price = FLUTE * number
# returns Price, number, and lesson
return price, number, lesson
except:
print("ERROR, number value must be entered. Please try again.")
# zoom function
def zoom():
# user input
print("Are you going to take lessons through zoom?")
zoom = input("(Enter y for Yes, anything else means no): ")
# determining fee
if zoom == 'Y' or zoom == 'y':
fee = 15
else:
fee = 0
# return fee
return fee
# total function
def total(lesson, number, price, fee):
# total price calculation
final = price + fee
# displaying final results
if lesson == 1:
print("$29.99 x", number, "= $" + format(price, ',.2f'))
print("Fee = $" + str(fee))
print("Your final total for", number, "Guitar lessons is: ")
print("$" + format(final, ',.2f'))
elif lesson == 2:
print("$20 x", number, "= $" + format(price, ',.2f'))
print("Fee = $" + str(fee))
print("Your final total for", number, "Piano lessons is: ")
print("$" + format(final, ',.2f'))
else:
print("$10 x", number, "= $" + format(price, ',.2f'))
print("Fee = $" + str(fee))
print("Your final total for", number, "Flute lessons is: ")
print("$" + format(final, ',.2f'))
# calling main
main()
| true |
c6fc5d8c9cc0d28f1433e9acd842fc34c7d96c54 | CyberCrypter2810/CFPython | /code202/ch_10/part_1/assign/pet_info.py | 861 | 4.375 | 4 | # pet_info.py
'''
Program takes inputted data from user
and stores them in the Pet class.
It will then retrieve the data from the
pet class.
'''
# importing pet.py
import pet
# main function
def main():
# create a list for pet info
animal = []
# ask user how many pets they have
num = int(input("How many pets do you have? "))
# loop for creating data for pet class
for var in range(1, num+1):
name = input("What is the name of your " + str(var) + " pet? ")
animal_type = input("What type of pet is it? ")
age = int(input("How old is your pet? "))
# sends data to pet class
pets = pet.Pet(name, animal_type, age)
# append the pet list
animal.append(pets)
# displays data from pet
for item in animal:
print()
print(str(item))
# calling main
main()
| true |
83d682282cb715e7a873013e011bf0e7909d1857 | CyberCrypter2810/CFPython | /code102/ch_2/average.py | 397 | 4.375 | 4 | # average.py
# collects three numbers from users
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# calculate the average/mean of all three numbers
average = (num1 + num2 + num3) / 3.0
# displays final calculation
print("The average of all three numbers is: " + format(average, '.2f'))
| true |
f63845543faeb82be88ff9b7b9650fd51e00b5e5 | CyberCrypter2810/CFPython | /code202/ch_13/discussion/Solar.py | 2,222 | 4.25 | 4 | # Solar.py
'''
Program create GUI Canvas of
the order of the planets of the
solar system. The Sun will be in the
left corner followed by the planets
in the correct order from their distance
from the sun.
'''
import tkinter as tk
class Solar:
def __init__(self):
# main window
self.main_window = tk.Tk()
# main window title
self.main_window.title("Solar System")
# solar system canvas
self.solar = tk.Canvas(self.main_window,
width = 1100,
height = 500)
# sun
self.solar.create_oval(10, 10, 200, 200, fill = 'yellow')
# mercury
self.solar.create_oval(200, 200, 230, 230, fill = 'grey')
# venus
self.solar.create_oval(250, 250, 300, 300, fill = 'red')
# earth
self.solar.create_oval(320, 320, 390, 390, fill = 'aqua')
# mars
self.solar.create_oval(410, 410, 450, 450, fill = 'darkorange3')
# Jupiter
self.solar.create_oval(480, 270, 630, 420, fill = 'tan')
# Saturn
self.solar.create_oval(640, 145, 745, 250, fill = 'goldenrod1')
# Uranus
self.solar.create_oval(765, 85, 855, 175, fill = 'deepskyblue2')
# Neptune
self.solar.create_oval(875, 195, 960, 280, fill = 'dodgerblue3')
# pluto
self.solar.create_oval(1000, 350, 1020, 370, fill = 'khaki1')
# Labeling each planet
self.solar.create_text(105, 210, text = "Sun")
self.solar.create_text(215, 240, text = "Mercury")
self.solar.create_text(275, 310, text = "Venus")
self.solar.create_text(353, 400, text = "Earth")
self.solar.create_text(430, 460, text = "Mars")
self.solar.create_text(555, 430, text = "Jupiter")
self.solar.create_text(692, 260, text = "Saturn")
self.solar.create_text(810, 185, text = "Uranus")
self.solar.create_text(918, 290, text = "Neptune")
self.solar.create_text(1010, 380, text = "Pluto")
# pack
self.solar.pack()
# tk main loop
tk.mainloop()
# instance of Solar class
solar = Solar() | true |
3ff676cddfdc44bbfa792d039b1d4421369968f1 | CyberCrypter2810/CFPython | /code202/ch_12/discussion/recursive_line.py | 666 | 4.40625 | 4 | # recursive_line.py
'''
Program prints lines of asterisks based on
a certain number. The function will have a recursion
until the certain number has been reached both up and
down.
'''
# main function
def main():
# asks user for an input
n = int(input("Enter a integer number: "))
# calls up_line funciton
up_line(n)
# calls the down line function
down_line(n - 1)
# up_line function
def up_line(n):
if n > 0:
up_line(n-1)
lines = '*' * n
print(lines)
# down_line function
def down_line(n):
if n > 0:
lines = '*' * n
print(lines)
down_line(n - 1)
# calling main
main()
| true |
376fe910502a6b5a3cf88ad1947a47b67199a94a | IIKovalenko/learn-python-the-hard-way | /ex14.py | 993 | 4.28125 | 4 | from sys import argv
script, user_name, age = argv
x = '>'
print(f"Hi {user_name}, I'm the {script} script. I am {age} years old.")
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_name}")
likes = input(x)
print(f"Where do you live {user_name}?")
lives = input(x)
print("What kind of computer do you have?")
computer = input(x)
print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}. Not sure where that is.
And you have a {computer} computer. Nice.
""")
# Study Drills
# 1.Find out what the games Zork and Adventure were. Try to find a copy and play it.
print("1Done")
# 2.Change the prompt variable to something else entirely.
print("2 Change into the \"x\"")
# 3.Add another argument and use it in your script, the same way you did in the previous exercise with first, second = ARGV.
print("3Done")
# 4.Make sure you understand how I combined a """ style multiline string with the {} format activator as the last print.
print("4Yes")
| true |
13a37744454374b01a2f283f75fdb7b4532e1161 | capitao-red-beard/fluent_python | /part_1/french_deck.py | 1,791 | 4.25 | 4 | import collections
from random import choice
# Creating a named tuple to represent a card.
Card = collections.namedtuple("Card", ["rank", "suit"])
# Creating a class to represent a french deck of cards.
class FrenchDeck:
# Defining the different values associated with a card.
ranks = [str(n) for n in range(2, 11)] + list("JQKA")
suits = "spades diamonds clubs hearts".split()
# Initialisation of a deck of cards.
def __init__(self):
self._cards = [Card(rank, suit)
for suit in self.suits for rank in self.ranks]
# Returns the length of a set of cards.
def __len__(self):
return len(self._cards)
# Returns a cards position in the deck.
def __getitem__(self, position):
return self._cards[position]
# Create a namedtuple of the deck of cards.
beer_card = Card("7", "diamonds")
# Print the card we just created.
print(beer_card)
# Initialise an object of FrenchDeck.
deck = FrenchDeck()
# Return the length of the deck of cards.
print(len(deck))
# Print the first card in the deck.
print(deck[0])
# Print a slice of cards from the deck.
print(deck[12::13])
# Print a random card from the deck.
print(choice(deck))
# Print a reversed version of the deck of cards.
for card in reversed(deck):
print(card)
# Check if a card exisits in the deck.
print(Card("Q", "hearts") in deck)
# Assign values to each suit in a deck of cards so we can sort them.
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
# Returns ranks for each card in a deck.
def spades_high(card):
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(suit_values) + suit_values[card.suit]
# Returns a sorted deck of cards.
for card in sorted(deck, key=spades_high):
print(card[0])
| true |
b4e380031960413e4d61fcbb6eec13a31c0d407a | GeorgeBell233/Python3-Binary-Search | /Alphanumeric Binary Search.py | 1,880 | 4.15625 | 4 | import math
def BinarySearch(List,searchItem,Index):
if len(List) == 0: #Catches index out of range errors for search items above or below the range of numbers in the list
return ("Not in list")
midpoint = math.floor((len(List)-1)/2) #-1 deals with python arrays starting from 0
itemValue = List[midpoint]
if itemValue == searchItem:
Index += midpoint
return (Index)
elif itemValue != searchItem and len(List) == 1:
return ("Not in list")
elif StringComparison(searchItem,itemValue) == True:
Index += midpoint+1 # +1 deals with python lists counting from 0
return (BinarySearch(List[midpoint + 1: len(List)],searchItem,Index)) #Uses list slicing to remove the first half of the list
elif StringComparison(searchItem,itemValue) == False:
return (BinarySearch(List[0:midpoint],searchItem,Index)) #Uses list slicing to remove the second half of the list
def StringComparison(Item1, Item2):
def CompareinLoop(SmallerItem):
for i in range(0,len(SmallerItem)):
if Item1[i] > Item2[i]:
return True
if Item1[i] < Item2[i]:
return False
return False
def StringToListToAscii(String):
List = list(String)
for i in range(0,len(List)):
List[i] = ord(List[i])
return List
Item1 = StringToListToAscii(Item1)
Item2 = StringToListToAscii(Item2)
if len(Item1) >= len(Item2):
return CompareinLoop(Item2)
else:
return CompareinLoop(Item1)
List = ["Ali", "Bob", "Canver", "David", "Eve", "Frankenstein", "Gobble", "Harvard", "Ivan", "Jacob","Jen","Ken", "Larry","Parminder","Yvonne","Zendaya"]
print(List)
Item = input("Enter the search item ")
print(BinarySearch(List,Item,0))
| true |
9a86d97c6fa2982aa666df9eb99ca1d38aa659dd | philster/interviewbit | /topic/trees/flatten.py | 2,871 | 4.40625 | 4 | #
# Flatten Binary Tree to Linked List
#
# Given a binary tree, flatten it to a linked list in-place.
#
# Example:
# Given
#
# 1
# / \
# 2 5
# / \ \
# 3 4 6
#
# The flattened tree should look like:
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
#
# Note that the left child of all nodes should be NULL.
#
class Solution:
# @param A : root node of tree
# @return the root node in the tree
def flatten(self, A):
curr = A
while curr is not None:
# print 'A.val: ' + str(A.val) + ', curr.val: ' + str(curr.val)
if curr.left is None and curr.right is None:
return A
if curr.left is not None:
temp = curr.right
# flatten left and then assign to right
curr.right = self.flatten(curr.left)
# remove link to left
curr.left = None
# traverse to the leaf node of right
while curr.right is not None:
curr = curr.right
# attach temp to leaf node of right
curr.right = temp
# traverse right
curr = curr.right
return A
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def printList(tree):
s = ''
curr = tree
while curr is not None:
s += str(curr.val) + ' -> '
if curr.left is not None:
return s + '[LEFT NODE FOUND!]'
curr = curr.right
return s + 'NULL'
if __name__ == '__main__':
# 1
# / \
# 2 5
# / \ \
# 3 4 6
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)
print 'Output : ' + printList(Solution().flatten(root)) # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
# input: 127 47 42 52 41 44 50 64 40 -1 43 45 49 51 63 77 -1 -1 -1 -1 -1 46 48 -1 -1 -1 55 -1 75 88 -1 -1 -1 -1 53 58 69 76 81 94 -1 54 56 60 68 73 -1 -1 79 87 92 100 -1 -1 -1 57 59 61 66 -1 72 74 78 80 85 -1 89 93 96 102 -1 -1 -1 -1 -1 62 65 67 71 -1 -1 -1 -1 -1 -1 -1 84 86 -1 90 -1 -1 95 99 101 -1 -1 -1 -1 -1 -1 -1 70 -1 83 -1 -1 -1 -1 91 -1 -1 98 -1 -1 -1 -1 -1 82 -1 -1 -1 97 -1 -1 -1 -1 -1
# print 'Output : ' + printList(Solution().flatten(root)) # 47 42 41 40 44 43 45 46 52 50 49 48 51 64 63 55 53 54 58 56 57 60 59 61 62 77 75 69 68 66 65 67 73 72 71 70 74 76 88 81 79 78 80 87 85 84 83 82 86 94 92 89 90 91 93 100 96 95 99 98 97 102 101
| true |
b94b4198480887b543c94051c8695c575967f900 | somphorsngoun/python_week_14 | /python/week14-2.py | 409 | 4.15625 | 4 | def splitBySpace(theString) :
# Write your code here !
result = []
String = ""
for n in range(len(theString)):
if theString[n] != " ":
String += theString[n]
else:
result.append(String)
String = ""
result.append(String)
return result
# MAIN CODE
word = input()
# Write your code here !
print(splitBySpace(word))
| true |
568830ae40d3976e9f17060370dc8bbcad85e98c | mcmido/John-Hammond | /Python/if-condition.py | 1,713 | 4.25 | 4 | #!/usr/bin/env python3
# Simple Structure
#if conditional_statment:
# statment()
'''
# Example
command = "destroy datacores"
if command == "destroy datacores":
print("Destroying all datacores")
# False v
command = "destroy datacores"
if 8 > 16:
print("hello world")
# Optional Else
if command == "hello" and 8 > 1:
pass
else:
print("This executes only if the first condition is false")
# Optional Elif (Between Original conditional test and 'else' keyword)
command = input("How would you like to proceed?\n Chose Between: destroy datacores, shut down, permabork the frambulator.\n> ").lower()
if command == "destroy datacores":
print("Destroying all datacores")
elif command == "shut down":
print("Shutting The system down")
elif command == "permabork the frambulator":
print("Are you sure? You will not be able to unbork this later..")
# None of the otheres evaluated to True
else:
print("Command not understood.")
# The first one to evaluate to True 'wins'
if 3!= 3:
print('Strange...')
elif 8 == 8:
print("First True elif Found....")
elif 8 > 4:
print("second True elif found....")
##################################################
# More complicated, but all the same rules apply
print("This happens befor the 'if' block")
'''
user_is_admin = True
# What conditionals allow you to do
if user_is_admin:
print ("Access Granted.")
command = input("How would you like to proceed??")
command = command.lower()
if command == "destroy datacores":
print("Destroying All Datacores")
elif command == "exit":
print("You don't have the guts, do you?")
else:
print("Access Denied, no correct answer")
else:
print("Access Denied.")
print("This Happens after the 'if' block.") | true |
21e42de07a4a2f5e940ef4aa73b1bdf64f8a4c2d | latajacysmok/cipher-machine_PY3 | /encryption.py | 622 | 4.25 | 4 | #a cipher is given which changes the vowels according to the key:
#key = {"a": "y", "e": "i", "i": "o", "o": "a", "y": "e"}
#The program has a cryptographic function and one that can decrypt the text.
def encryption(s):
key = {"a": "y", "e": "i", "i": "o", "o": "a", "y": "e"}
answer = key[letter] if letter in key.keys() else letter for letter in s]
print("".join(answer))
def decrypt(w):
key = {"a": "y", "e": "i", "i": "o", "o": "a", "y": "e"}
answer = [list(key.keys())[list(key.values()).index(letter)] if letter in list(key.values())
else letter for letter in w]
print("".join(answer))
| true |
a47f3ae5f431bb5ac0e603f48b1e04ff8b5e771d | Yungbluth/Euler | /4.py | 676 | 4.125 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def main():
palindrome = 0
for i in range(100, 999):
for j in range(100, 999):
x = i * j
palin = True
p = str(x)
for y in range(len(p)//2):
z = y + 1
if p[y] != p[-z]:
palin = False
if palin == True:
if x > palindrome:
palindrome = x
print(palindrome)
main()
| true |
e5c58e12180be893a21018bba8e6135a46bde8d2 | shi0524/algorithmbasic2020_python | /Python2/class17/Code05_ReverseStackUsingRecursive.py | 1,084 | 4.40625 | 4 | # -*- coding: utf-8 –*-
"""
给你一个栈,请你逆序这个栈,
不能申请额外的数据结构,
只能使用递归函数。 如何实现?
"""
def reverse(stack):
""" 逆序栈过程
拿栈底元素 1 ——> 递归调用 ——> 拿栈底元素 2 ——> 递归调用 ——> 拿栈底元素 3 ——> 递归调用 ——> 栈空 return
↓
将元素1压回栈 <—— 递归结束 <—— 将元素2压回栈 <—— 递归结束 <—— 将元素3压回栈 <—— 递归结束 <——
"""
if not stack:
return
i = f(stack)
reverse(stack)
stack.append(i)
def f(stack):
"""
栈底元素移除掉
上面的元素盖下来
返回移除掉的栈底元素
"""
result = stack.pop()
if stack:
last = f(stack)
stack.append(result)
return last
else:
return result
if __name__ == "__main__":
stack = [1, 2, 3]
print stack
reverse(stack)
print stack | false |
82008509a91f633c44caaa7ff02f1cda9093e0a3 | shi0524/algorithmbasic2020_python | /Python2/class17/Code02_Hanoi.py | 2,860 | 4.28125 | 4 | # -*- coding: utf-8 –*-
def hanoi1(n):
left_to_right(n)
def left_to_right(n):
""" 把1~N层圆盘 从左 -> 右
"""
if n == 1:
print('Move 1 from left to right')
return
else:
left_to_mid(n - 1)
print("Move {} from left to right".format(n))
mid_to_right(n - 1)
def left_to_mid(n):
""" 把1~N层圆盘 从左 -> 中
"""
if n == 1:
print("Move 1 from left to mid")
else:
left_to_right(n - 1)
print("Move {} from left to mid".format(n))
right_to_mid(n - 1)
def mid_to_right(n):
""" 把1~N层圆盘 从中 -> 右
"""
if n == 1:
print("Move 1 from mid to right")
else:
mid_to_left(n - 1)
print("Move {} from mid to right".format(n))
left_to_right(n - 1)
def mid_to_left(n):
""" 把1~N层圆盘 从中 -> 左
"""
if n == 1:
print("Move 1 from mid to left")
else:
mid_to_right(n - 1)
print("Move {} from mid to left".format(n))
right_to_left(n - 1)
def right_to_left(n):
""" 把1~N层圆盘 从右 -> 左
"""
if n == 1:
print("Move 1 from right to left")
else:
right_to_mid(n - 1)
print("Move {} from right to left".format(n))
mid_to_left(n - 1)
def right_to_mid(n):
""" 把1~N层圆盘 从右 -> 中
"""
if n == 1:
print("Move 1 from right to mid")
else:
right_to_left(n - 1)
print("Move {} from right to mid".format(n))
left_to_mid(n - 1)
def hanoi2(n):
if (n > 0):
func(n, "left", "right", "mid")
def func(n, _from, _to, another):
if n == 1:
print("Move 1 from {} to {}".format(_from, _to))
else:
func(n - 1, _from, another, _to)
print("Move {} from {} to {}".format(n, _from, _to))
func(n - 1, another, _to, _from)
def hanoi3(n):
""" 汉诺塔迭代版
"""
stack = []
stack.append({"finish": False, "base": n, "from": "left", "to": "right", "another": "mid"})
while stack:
task = stack.pop()
if task["base"] == 1:
print("Move 1 from {} to {}".format(task["from"], task["to"]))
if stack:
stack[-1]["finish"] = True
else:
if not task["finish"]:
stack.append(task)
stack.append({"finish": False, "base": task["base"] -1, "from": task["from"], "to": task["another"], "another": task["to"]})
else:
print("Move {} from {} to {}".format(task["base"], task["from"], task["to"]))
stack.append({"finish": False, "base": task["base"] -1, "from": task["another"], "to": task["to"], "another": task["from"]})
if __name__ == "__main__":
n = 3
hanoi1(n)
print("*" * 25)
hanoi2(n)
print("*" * 25)
hanoi3(n)
| false |
79ffc971d865a9cd08e252e5c183021283748864 | MariaC27/VisualizeCities | /quicksort.py | 2,164 | 4.34375 | 4 | # Author: Maria Cristoforo
# Date: November 4, 2020
# Purpose: the functions for Quicksort
# main compare function that takes another function as a parameter
def compare_func(compare_f, x, y):
if compare_f(x, y):
return True
# x is less than y
else:
return False
# x is not less than y
# these two compare functions are just for testing quicksort
# - won't actually be used in sort_cities
def compare_nums(a, b):
return a < b
def compare_strings(a, b):
return a.lower() < b.lower()
# these comparison functions used in sort_cities
def compare_city_population(c1, c2):
return c2.population < c1.population
# do c2 less c1 so that cities are printed out in order
# of largest to smallest population
def compare_city_name(c1, c2):
return c1.name.lower() < c2.name.lower()
def compare_city_latitude(c1, c2):
return c1.lat < c2.lat
# partitions sublist and returns the index where pivot is placed
def partition(the_list, p, r, compare_func):
i = p-1
j = p
pivot = the_list[r] #the chosen pivot is always the last element of the list
while j < r: # loops stops the second j = r
if compare_func(pivot, the_list[j]):
j = j + 1
else:
i = i + 1
the_list[j], the_list[i] = the_list[i], the_list[j] #swap
j = j + 1
the_list[i + 1], the_list[r] = the_list[r], the_list[i + 1]
#swap to get pivot in the right place
return i + 1
#code to test out the partition function
# mlist = [5, 2, 7, 10, 3, 33, 2, 1, 9, 0, 5]
# id = partition(mlist, 0, len(mlist)-1, compare_nums)
# print("index of pivot:", id)
# print("tested out partition:", mlist)
def quicksort(the_list, p, r, compare_func):
if (r-p) < 2:
return
# base case
q = partition(the_list, p, r, compare_func)
quicksort(the_list, p, q-1, compare_func)
quicksort(the_list, q, r, compare_func)
def sort(the_list, compare_func):
quicksort(the_list, 0, len(the_list)-1, compare_func)
# code to test out quicksort
# mlist = [5, 0, 7, 10, 3, 33, 2, 1, 9, 1, 5]
# sort(mlist, compare_nums)
# print("sorted:", mlist)
| true |
45c5ba683a408f15c3f21485ee24ac9febd9b4af | Jack-Walsh/cp1404practicals | /prac_01/shop_calculator.py | 1,022 | 4.46875 | 4 | """A shop requires a small program that would allow them to quickly work out the total price for a number of items, each with different prices.
The program allows the user to enter the number of items and the price of each different item.
Then the program computes and displays the total price of those items.
If the total price is over $100, then a 10% discount is applied to that total before the amount is displayed on the screen.
The output should look something like (bold text represents user input):
Number of items: 3
Price of item: 100
Price of item: 35.56
Price of item: 3.24
Total price for 3 items is $124.92
"""
total_price = 0
num_items = int(input("Number of items: "))
# print amount of item prices as inputted by user
for i in range(1, num_items + 1):
item_price = float(input("Price of item: "))
total_price += item_price
# apply discount of 10%
if total_price > 99:
total_price = total_price * 0.9
# print total
print("Total price for {} items is {}".format(num_items, total_price))
| true |
c3fc116d5fc25ecb9ba709dd1a3738c53648b75d | bookstein/SkillsTests | /skills1/skills1.py | 2,800 | 4.125 | 4 | # Things you should be able to do.
number_list = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"]
# Write a function that takes a list of numbers and returns a new list with only the odd numbers.
def all_odd(number_list):
def is_odd(num):
return num % 2 != 0
return filter(is_odd, number_list)
# Write a function that takes a list of numbers and returns a new list with only the even numbers.
def all_even(number_list):
def is_even(num):
return num % 2 == 0
return filter(is_even, number_list)
# Write a function that takes a list of strings and a new list with all strings of length 4 or greater.
def long_words(word_list):
def check_length(word):
return len(word) >= 4
return filter(check_length, word_list)
# Write a function that finds the smallest element in a list of integers and returns it.
def smallest(number_list):
def is_smaller(num1, num2):
if num1 < num2:
return num1
else:
return num2
return reduce(is_smaller, number_list)
# Write a function that finds the largest element in a list of integers and returns it.
def largest(number_list):
def is_larger(num1, num2):
if num1 > num2:
return num1
else:
return num2
return reduce(is_larger, number_list)
# Write a function that takes a list of numbers and returns a new list of all those numbers divided by two.
def halvesies(number_list):
def divide_by_2(number):
return float(number)/2
return map(divide_by_2, number_list)
# Write a function that takes a list of words and returns a list of all the lengths of those words.
def word_lengths(word_list):
def measure_length(word):
return len(word)
return map(measure_length, word_list)
# Write a function (using iteration) that sums all the numbers in a list.
def sum_numbers(number_list):
return reduce(sums, number_list)
# Created this function for sum_numbers, need it for average as well
def sums(num1, num2):
return num1 + num2
# Write a function that multiplies all the numbers in a list together.
def mult_numbers(number_list):
def multiply(num1, num2):
return num1 * num2
return reduce(multiply, number_list)
# Write a function that joins all the strings in a list together (without using the join method) and returns a single string.
def join_strings(word_list):
def combine_words(word1, word2):
return (word1 + " " + word2)
return reduce(combine_words, word_list)
# Write a function that takes a list of integers and returns the average (without using the avg method)
def average(number_list):
return (reduce(sums, number_list))/len(number_list)
| true |
cac3b3cc71620de571baddc4c60c0cedf32adbff | nurseiit/comm-unist | /data-science-not/weeks/m04_trees/p2/read_write_file_example.py | 2,071 | 4.625 | 5 | """
Here we demonstrate how to create a file, write something in that file, and read datastore from a file.
This mini-tutorial is useful to complete the exercises of this week and also assignment n.2 (MRP)
"""
if __name__ == '__main__':
"""Open a file (in write mode)
if the file does not exist, it will be created. If it exists, then whatever you write in it after opening
will overwrite the existing content"""
file_name = "file.txt" # can be any existing path on your computer!
file = open(file_name, "w") # the file is now open in write ("w") mode
string1 = "Let's write this in the file"
string2 = "...and then let's also write this!"
print("writing file {0} ...".format(file_name))
file.write(string1) # Let's write the 2 strings in the file
file.write(string2)
print("...done!")
file.close() # always "close" files when no longer needed
""" now check the content of file.txt!"""
input("Type enter to continue...")
""""# Now let's open a file
In the file read.txt, each line contains some datastore separated by the character "comma" (',')"""
read_file_name = "read.txt"
print("Let's open the file {0}...".format(read_file_name))
read_file = open(read_file_name, "r")
for line in read_file.readlines(): # read lines in file one by one
print("===== This is the next entire line: {0}".format(line))
values = line.split(',') # split the line using separator ','
for value in values:
value = value.strip() # IMPORTANT: always use strip() to 'strip' all non readable characters from a string (e.g. end of line, end of file etc.)
print("New value found in line: {0}".format(value))
read_file.close() # always "close" files when no longer needed
| true |
8c6967a2a93baf145a9af5ab0ef62925c7a6e7f5 | nurseiit/comm-unist | /data-science-not/weeks/m02_ccr/p2/complexity.py | 2,587 | 4.40625 | 4 | """
Your task is to
implement a function intersection(A,B,C) that
tests whether the intersection of the lists A, B, and C is empty
Assuming that the 3 lists have at most 1 element in common, in case of
not empty intersection the function prints the positions in the 3 lists at
which the common element is found.
Example:
A = [4, 7, 8, 4], B=[89, 76], C=[6,9,67]
(no intersection)
A = [4, 7, 8, 4], B=[9, 1, 7, 3, 4], C=[56, 33, 7]
intersection(A,B,C) prints the message
Intersection found at A[1], B[2], C[2]
Your solution should also print the time it took to execute the function
Note the import of the function "time" to capture the current time in your program
More info about importing modules: https://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Importing_Modules
Once you have completed your implementation, answer the following question:
What is the time complexity of your solution?
What about the worst case?
"""
from time import time
# use time() to capture the current system time in your code, e.g., start_time = time()
def intersection(A,B,C):
"""
sleep() calls are delays of 0.3s
introduced to make you appreciate the compelxity of the the 2 solution
(this and slow below)
"""
D = set(A + B + C)
A_set = set(A)
B_set = set(B)
C_set = set(C)
result = [val for val in D if val in A_set and val in B_set and val in C_set]
# O(N log N) for I use 'set'
for val in result:
print('Intersection found at A[%d], B[%d], C[%d]' % (A.index(val), B.index(val), C.index(val)))
if len(result) == 0:
print('No intersection found!')
def intersection_slow(A,B,C):
# O(N^3)
for a in A:
for b in B:
for c in C:
if a == b and b == c:
val = a
print('Intersection found at A[%d], B[%d], C[%d]' % (A.index(val), B.index(val), C.index(val)))
return
print('No intersection found!')
if __name__ == '__main__':
A = [4, 7, 8, 4]
B = [89, 76]
C = [6, 9, 67]
print('Fast:')
start = time()
intersection(A,B,C)
print('Done in %f seconds!' % (time() - start))
print('Slow:')
start = time()
intersection_slow(A, B, C)
print('Done in %f seconds!' % (time() - start))
D = [4, 7, 8, 4]
E = [9, 1, 7, 3, 4]
F = [56, 33, 7]
start = time()
print('Fast:')
intersection(D,E,F)
print('Done in %f seconds!' % (time() - start))
start = time()
print('Slow:')
intersection_slow(D, E, F)
print('Done in %f seconds!' % (time() - start))
| true |
d09a2de90a6f68248f166811199aa7691b070bf9 | 248808194/python-study | /set集合/set.py | 612 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Zhoutao
#使用set()来创建一个集合
empty_set = set()
print(empty_set)
#与字典一样,集合是无序的
###!!!###!!!你可以利用已有列表、字符串、元组或字典的内容来创建集合
print("字符串创建集合")
a=set('zhoutao')
print(a)
print(type(a))
print("列表创建集合")
a=set([1,2,3,4,5])
print(a)
print(type(a))
print("元祖创建集合")
a=set(('a','b','c',1,2,3))
print(a)
print(type(a))
print("当字典作为参数传入的时候只有键会被使用")
a=set({'a':1,'b':2,'c':3})
print(a)
print(type(a)) | false |
f89372152217c3efcd02e49efa17e3880eb3b12f | 248808194/python-study | /面向对象编程/特殊成员.py | 2,732 | 4.34375 | 4 | """
class f1:
def __init__(self):
print("init")
def __del__(self):
pass
def __call__(self, *args, **kwargs):
print("call")
# obj= f1() #类后面加()执行__init__方法
# obj() #对象后面加()执行 __call__方法
f1()() #f1()执行init方法在执行call方法 #这个是python变态的一个地方那个
"""
#str方法
"""
class f1:
def __init__(self):
print("init")
def __str__(self):
a="3"
c="3"
return a+c
def __call__(self, *args, **kwargs):
print("call")
obj = f1()
print(obj)
#如果定义了str方法,默认print(obj) 就是print str的时候默认是输出的对象在内存中的地址
#定义str方法,str中return什么就会输出什么
"""
#add方法
"""
class f1:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
a="3"
c="3"
return a+c
def __call__(self, *args, **kwargs):
print("call")
def __add__(self, other):
temp = "%s + %d "% (self.name,other.age)
return temp
obj1 = f1("zhoutao",30)
obj2 = f1("zhoutao1",33)
#obj1 = add 中的self
#obj2 = add中的other
result = obj1+obj2
print(result)# 结果就是zhoutao + 33
#__dict__拿到对象中封装所以的字段,并且以字典的形式呈现出来
a=obj1.__dict__
print(a)
"""
#__getitem__ ,__setitem__ ,__delitem__
#用于索引操作,如字典。以上分别表示获取、设置、删除数据
class FOO:
def __getitem__(self, key):
print("__getitem",key,type(key))
print(key.start) # 如果通过切片方式访问的话,key.start就是切片的起始位置,ret1 = OBJ[1:4:9] 就是1
print(key.stop) # 如果通过切片方式访问的话,key.start就是切片的结束位置,ret1 = OBJ[1:4:9] 就是4
print(key.step) # 如果通过切片方式访问的话,key.start就是切片的补偿,ret1 = OBJ[1:4:9] 就是4
def __setitem__(self, key, value):
print("__setitem__",key,value)
def __delitem__(self, key):
print("__delitem__",key)
OBJ = FOO()
# result = OBJ["k1"] #自动执行 __getitem__方法
# OBJ["K2"] = "ZHOUTAO" #自动执行 __setitem__方法
# del OBJ["K1"] #自动执行__delitem__方法
ret1 = OBJ[1:4:9] #如果通过切片方式访问的话,key的类型就是slice类型#
OBJ[1:4] = [11,22,33]
del OBJ[1:4]
#__getitem slice(1, 4, None) <class 'slice'>
#__iter__实现类似迭代器
# class FOO:
# def __iter__(self):
# return iter([11,22,33,44])
#
# OJB = FOO()
#
# for item in OJB:
# print(item)
class FOO:
def __iter__(self):
yield list([11,22,33,44])
OJB = FOO()
for item in OJB:
print(item)
| false |
199fce286d8df5538c399c7bcd2583f327c80bcd | EllisHornabrook/learning-python | /Notes/maps.py | 415 | 4.125 | 4 | from random import shuffle
words = ['gears', 'effect', 'duty', 'swamp']
anagrams = []
def jumble(word):
anagram = list(word)
shuffle(anagram)
return ''.join(anagram)
for word in words:
anagrams.append(jumble(word))
print(anagrams)
# using simple map takes for loop from 3 lines to 1 line
print(list(map(jumble, words)))
# or comprehension way
print( [ jumble(word) for word in words ] ) | true |
37e9b59805285e9b1ce91914493874853403bc16 | starovp/leetcode-sols | /problem-20-valid-parentheses/validpar.py | 1,676 | 4.21875 | 4 | """
20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
"""
class Solution:
# Runtime: 32 ms, faster than 82.66% of Python3 online submissions for Valid Parentheses.
# Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Valid Parentheses.
def isValid(self, s):
# s: str
# return: bool
# Create map of matching parentheses
match_map = {
')': '(',
'}': '{',
']': '['
}
stack = []
# Traverse string
for i in range(len(s)):
# Top of stack is assigned or non-element value if stack empty
top = stack[-1] if stack else 'X'
# If opening bracket, append to the top of stack
if s[i] in match_map.values():
stack.append(s[i])
# If current parenthesis doesn't match the top of stack, break
elif top != match_map[s[i]]:
return False
# Otherwise it's valid and we eliminate that parenthesis from stack
else:
stack.pop()
return len(stack)==0
if __name__ == '__main__':
solution = Solution()
print(solution.isValid("()"))
print(solution.isValid("()[]{}"))
print(solution.isValid("(]"))
print(solution.isValid("([)]"))
print(solution.isValid("["))
print(solution.isValid("]"))
| true |
5005773da0d01f8058c44c817cd38378abb6da66 | dr-sera/Algorithm_and_data_structure_python | /Task_8.py | 638 | 4.1875 | 4 | # 8. Определить, является ли год, который ввел пользователь, високосным или не високосным.
print('Введите год для проверки: ')
y = int(input())
if y % 4 != 0:
print('Введенный год не является високосным!')
elif y % 100 == 0:
if y % 400 == 0:
print('Введенный год является високосным!')
else:
print('Введенный год не является високосным!')
else:
print('Введенный год является високосным!')
| false |
636ff58f648e8d64499c174d6b692ebdc96424b9 | justenpinto/coding_practice | /interviewcake/hashtables/inflight_entertainment.py | 1,534 | 4.6875 | 5 | """
Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane
usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runtimes
will equal the exact flight length.
Write a function that takes an integer flight_length (in minutes) and a list of integers movie_lengths (in minutes) and
returns a boolean indicating whether there are two numbers in movie_lengths whose sum equals flight_length.
When building your function:
1. Assume your users will watch exactly two movies
2. Don't make your users watch the same movie twice
3. Optimize for runtime over memory
"""
def check_movie_lengths(flight_time, movies_lengths):
"""
Runtime: O(n)
Space: O(1)
We make one pass through movie_lengths, treating each item as the first_movie_length. At each iteration, we:
1. See if there's a matching_second_movie_length we've seen already (stored in our movie_lengths_seen set) that is
equal to flight_length - first_movie_length. If there is, we short-circuit and return True.
2. Keep our movie_lengths_seen set up to date by throwing in the current first_movie_length.
"""
movie_lengths_seen = set()
for movie_length in movies_lengths:
remaining_time = flight_time - movie_length
if remaining_time in movie_lengths_seen:
return True
else:
movie_lengths_seen.add(movie_length)
return False
if __name__ == '__main__':
pass
| true |
9f9a5666b006940a0fc09ed94ea6481bec8397d2 | justenpinto/coding_practice | /interviewcake/array/merging_meetings.py | 2,554 | 4.21875 | 4 | """
Your company built an in-house calendar tool called HiCal. You want to add a feature to see the times in a day when everyone is available.
To do this, you’ll need to know when any team is having a meeting. In HiCal, a meeting is stored as a tuple of integers
(start_time, end_time). These integers represent the number of 30-minute blocks past 9:00am.
For example:
(2, 3) # Meeting from 10:00 – 10:30 am
(6, 9) # Meeting from 12:00 – 1:30 pm
Write a function merge_ranges() that takes a list of multiple meeting time ranges and returns a list of condensed ranges.
For example, given:
[(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
your function would return:
[(0, 1), (3, 8), (9, 12)]
Do not assume the meetings are in order. The meeting times are coming from multiple teams.
Write a solution that's efficient even when we can't put a nice upper bound on the numbers representing our time ranges.
Here we've simplified our times down to the number of 30-minute slots past 9:00 am. But we want the function to work
even for very large numbers, like Unix timestamps. In any case, the spirit of the challenge is to merge meetings where
start_time and end_time don't have an upper bound.
"""
def merge_ranges(meetings):
"""
Runtime: O(n lg n)
Space: O(n)
First, we sort our input list of meetings by start time so any meetings that might need to be merged are now next to
each other.
Then we walk through our sorted meetings from left to right. At each step, either:
1. We can merge the current meeting with the previous one, so we do.
2. We can't merge the current meeting with the previous one, so we know the previous meeting can't be merged with
any future meetings and we throw the current meeting into merged_meetings.
"""
sorted_meetings = sorted(meetings, key=lambda tup: tup[0])
print("Meeting: %s - %s" % (meetings[0]))
new_meetings = [meetings[0]]
for start_time, end_time in sorted_meetings[1:]:
print("Meeting: %s - %s" % (start_time, end_time))
latest_meeting_start, latest_meeting_end = new_meetings[-1]
if start_time <= latest_meeting_end:
new_meetings[-1] = (latest_meeting_start, max(latest_meeting_end, end_time))
else:
new_meetings.append((start_time, end_time))
return new_meetings
if __name__ == '__main__':
print(merge_ranges([
(0, 1),
(3, 5),
(4, 8),
(10, 12),
(9, 10)
]))
print(merge_ranges([
(1, 5),
(2, 3)
]))
| true |
cf81ba9fe963e9f3723402738b09688f874926ef | minnella/Lab3 | /Pro4_lab3_Turtles.py | 421 | 4.21875 | 4 | import turtle # allows us to use the turtles library
wn = turtle.Screen() #creates a graphics window
#set the turtle background color
wn.bgcolor("lightblue")
#creates a turtle named Murtle
Murtle = turtle.Turtle()
#Murtle's attributes
Murtle.color("darkgreen")
Murtle.pensize(5)
#move Murtle with user input
sides = input("Number of sides: " )
for i in range(sides):
Murtle.forward(75)
Murtle.right(360/sides)
| true |
2a1c17ff203b20bea7a5fc6956c1b27cf88bf8ae | SrikanthParsha14/test | /testpy3/decorator_std.py | 1,718 | 4.15625 | 4 | """ The "right" usage of getter/setter
In class `Circle`, `self.edge` is the origin data, so it SHOULD be access directly. the `area`, are not a data holding directly by the object. But it related with the origin data `self.edge`. If we want the user to access `area` just like the origin data, only when we need getter/setter.
Another usage of getter, is protect a data to be read only after the object created. `color` is used as a read only property with getter.
"""
import numpy as np
class Circle(object):
def __init__(self, edge, color):
self.edge = edge
self._color = color
@classmethod
def e(cls):
return np.e
@staticmethod
def pi():
return np.pi
@property
def area(self):
return self.edge ** 2
@area.setter
def area(self, area):
self.edge = area ** 0.5
@property
def color(self):
return self._color
@color.deleter
def color(self):
self._color = "write"
def main():
c = Circle(5, "red")
print(Circle.e()) # class method, with a `cls` argument instead of `self`
print(c.e()) # also can be call from object
print(Circle.pi()) # static method is just a normal function like outside
print(c.pi()) # static method is just a normal function like outside
print(c.area) # getter
c.area = 7 # setter
print(c.edge) # getter
# c.color = "blue" # error: read only
print(c.color) # get read only color
# With prefix "_" tells user not to access it outside, but not forced.
# c._color = "blue"
del c.color # deleter invoke
print(c.color)
if __name__ == '__main__':
main()
| true |
3f4bd727e308e35901da7cb46197dbe2db44c7a2 | erodri17/Python3 | /lab_computer_programs.py | 1,072 | 4.53125 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name: Elmer Rodriguez
# Institution: University of Rochester
# Professor: Richard Sarkis
# Course: CSC 161: INTRO TO PROGRAMMING
# Assignment: Computer and Programs
# All Rights Reserved
# File: lab_computer_programs.py
# A simple program illustrating chaotic behavior.
#Defining the main function
def main():
#Printing a line to the user in order to program some context of the program
print("\nThis program illustrates a chaotic function")
#The following line is asking the user "How manu numbers should the program print?" and storing that information on the variable (n)
n = input("How many numbers should I print? ")
#The following line is asking the user "Enter a number between 0 and 1:" and storing that information on the variable (x)
x = input("Enter a number between 0 and 1: ")
#Running a loop within the parameters provided by the user (n) and printing an output stored in the variable (x)
for i in range(n):
x = 3.9 * x * (1 - x)
print(x)
#calling the main function
main()
| true |
622592726f68dbaf220a817314737b93c65d91d1 | saransh-khobragade/Python | /syntax/7.string.py | 791 | 4.125 | 4 | #LENGTH OF STRING----------------------------------------
a = "Hello, World!"
print(len(a)) #13
#CHECK IN STRING----------------------------------------
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
if "abc" not in txt:
print("Yes, 'abc' not is present.")
#SLICE----------------------------------------------------
#Saransh
#0123456
str = "Saransh"
print(str[1]) #a from index 1 only one element
print(str[-2]) #s from last second index only one element
print(str[2:5]) #llo [including:excluding]
#sorted()----------------------------------------------------
print(sorted("abc")) #['a', 'b', 'c']
#converting list to integers to single string
''.join(list(map(str,arr)))
#getting a string from list
w = "".join(input().split())
| true |
b1945d5007fa2cdfd9f6d2091b273b7b9ccda82c | Nobodylesszb/python_study | /wthpython/another_class/class.py | 583 | 4.1875 | 4 | class SomeClass:
some_var = 15
some_list = [5]
another_list = [5]
def __init__(self, x):
self.some_var = x + 1
self.some_list = self.some_list + [x]
self.another_list += [x]
some_obj = SomeClass(420)
print(some_obj.some_list,some_obj.another_list)
"""
output:
[5, 420] [5, 420]
"""
another_obj = SomeClass(111)
print(another_obj.some_list,another_obj.another_list)
"""
output:
[5, 111] [5, 420, 111]
"""
print(another_obj.another_list is SomeClass.another_list)
print(another_obj.another_list is some_obj.another_list)
"""
output:
True
"""
| false |
43dee36366235c99d9c320d180864770f5638f85 | Nobodylesszb/python_study | /wthpython/tuple/mutate_tuple.py | 380 | 4.125 | 4 | some_tuple = ("A", "tuple", "with", "values")
another_tuple = ([1, 2], [3, 4], [5, 6])
# some_tuple[2] = 'change this'
# """
# TypeError: 'tuple' object does not support item assignment
# """
another_tuple[2].append(1000)
print(another_tuple)
# another_tuple[2] += [99,999]
"""
output:
([1, 2], [3, 4], [5, 6, 1000])
TypeError: 'tuple' object does not support item assignment
""" | false |
a6e34317ff73a649aeb938cf9af7427f99d309bc | ARHimes78/Programming-Classes | /CIS1250 Python/HimesP3.py | 1,069 | 4.59375 | 5 | # HimesP3
# Programmer: Alan Himes
# EMail: ahimes1@cnm.edu
# Purpose: provides user capability to find fruit in a string
fruits = ['apple', 'orange', 'banana', 'pineapple', 'watermelon', 'grape', 'lemon']
sentence = raw_input("Please enter a sentence with a fruit in it: ")
#Changing the string into a list.
sentence = sentence.split()
#Creating a list of the words from the sentence that match
#words from the fruits list.
commonWords = list(set(fruits).intersection(set(sentence)))
if len(commonWords) == 0:
print "No fruits detected in this sentence."
else:
print "I found " + str(len(commonWords)) + " fruits in your sentence!"
print "Your fruits are: " + str(commonWords)
#Replacing the word in the sentence that is the same as the last
#element of commonWords(list of fruits in the sentence)
#with "Brussels sprouts".
sentence[sentence.index(commonWords[-1])] = 'Brussels sprouts'
#Changing the list of the sentence back to a string.
sentence = ' '.join(sentence)
print "Your sentence with Brussels sprouts: " + sentence
| true |
38e7ea6c33ca92d5dbe4b420b0e3550cd34f1153 | ARHimes78/Programming-Classes | /CIS1250 Python/HimesP2.py | 668 | 4.125 | 4 | # HimesP2
# Programmer: Alan Himes
# EMail: ahimes1@cnm.edu
# Purpose: provides user capability to view contact info
names = ['Jesse', 'Margaret', 'Thomas']
email = ['spam_collector_j@gmail.com',
'peggymobile@yahoo.com',
'slackerTom13675@aol.com']
phone = ['555-9381', '555-1200', '555-3333']
print names
nameChoice = raw_input("Choose one of the names for contact info: ")
#Name's index corresponds to the index of the other lists.
if nameChoice in names: print nameChoice \
+ "'s email: " + email[names.index(nameChoice)] \
+ " phone #: " + phone[names.index(nameChoice)]
#I just wanted to see if this would work.
if nameChoice not in names: print "Invalid choice, please run the program again."
| true |
15aa29b41e5d15bcb682d3496f972e03d27dd48f | Bruno-Nasc-Br/Curso-Pytho---Curso-em-video | /Desafio 004 tipos primitivos e saida de dados.py | 982 | 4.21875 | 4 | '''
Curso básico de Python
----------------------
www.cursoemvideo.com
-----------------------------
Professor: Gustavo Guanabara
Aluno: Bruno Nascimento
----------------------------------------------------------------------------
Desafio 004 = faça um programa que leia algo pelo teclado e mostre na tela
o seu tipo primitivo e todas as informações possiveis sobre ele.
----------------------------------------------------------------------------
'''
# INICIO DO PROGRAMA - DESAFIO 004 #
print ('-----------------------------------------------------')
print ('Digite um número para descobre o tipo primitivo dele.')
print ('-----------------------------------------------------')
n = input ('Digite aqui : ')
print('É um alfanumério ?')
print (n.isalnum())
print ('É decimal ?')
print (n.isdecimal())
print ('É alfabetico ?')
print (n.isalpha())
print ('Tem apenas letras MAIÚSCULAS ?')
print (n.isupper())
| false |
3bb434f108cce64147df49dcffacf436bb560b9c | manojdscode/pythonPrograms | /MenuDriven.py | 1,493 | 4.25 | 4 | # Menu driven simple calculator
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# Function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
# Function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
# Function to divide two numbers
def divide(num1, num2):
return num1 / num2
#Function to find modulus
def modulus(num1, num2):
return num1 % num2
print("Please select operation")
print("1. Addition")
print("2.Substraction")
print("3.Multiplication")
print("4.Division")
print("5.Modulus")
# Take input from the user
select = input("Select operations form 1, 2, 3, 4, 5 :")
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
if select == '1':
print(number_1, "+", number_2, "=",
add(number_1, number_2))
elif select == '2':
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == '3':
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == '4':
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
elif select == '5':
print(number_1, "%", number_2, "=",
modulus(number_1, number_2))
else:
print("Computer are more smart these days!! wink")
print("Dear user, You have entered a wrong choice.")
| true |
378e576ef7b1d9c506f7b4f99e3e2ee59052f079 | Python-ae/talkpython | /practice.py | 624 | 4.25 | 4 | # see this page!
# -> https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/
def main():
int_dict ={12: 'one', 11: 'two', 33: 'three'}
int_dict_keys = list(int_dict.keys())
int_dict[44] = 'last'
print(f"int key are: {int_dict_keys}")
print(' '.join(map(str, int_dict_keys))) #for integers only - using map
board = {'first': 100, 'second': 3993}
board['third'] = 333
listOfDictKeys = list(board.keys())
print(f" string keys are: {listOfDictKeys}")
print(' '.join(listOfDictKeys)) # for string wihout using map
if __name__ == '__main__':
main() | false |
705dc4c4fb8663eca4cedc8d6016fba0eafcb28f | tjpreston96/python_practice | /exercise_02.py | 542 | 4.21875 | 4 | # Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
# Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
# Solution:
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
x = int(input("Please enter the number 8: "))
print("Expected result => 40320")
print(fact(x))
| true |
2e129133c77a8a6f7f03585286ee9ee93da48e2c | allarassemmaxwell/assignment-in-python | /assignment3.py | 576 | 4.125 | 4 | print("*********************************************************")
print("******************** ASSIGNMENT THREE *******************")
print("*********************************************************")
print("\n")
count = 0
# FUNCTION TO REMOVE SPACE
def remove(string):
return string.replace(" ", "")
# GET TEXT FROM USER
user_text = input("Please enter a long text: ")
print("Original text: ",user_text)
print("Removed space: ",remove(user_text))
for i in user_text:
if (i.isspace()):
count += 1
print("The number of blank spaces is: ",count)
print("\n") | true |
ea698d79f6293f5d7e51ea2949847843f5edf612 | fedeMorlan/semin_python_2021 | /practico1/ej2_desafios_teoria1.py | 2,113 | 4.1875 | 4 | # ----------- primer desafío ----------------
# lee un numero y determina si es par o impar
num = int(input("ingresa un número: "))
if (num % 2 == 0):
print("es par")
else:
print("NO es par")
# --------------segundo desafío ------------------------
# lee un numero de teclado e imprime si es multiplo de 2, 3 o 5.
# terminé no utilizando elif porque puede ser multiplo de 2 y 5 ó 3 y 5.
num = int(input("ingresa un número más: "))
if (num % 2 == 0):
print("es múltiplo de 2. ")
# puede ser multiplo de 2 y de 5.
if (num % 5 == 0):
print("es múltiplo de 5. ")
# puede ser multiplo de 3 y de 5.
if (num % 3 == 0):
print("es múltiplo de 3. ")
else:
print("no es múltiplo ni de 2, ni de 3 ni de 5.")
# --------------tercer desafío -------------------------
# dado una letra ingresada imprime si es mayuscula o minuscula
char = input("Ingresar una letra: ")
if (char >= "A") and (char <= "Z"):
print("Es mayúscula")
elif (char >= "a") and (char <= "z"):
print("Es minúscula")
else:
print("No es una letra!")
# -------------cuarto desafío --------------------------
# imprime si un caracter ingresado es una comilla o no.
char = input("Ingresar un caracter: ")
# envuelvo el caracter de comilla con comillas diferentes (como alternativa a escapatoria con barra invertida)
if (char == "'") or (char == '"'):
print("es una comilla.")
else:
print("no es una comilla.")
# -------------quinto desafío ----------------------------
# dadas dos cadenas ingresadas por teclado, imprime la mas larga
str1 = input("Ingresar una cadena de texto: ")
str2 = input("Ingresar otra cadena de texto: ")
if (len(str1) > len(str2)):
print(str1)
elif (len(str1) < len(str2)):
print(str2)
else:
print("las dos cadenas ingresadas tienen igual longitud.")
# -------------sexto desafio -------------------------------
# imprime cuantas letras "a" contiene una cadena de caracteres
str1 = input("Ingresar una nueva cadena de texto: ")
total_a = 0
for c in str1:
if c == "a":
total_a = total_a + 1
print("la cadena tiene " + str(total_a) + " letras 'a'.")
| false |
2cc1f6dc22158f8ac72c4fdfbdb7566347775c74 | arzzon/PythonLearning | /PythonInbuilts/Advanced/Map/map.py | 644 | 4.71875 | 5 | '''
Map is used to generate another iterable from the iterable provided to it along with
the lambda function, where each element of the generated iterable is mapped/modified
to some value based on the lambda function logic provided to it.
It returns a map object which contains all those filtered elements. We can type cast
these objects to iterables like list/set etc.
Syntax:
=> map(lambda function, iterable)
type casting to list:
=> list( map(lambda function, iterable) )
'''
L = [1, 2, 3, 4, 5, 6]
# Each element in the list is squared.
squaredList = list(map((lambda x: x**2), L))
print(squaredList) | true |
3e293db90f067512b66b4fdd2f18d797a81614c8 | gustavoallfadir/python-challenges | /array_peaks.py | 2,167 | 4.40625 | 4 | '''
In this kata, you will write a function that returns the positions and the values of
the "peaks" (or local maxima) of a numeric array.
For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value
of 5 (since arr[3] equals 5).
The output will be returned as an object with two properties: pos and peaks. Both of
these properties should be arrays. If there is no peak in the given array, then the output
should be {pos: [], peaks: []}.
Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]) should return {pos: [3, 7],
peaks: [6, 3]} (or equivalent in other languages)
All input arrays will be valid integer arrays (although it could still be empty), so
you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context
of a mathematical function, we don't know what is after and before and therefore, we don't
know if it is a peak or not).
Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while [1, 2, 2, 2, 3] and
[1, 2, 2, 2, 2] do not. In case of a plateau-peak, please only return the position and value
of the beginning of the plateau.
For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]} (or equivalent in other languages)
Have fun!
'''
def pick_peaks(arr):
return {'pos':[i+1 for i,x in enumerate(arr[1:-1]) if arr[i] < x >= arr[i+2]], 'peaks':[x for i, x in enumerate(arr[1:-1]) if arr[i] < x >= arr[i+2]]}
print(pick_peaks([1,2,3,6,4,1,2,3,2,1])) #{"pos":[3,7], "peaks":[6,3]})
print(pick_peaks([3,2,3,6,4,1,2,3,2,1,2,3])) #{"pos":[3,7], "peaks":[6,3]})
print(pick_peaks([3,2,3,6,4,1,2,3,2,1,2,2,2,1])) #{"pos":[3,7,10], "peaks":[6,3,2]})
print(pick_peaks([2,1,3,1,2,2,2,2,1])) #{"pos":[2,4], "peaks":[3,2]})
print(pick_peaks([2,1,3,1,2,2,2,2])) #{"pos":[2], "peaks":[3]})
print(pick_peaks([2,1,3,2,2,2,2,5,6])) #{"pos":[2], "peaks":[3]})
print(pick_peaks([2,1,3,2,2,2,2,1])) #{"pos":[2], "peaks":[3]})
print(pick_peaks([1,2,5,4,3,2,3,6,4,1,2,3,3,4,5,3,2,1,2,3,5,5,4,3])) #{"pos":[2,7,14,20], "peaks":[5,6,5,5]})
print(pick_peaks([])) #{"pos":[],"peaks":[]})
print(pick_peaks([1,1,1,1])) #{"pos":[],"peaks":[]}) | true |
658fb5f20d1345f43b16a33ae32f544ef975912a | AngelaSophia/PYTHON | /revision.py | 1,239 | 4.5 | 4 | first_name="ayugi"
last_name="sophia"
school="akirachix"
country="kenya"
year_of_birth=1997
full_name=first_name+last_name
print(full_name)
print(full_name.upper())
print(school.upper())
age=2021-year_of_birth
print(age)
print(f"Hello, my fullname is {full_name},I am currently studing at {school} \n my nationality is {country} am {age} years old")
print("Hello, my name is {} and am taking my studies at {} \n am from this country{} finaly am {} years old".format(full_name,school,country,age))
name="lisa lab"
print(name.title())
first_name="laura"
last_name="betty"
full_name=f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.title()}!")
# use of f-string to compose a massage
massage=f"Hello,{full_name.title()}!"
print(massage)
# adding whitespace to Strings with tabs or new lines
fevorite_language="Python"
print(fevorite_language.rstrip())
sentence="I love my life and my country"
print(sentence.rstrip())
name="Brawlian,"
massage="Hello,would you like to do some Python today?"
sentence=f"{name} {massage}"
print(sentence)
var="Brawlian"
print(var.upper())
print(var.lower())
print(var.title())
Author="Michel"
Quote=" said be strong,don't be afraid,be focused "
output=f"{Author} {Quote}"
print(output)
| false |
2a63fc3468258185301d7d872bbabf8b3486f700 | JoshCoop1089/Private-Projects | /Python/2019/Kaggle Classes/1 Python/6 Strings and Dictionaries.py | 908 | 4.125 | 4 | def word_search(doc_list, keyword):
"""
Takes a list of documents (each document is a string) and a keyword.
Returns list of the index values into the original list for all documents
containing the keyword.
Example:
doc_list = ["The Learn Python Challenge Casino.", "They bought a car",
"Casinoville"]
>>> word_search(doc_list, 'casino')
>>> [0]
"""
ans = []
for i in range(len(doc_list)):
index = doc_list[i].lower().find(keyword)
if index != -1:
end = index+len(keyword)
if (doc_list[i][end] == ' ' or doc_list[i][end] == '.'
or doc_list[i][end] == ',' or end == len(doc_list[i])-1):
ans.append(i)
return ans
doc_list = ["casino", "The Learn Python Challenge Casino", "They bought a car, and a horse",
"Casinoville"]
ans = word_search(doc_list, 'car')
print(ans) | true |
1b9fb92b22ae83de878c7949ce4072d457b7015f | mlnance/Contact_Counter | /utility/util.py | 706 | 4.34375 | 4 | #!/usr/bin/python
__author__ = "morganlnance"
def calc_distance( vec1, vec2 ):
"""
Calculates the distance between two lists of 3D coordinates.
:param vec1: list( xyz coordinates defining point 1 )
:param vec1: list( xyz coordinates defining point 2 )
:return dist: float( the distance between the two points in 3D space )
"""
from math import sqrt, pow
# extract the xyz coordinates from the two points
x1 = vec1[0]
y1 = vec1[1]
z1 = vec1[2]
x2 = vec2[0]
y2 = vec2[1]
z2 = vec2[2]
# calculate the distance between the two points
dist = sqrt( pow( x2 - x1, 2 ) + pow( y2 - y1, 2 ) + pow( z2 - z1, 2 ) )
return dist
| false |
b5d8340a45eb7dac5aa35731c334c5202bfd4e39 | CristinaPineda/semana3-cienciaDados | /fizz1.py | 358 | 4.15625 | 4 | # Exercícios 2 - FizzBuzz parcial, parte 1
'''
Exercícios 2 - FizzBuzz parcial, parte 1
Receba um número inteiro na entrada e imprima
Fizz
se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada.
'''
numero = int(input('Digite um número inteiro: '))
if numero % 3 == 0:
print('Fizz')
else:
print(numero) | false |
6af93725e3436079d267bd3dc6633034cc9435d8 | Jeeukrishnan/Introduction-to-Machine-Learning | /GradientDescent.py | 1,023 | 4.1875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
#helper function
def plot_regression_line(X,m,b):
regression_x = X.values
regression_y = []
for x in regression_x:
y = m*x + b
regression_y.append(y)
plt.plot(regression_x,regression_y)
#read data
df=pd.read_csv("student_scores.csv")
#plot data
X=df["Hours"]
Y=df["Scores"]
plt.plot(X,Y,'o')
#def a function gradient descent such that it takes m,c and return a better value of m,c
##so that it reduces error
m=0
c=0
def grad_desc(X,Y,m,c):
for point in zip(X,Y):
x=point[0]
y_actual=point[1]
y_prediction=m*x+c
error=y_prediction-y_actual
delta_m= -1*(error*x)*0.23
delta_c=-1*(error)*0.23 #0.23 is learning rate
m=m+delta_m
c=c+delta_c
return m,c
#for i in range(0,10)
m,c=grad_desc(X,Y,m,c)
print (m,c)
plot_regression_line(X,m,c)
plt.show() | true |
e8b69587fe305a033a650625815f40be8181b6dc | rjk79/Data-Structures-Algorithms-System-Design | /engine/991_broken_calculator.py | 872 | 4.21875 | 4 | # Odd/Even, work in reverse
# case: x = 2, y = 8
# worst case u end up at 14 which is 2*(y-1) AKA jumpMax
# b/c you wouldnt blaze past 8 and go to 16..
# 2 ways to get to y
# double
# m = y/2
# -or-
# decrement
# 2m + 1 -> anything times 2 and plus 1 is ODD
# so had to come from 2m + 2 which is EVEN -> can also be accessed via double or dec
# if we had dec then we'd come from 2m + 4 which is 2(m + k)
# AKA 8 can be gotten from
# 5 * 2 - 1 - 1 (3 steps) OR
# 5 - 1 * 2 (2 steps => better)
# conclusion:
# even nums are best accessed via doubling
# odd accessed via decrement
def brokenCalc(X, Y):
import pdb; pdb.set_trace()
if X == Y: return 0
if X > Y:
return X - Y
elif X <= Y:
if Y % 2 == 0:
return 1 + brokenCalc(X, Y/2)
else:
return 1 + brokenCalc(X, Y+1)
brokenCalc(5, 8) | true |
270010706e0f6ea22ef3295f084f6af09a92dfca | ddanieltan/python-practice-exercises | /practicepython.org/1-character-input.py | 919 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 24 19:43:53 2016
@author: ddan
"""
#==============================================================================
# Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
#
# Extras:
#
# Add on to the previous program by asking the user for another number
# and printing out that many copies of the previous message.
# (Hint: order of operations exists in Python)
# Print out that many copies of the previous message on separate lines.
# (Hint: the string "\n is the same as pressing the ENTER button)
#==============================================================================
import datetime
def main():
name = input("Enter your name: ")
age = input("Enter your age: ")
print(name + ", you will turn 100 years old in " + 100)
| true |
71cbc3e2e0a4061412c7e3928a6b89bd5580cc73 | aberkb/leetcode | /easy-difficulty/merge-two-sorted-lists.py | 1,939 | 4.15625 | 4 | #Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
#https://leetcode.com/problems/merge-two-sorted-lists/
#Definition for singly-linked list.
#first recurrentsive solution:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
temp = ListNode(0)
if not l1:
return l2
elif not l2:
return l1
elif not l1 and not l2:
return "no input given!"
if l1.val < l2.val:
temp.next = l1
temp.next.next = self.mergeTwoLists(l1.next, l2)
else:
temp.next = l2
temp.next.next = self.mergeTwoLists(l1, l2.next)
return temp.next
#Runtime: 40 ms, faster than 40.83% of Python3 online submissions for Merge Two Sorted Lists.
#Memory Usage: 14.3 MB, less than 27.65% of Python3 online submissions for Merge Two Sorted Lists.
#iterative solution
#Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
temp = ListNode()
current = temp
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
if l1:
current.next = l1
elif l2:
current.next = l2
return temp.next
#Runtime: 40 ms, faster than 40.83% of Python3 online submissions for Merge Two Sorted Lists.
#Memory Usage: 14.3 MB, less than 11.74% of Python3 online submissions for Merge Two Sorted Lists.
| true |
bb560ce409990c52e40bb55c88600b0581b8c675 | aberkb/leetcode | /easy-difficulty/palindrome-number.py | 810 | 4.25 | 4 | #Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
#
#Follow up: Could you solve it without converting the integer to a string?
#
#Example 1:
#
#Input: x = 121
#Output: true
class Solution:
def isPalindrome(self, x: int) -> bool:
if str(x) == (str(x))[::-1]:
return True
return False
#Runtime: 56 ms, faster than 78.91% of Python3 online submissions for Palindrome Number.
#Memory Usage: 14.2 MB, less than 58.65% of Python3 online submissions for Palindrome Number.
#without converting to str
class Solution:
def isPalindrome(self, x: int) -> bool:
num = []
if x<0:
return 0
while x:
num += [x % 10]
x //= 10
return num == num[::-1]
| true |
a9f3948a5e59e3dcc9b67ac82d229904b706b79d | hardentoo/pythonlearn | /rutour/tour_006.py | 619 | 4.40625 | 4 | # http://python-rutour.rhcloud.com/tour/Lists/
mylist = [1, 'два', 3.1]
print(len(mylist)) # Число элементов в списке
print(mylist[0]) # Доступ к первому элементу
mylist.append("new")
# Добавляем новый элемент в конец списка
print("Добавлен---->", mylist)
mylist.pop(0) # Удаляем первый элемент
print("Удалён---->", mylist) # Вложенные списки
superlist = [[1, 2, 3], [4, 5, 6]]
print(superlist)
print(superlist[1][1]) # Получаем 2 элемент во втором списке
| false |
75dc964641ba6c17e48c4e615a59231c26c662ef | muditabysani/Trees-3 | /Problem2.py | 915 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
# left part of first tree must be same as the right part of the second tree
# right part of first tree must be same as the left part of the second tree
return self.helper(root, root)
def helper(self, node1, node2):
if node1 == None and node2 == None:
# If both the trees are none then they are symmetrix
return True
if node1 == None or node2 == None:
# If one of them is None and other is not none then they are not symmetric
return False
# Finally check for the value at the current node for both the tree nodes and compare the left with right and right with left
return (node1.val == node2.val) and self.helper(node1.left, node2.right) and self.helper(node1.right, node2.left) | true |
96c85971c58634b63fa3be9693b608017a82b175 | CodesByQuady/Dice-Rolling-Game | /Dice Rolling Game.py | 1,742 | 4.4375 | 4 |
import random
def diceNum(): #This function is what assigns a number to the dice
dice = random.randint(1,6) #The random.randint(1,6) will assign dice a number between 1,6
print('You have rolled:',dice)
def diceRoll(): #This function is the actual game.
counter = 0 #This count how many times the user rolls the dice
while True: #Condtional for loop
choice = input("Press enter to roll the dice, type 'end' to end game: ")
if choice == '': #When the user presses enter, the dice will be rolled,
#the diceNum() will be called and the counter will be increased by 1
diceNum()
counter += 1
c2 = input("Would You Like to roll again? Yes/No: ")
if c2 == 'Yes': #The game will restart with a different
#outcome everytime.
continue
elif c2 == 'No': #The game will end and the amount of times the user rolled
#will be printed to the user.
print('Have a good day, user!')
print('You have rolled:',counter,'times')
break
else:
print("That's not a valid input.") #This is a fallsafe incase the user types
#the wrong input.
elif choice == 'end': #Game will end, then it prints how many times the user rolled.
print('Have a good day user!')
print('You have rolled:',counter,'times')
break
diceRoll()
#I used two functions to avoid repeating code over and over for each condtion.
#Functions will allow the program to be easier to read.
| true |
a594c9475b7f70199d1a5674741159b717a4a8ad | Eradch/4 | /6.py | 514 | 4.125 | 4 | from itertools import cycle
print('Программа повторяет элементы списка. Для генерации следющего повторения необходимо нажать Enter, для выхода',
' из программы нажмите q')
u_list = input('Введите список, разделяя элементы пробелом: ').split()
iter_ = cycle(u_list)
quit = None
while quit := 'q':
print(next(iter_), end='')
quit = input()
| false |
4c6da32d34bb2bde60a6032153d208a78cd6d98e | zacreid/CodingClubProblemSet | /Python/fizzbuzz.py | 561 | 4.15625 | 4 | '''
Coding Club Quick Test FizzBuzz - Zac Reid
- How it works?
- If it is divisable by 3 say Fizz
- If it is divisable by 5 say Buzz
- If both of the above statements are true say FizzBuzz
- Example output 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz
(1 <= input <= 100)
'''
def fizzBuzz(num):
if num % 15 == 0:
return 'FizzBuzz'
if num % 3 == 0:
return 'Fizz'
if num % 5 == 0:
return 'Buzz'
return num
for x in range(1000):
print(fizzBuzz(x)) | false |
70c060e6763cc051c743e4cfb79bbed7c94a57a1 | allanoh/andelasolutions | /Day1/fizzbuzz.py | 291 | 4.3125 | 4 | def fizz_buzz(args):
"""
Checking if the number is divisible by both 3 and 5
"""
if args % 3 == 0 and args % 5 == 0:
return "FizzBuzz"
elif args % 3 == 0:
return 'Fizz'
elif args % 5 == 0:
return 'Buzz'
else:
return args
| true |
c3372635e09ce64d85e2ba4d246678b609417cf3 | thulanimbatha/Day-4-of-100 | /rows-and-cols.py | 461 | 4.28125 | 4 | # Put and X into a grid
row1 = ["~", "~", "~"]
row2 = ["~", "~", "~"]
row3 = ["~", "~", "~"]
# now create a grid/map
grid = [row1, row2, row3]
# print it out
print(f"{row1}\n{row2}\n{row3}")
# prompt user
mark = input("This is a 3 x 3 grid. Place your coordinates(row first then column: ")
grid[int(mark[0]) - 1][int(mark[1]) - 1] = "X" # avoid IndexOutOfBound error - otherwise user must enter num (0-2) instead of (1-3)
print(f"{row1}\n{row2}\n{row3}")
| false |
fac4a408bc444d2e4ad0c05d37566bef11df3f58 | SteveDengZishi/HackerRank | /Closest_Number.py | 1,980 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 30 12:28:24 2017
@author: stevedeng
"""
"""
Sorting is often useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses, as well.
Challenge
Given a list of unsorted integers, , can you find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.
Input Format
The first line of input contains a single integer, , representing the length of array .
In the second line, there are space-separated integers, , representing the elements of array .
Output Format
Output the pairs of elements with the smallest difference. If there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers. If there's a number which lies in two pair, print it two times (see the sample case #3 for explanation).
Constraints
Sample Input #1
10
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854
Sample Output #1
-20 30
Explanation
(30) - (-20) = 50, which is the smallest difference.
Sample Input #2
12
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470
Sample Output #2
-520 -470 -20 30
Explanation
(-470) - (-520) = 30 - (-20) = 50, which is the smallest difference.
Sample Input #3
4
5 4 3 2
Sample Output #3
2 3 3 4 4 5
Explanation
Here, the minimum difference will be 1. So valid pairs are (2, 3), (3, 4), and (4, 5). So we have to print 2 once, 3 and 4 twice each, and 5 once.
"""
import math
num=int(input())
var=input()
lst=var.split()
for i in range(num):
lst[i]=int(lst[i])
lst.sort()
d=math.inf
for i in range(len(lst)-1):
diff=abs(lst[i+1]-lst[i])
if diff<=d:
d=diff
for i in range(len(lst)-1):
if abs(lst[i+1]-lst[i])==d:
print("{a} {b}".format(a=lst[i],b=lst[i+1]),end=" ")
| true |
e95c04b16cfc655f531ea2c517b906df21bbc037 | jskd/ProgComp | /defis/0/LI_Xiang/anagram | 836 | 4.125 | 4 | #! /usr/bin/python3
import sys
import os
#return a sorted String
def sort_string(word):
sorted_list = list(word.lower())
sorted_list.sort()
return "".join(sorted_list)
#add a sorted string into the map
def add_sorted_string(word_map,word):
sortedString = sort_string(word)
if sortedString not in word_map:
word_map[sortedString] = word
else:
word_map[sortedString] += "," + word
mydict_map = {}
result = []
#load dictionnary
for row in open(sys.argv[1]).readlines():
add_sorted_string(mydict_map,row.strip("\n"))
#match each word in parameters
for i in range(2,len(sys.argv)):
sortedString = sort_string(sys.argv[i])
if sortedString in mydict_map:
for s_string in mydict_map[sortedString].split(","):
result.append(s_string)
result.sort()
print(str(sys.argv[i])+":")
for r in result:
print(r)
result = []
| true |
621713bdaacb316fa529e4aa88960bc2c057b92e | snehalk19/python_program | /zero_converter.py | 998 | 4.125 | 4 | '''You are given a number n. The number n can be negative or positive. If n is negative, print numbers from n to 0 by adding 1 to n. If positive, print numbers from n-1 to 0 by subtracting 1 from n.'''
{
#Initial Template for Python 3
//Position this line where user code will be pasted.
def main():
testcases=int(input()) #testcases
while(testcases>0):
numbah=int(input())
if(numbah>0):
pos(numbah)
elif(numbah<0):
neg(numbah)
else:
print("already Zero",end="")
print()
testcases-=1
if __name__=='__main__':
main()
}
''' Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above. '''
#User function Template for python3
def pos(n):
while(n>0):
n=n-1
print(n,end=" ")
def neg(n):
while(n<=0):
print(n,end=" ") ##Write the code
n=n+1 | true |
0f8625a82147ce11835fc175b4cf74152a3f5409 | Bearspirit/all_lessons | /glava9_classes/Classes.py | 1,273 | 4.34375 | 4 | """Класс Privileges определяем без атрибута, атрибут определяется ниже.
Обрати внимание, что как определяется метод - табуляция на одном уровне
"""
class Privileges():
def __init__(self):
self.privileges = [
'разрешено добавлять сообщения',
'разрешено удалять пользователей',
'разрешено банить пользователей'
]
def show_privileges(self):
print(self.privileges)
class Users():
def __init__(self, first_name, last_name, age, location):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.location = location
def describe_user(self):
print(
"Name: " + self.first_name + ";" +
"\nLast name: " + self.last_name + ";" +
"\nAge: " + str(self.age) + ";" +
"\nLocation: " + self.location + "."
)
def great_user(self):
print("Hey, " + self.first_name + ", You are Great!\n")
class Admin(Users):
def __init__(self, first_name, last_name, age, location):
super().__init__(first_name, last_name, age, location)
self.for_privileges = Privileges()
| false |
e3ecbcab7ccc38d76dcd5c2e33aa145fd08b7cbe | Joaovismari/Python | /colecoes/listas.py | 1,496 | 4.3125 | 4 | #Listas
programadores = ['Victor', 'Juliana', 'Samuel', 'Caio', 'Luana']
print(type(programadores)) # type ‘list’
print(len(programadores)) # 5
print(programadores[4]) # Luana
programadores.remove('Samuel')# remove Elemento pelo valor passado
programadores.pop(2)# remove elemento pela posição passada
programadores.append('João') #adiciona elemento na ultima posição da lista
programadores.insert(0,'Kratos')#adiciona elemento passando indice aonde será armazenado na lista
print(programadores)
programadores.sort() #organiza em ordem crescente
print(programadores)
programadores.reverse() #organiza em ordem decrescente
print(programadores)
aluno=['João', 28, 1.81] #podem ter tipos diferentes de dados na mesma lista
print(aluno)
aluno.clear() # remove todos os elementos de uma lista
print(aluno)
aluno.append('j')
aluno.append('j')
aluno.append('k')
aluno.append('j')
print(aluno.count('j')) #contabiliza o numero de vezes que o elemento passado aparece na lista
print(aluno.index('j')) #devolve indice aonde o elemento aparece a primeira vez na lista
print(aluno.index('j',2)) #devolve indice aonde o elemento aparece a primeira vez após o indice passado '2'
#programadores.pop(12) Erro ao remover uma posição inexistente IndexError
numeros = [15, 5, 0, 20, 10]
nomes = ['Caio', 'Alex', 'Renata', 'Patrícia', 'Bruno']
print(min(numeros)) # 0
print(max(numeros)) # 20
print(min(nomes)) # Alex
print(max(nomes)) # Renata
print(sum(numeros)) #soma elementos de uma lista | false |
072d0a72463453412d7011ad3d1fc394301acf08 | yyq1609/Python_road | /012 函数闭包&模块/3. 内置函数(map,filter,reduce).py | 1,134 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
map操作的 func 是一个函数 v 必须是可迭代
"""
# v = [11, 22, 33]
# def func(arg):
# return arg + 100
#
# result = map(func, v) # 将函数的返回值添加到空list中[111, 122, 133]
# print(list(result))
#
# # 使用lambda 改写
# result = map(lambda x: x+100, v)
# print(result) # py2直接返回
# print(list(result)) # py3会返回一个object,可用list()查看
"""
filter
"""
# v = [1, 2, 3, 'welcome', 4, 'hello']
# result = filter(lambda x: type(x) == int, v) # 生成新list
# print(list(result))
"""
reduce (py2中是内置函数,py3被移到别处
reduce 有两个参数,第一次取前两个值,下次把函数return 值作为x,再继续取1个值作为y
"""
# import functools
# v = [1, 2, 3, 4, 's']
# result = functools.reduce(lambda x, y: x+y, v)
# print(result)
"""
zip
"""
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b) # 打包为元组的列
print(list(zip(a, c)))
# 元素个数与最短的列表一致
print(list(zip(*zipped)))
# 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
| false |
ffbdfd1b90176fff23a04b9097939f8b489a4efd | anjali-kundliya/Hactoberfest-2022 | /Python/Tribonacci.py | 697 | 4.5 | 4 |
# This code will return the nth element of the Tribonacci sequence where
# for n=0 it prints 0, for n=1 it prints 1
class NegativeNumber(Exception):
pass
def tribonacci_iter(n):
if n < 0:
raise NegativeNumber("Fibonacci not defined for negative numbers!")
if n==0:
return 0
if n==1:
return 1
# Assigning variables to first 3 elements of Tribonacci sequence
a, b ,c = 0, 1, 1
# For loop for finding the nth number in sequence
for i in range(2, n ):
a, b, c = b, c, a + b + c
return c
if __name__ == "__main__":
n = int(input("Enter number: "))
print(tribonacci_iter(n))
| true |
43fc45d7984c7e84d59e3113502276f318f474a5 | sgs00/project-euler | /euler009.py | 632 | 4.40625 | 4 | """
Project Euler Problem 9
=======================
A Pythagorean triplet is a set of three natural numbers, a < b < c, for
which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def pythagorean_1000():
for a in range(1, 1000):
for b in range(1, 1000-a):
c = 1000 - a - b
if is_pythagorean(a, b, c):
return a*b*c
def is_pythagorean(a, b, c):
return a**2 + b**2 == c**2
if __name__ == "__main__":
print(pythagorean_1000())
| false |
fdbeb30ad34b122b265398b813f1fc6732bddfde | arsalan2400/HPM573S18_AHMED_HW1 | /TutorialQ4.py | 380 | 4.125 | 4 |
lily = ['Wax apple','kiwi','strawberries']
reddy= ['mango','blueberries','watermelon']
both = lily + reddy
print(both)
both2=[]
both2.append(lily)
both2.append(reddy)
print(both2)
lily[1] = 'gala apples'
print(lily)
#this is just to show it begins at zero, not 1
print(both) #still uses kiwi#
print(both2) #booth 2 is dependent on lily list, so it will change to gala apples#
| false |
837ec4e0d983c2a9071d73e3df5293b4cbab8657 | JinxinZhao315/march-hols | /assignments/02-identification/get-details.py | 1,087 | 4.28125 | 4 | name = input("What is your name? ")
# If length of name is greater than 20,
# print something
if len(name)>20:
print('Wow aristocracy')
age = input("What is your age? ")
if int(age)<10:
print('Smol')
elif 10<int(age)<20:
print('Big boi')
else:
print('Big big boi')
# If age is less than 10, print "Smol"
# ELse if age is between 10 and 20, print "Big boi"
# Else, print "Big big boi"
coolness = input("Rate your coolness out of 100.0")
# If coolness is more than 100.0, just print some error
if float(coolness)>100.0:
coolness_str = 'Cool Beyond Assessment'
print(coolness_str)
elif float(coolness)>75.0:
coolness_str = 'Admiringly Cool'
print(coolness_str)
elif float(coolness)>50.0:
coolness_str = 'Moderately Cool'
print(coolness_str)
elif float(coolness)>25.0:
coolness_str = 'Lame'
print(coolness_str)
else:
coolness_str = 'Lacking Confidence'
print(coolness_str)
# Now print a string like
# My name is Arnold Tan, I am 69 and I'm Really Cool
print("My name is {}, I am {} and I am {}".format(name,age,coolness_str))
| true |
3565a6e7f247d33177e58703871f3abdeb5c4f56 | nsabuj/Data-Structures-and-Algorithms | /tree/VerticalSearch.py | 1,745 | 4.25 | 4 | import heapq
# Python program for printing vertical order of a given
# binary tree
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, key):
self.val = key
self.left = None
self.right = None
# Utility function to store vertical order in map 'm'
# 'hd' is horizontal distance of current node from root
# 'hd' is initially passed as 0
def verticalTraversal( node):
if node==None:
return
qu=[]
horiz_dis=0
node.horiz_dis=horiz_dis
qu.append(node)
m=dict() #Hashmap to store horizontal distances of tree
qusize=len(qu)
while qu:
qusize=len(qu)
if qusize>0:
qu.sort(key=lambda x: x.val, reverse=False) #sorting inside level
i=0
while i<qusize: # continue until the end of the level
current_node=qu.pop(0)
horiz_dis=current_node.horiz_dis
try:
m[horiz_dis].append(current_node.val)
except:
m[horiz_dis]=[current_node.val]
if current_node.left:
current_node.left.horiz_dis=horiz_dis-1
qu.append(current_node.left)
if current_node.right:
current_node.right.horiz_dis=horiz_dis+1
qu.append(current_node.right)
i+=1
values=[m[i] for i in sorted(m.keys())]
return values
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(7)
print(verticalTraversal(root))
| true |
e89caddc264c9cc01a466d2ec8a819e0ce4c7d15 | nsabuj/Data-Structures-and-Algorithms | /sorting/insertionSort.py | 252 | 4.125 | 4 | def insertionSort(arr):
for i in range(0,len(arr)-1):
while arr[i-1]>arr[i] and i>0:
print(i)
arr[i],arr[i-1]=arr[i-1],arr[i]
i-=1
return arr
print(insertionSort([3,4,7,12,2,7,9,34])) | false |
7107072ee8f7023cdd35cbd884db04fa84d8d4da | furas/python-examples | /text-game/example-2.py | 1,426 | 4.125 | 4 | rooms = {
'room1': {
'description': "Your in a room how to get out...",
},
'room2': {
'description': "This is the second room",
},
'room3': {
'description': "This is the third room",
},
}
def show_room(name):
print(rooms[name]['description'])
star
looking_forward = False
looking_backward = False
while True:
answer = input().lower()
if answer == 'exit':
print("Good Bye")
return
if answer == "look forward":
if not looking_forward:
print("You are looking forward")
looking_forward = True
looking_backward = False
else:
print("You are already looking forward, so what next")
elif answer == 'look backward':
if not looking_backward:
print("You are looking backward")
looking_forward = False
looking_backward = True
else:
print("You are already looking backward, so what next")
elif answer == 'go there':
if looking_forward:
return 'room2'
if looking_backward:
return 'room3'
else:
print('Go where ???')
# --------------------------------
name = 'room1'
while name is not None:
name = show_room(name)
| true |
b2304edd9ba6a19229f1abceb3b4665895efaf5b | SeanWang17/cs560 | /mapper_stopwords.py | 642 | 4.34375 | 4 | #!/usr/bin/env python
import os
import re
import sys
#works_path = r'works/'
# tokenize function
def tokenize(text):
min_length = 3 # typically, words with length smaller than 3 is not meaningful
words = map(lambda word: word.lower(), text.strip().split(' ')) # case insensitive
p = re.compile('^[a-zA-Z]+$') # remove the mess up
filtered_words = list(filter(lambda token: p.match(token) and len(token)>=min_length, words))
return filtered_words
# get the word + count
for line in sys.stdin:
words = tokenize(line.decode('utf-8'))
if words:
for word in words:
print('%s\t%s' % (word,1))
| true |
ff7239624a683afda20c6cdaae215a35b5c46876 | taggedzi/learning_python | /src/attributes/builtins/abs.py | 2,520 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from src.lp_utilities.random_gen import random_signed_complex
from src.lp_utilities.random_gen import random_signed_float
from src.lp_utilities.random_gen import random_signed_integer
from src.lp_utilities.separator import separator
"""
The abs() function returns the the Mathematical absolute value of the input value if
it can be understood as an integer, float, or complex number.
Complex numbers are numbers that contain imaginary components sqrt(-1)
For more information about complex numbers in python see:
* Complex - http://python-reference.readthedocs.io/en/latest/docs/functions/complex.html
"""
NUMBER_OF_TESTS_TO_RUN = 6
def print_abs(input_value, output_value):
"""
This method just does formatting for the abs function examples
:param input_value: Number The value sent to the abs() function
:param output_value: Number The value the abs() function returns
:return: Void
"""
print("abs({}) = {}".format(input_value, output_value))
def abs_integer():
separator("abs(integer) - Absolute Value - Integer")
for _ in range(NUMBER_OF_TESTS_TO_RUN):
integer_ = random_signed_integer(100)
result = abs(integer_)
print_abs(integer_, result)
def abs_float():
separator("abs(float) - Absolute Value - Floating Point")
for _ in range(NUMBER_OF_TESTS_TO_RUN):
# Generate a random float with a random sign
float_ = random_signed_float(100)
result = abs(float_)
print_abs(float_, result)
def abs_complex():
separator("abs(complex) - Absolute Value - Complex Numbers - Returns the absolute value of the magnitude of the "
"complex number.")
for _ in range(NUMBER_OF_TESTS_TO_RUN):
# Generate a random complex number with a random sign
complex_ = random_signed_complex(100)
result = abs(complex_)
print_abs(complex_, result)
def abs_string():
separator("abs(string) - Absolute Value - String")
try:
print_abs("5", abs("5"))
except TypeError as e:
print("Attempted to execute abs(\"{}\") and it throws a TypeError.".format(5))
print("Strings cannot be passed to the abs function even if the contents of the string are numbers.")
print("The exception message is:")
print(e)
def main():
abs_integer()
abs_float()
abs_complex()
abs_string()
if __name__ == "__main__": # pragma: no cover
# execute only if run as a script
main()
| true |
43cb8645f226c8251660357e3beda646783f67ce | taggedzi/learning_python | /src/attributes/for_loops.py | 2,543 | 4.875 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from src.lp_utilities.separator import separator
"""
For loops depend on the items they loop through being iterable.
For an object to be iterable it must have a next method. In python 2 it is "next" in Python 3 it is "__next__"
For many of these examples there may be better ways to perform the operation using something other
than a for loop however, this file exists to show how to use for loops. So they will be used.
For more information on what an iterable object is
* The Iterator Protocol - https://anandology.com/python-practice-book/iterators.html#the-iteration-protocol
"""
separator("Print a range from 0 to 5")
for i in range(0, 5):
print("{}".format(i))
separator("Print the characters of a string one at a time, iterating through the string.")
number = "654,321.123"
for i in range(0, len(number)):
print(number[i], end='')
print("")
separator("Filter a string by looping through it and removing any non-numeric characters.")
clean_number = ''
for i in number:
if i in "0123456789":
clean_number = clean_number + i
print(clean_number)
separator("Use a for loop and a range to print even numbers.")
for i in range(0, 10, 2):
print(i)
separator("Use continue in a for loop to skip any entries that are not 'spam'.")
breakfast = ['eggs', 'turkey', 'spam', 'pancakes']
for item in breakfast:
if 'spam' is not item:
continue
print('I want {} for breakfast.'.format(item))
separator("Use break in a for loop stop the loop if it encounters 'spam'.")
breakfast = ['eggs', 'turkey', 'spam', 'pancakes']
for item in breakfast:
if 'spam' is item:
break
print('I want {} for breakfast.'.format(item))
separator("Use nested for loops to show multiplication table.")
for i in range(1, 10):
for j in range(1, 10):
print("{:<4}".format(j * i), end=" ")
print("\n")
separator("Demonstrate the use of an else statement.")
for i in range(1, 3):
print(i)
else:
print('Finished loop without breaking')
separator("Demonstrate the use of an else statement when a break is triggered.")
for i in range(1, 10):
print(i)
break
else:
print("This will never happen because of the break above.")
separator("Demonstrate what is happening under the hood using 'next' and 'iter'.")
demo = [1, 2, 3, 4, 5]
iter_ = demo.__iter__()
i = 0
while i <= 4:
try:
# python 3 way
print(iter_.__next__())
except AttributeError as _:
# python 2 way
print(iter_.next())
i += 1
| true |
210cbca48405b6b921d04f61cd5c6053335a1ea9 | taggedzi/learning_python | /src/attributes/builtins/all.py | 1,436 | 4.53125 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from src.lp_utilities.separator import separator
"""
The "all()" function simply tests to see if ALL of the elements in an iterable evaluate to a True condition
For more information on what an iterable object is
* The Iterator Protocol - https://anandology.com/python-practice-book/iterators.html#the-iteration-protocol
For more information on what evaluates to True in Python see:
* Truth Testing Procedure Explained - https://docs.python.org/3/library/stdtypes.html#truth
"""
def print_all(input_, result_):
print("Running all({}) returns {}".format(input_, result_))
def all_list_with_all_good_elements():
# Demo a list of values that evaluate to true
separator("all(iterable) - with all items iterable - Returns true if all elements are iterable (non empty)")
good_list = [1, 2, 3, 4, 5, 'Cat', {'Carbon'}, ["Bacon"]]
result = all(good_list)
print_all(good_list, result)
def all_list_with_empty_element():
# Demo a list with 1 value that evaluates to false
separator("all(iterable) - with non-iterable items - Returns false if any elements are non iterable (empty)")
bad_list = [1, 2, None, 4, 5]
result = all(bad_list)
print_all(bad_list, result)
def main():
all_list_with_all_good_elements()
all_list_with_empty_element()
if __name__ == '__main__': # pragma: no cover
# execute only if run as a script
main()
| true |
5602b3a65cbb78e46bd24a5ed1eb3b4e7905aa0b | c-sauve/python | /Python Knowlege/Basics/Operations.py | 2,566 | 4.5625 | 5 | #!/usr/bin/python3
# operators return a boolean. They are commonly used in if, while, and for statements
#Equal to (==)
print("5 == 5 will result in " + str(5 == 5)) # This will return True
print("5 == 6 will result in " + str(5 == 6)) # This will return False
#Not equal to (!=) or (<>) (<> is no longer in use after python 3 or above but it can be used in python 2 or below)
print("5 != 3 will result in " + str(5 != 3)) # This will return True
print("5 != 5 will result in " + str(5 != 5)) # This will return False
#Greater than (>)
print("5 > 3 will result in " + str(5 > 3))# This will return True
#Greater than or equal to (>=)
print("5 >= 3 will result in " + str(5 >= 3)) # This will return True
#Less than (<)
print("5 < 3 will result in " + str(5 < 3))# This will return False
#Less than or equal to (<=)
print("5 <= 3 will result in " + str(5 <= 3)) # This will return False
# Binary operations
# Assigning Values and Bitwise Operations
print("Lets play with binary operations")
var_binary_a = 0b11001100
var_binary_b = 0b11110000
print("The two binary values we will be using are " + bin(var_binary_a) + " and " + bin(var_binary_b))
print("The numbers both those binary values produce are " + str(var_binary_a) + " and " + str(var_binary_b))
print("Operations with Binary go as following. \n Using & (and) means if both sides have a 1 it will stay. Otherwise if a 0 value is involved it will produce a 0 even if the other value has a 1.")
print("For example bin(" + bin(var_binary_a) + " & " + bin(var_binary_b) + ") will result in " + bin(var_binary_a&var_binary_b))
print("Using | (or) means any values with a 1 will stay even if the other value has a 0. If both values have a 0 then it will be 0")
print("For example bin(" + bin(var_binary_a) + " | " + bin(var_binary_b) + ") will result in " + bin(var_binary_a|var_binary_b))
print("Using >> (a right shift) this means we will move the values to the right x amount of places. In this example lets use 3. So we will shift all the values three slots to the right.")
print("For example bin(" + bin(var_binary_a) + " >> 3 ) will result in " + bin(var_binary_a >> 3) + " the value now is " + str((var_binary_a << 3)))
print("Using << (a left shift) this means we will move the values to the right x amount of places. In this example lets use 3. So we will shift all the values three slots to the right.")
print("For example bin(" + bin(var_binary_a) + " << 2 ) will result in " + bin(var_binary_a << 2) + " the value now is " + str((var_binary_a << 2)))
| true |
caf31485eb383944285930a76c80c022603a1d1c | williamboco21/pythonfundamentals | /FUNDPRO/MP04-recursion.py | 232 | 4.125 | 4 | def asterisk(n):
if n == 1:
print("*", end=" ")
else:
asterisk(n-1)
print("")
for i in range(n):
print("*", end=" ")
num = int(input("Enter the value of number: "))
asterisk(num)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.