blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e2ebc137a9440a7c310265958339e7e88b788fa3 | sandgate-dev/codesignal-practice | /arcade/areSimilar.py | 1,322 | 4.15625 | 4 | # Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
#
# Given two arrays a and b, check whether they are similar.
#
# Example
#
# For a = [1, 2, 3] and b = [1, 2, 3], the output should be
# areSimilar(a, b) = true.
#
# The arrays are equal, no need to swap any elements.
#
# For a = [1, 2, 3] and b = [2, 1, 3], the output should be
# areSimilar(a, b) = true.
#
# We can obtain b from a by swapping 2 and 1 in b.
#
# For a = [1, 2, 2] and b = [2, 1, 1], the output should be
# areSimilar(a, b) = false.
#
# Any swap of any two elements either in a or in b won't make a and b equal.
# def areSimilar(A, B):
# count = 0
# list_a = []
# list_b = []
# for i in range(len(a)):
# if a[i] != b[i]:
# count += 1
# # If differ append each to lists
# list_a.append(a[i])
# list_b.append(b[i])
#
# if count == 0:
# return True
# elif count == 2:
# # Check if lists are different
# return set(list_a) == set(list_b)
# else:
# return False
# SHort and Simple
from collections import Counter as C
def areSimilar(A, B):
return C(A) == C(B) and sum(a != b for a, b in zip(A, B)) < 3
a = [4, 6, 3]
b = [3, 4, 6]
print(areSimilar(a, b))
| true |
283ca0e2270a6c2dce198bf03761758d8b39e2e8 | eloydrummerboy/Socratica | /16_Map_Filter_Reduce.py | 1,925 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 16:12:42 2017
@author: eloy
"""
# Map, Filter, Reduce
import math
def area(r):
"""Area of a circle with readius 'r'."""
return math.pi * (r**2)
# What if we need to compute the areas for multiple circles?
radii = [2,5,7.1,0.3,10]
# Method 1: Direct method
areas = []
for r in radii:
a = area(r)
areas.append(a)
print(areas)
# Method 2: use 'map' function
map(area,radii) # This returns a map object, which is an iterator
# To see the list, we need to pass the map into the list constructor
list(map(area,radii))
temps = [("Berlin", 29), ("Cairo", 36), ("Buenos Aires", 19),
("Los Angeles", 26),("Tokyo",27), ("New York", 28),
("London",22), ("Beijing", 32)]
c_to_f = lambda data: (data[0], (9/5)*data[1] + 32)
list(map(c_to_f,temps))
# Filter Function
# Use case, select all values above the average
import statistics
data = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1]
avg = statistics.mean(data)
filter(lambda x: x>avg, data)
# Again, this retuns a filter object, an iterable, not a list
list(filter(lambda x: x>avg, data))
# Use Case 2: Remove missing data
countries = ["","Argentina","","Brazil","Chile","","Colombia","","Ecuador","","","Venezuela"]
list(filter(None, countries))
# Here, None menas there is no supplied function. The data itself
# acts as the function. So all values will get passed through
# except those that Python interprets as False. Which are most variations
# of empty sets, nulls, 0, {}, (), {}, etc.
# Reduce
# As of Python 3, it is no longer a builtin function, it has been
# demoted to the functools module
from functools import reduce
# Multiply all numbers in a list
data = [2,3,5,7,11,13,17,19,23,29]
# Need a function that takes in two imputs
multiplier = lambda x,y: x*y
reduce(multiplier,data)
product = 1
for x in data:
product = product*x
print(product)
| true |
a1d4f6150896221b22006fb8d2c9719091827add | eloydrummerboy/Socratica | /17_Sorting_In_Python.py | 2,074 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 16:52:49 2017
@author: eloy
"""
# Sorting in Python
# Sorthing alphabetically
# Alkaline earth metals
earth_metals = ["Beryllium", "Magnesium", "Calcium", "Strontium",
"Barium", "Radium"]
earth_metals.sort()
print(earth_metals)
earth_metals.sort(reverse=True)
print(earth_metals)
# What if elemtns are in a tuple instead of a list?
earth_metals = ("Beryllium", "Magnesium", "Calcium", "Strontium",
"Barium", "Radium")
earth_metals.sort()
# Tuples are immutable objects!!
help(list.sort)
# Key is a function that will be used to determine which values
# you sort by
# name - radius km - density g/cm3 - avg. dist. from sun AUs)
planets = [
("Mercury",2440,5.43,0.395),
("Venus",6052,5.24,0.723),
("Earth",6378,5.52,1.000),
("Mars",3396,3.93,1.530),
("Jupiter",71492,1.33,5.210),
("Saturn",60268,0.69,9.551),
("Uranus",25559,1.27,19.213),
("Neptune",24764,1.64,30.070),
]
# Currently sorted by distance from sun
# lets sort by size, largest first
# We need a function to return the size, so we
# can then set that as our key, and sort by it
# We use a lambda expression
size = lambda planet: planet[1]
planets.sort(key=size, reverse = True)
print(planets)
# Now let's do least dense to most dense
density = lambda planet: planet[2]
planets.sort(key=density)
print(planets)
# Sort changes the base list. What if we want it to stay the same
# and create a copy? What if we want to sort a tuple?
# Answer: Use sorted()
help(sorted)
earth_metals = ["Beryllium", "Magnesium", "Calcium", "Strontium",
"Barium", "Radium"]
sorted_earth_metals = sorted(earth_metals)
print(sorted_earth_metals)
print(earth_metals)
# Sorting Tuples
data = (7,2,5,6,1,3,9,10,4,8)
sorted_data = sorted(data)
print(sorted_data)
print("Note the type of the result is now a list, not a tuple")
print(type(sorted_data))
print(data)
print("But the original tuple is unchanged. Of course. It's immutable!")
# Remember, strings are iterable
sorted("Alphabetical")
| true |
8ba44fb8896d528b0434994a25d38fb5cb30f45d | nyhuiss7817/cti110 | /P3HW1_AgeClassifier_NyhuisSteven.py | 1,223 | 4.5 | 4 | # CTI-110
# P3HW1 Age Classifier
# Classifier of a person by age
# Steven Nyhuis
# 03/20/18
'''
Write a program that asks the user to enter a person’s age. The person should display a
message indicating whether the person is an infant, a child, a teenager, or an adult.
Follow these guidelines:
If the person is 1 year old or less, he or she is an infant.
If the person is older than one year, but younger than 13 years, he or she is a child.
If the person is at least 13 years old, but less than 20 years old, he or she is a teenager.
If the person is at least 20 years old, he or she is an adult.
'''
# create a def for main classifier
def age():
# age list
ADULT = 20
TEEN = 13
CHILD = 1
# define the rest of the scores
age = float(input('Enter age in years: '))
if age >= ADULT:
print('You are an Adult')
else:
if age >= TEEN:
print('You are a Teenager')
else:
if age > CHILD:
print('You are a Child')
else:
print('You are an Infant')
# Finish with the def age()
# program start
age()
age()
age()
age()
age()
age()
age()
age()
age()
| true |
366c886188be0848cdfc13d31e974cb7ee0aee1e | nyhuiss7817/cti110 | /P3T1_AreasOfRectangles_NyhuisSteven.py | 1,422 | 4.4375 | 4 | # CTI-110
# P3T1-Areas of rectangle
# program to compare the size of two retangles
# Steven Nyhuis
# 03/06/18
'''
Write a program that asks for the length and width of two rectangles.
The program should tell the user which rectangle has the greater area,
or if the two rectangles have equal area.
This program’s logic should have three branches:
1. The first rectangle has the larger area
2. The second rectangle has the larger area
3. Both rectangles have equal area
'''
# list of varables
length1_SN = 0
width2_SN = 0
length2_SN = 0
width2_SN = 0
area1_SN = 0
area2_SN = 0
# Get the dimensions of rectangle 1.
length1_SN = int(input('Enter the length of rectangle 1: '))
width1_SN = int(input('Enter the width of rectangle 1: '))
# Get the dimensions of rectangle 2.
length2_SN = int(input('Enter the length of rectangle 2: '))
width2_SN = int(input('Enter the width of rectangle 2: '))
# Calculate the areas of the rectrangles.
area1_SN = length1_SN * width1_SN
area2_SN = length2_SN * width2_SN
# Determine which has the greater area.
if area1_SN > area2_SN:
print('Rectangle 1 has the greater area.')
else:
if area2_SN > area1_SN:
print('Rectangle 2 has the greater area.')
else:
print('Both have the same area.')
# Printing the area for SA
print('The area of Rectangle 1 is ', area1_SN)
print('The area of Rectangle 2 is ', area2_SN)
| true |
446a7447a9a856c5e8b2a1660f180d97442ffbfd | leeandher/learning-python | /learnpython.org/06 - basic_string_operations.py | 1,905 | 4.46875 | 4 | print('--- Running basic_string_operations.py ---')
str = "Hello world!"
# Getting the length of a string
print(len(str)) # 12
# Getting the first appearance of 'o'
print(str.index('o')) # 4
# Counting the number of 'l's
print(str.count('l')) # 3
# Slicing a string -> [start : stop : step]
# start is included, stop is excluded
print(str[3:7]) # lo_w
print(str[2:9:2]) # lowr
print(str[3:7:2]) # l_
# Reversing a string
print(str[::-1])
# Formatting the strings
print(str.upper())
print(str.lower())
# Checking contents of the string
print(str.startswith("Hello")) # True
print(str.endswith("World!")) # False
# Converting to a list
print(str.split(' '))
print(str.split('l'))
# Exercise
s = "Strings are awesome!"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" % s[1::2]) # (0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))
print('--- Finished basic_string_operations.py ---')
| true |
b7b1314839f0555f872bbd598811f0711aeb563a | AfridShaik/293653_daily_commit | /Submission/ifelse_4.py | 241 | 4.1875 | 4 | data_type = input("Enter the data type")
if type(data_type) == int:
print("integer")
elif type(data_type) == str:
print("string")
elif type(data_type) == float:
print("float")
elif type(data_type) == complex:
print("complex") | false |
f84a21b9fe0cddf821144c1567da54c3cc2aa17f | stephenmoye/Python-Programming-Projects | /Chapter 2/5-distance-traveled.py | 677 | 4.4375 | 4 | # Distance Traveled
# Assuming there are no accidents or delays, the distance that a car travels down the interstate can
# be calculated with the following formula:
# Distance=Speed×Time
# A car is traveling at 70 miles per hour. Write a program that displays the following:
# The distance the car will travel in 6 hours
# The distance the car will travel in 10 hours
# The distance the car will travel in 15 hours
SPEED = 70
TIME1 = 6
TIME2 = 10
TIME3 = 15
print("The car will travel", SPEED * TIME1, "miles in", TIME1, "hours")
print("The car will travel", SPEED * TIME2, "miles in", TIME2, "hours")
print("The car will travel", SPEED * TIME3, "miles in", TIME3, "hours")
| true |
ac24988a59b921824c291f15394bfc9609700260 | stephenmoye/Python-Programming-Projects | /Chapter 7/total-sales.py | 572 | 4.1875 | 4 | # Total Sales
# Design a program that asks the user to enter a store’s sales for each day of the week. The
# amounts should be stored in a list. Use a loop to calculate the total sales for the week and
# display the result
def sales():
allSales = []
for x in range(1, 8):
print("Enter the stores sales for day", x)
day = float(input())
allSales.append(day)
total(allSales)
def total(allSales):
total = 0
for y in range(0, 7):
total = total + allSales[y]
print("Total sales for the week: $", total)
sales()
| true |
4a6f8cfd8476a99e2a6afa566661257dd2824429 | stephenmoye/Python-Programming-Projects | /Chapter 3/magic-dates.py | 851 | 4.5 | 4 | # Magic Dates
# The date June 10, 1960, is special because when it is written in the following format, the month
# times the day equals the year:
# 6/10/60
# Design a program that asks the user to enter a month (in numeric form), a day, and a two-digit
# year. The program should then determine whether the month times the day equals the year. If
# so, it should display a message saying the date is magic. Otherwise, it should display a message
# saying the date is not magic.
print("~*Magic Date Detector*~")
print("Please input all dates in 2 digit number form MM/DD/YY")
month = int(input("What is the month? "))
day = int(input("What is the day? "))
year = int(input("What is the year? "))
if month * day == year:
print(month, "/", day, "/", year, "is a Magic Date!")
else:
print(month, "/", day, "/", year, "is NOT a Magic Date. :(")
| true |
c2ebd1a391b839144fb1381025e4cc911f1bb847 | blee1710/DataStructurePractice | /Recursion/fibonacci.py | 676 | 4.21875 | 4 | """
Given number (num), return index value of Fibonacci sequence
where the sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
The pattern of the sequence is that each value is the
sum of the previous two values
EG. IN => 8 || OUT => 21
"""
# O(2^n)
# adds readability, but call stack memory is higher (no tail call optimisation)
def fibonacciRecursive(num):
if num < 2:
return num
return fibonacciRecursive(num-1) + fibonacciRecursive(num-2)
# O(n)
def fibonacciIter(num):
sequence = [0,1]
for x in range(2,num+1):
sequence.append(sequence[x-2] + sequence[x-1])
return sequence[num]
print(fibonacciRecursive(8))
print(fibonacciIter(8)) | true |
50cf2d8ea62466813c80dd849da049e45a8d37b9 | blee1710/DataStructurePractice | /Arrays/reverse_string.py | 364 | 4.125 | 4 | # Create a function which reverses a string
# eg. IN => 'Hi i'm Brandon' | OUT => 'nodnarB m'i iH'
#Time: O(n)
#Space: O(n)
def reverse(str):
reverselist = []
for i in range(len(str)-1, -1,-1):
reverselist.append(str[i])
return ''.join(reverselist)
#return str[::-1]
#Running test case
input = "Hi i'm Brandon"
print(reverse(input))
| false |
fc2ecf9977a02343db4bf79477aa1de9fb988243 | recdec1/ProjectEuler | /cansumfunction.py | 664 | 4.125 | 4 | def CanSum(targetSum, numbers, memo = {}):
if (targetSum in memo): return memo[targetSum]
if (targetSum == 0): return True
if (targetSum < 0): return False
#here are the two base cases, true if 0, false if below 0.
for num in numbers:
remainder = targetSum - num
if (CanSum(remainder, numbers, memo) == True):
memo[targetSum] = True
return True
# here the false return is included after the recursive for loop to see if
# all possible answers are possible before false is called.
memo[targetSum] = False
return False
print(CanSum(345, [2, 6 ]))
print(CanSum(7, [2, 4]))
| true |
13d3a1dbc358e7483aa9675b95d4e58fac0638dd | maxflex/algorithms | /py/reverse_a_linked_list_recursive.py | 1,086 | 4.15625 | 4 | # https://practice.geeksforgeeks.org/problems/reverse-a-linked-list
'''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 would be added by GfG's Online Judge.'''
# Node Class
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self, val):
self.head = Node(val)
def add(self, val):
current = self.head
while current.next != None:
current = current.next
current.next = Node(val)
def show(self):
current = self.head
while current != None:
print(current.val)
current = current.next
def reverse(self, node):
if node.next == None:
self.head = node
return
self.reverse(node.next)
node.next.next = node
node.next = None
def reverse_print(self, node):
if node.next != None:
self.reverse_print(node.next)
print(node.val)
ll = LinkedList(5)
ll.add(10)
ll.add(15)
ll.reverse_print(ll.head)
print('-----')
ll.reverse(ll.head)
ll.show()
| true |
492aebd193e993166adce508411a2ceedb9bbf2a | ambuj991/Data-structure-and-algorithms | /binary tree/binary_tree.py | 1,172 | 4.34375 | 4 | # Depth First Traversals:
# (a) Inorder (Left, Root, Right) : 4 2 5 1 3
# (b) Preorder (Root, Left, Right) : 1 2 4 5 3
# (c) Postorder (Left, Right, Root) : 4 5 2 3 1
# Breadth First or Level Order Traversal : 1 2 3 4 5
# 1
# / \
# 2 3
# / \
# 4 5
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val,end=" ")
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val,end=" ")
def printPreorder(root):
if root:
print(root.val,end=" ")
printPreorder(root.left)
printPreorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Preorder traversal of binary tree is")
printPreorder(root)
print("\nInorder traversal of binary tree is")
printInorder(root)
print("\nPostorder traversal of binary tree is")
printPostorder(root) | true |
9da1749d3221047e87663ad1ea9e588143a2933d | Asha-N1/internship | /Basics/regex.py | 1,524 | 4.40625 | 4 | # RegEx in python
# importing re module
import re
# function to check the given email is valid or not
def validate_email(email): # function for email
return re.match(r'[\w-]{1,20}@\w{2,20}\.\w{2,3}$',email) # pattren for checking email
# function to check the given website url is valid or not
def validate_website(url):
return re.findall('((http|https)://)(www.)?', url)
# function to check the given pincode is valid or not
def validate_pincode(pincode):
return re.findall('^[1-9][0-9]{5}$', pincode)
# main function
def main():
email = input("enter the email:") # providing email
valid =validate_email(email) # calling function
if valid: # checking valid
print(email, 'is correct') # format correct
else:
print(email, 'is invalid') # format incorrect
url = input("enter the website url:") # providing email
valid=validate_website (url) # calling function
if valid: # checking valid
print(url, 'is correct') # format correct
else:
print(url,'is invalid') # format incorrect
pincode = input("enter the pincode belongs to india:") # providing email
valid =validate_pincode(pincode) # calling function
if valid: # checking valid
print(pincode, 'is correct') # format correct
else:
print(pincode,'is invalid') # format incorrect
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main() | true |
2d5665119ecf6dbef6d0ed21cccbbc20662903c6 | Asha-N1/internship | /Basics/numpysomeconcepts.py | 745 | 4.28125 | 4 | # numpy in arrays copy and view
import numpy as np # importing numpy as np
def copy():
arr = np.array([1,2,3,4,5]) # creating array
arr1 = arr.copy() # copying array to new variable
arr[0] = 6 # adding element to the existing array
print(arr) # after adding the element
print(arr1) # disply the array before we adding element copying the same array
arr2 = arr.view() # disply the array after affecting of original array
print(arr) # modified array
print(arr2) # modified array
x = arr.copy() # copying array
y = arr.view() # view array
print(x.base) # displaying base of copying of array
print(y.base) # displaying base of view of array
copy() # calling function
| true |
ec78abd525dca436ab27c939d757e1310b4f0c74 | Asha-N1/internship | /Basics/while_loop.py | 468 | 4.21875 | 4 | # program to add natural num
def main():
n = 20
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
print("\n")
counter = 0
# else with while loop
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
# main execution
if __name__ == '__main__':
main()
| true |
773db8b97af938894f8b83a4f18a423a96164357 | liewjls/metrikus_chessboard | /main/chess_controller.py | 1,672 | 4.15625 | 4 | '''
Created on 27 Aug 2021
@author: jenny
'''
from chess_board import ChessBoard
def print_menu():
print("m. Move pieces")
print("p. Print current board")
print("e. Exit")
return
if __name__ == '__main__':
print("Hello Chess Controller")
chess_game = ChessBoard()
option = True
chess_game.print_pieces_position()
while(option):
print_menu()
choice = input("Enter option:")
choice = choice.lower().replace(' ', '')
if choice == 'm':
pieces_type = input("Enter piece notation: ")
pieces_type = pieces_type.replace(' ', '').lower()
if chess_game.validate_pieces_notation(pieces_type):
start_square = input("Enter start-square: ")
end_square = input("Enter end-square: ")
#Remove all empty spaces from the user input
#Also convert into lowercase too.
start_square = start_square.replace(' ', '').lower()
end_square = end_square.replace(' ', '').lower()
if chess_game.update_pieces_notation(pieces_type, start_square, end_square):
chess_game.print_pieces_position()
else:
print("Invalid Option. Ignored.")
elif choice == 'p':
chess_game.print_pieces_position()
elif choice == 'e':
print("exiting now. Bye bye")
option = False
else:
print("Invalid choice. Choose again")
print("Completed Chess Game") | true |
c2eed10e9912eff15901fd26902cdeb191533070 | Anakinliu/PythonProjects | /CodeWars/4kyu/Permutations.py | 1,519 | 4.40625 | 4 | """
在此kata中,您必须创建输入字符串的所有排列并删除重复项(如果存在)。
这意味着,您必须按所有可能的顺序对输入中的所有字母进行混洗。
Examples:
permutations('a'); # ['a']
permutations('ab'); # ['ab', 'ba']
permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
ABCD -> ABCD, ACBD, BACD, BCAD, CBAD, CABD,
AB -> AB, BA
"""
def permutations(string):
# def do(chosen, remaining, res):
# if len(remaining) == 1:
# res.append(''.join(remaining+chosen))
# return
# d = remaining.pop()
# chosen.append(d)
# do(chosen, remaining, res)
# chosen.pop()
# remaining.insert(0, d)
# do(chosen, remaining, res)
def do(s, fixed_len, res):
if fixed_len == len(s) - 1:
res.add(''.join(s))
return
do(s, fixed_len + 1, res)
for i in range(fixed_len + 1, len(s)):
temp = s.copy()
temp[fixed_len], temp[i] = temp[i], temp[fixed_len]
do(temp, fixed_len + 1, res)
r = set()
# do(c, remain, r)
do(list(string), 0, r)
print(list(r))
pass
# Sebek, maxx_d2
def permutations2(string):
if len(string) == 1:
return set(string)
first = string[0]
rest = permutations2(string[1:])
result = set()
for i in range(0, len(string)):
for p in rest:
result.add(p[0:i] + first + p[i:])
return result
print(permutations2('ABC'))
| false |
664fc8dcf306ce04b7da9243255d2de420861fc5 | z76316/Intro-to-Computer-Science | /symmetric.py | 1,255 | 4.5 | 4 | # A list is symmetric if the first row is the same as the first column,
# the second row is the same as the second column and so on. Write a
# procedure, symmetric, which takes a list as input, and returns the
# boolean True if the list is symmetric and False if it is not.
def symmetric(array):
# Your code here
while not array:
return True
n = len(array)
m = len(array[0])
if n != m:
return False
for i in range(0, n, 1):
for j in range(0, n, 1):
p = array[i][j]
q = array[j][i]
if p != q:
return False
return True
print symmetric([[1, 2, 3],
[2, 3, 4],
[3, 4, 1]])
# >>> True
print symmetric([["cat", "dog", "fish"],
["dog", "dog", "fish"],
["fish", "fish", "cat"]])
# >>> True
print symmetric([["cat", "dog", "fish"],
["dog", "dog", "dog"],
["fish", "fish", "cat"]])
# >>> False
print symmetric([[1, 2],
[2, 1]])
# >>> True
print symmetric([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]])
# >>> False
print symmetric([[1, 2, 3],
[2, 3, 1]])
# >>> False
print symmetric([]) | true |
d7250f6d4a7702c504ad28a8a0412dc02952a7c9 | JerryCui/examples | /tripleStub.py | 433 | 4.34375 | 4 | '''Stub for triple exercise.'''
def tripleAll(nums):
''' print triple each of the numbers in the list nums.
>>> tripleAll([2, 4, 1, 5])
6
12
3
15
>>> tripleAll([-6])
-18
'''
# code here
for item in nums:
tripleitems = 3*item
printout = '{} s triple is {}'.format(item, tripleitems)
print(printout)
tripleAll([2, 4, 1, 5])
tripleAll([-6])
| true |
70773c414b17025590b17652774a73c82138507d | ShanePAustin/pands | /code/week05/Lab5/studentRecord.py | 447 | 4.125 | 4 | #studentRecord.py
#A program that stores and prints student data
#Shane Austin
student = {
"name": "Mary",
"courses": [
{
"subject" : "Programming",
"grade" : 45
},
{
"subject" : "History",
"grade" : 99
}
]
}
print ("Student: {}".format(student["name"]))
for course in student["courses"]:
print("\t {} \t: {}".format(course["subject"], course["grade"])) | false |
9e6b6a9f0fb87fd23d169d623ce5ba64e51e4194 | ShanePAustin/pands | /code/week05/weekday.py | 313 | 4.375 | 4 | #weekday.py
#A program that outputs whether or not today is a weekday.
#Author: Shane Austin
import datetime
time = datetime.datetime.now()
today = (time.strftime("%A"))
if (today == 'Saturday' or today == 'Sunday'):
print("It is the weekend, yay!")
else:
print ("Yes, unfortunately today is a weekday.")
| true |
3726a54f00cfeb836e93d270d5d44bbfac48cd63 | mrityunjay2627/GitLearn | /hilo.py | 1,498 | 4.25 | 4 | low = 1
high = 1000
print("Please think of a number between {} and {}".format(low, high))
input("Press ENTER to start") # Remember
guesses = 1
while low != high:
# print("\tGuessing in the range of {} to {}".format(low, high))
guess = low + (high - low) // 2
high_low = input("My guess is {}. Should I guess higher or lower? "
"Enter h or l, or c if my guess was correct "
.format(guess)).casefold()
if high_low == "h":
# Guess higher. The low end of the range becomes 1 greater than the guess.
low = guess + 1
elif high_low == "l":
# G
# uess lower. The high end of the range becomes one less than the guess.
high = guess - 1
elif high_low == "c":
print("I got it in {} guesses!".format(guesses))
break
else:
print("Please enter h, l or c")
# guesses = guesses + 1
# An augmented assignment is used to replace a statement where an operator takes a
# variable as one of its arguments and then assigns the result back to same variable.
# A simple example is x += 1 which is expanded to x = x + (1).
# Similar constructions are often available for various binary operators.
guesses += 1
else: # else for while loop. See the indentation. Will run when low = high.
# When a loop terminates normally, the else block is executed.
print("You thought of the number {}".format(low))
print("I got it in {} guesses".format(guesses))
| true |
7b784f260f46c5b3ca9fbde0f27ad4bd927d6fb8 | abhikushwaha/Hacktoberfest2019 | /Python/nth_fibonacci.py | 297 | 4.34375 | 4 | #Python Program to calculate the nth Fibonacci Number
from math import sqrt
def fibonacci(n):
return int(1/sqrt(5)*(((1+sqrt(5))/2)**n - ((1-sqrt(5))/2)**n))
your_number=int(input("Enter the value so that we can calculate its corresponding Fibonacci Number:"))
print(fibonacci(your_number))
| false |
39cdeb48f7cbeeb26679e2a58c262eb886fcd9ba | abhikushwaha/Hacktoberfest2019 | /Python/ControlFlow.py | 1,552 | 4.34375 | 4 | # Python program to learn about control flow
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, it is a little higher than that')
# You can do whatever you want in a block ...
else:
print('No, it is a little lower than that')
# you must have guessed > number to reach here
print('Done')
number = 23
running = True
#You can have an else cause for a while loop
while running:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
running = False
# New block ends here
elif guess < number:
# Another block
print('No, it is a little higher than that')
# You can do whatever you want in a block ...
else:
print('No, it is a little lower than that')
# you must have guessed > number to reach here
else:
print('the while loop is over')
print('Done')
#for loop
for i in range (1,5):
print(i)
else:
print('the for loop is over')
print(list(range(5)))
while True:
s = input('Ente somting: ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
print()
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('too small')
continue
print('Input is of sufficent length')
| true |
c65b67fbe4d49e36691733878bb9cb12eb07b0e4 | snsunlee/LeetCode | /回溯法/212.单词搜索ii.py | 2,825 | 4.21875 | 4 | """
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:
你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。
"""
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for c in word:
if c not in node:
node[c] = {}
node = node[c]
node['#'] = True
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
node = Trie()
for word in words:
node.insert(word)
node = node.root
visited = [[0] * len(board[0]) for i in range(len(board))]
result = []
temp = ''
row = len(board)
col = len(board[0])
for i in range(row):
for j in range(col):
if board[i][j] in node:
self.dfs(board, i, j, visited, node, temp, result)
return result
def dfs(self, board, i, j, visited, node, temp, result):
row = len(board)
col = len(board[0])
if '#' in node and temp not in result:
return result.append(temp)
if i > row-1 or i < 0 or j > col-1 or j < 0:
return
if board[i][j] not in node or visited[i][j] == 1:
return
temp += board[i][j]
visited[i][j] = 1
self.dfs(board, i + 1, j, visited, node[board[i][j]], temp, result)
self.dfs(board, i - 1, j, visited, node[board[i][j]], temp, result)
self.dfs(board, i, j + 1, visited, node[board[i][j]], temp, result)
self.dfs(board, i, j - 1, visited, node[board[i][j]], temp, result)
visited[i][j] = 0
###val:
print(Solution().findWords([
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
],["oath","pea","eat","rain"])) | false |
46cfce96b6158721a5c2f409e915b51f2ed73f2f | mocarskijosh/PythonCrashCourseNotes | /Part1/Chapter8Functions/functions.py | 2,661 | 4.75 | 5 | # Chapter 8 Functions
'''
# Store functions in separate files called modules to help organize the main program
# Def a function
def greetUser():
"""Display a simple greeting."""
print("Hello!")
greetUser()
# Passing Information to a Function
def greetUser(username):
"""Display a simple greeting."""
print("Hello, " + username.title() + "!")
greetUser('jessie')
# In addition to calling functions normally, you can also call a function like the following
# This is called Keyword Arguments
def describePet(animalType, petName):
"""Display information about a pet."""
print("\nI have a " + animalType + ".")
print("My " + animalType + "'s name is " + petName.title() + ".")
describePet(animalType='hamster', petName='harry')
=>
$ python functions.py
I have a hamster.
My hamster's name is Harry.
# Default Values
def describePet(petName, animalType = 'dog'):
"""Display information about a pet."""
print("\nI have a " + animalType + ".")
print("My " + animalType + "'s name is " + petName.title() + ".")
describePet('willie')
=>
$ python functions.py
I have a dog.
My dog's name is Willie.
# Returning a Dictionary
def buildPerson(fname, lname):
"""Return a dictionary of information about a person."""
person = {'first': fname, 'last': lname}
return person
musician = buildPerson('jimi', 'hendrix')
print(musician)
=>
$ python functions.py
{'first': 'jimi', 'last': 'hendrix'}
# Preventing a Function from Modifying a List
# sending a copy of a list to a function.....
# functionName(listName[:])
# Passing an Arbitrary Number of Arguments
def makePizza(*toppings):
"""Printing the list of toppings that have been requested."""
print(toppings)
makePizza('pepperoni')
makePizza('mushrooms', 'green peppers', 'extra cheese')
=>
$ python functions.py
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
# this is also valid
def makePizza(size, *toppings):
~~~~~
makePizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# Passing Key-Value Pairs as Function Arguments
def buildProfile(first, last, **userInfo):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['firstName'] = first
profile['lastName'] = last
for key, value in userInfo.items():
profile[key] = value
return profile
userProfile = buildProfile('albert', 'einstein',
location='princeton',
field='physics')
print(userProfile)
=>
$ python functions.py
{'firstName': 'albert', 'lastName': 'einstein', 'location': 'princeton', 'field': 'physics'}
'''
| true |
ad78e93812e64596d24db9aa27970fcf7bb1ad67 | yw892/MS_Interview | /q1.py | 1,538 | 4.21875 | 4 | def binary_search_next_larger_pos(arr, val, low, high):
"""
The function is to find the position of the minimum number that is larger than
val in a descending order list by using the binary search
:param arr: list
:val: integer
:low: integer
:high: integer
:return: integer, if val is larger than the largest value in the list, return -1
"""
if arr[-1] > val:
return len(arr) - 1
elif arr[0] < val:
return -1
while low <= high:
mid = int((low + high) / 2)
if arr[mid] < val:
high = mid - 1
elif arr[mid] > val:
low = mid + 1
else:
return mid
return high
def next_number(num):
"""
The function is to find the minimum number which is larger than given number
:param num: integer
:return: integer, if num is already the maximum number, return None
"""
num_list = list(map(int, str(num)))
if len(num_list) <= 1:
return num
pos = len(num_list) - 2
while pos >= 0:
if num_list[pos] < num_list[pos+1]:
break
pos -= 1
if pos < 0:
print('No next number, maximum number already')
return
else:
path = num_list[pos+1:]
replace_pos = binary_search_next_larger_pos(path, num_list[pos], 0, len(path))
path[replace_pos], num_list[pos] = num_list[pos], path[replace_pos]
return int(''.join(list(map(lambda x:str(x), num_list[:pos+1] + path[::-1]))))
print(next_number(987136524))
| true |
db02fe91b0a3452ca05f9e6f43ff22d9a3685698 | Ze1598/Python_stuff | /examples/for_loop_practice.py | 2,514 | 4.25 | 4 | #Loop practice
print('Loop 1')
for i in range(10):
print('*', end=' ')
print()
print()
print('Loop 2')
for i in range(10):
print('*', end=' ')
print()
for j in range(5):
print('*', end=' ')
print()
for h in range(20):
print('*', end=' ')
print()
print()
print('Loop 3')
for i in range(10):
for j in range(10):
print('*', end=' ')
print()
print()
print()
print('Loop 4')
for i in range(10):
for j in range(5):
print('*', end=' ')
print()
print()
print()
print('Loop 5')
for i in range(5):
for j in range(20):
print('*', end=' ')
print()
print()
print()
print('Loop 6')
for i in range(10):
for j in range(10):
print(j, end=' ')
print()
print()
print()
print('Loop 7')
for i in range(10):
for j in range(10):
print(i, end=' ')
print()
print()
print()
print('Loop 8')
for i in range(10):
for j in range(i):
print(j, end=' ')
print()
print()
print()
print('Loop 9')
for i in range(10):
#Spaces before
for h in range(i):
print(' ', end=' ')
#Numbers
for j in range(10-i):
print(j, end=' ')
print()
print()
print()
print('Loop 10')
for i in range(1, 10):
for j in range(1, 10):
#Format the spacing between numbers
if (i*j < 10) and (j > 1):
print(' ', end='')
print(i*j, end=' ')
print()
print()
print()
print('Loop 11')
for i in range(1, 10):
#Leading whitespace for each row
for j in range(9-i):
print(' ', end=' ')
#Numbers up to the middle, included
for h in range(1, i+1):
print(h, end=' ')
#Numbers after the middle, middle excluded
for g in range(i-1,0,-1):
print(g, end=' ')
print()
print()
print()
print('Loop 12')
#The upper half (middle row included)
for i in range(1, 10):
#Leading whitespace for each row
for j in range(9-i):
print(' ', end=' ')
#Numbers up to the middle of the row, included
for h in range(1, i+1):
print(h, end=' ')
#Numbers after the middle of the row
for g in range(i-1,0,-1):
print(g, end=' ')
print()
#The bottom half (middle row not included)
for i in range(1, 9):
#Leading whitespace for each row
for j in range(i):
print(' ', end=' ')
#Numbers up to the middle of each row, row included
for h in range(1, 10-i):
print(h, end=' ')
#Numbers after the middle of each row
for g in range(8-i, 0, -1):
print(g, end=' ')
print()
| false |
87238d3989bdada05c28205103914581bd5c2023 | Ze1598/Python_stuff | /small_projects/second encryption attempt.py | 287 | 4.34375 | 4 | string = input('Insert string:')
encrypted = '' #will hold the encrypted result
decrypted = ''
encrypted += string[1::2] #get the odd-index characters
encrypted += string[::2] #get the even-index characters
# print('--1', len(string))
# prsint('--2', len(encrypted))
print(encrypted)
| true |
46e13c6d3783185c912b87f49418ede576bd907c | Ze1598/Python_stuff | /examples/shuffled_bin_search.py | 1,532 | 4.34375 | 4 | # Look for an integer in a shuffled list
from random import shuffle, randint
def shuffled_bin_search (x):
'''
Find the index of a given integer in a shuffled list.
Parameters
----------
x : int
The number we are looking for.
Returns
-------
middle : int
The index at which the target integer is located at.
'''
# Create and shuffle a list with the integers between 1 and 100, inclusive
a = list(range(1,101))
shuffle(a)
# At first, the middle is the middle of the whole list
middle = len(a) // 2
# The lower bound starts as the beginning of the list
low = 0
# The upper bound starts as the end of the list
high = len(a) - 1
# Run the loop until we find what we are looking for
while True:
# If the number at index `middle` is the one we are looking for,\
# then return that index (the answer)
if x == a[middle]:
return middle
# Else, update the lower or upper bounds as necessary
else:
# If the target number is between the lower bound and the middle,\
# then update the upper bound to be the middle and calculate the\
# middle again
if x in a[low : middle+1]:
high = middle
middle = (low+high) // 2
# If the target number is between the middle and the upper bound,\
# then update the lower bound to be the middle and calculate the\
# middle again
elif x in a[middle: high+1]:
low = middle
middle = (low+high) // 2
if __name__ == "__main__":
for i in range(3):
num = randint(1, 101)
print(f"{num} is at index {shuffled_bin_search(num)}") | true |
dd460bffa1b29b01c71d556f6f8d9115a5905ad6 | Ze1598/Python_stuff | /examples/binary_search_example.py | 1,477 | 4.375 | 4 | from random import randint
def binary_search(num, lower_bound, upper_bound):
#The mid point is the floored average of the lower and upper bounds
mid_pos = (lower_bound+upper_bound)//2
#Run the loop while the number hasn't been found
while mid_pos != num:
#Each iteration one of the bounds is modified, so we can update the mid point here
mid_pos = (lower_bound+upper_bound)//2
#If the mid point is bigger than the number, then update the upper bound to\
#be the current value of the mid point - 1
if mid_pos > num:
print(mid_pos, 'is too high.')
upper_bound = mid_pos - 1
#If the mid point is smaller than the number, then update the lower bound to\
#be the current value of the mid point + 1
elif mid_pos < num:
print(mid_pos, 'is too low.')
lower_bound = mid_pos + 1
#When the number is found, print a statement with the number
else:
print(mid_pos, 'is the correct answer.')
#The initial lower bound is the smallest number in the range
lower_bound = 1
#The initial upper bound is the biggest number in the range
upper_bound = 128
#The number to be guessed is a random integer in the inclusive range of lower bound to upper bound
rand_num = randint(lower_bound, upper_bound)
print('Number to be guessed:', rand_num)
#Call the function to find the random number using binary search
binary_search(rand_num, 1, 128) | true |
34e9a3521058a4b8e8fb0bf4e65b31c3bb317508 | Ze1598/Python_stuff | /examples/product_pairs.py | 1,059 | 4.25 | 4 | from random import randint
def product_pairs(n):
'''
Given a list of integers, find pairs of numbers
from the list whose product equals the sum of
all numbers in the list.
'''
print('n:', n)
# The list of integers (1 to n, inclusive)
num_list = list(range(1, n+1))
# Sum of the list's numbers
num_sum = sum(num_list)
# List to hold the pairs found
pairs = []
# Loop through the list of integers
for i in range(len(num_list)):
# If we can evenly divide the sum by the current number
if (num_sum%num_list[i] == 0):
# And if the result of the division is in the list
if (num_sum / num_list[i]) < n:
# Then it means we found a pair
pair = sorted((num_list[i], int(num_sum / num_list[i])))
# Check if the pair is already in the found list
if pair not in pairs:
pairs.append(pair)
return pairs
for i in range(3):
print(product_pairs(randint(1,1000)))
print() | true |
ce2deb49ac9515928e91617de8326efd9794e635 | makto/codinPy | /euler/p19.py | 744 | 4.25 | 4 | #!/usr/bin/env python
"""
How many Sundays fell on the first of the month during the twentieth century?
"""
smalls = (4, 6, 9, 11)
def is_leap(year):
if year % 400 == 0:
return True
elif year % 4 == 0 and year % 100 != 0:
return True
return False
def days_of_month(month, year):
if month == 2:
if is_leap(year):
return 29
else:
return 28
elif month in smalls:
return 30
else:
return 31
past_days = sum([days_of_month(m, 1900) for m in xrange(1, 13)])
total = 0
for year in xrange(1901, 2001):
for month in xrange(1, 13):
if (past_days+1) % 7 == 0:
total += 1
past_days += days_of_month(month, year)
print total
| false |
0c9fdcd899335bb856fd379432277ad7476828e9 | bsamaripa/dailybyte | /problems/Week 1/004-correct-capitalization.py | 862 | 4.3125 | 4 | import unittest
"""
This question is asked by Google. Given a string, return whether or not it
uses capitalization correctly. A string correctly uses capitalization if
all letters are capitalized, no letters are capitalized, or only the first
letter is capitalized.
"""
class TestCorrectCapitalization(unittest.TestCase):
def correct_capitalization(self, input: str) -> bool:
if len(input) is 0: return False
return False
def test_correct_capitalization(self):
self.assertEqual(self.correct_capitalization(''), False)
self.assertEqual(self.correct_capitalization('USA'), True)
self.assertEqual(self.correct_capitalization('Calvin'), True)
self.assertEqual(self.correct_capitalization('compUter'), False)
self.assertEqual(self.correct_capitalization('coding'), True)
if __name__ == '__main__':
unittest.main() | true |
9f8cdad673df8e466246ae2bafaf722dd12f8477 | 06opoTeHb/Ataurus | /ataurus/data_parse/utils.py | 1,076 | 4.15625 | 4 | def get_sublists(main_list: list, count: int):
"""
Function splits the main list to $count sublists: extra elements will be appended into the first sublists.
:param main_list: a list that will be split
:param count: count of sublists
:return: list of sublists
"""
if not main_list:
return [[]]
# Minimal count of elements per sublist
count_per_list = len(main_list) // count
# If count of elements more or equal count of sublists
if count_per_list != 0:
# Split the main list to 2 parts
rest_list = main_list[count * count_per_list:]
main_list = main_list[:count * count_per_list]
sublists = [main_list[x:x + count_per_list] for x in range(0, len(main_list), count_per_list)]
# Append extra elements into the first sublists
for index, element in enumerate(rest_list):
sublists[index].append(element)
# If count of elements less than count of sublists
else:
sublists = [main_list[x:x + 1] for x in range(0, len(main_list))]
return sublists
| true |
b536110bb9e9367f23cdc53cb426a21f909428b0 | DiegotheSoftRoboticist/Python-coding | /Module 5/list_methods.py | 949 | 4.1875 | 4 | alphabet = ["a","b","c"]
print(alphabet)
alphabet.append("d")
print(alphabet)
alphabet.extend(["d","Diego",5])
print(alphabet)
alphabet.insert(1,"d")
print(alphabet)
alphabet.clear
print(alphabet)
alphabet = ["a","b","c"]
print(alphabet)
alphabet.pop(2)
print(alphabet)
alphabet.remove("b")
print(alphabet)
print(alphabet.index("a"))
alphabet = ["a","b","c","a"]
print(alphabet.index("a",1)) #tells you the index of "a" afte the first index
print(alphabet.count("a"))
alphabet.reverse()
print(alphabet)
alphabet.sort()
print(alphabet)
alphabet = ["a","b","c","a","f","d","g","h","j","n","m","z"]
#print("These are the letters I know ".join(alphabet)) # string methods to create strings from lists
#slicing
print(alphabet[1:7])
print(alphabet[1:7:2])
print(alphabet[1::2])
print(alphabet[1::-1])
alphabet[1:3] = [1,1,1,1,1,1]
print(alphabet)
#Swapping Values
alphabet[1], alphabet[2] = alphabet[2], alphabet[1] | false |
fa2786638f2210c9b5de6ce6b3d06fce21606a71 | josephguerrero1/FIzzBuzz_Python | /index.py | 1,460 | 4.40625 | 4 | # Imported the random module onto my python script.
import random
# Created a function called FizzBuzz.
# The function takes in an argument of num, which is a number.
# The first conditional statement uses a Modulo operator, which will determine if an integer is divisible by another integer.
# In the first conditional statement, if the num argument is divisible by both 3 and 5, the function will print out 'FizzBuzz' to the terminal.
# Otherwise, the function will run the next conditional statement.
# In the second conditional statement, if the num argument is divisible by 3, the function will print out 'Fizz' onto the terminal.
# Otherwise, if the num argument is divisible by 5, the function will print out 'Buzz' onto the terminal.
# Otherwise, the function will print out 'Input is not an integer, or the integer is not divisible by 3 or 5.' onto the terminal.
def FizzBuzz(num):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
else:
if num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print("Input is not an integer, or the integer is not divisible by 3 or 5.")
# Here the variable n equals a built in function called 'random' that will generate a random number between the numbers of 0 and 15.
n = random.randint(0, 15)
# The result n will be printed onto the console.
# The function FizzBuzz will be called and executed.
print(n)
FizzBuzz(n)
| true |
a2f0e4e69c05b4b12011790d1439db6f98c1807d | rahulkawadkar/PythonScripts | /ArtihPy.py | 579 | 4.125 | 4 | var1 = int(input("Enter First Digit : "))
print ("First digit is :", var1)
var2 = int(input("Enter Second Digit : "))
print ("Second digit is: ", var2)
sum = var1+var2
diff = var1-var2
product = var1*var2
div = var1/var2
mod = var1%var2
print("Sum of two digits is : " , sum)
print("Difference of two digits is : " , diff)
print("Product of two digits is : " , product)
print("Division of two digits is : " , div)
print("Modulo of two digits is : " , mod)
str1 = input("Was the result correct? Enter 'Yes' or 'No'\n")
print ("ThankYou, your response was: " + str1) | true |
76c8882daeaaad7993842d858ac8f7b953630a1c | philip-33/ATBS-python | /ch07_strongpass.py | 1,178 | 4.34375 | 4 | #! python3
'''
This program uses regexes (regi?) to check
the strength of a given password, then reports
the result to the user. Also, this module follows
PyLint conventions (except C0103).
A strong password:
-is at least eight characters long
-contains both uppercase and lowercase characters
-has at least one digit
(and my own addition)
-has at least one non-character, non-numeral symbol
'''
import re
userpass = input("Please enter a password to test: ")
charRegex = re.search('.{8,}', userpass)
lcaseRegex = re.search('[a-z]+', userpass)
ucaseRegex = re.search('[A-Z]+', userpass)
digiRegex = re.search('[0-9]+', userpass)
symbolRegex = re.search('[^a-zA-Z0-9]+', userpass)
print("Your password...")
if charRegex is None:
print("Is too short (less than 8 characters)")
if None in [lcaseRegex, ucaseRegex]:
print("Does not contain both uppercase and lowercase characters")
if digiRegex is None:
print("Does not contain any numbers")
if symbolRegex is None:
print("Does not contan any non-alphanumeric symbols, such as !@#$%^&*")
if not None in [charRegex, lcaseRegex, ucaseRegex, digiRegex, symbolRegex]:
print("Is strong enough for general use.")
| true |
08951597bc34fd66a377d20906ddd8583d6c3629 | iamabdil/python_competition | /Q15.py | 1,186 | 4.9375 | 5 | '''
Q15: Make function powers_of_series that takes a Series and a positive integer k as parameters and returns a DataFrame. The resulting DataFrame should have the same index as the input Series. The first column of the dataFrame should be the input Series, the second column should contain the Series raised to power of two. The third column should contain the Series raised to the power of three, and so on until (and including) power of k. The columns should have indices from 1 to k.
The values should be numbers, but the index can have any type. Test your function from the main function. Example of usage:
s = pd.Series([1,2,3,4], index=list("abcd"))
print(powers_of_series(s, 3))
Should print:
1 2 3
a 1 1 1
b 2 4 8
c 3 9 27
'''
import pandas as pd
def powers_of_series(s, k):
df = pd.DataFrame(index=s.index)
for i in range(k):
df[i+1] = [x**(i+1) for x in s]
return(df)
def main():
s = pd.Series([1,2,3,4], index=list("abcd"))
print(powers_of_series(s, 3))
if __name__ == "__main__":
main()
'''
Joke of the Question:
Why did the programmer quit their job? Answer: Becauses they didn’t get arrays.
''' | true |
5402af0312f6c00e1db114996429cdb8809b67ba | pbragancacabral/Secret-Messages | /caesar.py | 1,711 | 4.15625 | 4 | import random
import string
from ciphers import Cipher
class Caesar(Cipher):
"""In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift,
is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which
each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example,
with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius
Caesar, who used it in his private correspondence.
Source: Wikipedia
This implementation is case-insensitive."""
_ALPHABET = string.ascii_uppercase
def __init__(self, offset=random.randint(1, 26)):
self.CIPHER = self._ALPHABET[offset:] + self._ALPHABET[:offset]
"""Takes one string and encrypts it based on the Caesar cipher."""
def encrypt(self, text):
output = []
text = text.upper()
for char in text:
try:
index = self._ALPHABET.index(char)
except ValueError:
output.append(char)
else:
output.append(self.CIPHER[index])
return "".join(output)
"""Takes one string and decrypts it based on the Caesar cipher."""
def decrypt(self, text):
output = []
text = text.upper()
for char in text:
try:
index = self.CIPHER.index(char)
except ValueError:
output.append(char)
else:
output.append(self._ALPHABET[index])
return "".join(output)
| true |
d962ee9cc321f858266bdd07f8d8a3504cf571fb | Preetpalkaur3701/python-programmes | /naturalnumber.py | 571 | 4.40625 | 4 | print "Hi ! Here you can find the sum of natural numbers"
print "Please enter only positive numbers , negative numbers are not included in natural numbers"
#in next line the function is used which gives a path to the programme by which the we can get the sum of numbers.
def sum(a,b):
c= a+b
return c
#here a and b are the inputs taken from user.
a = input("Enter first number")
b = input("Enter second number")
print ("sum"+str(sum(a,b)))
#sum >0 is written here because natural numbers are always positive.
if sum > 0 :
print "the sum of your is natural number"
| true |
98e7455031dfcc1206ebc846b98417741a577cfe | Preetpalkaur3701/python-programmes | /loops.py | 276 | 4.1875 | 4 | """
Task
Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1 <=i <= 10 ) should be printed on a new line in the form: n x i = result.
"""
n = int(input("Enter the number"))
for i in range(1,11):
print('{0} x {1} = {2}'.format(n, i, n * i))
| true |
bff3d65a8a3cea7e6cc0f8c07e2dddd9f15eabf0 | wangfaping0707/PythonProject | /rfresh_Python/chapter3_demo/StudyDay1_demo.py | 1,543 | 4.4375 | 4 |
# 以 # 开头的注释可以注释一行文本,Python 另外提供了注释多行文
# 本的功能。多行注释用三个单引号 ‘’’ 或者三个双引号 “”" 将注释括起来,例如:
# 使用3个单引号注释多行文本
'''
# 首先定义变量 x
# 让后将变量 x 修改为 456
x = 123
x = 456
'''
"""
# 首先定义变量 x
# 让后将变量 x 修改为 456
x = 123
x = 456
"""
# 输入与输出,Python 提供了 input 语句用于读取键盘输入,input 语句读取用户输入的一行文本。
line = input()
print(line)
# 在第 1 行,使用 input 语句读取用户输入的一行文本,将该文本保存到变量 line 中。
# 在第 2 行,用户输入一行文本 ‘hello world’。
# 在第 3 行,查看变量 line。
# 在第 4 行,显示结果为文本 ‘hello world’
# 可以在 input 语句中加入参数,该参数作为用户输入的提示符,例如:
number = input('Please input a number: ')
print(number)
# 在第 1 行,使用 input 语句读取用户输入的一行文本,将该文本保存到变量 number 中。input 语句带有一个参数 'Please input a number: '。
# 在第 2 行,input 语句首先输出 input 语句的参数 'Please input a number: ',这样用户就根据该提示输入数
# 字,然后 input 语句再读取用户输入的一行文本 123。
# 使用 print 语句输出多项内容: 在输入中,每项内容使用逗号分开 在输出中,每项内容使用空格分开
print(123, 'hello world', 1 + 1, "1+1")
| false |
365421753d99a59fa1849d648ca188004c4f26a0 | wangfaping0707/PythonProject | /Basic_Python/chapter5/demo5.4.6.py | 918 | 4.34375 | 4 | # 比较运算符:==
print('foo' == 'foo')
print('foo' == 'bar')
# is:相同运算符
# is 运算符检查两个对象是否相同(而不是相等)。变量x和y指向同一个列表,而z指向另一个列表,内存地址不一样,
# 虽然值的内容一样,但并非同一个对象
# 总之,==用于检查两个对象是否相等,而is用来检查两个对象是否相同(是同一个对象)
x = y = [1, 2, 3, 4, 5]
z = [1, 2, 3, 4, 5]
print("x和y是否相等?", x == y)
print("x和z是否相等?", x == z)
print("x is y?", x is y)
print("x is z?", x is z)
print(ord('a'))
print(ord('b'))
print(ord('王'))
print(ord('发'))
print(ord('平'))
print(chr(29579))
print(chr(21457))
print(chr(24179))
# in 成员资格运输符
name = input("请输入你的芳名:")
if 's' in name:
print("Your name contains the letter 's'!")
else:
print("Your name does not contains the letter 's'!")
| false |
218f2c3d898830752b667c53754dd6aaf31a1184 | wangfaping0707/PythonProject | /rfresh_Python/chapter3_demo/StudyDay18_demo.py | 2,600 | 4.75 | 5 | """
python-map的用法: map()函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
map() 函数语法:map(function, iterable, ...)
参数: function -- 函数 iterable -- 一个或多个序列
注意:map()函数不改变原有的 list,而是返回一个新的 list。
"""
# 当seq只有一个时,将函数func作用于这个seq的每个元素上,并得到一个新的seq。
# 以下实例展示了 map() 的使用方法:
list_x = [1, 2, 3, 4, 5, 6]
def square(x): # 计算平方数
return x * x
re = map(square, list_x) # re是一个对象,需要把它转为1列表
list_y = list(re)
print("平方之后的列表值:", list_y)
"""
利用map()函数,可以把一个 list 转换为另一个 list,只需要传入转换函数。
由于list包含的元素可以是任何类型,因此,map() 不仅仅可以处理只包含数值的 list,
事实上它可以处理包含任意类型的 list,只要传入的函数f可以处理这种数据类型。
假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,
把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list:
"""
names = ['adam', 'LISA', 'barT'] # 期望转换后的输出:['Adam','Lisa','Bart']
def format_name(s):
s1 = s[0:1].upper() + s[1:].lower()
return s1
s2 = map(format_name, names)
print("姓名转换后的名字:", list(s2))
# 用lambda表达式来使用map
result = map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
print(list(result))
# 提供了两个列表,对相同位置的列表数据进行相加, 当seq(序列)多于一个时,map可以并行(注意是并行)地对每个seq执行如下图所示的过程:
# python3中可以处理类表长度不一致的情况,但无法处理类型不一致的情况,
L1 = [1, 3, 5, 7, 9, 20, 40]
L2 = [2, 4, 6, 8, 10, 25]
result2 = map(lambda x, y: x + y, L1, L2)
print("使用lambda表达式的运行结果:", list(result2))
# python3中可以处理类表长度不一致的情况,但无法处理类型不一致的情况,
l4 = map(lambda x, y: (x ** y, x + y), [1, 2, 3], [1, 2])
print("l4的类型是:", l4)
for i in l4:
print(i)
# l4 = map(lambda x, y: (x ** y, x + y), [1, 2, 3], [1, 2, 'a'])
# for i in l4:
# print(i)
# 特殊用法,做类型转换:
T = map(int, '1234')
for i in T:
print(type(i))
print(i)
| false |
04bda523cb48ded4cff1bec1c2dafb6b1345f2cb | wangfaping0707/PythonProject | /Basic_Python/chapter5/demo5.5.4.py | 532 | 4.3125 | 4 | # 并行迭代
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
# 如果要打印名字和对应的年龄,可以如下操作
for i in range(0, len(names)):
print(names[i], 'is', ages[i], 'years old')
# 并行迭代根据:内置函数zip,它将两个序列缝合起来,并返回一个由元组组成的序列
print(zip(names, ages))
print(type(zip(names, ages)))
print(list(zip(names, ages)))
print(dict(zip(names, ages)))
for name, age in zip(names, ages):
print(name, 'is', age, "years old")
| false |
8f2890edd72ff4fcf9068fc81a151c486b33122c | wangfaping0707/PythonProject | /Basic_Python/chapter9/demo9.6.2.py | 1,229 | 4.53125 | 5 | """
迭代器
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器:
Iterable 可迭代的 ————》形容词
Iterator 迭代器————》名词
"""
from collections.abc import Iterable,Iterator
import sys
list = [1,2,3,4]
# 判断list是否是一个可迭代的对象
print("list是否可迭代:",isinstance(list,Iterable))
print("list是否是一个迭代器::",isinstance(list,Iterator))
# 通过iter()方法取得list的迭代器
# 对一个对象调用iter()可以得到他的迭代器
it = iter(list) # 创建list的 迭代器对象 迭代器就是用于记录迭代中每次遍历的位置
print("看一下迭代器究竟是什么?",)
print("迭代器类型是什么?",type(it))
print(next(it)) # 输出迭代器的下一个元素
# 1、迭代器对象可以使用常规for语句进行遍历:
for x in it:
print(x,end="/")
| false |
0429914cd4829fd0dc2497d1ee4f78f32e97eb63 | wangfaping0707/PythonProject | /Basic_Python/chapter6/demo6.6.py | 743 | 4.375 | 4 | # 递归 : 一个函数调用自身成为递归
def recursion(depth):
depth +=1
print(depth)
return recursion(depth)
recursion(0)
# 今天在用python写一个递归查询数据库的程序时,报了一个错误:
# RecursionError: maximum recursion depth exceeded in comparison
# 错误的大致意思就是递归超过了最大的深度。
# 查询过相关文档和资料后才发现了问题原因,python的递归深度是有限制的,默认为1000。当递归深度超过1000时,就会报错
# 补充测试
# 由于对最大递归层数产生兴趣,于是我在自己电脑上用以下代码做了测试:
#
# def recursion(depth):
# depth += 1
# print(depth)
# recursion(depth)
#
# recursion(0) | false |
ab400662b62c4900a55b88ca97d4592cd81be72d | wangfaping0707/PythonProject | /rfresh_Python/chapter4_demo/StudyDay20_demo.py | 1,264 | 4.34375 | 4 | """
Python3 filter() 函数:
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,
最后将返回 True 的元素放到新列表中。
以下是 filter() 方法的语法: filter(function, iterable) function -- 判断函数 iterable -- 可迭代对象
返回值: 返回一个迭代器对象
"""
# 实例: 过滤出列表中的所有奇数:
def is_odd(n):
return n % 2 == 1
result = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print("返回过滤后的列表:", list(result))
result1 = filter(lambda x: True if x % 2 == 1 else False, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print("打印result1的结果:", list(result1))
# 需求;过滤掉小写,只保留大写字母 Python提供了isupper(),islower(),istitle()方法用来判断字符串的大小写
list_word = ['s', 'S', 'd', 'F', 'L', 'S']
result2 = filter(lambda x: True if x.isupper() else False, list_word)
result3 = filter(lambda x: True if x.islower() else False, list_word)
print(list(result2))
print(list(result3))
| false |
610734217fd8e7ba7d0b9b567db3eb38068e33ef | wangfaping0707/PythonProject | /Basic_Python/chapter7/demo7.2.3.py | 540 | 4.125 | 4 | # 属性 函数和方法
class example:
name = 'lover'
def method(self):
print("打印方式一", 'I have a {}'.format(self.name))
print("打印方式二", 'I have a %s' % self.name)
def function(self):
print("I don't ..........")
# 在python中,函数名加(),表示返回的是一个函数的计算结果,不加括号表示的是对函数的调用,是函数的一个地址。
instance = example()
print(instance)
instance.method()
print(instance.method,"类型是:",type(instance.method))
| false |
367b7d249a08dc98981d48e217bc5df7528cc551 | wangfaping0707/PythonProject | /rfresh_Python/chapter4_demo/decorator_demo/decorator6_demo.py | 995 | 4.25 | 4 |
import time
"""
类装饰器:一般依靠类内部的__call__方法
1、不带参数的类装饰器: 基于类装饰器的实现,必须实现 __call__ 和 __init__两个内置函数
__init__ :接收被装饰函数
__call__ :实现装饰逻辑
2、带参数的类装饰器
带参数和不带参数的类装饰器有很大的不同
__init__ :不再接收被装饰函数,而是接收传入参数
__call__ :接收被装饰函数,实现装饰逻辑
"""
class Foo(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
self.func(*args, **kwargs)
end_time = time.time()
print("执行这个函数所需要的时间:", (end_time - start_time))
@Foo # bar = Foo(bar)->命名一个变量bar,和函数同名的变量,然后 bar = Foo(add) 然后在bar() 也就是Foo(add)()
def add(a, b):
print("执行add函数计算结果:", (a + b))
time.sleep(3)
add(3, 4)
| false |
5158c973cd1f10ba239c6c50d8715e98a5b33dbd | felsen/fluent-python | /parents.py | 1,420 | 4.53125 | 5 | """
Initializing parent class methods and attributes.
"""
class A(object):
def spam(self):
print("spam A")
class B(A):
def spam(self):
print("spam B")
# here, parents class method is overidden in subclass. this will call the parent class spam.
super().spam() # super will always look for the parent class attr & methods
a = A()
a.spam() # spam A
b = B()
b.spam() # spam B
# spam A
class C(object):
def __init__(self):
self.x = 1
print(self.x)
class D(C):
def __init__(self):
# Whenever the class D is called, first super will initialize the C class __init__, then self.y will be printed.
super().__init__()
self.y = 2
print(self.y)
print("----------")
c = C()
c # 1
d = D()
d # 1
# 2
class E(D, C):
def __init__(self):
super().__init__()
self.z = 3
print(self.z)
print("------------")
e = E()
e # 1
# 2
# 3
class Proxy(object):
def __init__(self, obj):
self._obj = obj
def __getattr__(self, name):
return getattr(self._obj, name)
def __setattr__(self, name, value):
# another usage of super is override the any magic methods.
# this will call the original __setattr__
if name.startswith('_'):
super().__setattr__(name, value)
else:
setattr(self._obj, name, value)
| false |
d446576fb67536d49ecb3e71c64f58dd1b50f3e7 | ndragotta123/A-B-C- | /abc_learning.py | 1,074 | 4.34375 | 4 | # Python3 accepts input
# I wrote this to help my child learn the A B C's and a bit about Python3
abc_dict = {
'a': 'apple', 'b': 'banana', 'c': 'cat', 'd': 'dog', 'e': 'elephant',
'f': 'fox', 'g': 'gorilla', 'h': 'horse', 'i': 'igloo',
'j': 'jellyfish', 'k': 'kangaroo', 'l': 'lamb', 'm': 'moon',
'n': 'net', 'o': 'ostrich', 'p': 'penguin', 'q': 'queen',
'r': 'raccoon', 's': 'summer', 't': 'turkey', 'u': 'umbrella',
'v': 'violin', 'w': 'winter', 'x': 'xylophone', 'y': 'yarn', 'z': 'zebra',
}
# accepts letter in any case
# rejects non-alphabetic characters with friendly message
prompt = "\nPlease pick a letter:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
abc = input(prompt).lower()
if abc == 'quit':
break
if not abc.isalpha():
print("\n***That is not a letter*** Please choose a letter.")
continue
else:
if abc in abc_dict:
print("\n" + abc.capitalize() + " is for " +
abc_dict[abc].capitalize() + "!")
| true |
1ddda0aa186bad22f1cd0c64d1b7ee23afcaf159 | emchampion/pythonstuff | /cypher.py | 1,733 | 4.125 | 4 | #!/usr/bin/env python
""" crypto.py
Implements a simple substitution cypher
"""
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
#menu called by the main
def menu():
response = raw_input(" 0) Quit \n 1) Encode \n 2) Decode \n")
return response
#counts where it is at in the alpha and prints from the key
def encode(var1):
final = " "
var1 = var1.upper()
for x in range(0, len(var1)): #loops for the range of the var1
for y in range(0, len(alpha)): #loops through to check characters
findx = var1[x].find(alpha[y]) #finds the equivilant from the alpha
if findx != -1:
foundx = y
final = "{1}".format(foundx,key[foundx])
print final #prints the results as it loops one character at a time
return
#takes leters from the key and prints them from the alpha
def decode(var2):
final = " "
var2 = var2.upper()
for x in range(0, len(var2)): #loops for the range of the var2
for y in range(0, len(key)):
findx = var2[x].find(key[y]) #finds the equivilant from the key
if findx != -1:
foundx = y
final = "{1}".format(foundx,alpha[foundx])
print final
return
#main that lets us select what to do
def main():
keepGoing = True
while keepGoing:
response = menu()
if response == "1":
plain = raw_input("text to be encoded: ")
print encode(plain)
elif response == "2":
coded = raw_input("code to be decyphered: ")
print decode(coded)
elif response == "0":
print "Thanks for doing secret spy stuff with me."
keepGoing = False
else:
print "I don't know what you want to do..."
return
main()
| true |
55901f052a0fbf688246a9a8c2fbb9225eaab65d | greene-matthew/CSC444 | /Rijndael/Rijndeal.py | 2,495 | 4.15625 | 4 | # Rijndael
# Sample template to show how to implement AES in Python
from __future__ import division
from sys import stdin
from hashlib import sha256
import re
from Crypto import Random
from Crypto.Cipher import AES
# the AES block size to use
BLOCK_SIZE = 16
# the padding character to use to make the plaintext a multiple of BLOCK_SIZE in length
PAD_WITH = "#"
# the key to use in the cipher
dictionary = "dictionary1-3.txt"
#dictionary = "dictionary4.txt"
#dictionary = "dictionary5.txt"
threshold = 0.75
d = open(dictionary, "r")
dictionary = d.read().rstrip("\n").split("\n")
d.close()
# decrypts a ciphertext with a key
def decrypt(ciphertext, key):
# hash the key (SHA-256) to ensure that it is 32 bytes long
key = sha256(key).digest()
# get the 16-byte IV from the ciphertext
# by default, we put the IV at the beginning of the ciphertext
iv = ciphertext[:16]
# decrypt the ciphertext with the key using CBC block cipher mode
cipher = AES.new(key, AES.MODE_CBC, iv)
# the ciphertext is after the IV (so, skip 16 bytes)
plaintext = cipher.decrypt(ciphertext[16:])
# remove potential padding at the end of the plaintext
# figure this one out...
# return plaintext.rstrip("#")
return plaintext.replace("#", "")
# encrypts a plaintext with a key
def encrypt(plaintext, key):
# hash the key (SHA-256) to ensure that it is 32 bytes long
key = sha256(key).digest()
# generate a random 16-byte IV
iv = Random.new().read(BLOCK_SIZE)
# encrypt the ciphertext with the key using CBC block cipher mode
cipher = AES.new(key, AES.MODE_CBC, iv)
# if necessary, pad the plaintext so that it is a multiple of BLOCK SIZE in length
plaintext += (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * PAD_WITH
# add the IV to the beginning of the ciphertext
# IV is at [:16]; ciphertext is at [16:]
ciphertext = iv + cipher.encrypt(plaintext)
return ciphertext
def checkIfValid(decryptedString,key):
words = len(decryptedString)
validWords = 0
for x in decryptedString:
x = re.sub(r'[^A-Za-z]', '', x)
if x.lower() in dictionary:
validWords += 1
if ((validWords / words) >= threshold):
# if("%PDF-" in decryptedString[0]):
return True
else:
return False
# MAIN
plaintext = stdin.read().rstrip("\n")
ciphertext = plaintext
for word in dictionary:
#if(word[0] == "J" or word[0] == "j"):
#print(word)
decryptedString = decrypt(ciphertext, word)
if (checkIfValid(decryptedString.split(" "),word)):
print("KEY=" + str(word))
print(decryptedString)
| true |
5f649da4890e1993c5aff11beecddbf52ad0d0b4 | saradiya/pythonDsa | /LinkedList/finalLinkedlist.py | 1,700 | 4.28125 | 4 | class Node:
def __init__(self, data):
self.data =data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
## 1.
# starting of linkedlist
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
## 2.
# at mid position linkedlist
def after(self, prev_node, new_data):
#checking if the prev_node is exist or not
if prev_node.next == None:
print("No LinkedList found")
return
new_node = Node(new_data)
# assign previous node next to the new_data node [next]
new_node.next = prev_node.next
#given head of new to next of previous
prev_node.next = new_node
## 3.
# appending the node at the last
def append(self, new_data):
new_node = Node(new_data)
# checking if node is empty or not
if self.head==None:
self.head=new_node
# if condition is false iterate to last element of the list
last = self.head
while(last.next):
last = last.next
## 4
# function to print the linked list
def printList(self):
# taking head node to temp
temp = self.head
# loop till we have elements in temp
while(temp):
print(temp.data)
temp = temp.next
# code execution to start
if __name__ == "__main__":
llist = LinkedList()
llist.append(6)
llist.push(2)
llist.push(3)
llist.after(llist.head.next, 8)
#printing the list
llist.printList() | true |
08cdf174a0c9a09d609713c7f720fcd376be5d13 | saradiya/pythonDsa | /LinkedList/LinkedList_between.py | 399 | 4.1875 | 4 | # TIME COMPLEXITY OF INSERTAFTER IS [ O(n)] AS IT DOES CONSTANT AMOUNT OF WORK
# it involves 5 steps
def afterinsert(self, prev_node, new_data):
# checkif node is present or node
if prev_node == None:
print("Given previous node should be a linkedlist:")
return
new_data = Node(new_data)
new_data.next = prev_node.next
prev_node.next = new_node
| true |
a84c1f193a95d62ef3935f2c8c346fa7c673dc2e | MihailRascalov/wd | /3_wprowadzenie/zadanie_10.py | 476 | 4.125 | 4 | # Napisz funkcję, która wykorzystuje symbol **. Funkcja ma przyjmować listę zakupów w
# postaci: klucz to nazwa produktu, a wartośc to ilość. Funkcja ma zliczyć ile jest
# wszystkich produktów w ogóle i zwracać tę wartość.
def add_product(** products):
"""The function returns the number of products in general"""
sum = 0
for x in products:
sum += products[x]
return sum
print(add_product(apple=10, banana=5, onion=3, chilli_pepper=3)) | false |
81e673d2f4d4646cac1e8a0072e9ba87d267f4b2 | MihailRascalov/wd | /3_wprowadzenie/zadanie_9.py | 783 | 4.1875 | 4 | # Wykorzystując poprzedni przykład zdefiniuj funkcję, która będzie liczyć iloczyn elementów
# ciągu.
def product_of_the_arithmetic_sequence(a1 = 1, r = 1, how_many_elements = 10):
"""The function returns the product of any arithmetic string
a1 => initial value
r => the amount by which the next elements grow
ile_elementów => how many items to multiply"""
if how_many_elements == 1:
return a1
elif how_many_elements == 0:
return 0.0
sum = a1
list = [a1]
for i in range(1, how_many_elements):
sum += r
list.append(sum)
result = 1
for x in list:
result = result * x
return result
print(product_of_the_arithmetic_sequence())
print(product_of_the_arithmetic_sequence(1, 2, 5)) | false |
b565bca20304836f2614c70252fceaaf6076e4a9 | swifty-sheep/Coding_Interview | /gfg/back_tracking/knights_tour.py | 1,528 | 4.28125 | 4 | """ Knight's Tour example for back tracking algorithm."""
from typing import List
class KnightsTour:
def __init__(self, n):
self.n = n
def is_safe(self, x: int, y: int, board: List[List[int]]) -> bool:
if 0 <= x < self.n and 0 <= y < self.n and board[x][y] == -1:
return True
return False
def print_solution(self, board):
for i in range(self.n):
for j in range(self.n):
print(board[i][j], end=" ")
print()
def solve_kt_util(self, board, curr_x, curr_y, move_x, move_y, pos):
if pos == self.n ** 2:
return True
for i in range(8):
new_x = curr_x + move_x[i]
new_y = curr_y + move_y[i]
if self.is_safe(new_x, new_y, board):
board[new_x][new_y] = pos
if self.solve_kt_util(board, new_x, new_y, move_x, move_y, pos+1):
return True
board[new_x][new_y] = -1
return False
def solve_kt(self):
board = [[-1 for i in range(self.n)] for i in range(self.n)]
move_x = [2, 1, -1, -2, -2, -1, 1, 2]
move_y = [1, 2, 2, 1, -1, -2, -2, -1]
board[0][0] = 0
pos = 1
if not self.solve_kt_util(board, 0, 0, move_x, move_y, pos):
print("solution not exist")
else:
self.print_solution(board)
def main():
knights_tour = KnightsTour(8)
knights_tour.solve_kt()
# Driver Code
if __name__ == "__main__":
main()
| false |
f01bccaddb7fdd1c340f2c464406daac72207539 | swifty-sheep/Coding_Interview | /graph/bfs.py | 1,500 | 4.375 | 4 | """python program to print bfs traversal from a given source vertex.
bfs(int s) traverses vertices reachable from s."""
from graph.graph import Graph
class GraphBfs(Graph):
"""this class represents a directed graph using adjacency list
representation."""
def bfs(self, s):
# mark all vertices as not visited
visited = [False] * (max(self.graph) + 2)
# create a queue for bfs
queue = []
# mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# dequeue a vertex from queue and print it
s = queue.pop(0)
print(s, end=" ")
for i in self.graph[s]:
if not visited[i]:
queue.append(i)
visited[i] = True
def run_graph_one():
graph = GraphBfs()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
print("Following is BFS starting from vertex 2")
graph.bfs(2)
def run_graph_two():
graph = GraphBfs()
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 4)
graph.add_edge(2, 5)
graph.add_edge(3, 5)
graph.add_edge(4, 5)
graph.add_edge(4, 6)
graph.add_edge(5, 6)
print("\nFollowing is BFS starting from vertex 1")
graph.bfs(1)
def main():
run_graph_one()
run_graph_two()
if __name__ == "__main__":
main()
| true |
7b0c9bd8228ccd01074dfab7f782305416a74d08 | mastertech-usa/fundamentos_python | /funciones2.py | 2,501 | 4.40625 | 4 | """
Script2 para explicar funciones en Python.
Argumentos
"""
# 1. Considere la siguiente función
def suma_lista(lista):
"""Esta función suma los números de una lista
Parameters:
lista : Lista con números
Return:
suma: suma de los elementos de la lista
"""
suma = 0
for elem in lista:
suma += elem
return suma
milista = [12.5,10,13.4,13.22,7,2.34]
print(suma_lista(milista)) # En este llamado el argumento es milista y es OBLIGATORIO
# Que pasa si no envio el argumento
# suma_lista()
# 2. Valores por defecto
def suma_lista2(lista = [1,2,3]):
"""Esta función suma los números de una lista
La diferencia con la anterior función es que en esta el parametro lista
tiene un valor por defecto, por lo tanto cuando llamemos a esta función
los argumentos son opcionales.
Parameters:
lista : Lista con números
Return:
suma: suma de los elementos de la lista
"""
suma = 0
for elem in lista:
suma += elem
return suma
milista = [12.5,10,13.4,13.22,7,2.34]
print(suma_lista2(milista)) # Con argumento
print(suma_lista2()) #Sin argumento, ahora si se puede pq hay un valor por defecto en la definición del parametro.
# 3. Funciones definidas con multiples parametros/LLamados con multiples argumentos
def elimina_caracteres(texto,eliminar = ["a","e","i","o","u"]):
"""Esta función elimina de un texto un conjunto de caracteres.
Parameters:
texto : String con texto del cual se quiere eliminar caracteres
eliminar: Lista con los caracteres que quiero eliminar.
Return:
textopro: Texto sin los caracteres que se especificaron.
"""
textopro = ""
for caracter in texto:
if caracter not in eliminar:
textopro = textopro + caracter
return textopro
mi_texto = "Colombia"
print(elimina_caracteres(mi_texto)) # Un solo argumento
print(elimina_caracteres(mi_texto,["l"])) # Multiples argumentos asignados por posición!!!
#4. Python definición de argumentos por palabra clave
result1 = elimina_caracteres(texto=mi_texto, eliminar=["l"]) # Todos los argumentos deben ir definidos por palabra clave
result2 = elimina_caracteres(eliminar=["l"],texto=mi_texto) # Diferente orden
print(result1, " ", result2)
# elimina_caracteres(texto=mi_texto, ["l"]) # Error | false |
6b40dad287ee7d8dec9e87d730e34bd42fcc0534 | mastertech-usa/fundamentos_python | /Ejercicio_1_1.py | 681 | 4.15625 | 4 | """
PROBLEMA 1:
ENUNCIADO: Dados dos números enteros, hallar la suma.
ANÁLISIS: Para la solución de este problema, se requiere que el usuario ingrese dos números enteros y el sistema realice el cálculo respectivo para hallar la suma, para esto se debe usar la siguiente expresión.
Expresión Matemática: suma = numero 1 + numero 2
Entrada: Dos números enteros (números 1 y número 2).
"""
# Capturar los números de entrada por parte del usuario
num_1 = input("Ingrese el primer numero:")
num_2 = input("Ingrese el segundo numero:")
#Suma y realizar type casting
suma = int(num_1) + int(num_2)
print("El resultado de la suma es {}".format(suma))
| false |
3efdf845705dfdd017cc37cd085e53cdbd48f5dd | olgabienkowska/learningPython | /Python for Data Science/Udemy/findWord.py | 311 | 4.1875 | 4 | #Create a basic function that returns True if the word 'dog' is contained in the input string. Don't worry about edge cases like a punctuation being attached to the word dog, but do account for capitalization.
def findDog(phrase):
return 'dog' in phrase.lower().split()
findDog('Is there a dog here?') | true |
d7483f16490601b2648e9f4874d8d7ab24799b35 | ashrafulemon/python | /pp43.py | 392 | 4.125 | 4 | #63 regular expressions > re
import re
pattern = r"colour"
#match >> prothom ongso match kore ki na ta dekhe
if re.match(pattern,"colour is a colour"):
print("match")
else:
print("not match")
#search >> poro tate kothao match kore ki na
if re.search(pattern,"red is a colour"):
print("match")
else:
print("not match")
#findall
print(re.findall(pattern,"red is a colour,i like colour")) | false |
90ec3fdf231a1ae8cf4afb9bc2c8afd16ba059e4 | ashrafulemon/python | /p64.py | 241 | 4.15625 | 4 | # 5.18 string modification
#add
#remove
#change
#add
index =2
str1= "hello"
str2= str1[:index] +'e'+ str1[index:]
print(str2)
#remove
str2= str1[:index]+str1[index+1:]
print(str2)
#change
str2=str1[:index]+"e"+str1[index+1:]
print(str2) | false |
c9b9544d08511cd8c78cdc944d188618c20b84ad | Christina2727/MIT | /MIT/Lecture 3/functions.py | 947 | 4.28125 | 4 | # Christina 1-19-18
# functions.py
# Defining Functions
# def starts a function definition
# names of functions follow variable naming conventions
# functions can take zero or more parameters
def is_a_party(apples, pizzas):
# Returns True if you have enough apples and pizzas to make a party happen
if apples > 10 and pizzas > 10:
return True
else:
return False
# A function with zero parameters
def throw_party():
num_apples = int(input("How many apples do you have? "))
num_pizzas = int(input("How many pizzas do you have? "))
# Ask if this is enough for a party
if is_a_party(num_apples, num_pizzas):
return ("Dude let's party down")
else:
return ("You'll have to go to the store first.")
## Testing the functions
#print(is_a_party(20, 20))
#print(is_a_party(5, 15))
#print(is_a_party(5, 2))
#print(is_a_party(14, 8))
print(throw_party())
| true |
3102755f80a54216d85ce0d12fbafd02fbcd1183 | Christina2727/MIT | /MIT/Hmwk 2/hmwk2ex 2.4.py | 766 | 4.375 | 4 | import math
import random
def rand_divis_3():
x = random.randint(0,100)
print(x)
if (x%3) == 0:
print(True)
else :
print(False)
return
rand_divis_3()
"""2. Write a method roll dice that takes in 2 parameters - the number of sides
of the die, and the number of dice
to roll - and generates random roll values for each die rolled.
Print out each roll and then return the string
“That’s all!” An example output:
>>> roll_dice(6, 3)
4
1
6
That’s all!
***** HELP CHARLIE ****
SEND THE ANSWER TO THIS IN A SEPERATE EMAIL, WE ARE GOING TO TRY TO
FIGURE IT OUT FIRST"""
def roll_dice(a,b):
for a in roll_dice():
print(a)
print("Thats all")
pass
| true |
20629edefcbc91632857ef7b77a7095db1445fdf | Faisal413/stc_second_assignment | /is_prime.py | 450 | 4.21875 | 4 | num = int(input('Please enter an integer: '))
# return all the nontrivial positive divisors of a given number
n = abs(num)
divisors = []
while n > 1:
if num % n == 0:
divisors.append(n)
n -= 1
# check whether the input num is a prime number
boo = len(divisors) == 1
if boo:
print(f'The inputted number {num} is a prime')
else:
print(f'The inputted number {num} is NOT a prime, it has divisors {divisors}') | true |
fe09fa812a9e7e163d0e89a3712e256e6e3c5488 | n3rdpower/pyclass_ladies | /PBJ/PBJ_Goal1.py | 736 | 4.25 | 4 | #Basics for Exercise 1
peanut_butter = int(raw_input("How many servings of peanut butter do you have? "))
jelly = int(raw_input("How many servings of jelly do you have? "))
bread_slice = int(raw_input ("How many slices of bread do you have? "))
if peanut_butter >= 1 and jelly >= 1 and bread_slice >= 2:
print "It's Peanut Butter Jelly Time!"
elif peanut_butter < 1 and jelly >= 1 and bread_slice >= 2:
print "you need more peanut butter"
elif jelly < 1 and peanut_butter >= 1 and bread_slice >= 2:
print "you need more jelly"
elif bread_slice < 2 and jelly >= 1 and peanut_butter >= 1:
print "you need more bread to make a decent PB&J"
else:
print "Bottom line: you are simply not prepared for Peanut Butter Jelly Time"
| true |
418e6d5c20d70036fa140e5a81e8830cd376aafd | hieugomeister/ASU | /CST100/Chapter_3/Chapter_3/Ch_3_Solutions/Ch_3_Projects/3.7/fib.py | 1,681 | 4.21875 | 4 | """
File: fib.py
Project 3.7
Employs memoization to improve the efficiency of recursive Fibonacci.
Counts the calls and displays the results.
The complexity of this implementation is linear. The reason is that when n > 2,
each fib(n) is computed as the sum of the constant-time lookups of
of fib(n - 1) and fib(n - 2). There are approximately n of these lookups.
"""
class Counter(object):
"""Tracks a count."""
def __init__(self):
self._number = 0
def increment(self):
self._number += 1
def __str__(self):
return str(self._number)
def fib(n, counter, table):
"""Count the number of calls of the Fibonacci
function."""
counter.increment()
if n < 3:
return 1
else:
# Attempt to get values for n - 1 and n - 2
# from the table
# If unsuccessful, recurse and add results to
# the table
result1 = table.get(n - 1, None)
if result1 is None:
result1 = fib(n - 1, counter, table)
table[n - 1] = result1
result2 = table.get(n - 2, None)
if result2 is None:
result2 = fib(n - 2, counter, table)
table[n - 2] = result2
return result1 + result2
def main():
"""Tests the function with some powers of 2."""
problemSize = 2
print("%12s%15s" % ("Problem Size", "Calls"))
for count in range(5):
counter = Counter()
# The start of the algorithm (note the empty dictionary)
fib(problemSize, counter, {})
# The end of the algorithm
print("%12d%15s" % (problemSize, counter))
problemSize *= 2
if __name__ == "__main__":
main()
| true |
ba77576dc33610dc70967ca451a3cc2689cfea75 | hieugomeister/ASU | /CST100/Chapter_1/Chapter_1/Ch_1_Solutions/Ch_1_Projects/1.1/salaryprob.py | 990 | 4.34375 | 4 | """
Program: sphere.py
Project 1.1
Given the radius compute the diameter, circumference, and volume
of a sphere.
Useful facts:
diameter = 2 * radius
circumference = diameter * 3.14
surface area = 4 * PI * radius * radius
volume = 4/3 * PI * radius * radius * radius
"""
# include math library object for math operations.
import math
# Request the input => varname = float(input("message: "))
hourlywage = float(input("Enter your hourly wage: "))
totalreghour = float(input("Enter your regular hours: "))
totalothours = float(input("Enter your total OT hours: "))
# Compute the results, declare varname and compute on the fly
regpay = hourlywage * totalreghour
otpay = (1.5 * hourlywage) * totalothours
totalweeklypay = regpay + otpay
totalregularannual = regpay * 48
# Display the results
print("Regular pay : $",regpay)
print("OT Pay : $",otpay)
print("Total Weekly pay : $",totalweeklypay)
print("Total Yearly pay : $",totalregularannual)
| true |
5caa3686d7a543e290228c06051e6d89e7b76a72 | hieugomeister/ASU | /CST100/Chapter_3/Chapter_3/Ch_3_Solutions/Ch_3_Projects/3.9/quicksort.py | 1,921 | 4.1875 | 4 | """
File: quicksort.py
Project 3.9
Uses insertion sort in quicksort to sort sublists whose length < 50.
"""
def quickSort(lyst):
quicksortHelper(lyst, 0, len(lyst) - 1)
def quicksortHelper(lyst, left, right):
"""Calls insertionSort if length of sublist < 50."""
if left < right:
if right - left + 1 >= 50:
pivotLocation = partition(lyst, left, right)
quicksortHelper(lyst, left, pivotLocation - 1)
quicksortHelper(lyst, pivotLocation + 1, right)
else:
insertionSort(lyst, left, right)
def partition(lyst, left, right):
# Find the pivot and exchange it with the last item
middle = (left + right) // 2
pivot = lyst[middle]
lyst[middle] = lyst[right]
lyst[right] = pivot
# Set boundary point to first position
boundary = left
# Move items less than pivot to the left
for index in range(left, right):
if lyst[index] < pivot:
swap(lyst, index, boundary)
boundary += 1
# Exchange the pivot item and the boundary item
swap(lyst, right, boundary)
return boundary
def insertionSort(lyst, left, right):
"""Note extra args for bounds of sublist."""
i = left + 1
while i <= right:
itemToInsert = lyst[i]
j = i - 1
while j >= 0:
if itemToInsert < lyst[j]:
lyst[j + 1] = lyst[j]
j -= 1
else:
break
lyst[j + 1] = itemToInsert
i += 1
def swap(lyst, i, j):
"""Exchanges the values at i and j."""
lyst[i], lyst[j] = lyst[j], lyst[i]
import random
def main():
"""Tests quicksort with 4 lists."""
size = 40
for count in range(4):
lyst = list(range(size))
random.shuffle(lyst)
quickSort(lyst)
print(lyst)
print("Size: ", size)
size *= 4
if __name__ == "__main__":
main()
| true |
17b0bc8a7126f4024711eb34c6cea18d5043ce9f | avijoshi4u/Python | /listComprehensions.py | 807 | 4.3125 | 4 | '''list comprehensions are a shortcut to create a one list
out of another by applying the logic we want on the first list as well as we can apply
conditions on the right hand side only if the condition is satisfied that item will be included in the resulting list'''
lst = [x for x in range(2,21,2)]
print(lst)
# Using list comprehension
lst2 = [x for x in range(1,21) if x%2==0]
print(lst2)
# Product of two list using normal way
a=[1,2,3,4,5]
b=[6,7,8,9,10]
z=[]
for i in range(len(a)):
z.append(a[i]*b[i])
print(z)
# Product Using list comprehension
z= [a[x]*b[x] for x in range(len(a))]
print(z)
# common element in two list
c = [2,4,7,8,9]
d = [2,4,11,12,14]
lst3 = [c[x] for x in range(len(a)) if c[x]==d[x]]
print(lst3)
result = []
result = [i for i in c if i in d]
print(result)
| true |
fc9b1c2284972c708e5023f485ca37e78dc43ad8 | uddeshh/pyDSA | /linkedlist.py | 1,010 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linkedlist:
def __init__(self):
self.head=None
def append(self,data):
new_node=Node(data)
if self.head is None:
self.head=new_node
return
last_node=self.head
while last_node.next:
last_node=last_node.next
last_node.next=new_node
def prepend(self,data):
new_node=Node(data)
new_node.next=self.head
self.head=new_node
def printit(self):
cur_node=self.head
while cur_node:
print(cur_node.data)
cur_node=cur_node.next
def insertit(self,prev_node,data):
if not prev_node:
return
new_node=Node(data)
# cur_node=Node(data1)
new_node.next=prev_node.next
prev_node.next=new_node
ll=Linkedlist()
ll.append(1)
ll.append(2)
ll.append(3)
ll.insertit(ll.head.next,5)
ll.append(4)
ll.prepend(9)
ll.printit()
| false |
181a31c1605a8f22396bf5222f21203e6b2c877f | johnsonpthomas/python | /pallindrome.py | 270 | 4.53125 | 5 | def pallindrome(a):
#print(a)
#print(a[::-1])
#-- Check if the string is same as the reverse of the string using ::-1
if a == a[::-1]:
print(a + ' is pallindrome')
else:
print(a + ' is not pallindrome')
pallindrome('malayalam')
pallindrome('malayalee')
| false |
2f326ac22657a3a128dc2507beb2da92092415ed | Yogeshwarathe/Calculatar | /calculatar/calculatar.py | 819 | 4.15625 | 4 | from opratarsInCalculatar import *
while True:
def calculatar(num1,num2,operation):
if operation =="add" or operation=="ADD":
add(num1,num2,operation)
elif operation == "subtract" or operation == "SUBTRACT":
sub(num1,num2,operation)
elif operation == "multiply" or operation == "MULTIPLY":
mul(num1,num2,operation)
elif operation == "division" or operation == "DIVISION":
div(num1,num2,operation)
elif operation == "modulas" or operation == "MODULAS":
mod(num1,num2,operation)
calculatar(num1 = int(raw_input("Enter number ")),num2 = int(raw_input("Enter second number ")),operation = (raw_input("Enter any operation for example 1.add 2.subtract 3.multiply 4.division 5.modulas ")))
Agen = raw_input("Do you want to play Agen Yes/No ")
if Agen == "No" or Agen == 'no':
break | true |
de6e356e371d77ad90de933ca98f644c76d1ae31 | NawabRizwan/progams | /fibonacci modified.py | 374 | 4.15625 | 4 | '''python program that takes a number FROM the fibonacci series as
input and prints the sum of fibonacci sequence upto that number'''
n = int(input("Enter a number from the fibonacci series"))
t1 = 0
t2 = 1
sum = 1;
nextNum = 0;
if n == 0 or n == 1:
print(str(n))
else:
while nextNum < n:
nextNum = t1+t2;
sum += nextNum;
t1 = t2;
t2 = nextNum
print(str(sum))
| true |
2c5fbbea127647a1999785f6f0440eef1e88a6c2 | sholjakundu/Pythonprojects | /evenodd.py | 397 | 4.21875 | 4 | """
WAP to find the even, odd no. from the list of entered values
"""
n=[]
num=int(input("Enter the total number of list elements: "))
for i in range(1,n+1):
value=int(input("please enter the element:"))
n.append(value)
even=[]
odd=[]
for j in n:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list ",even)
print("The odd list ",odd) | true |
8bec17d44f594fb565ba7ad184c16a26436f983d | daviguetta/POOcomPython | /Conceitos chaves.py | 828 | 4.21875 | 4 |
#CLASSE EM PYTHON
class Carro():
# __init__ CONSTRUTOR DO PYTHON - METODO PARA A ATRIBUIÇÃO DE ATRIBUTOS PARA UMA INSTÂNCIA
# "def" define um metodo dentro da classe
def __init__(self,arg,arg2):
self.Atributo1 = arg
self.Atributo2 = arg2
def getAtributo1():
return self.Atributo1
# HERANÇA
# Classe PAI
class Veiculo():
def __init__(self, initMarca, initModelo, initAreaDeAtuacao):
self.Marca = initMarca
self.Modelo = initModelo
self.AreaDeAtuação = initAreaDeAtuacao
# Classe FILHA
# Invoca a classe pai como parâmetro
class Carro(Veiculo):
def __init__(self, initMarca, initModelo, initAreaDeAtuacao):
#super() é responsavel por invocar a herança da classe pai
super().__init__(initMarca, initModelo, initAreaDeAtuação)
| false |
6d0c1a9e2a4d82c5604df3622ada49404162968e | Depredador1220/PythonEjemplos | /OperacionesConPilas.py | 717 | 4.25 | 4 | """Operaciones con Pilas"""
pila = []
tamaño_pila = 3
def mostrarElementosPila():
print("Elementos actuales en la pila: ")
for elemento in pila:
print(elemento)
def pushPila(elemento):
print(f"Colocando {elemento} a la pila")
if len(pila) < tamaño_pila:
pila.append(elemento)
else:
print("Pila llena")
def popPila():
if len(pila) > 0:
print(f"Elimina el elemento de la pila {pila.pop()}")
else:
print("Pila vacia")
def main():
pushPila(1)
pushPila(2)
pushPila(3)
mostrarElementosPila()
pushPila(4)
popPila()
mostrarElementosPila()
popPila()
popPila()
popPila()
if __name__ == "__main__":
main()
| false |
c9160cfc8dd699d23e79d6310fc9dbbfb7e439b0 | Bishajit/Dev-opsassignement-notes | /Project 6.py | 201 | 4.3125 | 4 | print("Enter name: ")
name = input()
if len(name)<3:
print("name is not 3 characters")
elif len(name)>50:
print("name is more than 50 characters")
else:
print("name looks good")
| false |
53d9a38a7ea1a7579b5b2d653034f57c2a7a13f3 | a-morev/Python_Algos | /Урок 1. Практическое задание/task_9.py | 829 | 4.3125 | 4 | """
Задание 9. Вводятся три разных числа. Найти, какое из них является средним
(больше одного, но меньше другого).
Подсказка: можно добавить проверку, что введены равные числа
"""
num_a = int(input('Первое число: '))
num_b = int(input('Второе число: '))
num_c = int(input('Третье число: '))
if num_a == num_b or num_a == num_c or num_b == num_c:
print('Введены равные числа!')
elif num_a > num_b > num_c or num_a < num_b < num_c:
print(f'Среднее число: {num_b}')
elif num_c > num_a > num_b or num_c < num_a < num_b:
print(f'Среднее число: {num_a}')
else:
print(f'Среднее число: {num_c}')
| false |
9919a9040b6b17f3beceb21d6c6cf42f86b0780a | Eshanafix/python-practice | /Dictionaries.py | 540 | 4.1875 | 4 |
#Dictionary, hashmaps?
student = {"name" : "John", "age" : 25, "courses": ["math", "comp sci"]}
student["phone"] = "555-555"
print(student)
print(student["name"])
print(student["courses"])
print(student.get("name"))
print(student.get("phone" , "not found"))
student["name"] = "Akbar"
print(student)
student.update({"name": "ya", "age" : 26})
print(student)
del student["age"]
print(student)
print(len(student))
print(student.keys())
print(student.values())
print(student.items())
for key, value in student.items():
print(key,value)
| false |
508f7c415290e8af1a3bde94965a5960e0ea1547 | andrecontisilva/Python-aprendizado | /HackerRank/30DaysOfCode/HackerRank_Python3_Day00-HelloWorld.py | 776 | 4.125 | 4 | """
Site: HackerRank
Type: Practice
Subdomain: Tutorials - 30 Days Of Code
Difficulty: Easy
Skill: Python 3
Problem: Day 0: Hello, World.
URL: https://www.hackerrank.com/challenges/30-hello-world/problem
"""
# SOLUTION:
# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()
# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')
# TODO: Write a line of code here that prints the contents of input_string to stdout.
print(input_string)
"""
NOTE:
Hello World! - Python Official Documentation (v3.9.1 PT-BR):
https://docs.python.org/pt-br/3/tutorial/index.html
https://docs.python.org/pt-br/3/tutorial/appetite.html
https://docs.python.org/pt-br/3/tutorial/interpreter.html
"""
| true |
bab2781c37849f98a1f1d1f26f74429949e79398 | maguas01/hackerRank | /pStuff/Anagram.py | 990 | 4.125 | 4 | #!/bin/python
'''
Sid is obsessed with reading short stories. Being a CS student, he is doing some interesting
frequency analysis with the books. He chooses strings s1 and s2 in such a way that
|len(s1) - len(s2)| <= 1 .
Your task is to help him find the minimum number of characters of the first string he needs
to change to enable him to make it an anagram of the second string.
Note: A word x is an anagram of another word y if we can produce y by rearranging the
letters of x.
'''
import sys
def anagram(s):
if len(s) % 2 == 1 :
return -1
count = 0
s1 = sorted(s[len(s)/2:])
s2 = sorted(s[:len(s)/2])
s2 = "".join(s2)
for i in range( len(s1) ) :
j = s2.find(s1[i])
if j != -1 :
s2 = s2[:j] + s2[j+1:]
return len(s2)
def main() :
q = int(raw_input().strip())
for a0 in xrange(q):
s = raw_input().strip()
result = anagram(s)
print(result)
if __name__ == "__main__" :
main() | true |
ad5c959dfaf3d9dc5846a635a5b7e04f375d4a15 | maguas01/hackerRank | /pStuff/TreeLevelOrderTraversal.py | 745 | 4.15625 | 4 | '''
You are given a pointer to the root of a binary tree.
You need to print the level order traversal of this tree. In level order traversal, we visit the
nodes level by level from left to right. You only have to complete the function
1 <= Nodes in the tree <= 500
'''
import Queue
'''
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)
'''
def levelOrder(root):
if root == None :
return
q = Queue.Queue()
q.put(root)
while(not q.empty()) :
front = q.get()
print (front.data),
if front.left != None :
q.put(front.left)
if front.right != None :
q.put(front.right)
| true |
33dffcc57f8bba8b06fc3b1f012b3c23323b561a | joeandersen/CSSE7030 | /python the hard way/ex3.py | 815 | 4.3125 | 4 | #This line prints the string
print "I will now count my chickens:"
#This line prints the string and then the result of the mathematics
print "Hens", 25.0+30.0/6
#This line does pretty much the same thing...
print "Roosters", 100-25*3%4
#This line just prints the string
print "Now I will count the eggs:"
#This line calculates 3+2+1-5+2-0+6 = 7
print 3+2+1-5+4%2-1.0/4+6
#This line prints stuff
print "Is it true that 3+2<5-7?"
#this one prints the boolean result of the lt statement...
print 3+2<5-7
#This line prints the string and then the number...
print "What is 3+2?", 3+2
print "What is 5-7?", 5-7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5>-2
print "Is it greater or equal?", 5>=-2
print "Is it less or equal?",5<=-2
print 7/4
print 7.0/4.0
print -7/4
| true |
0ef353ca7f9bbc24864feb46ccb89ccf8772378d | tejasri12345/python_training | /Day1/Strings/calculate_distance.py | 236 | 4.1875 | 4 | import math
x1=int(input("enter x1 value: "))
x2=int(input("enter x2 value: "))
y1=int(input("enter y1 value: "))
y2=int(input("enter y2 value: "))
dist = math.sqrt((x2-x1)**2+(y2-y1)**2)
distance = "{:.2f}".format(dist)
print(distance) | false |
16608864a183d451c25272cb6366a225f8601c1f | Avinashjs206/Number_gussing_game | /main.py | 1,081 | 4.125 | 4 | import random
import math
# Taking Lower inputs
lower = int(input("Enter a Lower number:- "))
# Taking Upper Inputs
upper = int(input("Enter a upper number:- "))
# generating random number between the lower and the upper
x = random.randint(lower, upper)
print("\n\tyou have only", round(math.log(upper - lower +1, 2)), "chances the guess the integer!")
# Inirilizing the number of guesses.
count = 0
# for calculation of minimum number of guesses depends upon range
while count < math.log(upper - lower +1, 2):
count += 1
# taking guessing number as input
guess = int(input("Entere your guess:- "))
# Condition testing
if x == guess:
print("Congratulation you did in", count, "try!" )
# Once guessed, loop will break
break
elif guess > x:
print("Your guess is to high!")
elif guess < x:
print("Your guess is to low!")
# If Guessing is more than required guess,
# Show this output
if count >= math.log(upper - lower +1, 2):
print("\nThe number is %d" %x)
print("\tBetter Luck next time!")
| true |
1f245566a81613633ed2b095b4b1d3d6e35c10e4 | N3d/randomCode | /rot13.py | 507 | 4.25 | 4 | #!/usr/bin/python
"""
* python program to encrypt string using the Cesar13 crypting algorithm
*
* usage:
python rot13.py STRING
"""
import sys
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) <= 1:
print("rot13: require the string to encode\n")
sys.exit()
original = argv[1];
encode = original.encode("rot13")
print("Original: {0} \nCrypted: {1} \n".format(original,encode))
if __name__ == "__main__":
sys.exit(main())
| true |
42adb72acc8679672a0f2e1f0a2a94db3cca0584 | tathagatnawadia/Python_Experiments | /generator.py | 2,390 | 4.15625 | 4 | from util.utils import *
# A simple generator
cities = ["Paris", "Berlin", "Hamburg"]
for location in cities:
print(location)
# Using "next" and "iter"
city_iterator = iter(cities)
while city_iterator:
try:
city = next(city_iterator)
print(city, " ", end="")
except Exception as e:
print("Exception caught !! ", e.__class__)
break
# Using yield()
def fibonacci():
"""Generates an infinite sequence of Fibonacci numbers on demand"""
a, b = 0, 1
while True:
# Dont worry about unending while, since python saves state of local objects
# once a yield statement is called.
# Next time the function is called, python will continue with the while
yield a
a, b = b, a + b
f = fibonacci()
counter = 0
for x in f:
print(x, " ", end="")
counter += 1
if counter > 5:
break
print()
# Generator can have return statements too
def gen():
yield 1
yield 2
return -1
try:
g = gen()
print(next(g), next(g), next(g))
except Exception as e:
print("Exception caught !! ",e.__class__, e)
# Using "yield from"
def gen():
yield from cities
g = gen()
for x in g:
print(x, " ", end="")
# .send() to generators and wrapping them around
from functools import wraps
def get_ready(gen):
"""
decorator to advance to first yield
"""
@wraps(gen)
def generator(*args, **kwargs):
g = gen(*args, **kwargs)
next(g)
return g
return generator
@get_ready
def infinite_looper(objects):
# Setting up the infinite looper
count = -1
message = yield None
while True:
if message != None:
# If no index(message) was given count = 0
# else count = message
count = 0 if message < 0 else message
count += 1
if count >= len(objects):
# If overflow count = 0
count = 0
message = yield objects[count]
x = infinite_looper(["pacman", 1, {"name": "Nawadia"}, 3.3344, ("red", "green", "blue")])
print(next(x))
print(x.send(2))
print(next(x))
print(next(x))
# Using itertools with powerset, combinations and permutations
import itertools
combi = itertools.combinations(['red', 'green', 'blue'],2)
perms = itertools.permutations(['red', 'green', 'blue'])
print(list(combi))
print(list(perms))
# TODO : recursive generators
| true |
309141ec83d35d268f42b8a3cbdb18613796902f | shobhit-arora/CodeWars-Python | /BitCounting.py | 707 | 4.1875 | 4 | """
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary
representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def count_bits(n):
a = str("{0:b}".format(n))
print(a.count("1"))
count_bits(1234)
# Explanation: covert the dec number to bin and covert this bin number to a string
# then count the number of 1s in the string using count method
'''
def countBits(n):
return bin(n).count("1")
'''
'''
def countBits(n):
return '{:b}'.format(n).count('1')
''' | true |
6a56645e86a588ec20a65bd9454a5f77b454a797 | priyank-py/GettingStarted | /PythonBatch-(S-A-A-L-N))/28tkinter_calculator.py | 2,035 | 4.125 | 4 | from tkinter import *
root = Tk()
root.title('My Calculator')
root.geometry('640x480')
val1 = Label(root, text='Value 1:')
val1.grid(row=0, column=0)
ent1 = Entry(root)
ent1.grid(row=0, column=1)
val2 = Label(root, text='Value 2:')
val2.grid(row=1, column=0)
ent2 = Entry(root)
ent2.grid(row=1, column=1)
def addition():
try:
a = int(ent1.get())
b = int(ent2.get())
except ValueError:
result = Label(root, text="You can only enter numbers")
result.grid(row = 3, column=0)
result = Label(root, text="result = "+str(a+b))
result.grid(row = 3, column=0)
def subtraction():
try:
a = int(ent1.get())
b = int(ent2.get())
except ValueError:
result = Label(root, text="You can only enter numbers")
result = Label(root, text="result = "+str(a-b))
result.grid(row = 3, column=0)
def multiplication():
try:
a = int(ent1.get())
b = int(ent2.get())
except ValueError:
result = Label(root, text="You can only enter numbers")
result.grid(row = 3, column=0)
result = Label(root, text="result = "+str(a*b))
result.place(row=3, column=0)
def division():
try:
a = int(ent1.get())
b = int(ent2.get())
except ValueError:
result = Label(root, text="You can only enter numbers")
result.grid(row = 3, column=0)
try:
result = Label(root, text="result = "+str(a/b))
except ZeroDivisionError:
result = Label(root, text="Denominator cannot be zero")
finally:
result.grid(row=3, column=0)
add_btn = Button(root, text="+", command=addition)
add_btn.grid(row=2, column=0)
sub_btn = Button(root, text="-", command=subtraction)
sub_btn.grid(row=2, column=1)
mul_btn = Button(root, text="x", command=multiplication)
mul_btn.grid(row=2, column=2)
div_btn = Button(root, text="/", command=division)
div_btn.grid(row=2, column=3)
root.mainloop()
| true |
ef7d0c54dc9174d00c56671a8f7f9980ada3863c | mariaVela790/PythonPractice | /ex5.py | 1,362 | 4.84375 | 5 | #In this program we will be learning about formatting strings
#to format we put an f in front of the string and insert variables
#using curly braces {} one example is the following:
# f"Here is a string with the number {5}"
message = f"Here is a string with the number {5}"
my_name = 'Zed A. Shaw'
my_age = 35 #not a lie
my_height = 74 #inches
my_weight = 180 #lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
rate_for_in_to_cm = 2.54
rate_for_lbs_to_kg = round(.45)
print(rate_for_lbs_to_kg)
print(message)
print(f"Let's talk about {my_name}") #Let's talk about Zed A. Shaw
print(f"He's {my_height} inches tall") #He's 74 inches tall
print(f"He's {my_height * rate_for_in_to_cm} centimeters tall") #He's {converted amount} inches tall
print(f"He's {my_weight} pounds heavy.") #He's 180 pounds heavy
print(f"He's {my_weight * rate_for_lbs_to_kg} kg heavy.") #He's 180 pounds heavy
print("Actually that's not too heavy.") #Actually that's not too heavy
print(f"He's got {my_eyes} eyes and {my_hair} hair.") #He's got Blue eyes and Brown hair
print(f"His teeth are usually {my_teeth} depending on the coffee.") #His teeth are usually White depending on the coffee
#This line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
#If I add 35, 74, and 180 I get 289 | true |
1cdcdd39c64d46a08367e4a693cc53d0bfa840c9 | saraalrumih/100DaysOfCode | /day 030.py | 329 | 4.21875 | 4 | # for loop 2
# print odd numbers between 1 to 10
for i in range(1,10,2):
print(i)
else:
print("These are the odd numbers between 1 to 10.\n\n")
# nested for loops
mothers =("Sara","Jana","Renad")
daughters =("Mai","Fai","Nora")
for mom in mothers:
for girl in daughters:
print(mom," is ",girl,"'s mother.")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.