blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8b2aadc3171527ad7c2880ee3d5167cd0542ba85 | edu-athensoft/ceit4101python | /stem1400_modules/module_4_function/func1_define/function_3.py | 392 | 4.15625 | 4 | """
function
- without returned value
- with returned value
"""
def showmenu():
print("egg")
print("chicken")
print("fries")
print("coke")
print("dessert")
return "OK"
# call it and lost returned value
showmenu()
print()
print(showmenu())
print()
# call it and keep returned value
isdone = showmenu()
print(isdone)
print(isdone+" -2nd")
print(isdone+" -3rd")
| true |
7a13ea84858a0824e09630477fe3861eb26571ae | edu-athensoft/ceit4101python | /stem1400_modules/module_12_oop/oop_06_instance/s5_add_attribute/instance_attribute_2.py | 593 | 4.46875 | 4 | """
Adding attributes to an object
"""
# defining a class
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
# self.color does not exist.
def sleep(self):
print('sleep() is called')
def eat(self):
print('eat() is called')
# def antimethod(self):
# pass
# main program
tom = Cat("Tom",1)
# print(tom.color)
# AttributeError: 'Cat' object has no attribute 'color'
tom.color = "Orange"
print(tom.color)
peter = Cat("Peter",1)
print(peter.color)
# AttributeError: 'Cat' object has no attribute 'color' | true |
420933e86e4ecad7a1108f09fcbf2531af0ee7df | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_func_03_len.py | 1,458 | 4.125 | 4 | # len()
# How len() works with tuples, lists and range?
testList = []
print(testList, 'length is', len(testList))
testList = [1, 2, 3]
print(testList, 'length is', len(testList))
testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))
testRange = range(1, 10)
print('Length of', testRange, 'is', len(testRange))
# How len() works with strings and bytes?
testString = ''
print('Length of', testString, 'is', len(testString))
testString = 'Python'
print('Length of', testString, 'is', len(testString))
# byte object
testByte = b'Python'
print('Length of', testByte, 'is', len(testByte))
testList = [1, 2, 3]
# converting to bytes object
testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte))
# How len() works with dictionaries and sets?
testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))
# Empty Set
testSet = set()
print(testSet, 'length is', len(testSet))
testDict = {1: 'one', 2: 'two'}
print(testDict, 'length is', len(testDict))
testDict = {}
print(testDict, 'length is', len(testDict))
testSet = {1, 2}
# frozenSet
frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))
# How len() works for custom objects?
# skip
class Session:
def __init__(self, number=0):
self.number = number
def __len__(self):
return self.number
# default length is 0
s1 = Session()
print(len(s1))
# giving custom length
s2 = Session(6)
print(len(s2))
| true |
abf7b2cfe1d7d7c171855ca4dad7e57f6fd6943d | edu-athensoft/ceit4101python | /evaluate/evaluate_3_project/python1_beginner/guessing_number/guessing_number_v1.py | 1,689 | 4.25 | 4 | """
Guessing number version 1.0
problems:
1. how to generate a random number/integer within a given range
2. how to validate the number and make it within your upper and lower bound
3. comparing your current number with the answer
case #1: too small
case #2: too big
case #3: bingo
4. max 5 times
failed for 5 times -> get "???"
won within 5 times -> get "???"
5. difficulty problem
fixed difficulty (version 1.0)
adjustable difficulty (version 1.1)
6. the number of turns you may play (version 2)
"""
import random
def generate_answer():
answer = random.randrange(1,101)
return answer
def set_difficulty():
chances = 5
return chances
def get_valid_number():
x = None
while True:
myinput = input("enter a number (1-100):")
# validate myinput
if myinput.isdigit():
x = int(myinput)
if x > 100 or x < 1:
print("Warning: Please input a valid number!")
else:
# print("Your input is {}".format(x))
break
else:
print("Warning: Please input a valid number!")
return x
def compare(x, answer):
flag = False
if x > answer:
print("Too big")
elif x < answer:
print("Too small")
else:
print("bingo")
flag = True
return flag
# main program, main logic
answer = generate_answer()
print("answer =", answer)
chances = set_difficulty()
for i in range(chances):
x = get_valid_number()
if compare(x, answer):
break
else:
print("You have {} chances left".format(chances - i - 1))
print()
| true |
5378ef0faa41bacd228ee02bc616d4fc74fd8bfb | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_func_04_sorted.py | 1,380 | 4.375 | 4 | # sorted()
# sorted(iterable[, key][, reverse])
# sorted() Parameters
# sorted() takes two three parameters:
#
# iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator
# reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order)
# key (Optional) - function that serves as a key for the sort comparison
# Return value from sorted()
# sorted() method returns a sorted list from the given iterable.
# Sort a given sequence: string, list and tuple
# vowels list
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList))
# string
pyString = 'Python'
print(sorted(pyString))
# vowels tuple
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))
# Sort a given collection in descending order: set, dictionary and frozen set
# set
pySet = {'e', 'a', 'u', 'o', 'i'}
print(sorted(pySet, reverse=True))
# dictionary
pyDict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print(sorted(pyDict, reverse=True))
# frozen set
pyFSet = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(pyFSet, reverse=True))
# Sort the list using sorted() having a key function
# take second element for sort
def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
sortedList = sorted(random, key=takeSecond)
# print list
print('Sorted list:', sortedList) | true |
4fbf6cc6d51892c9a80e5d4266be5ad184d5ff30 | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_7_array/array_3_search.py | 571 | 4.21875 | 4 | """
Searching element in a Array
"""
import array
# initializing array with array values
# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])
# printing original array
print("The new created array is : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
# using index() to print index of 1st occurrence of 2
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
# using index() to print index of 1st occurrence of 1
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))
| true |
c1fe6f37a7e4522a78a2e1d2922bdb6102636941 | edu-athensoft/ceit4101python | /stem1400_modules/module_10_gui/s04_widgets/s0401_label/label_7_justify.py | 1,117 | 4.1875 | 4 | """
Tkinter
place a label widget
justify=left|center(default)|right
"""
from tkinter import *
root = Tk()
root.title('Python GUI - Label justify')
root.geometry("{}x{}+200+240".format(640, 480))
root.configure(bg='#ddddff')
# create a label widget
label1 = Label(root, text='Tkinter Label 1',
height=3, width=28,
font = "Helnetic 20 bold italic",
bg='#72EFAA', fg='black',
wraplength=180,
justify='right')
# show on screen
label1.pack()
# create a label widget
label2 = Label(root, text='Tkinter Label 2',
height=3, width=28,
font = "Helnetic 20 bold italic",
bg='#EF72AA', fg='black',
wraplength=180,
justify='left')
# show on screen
label2.pack()
# create a label widget
label3 = Label(root, text='Tkinter Label 3',
height=3, width=28,
font = "Helnetic 20 bold italic",
bg='#EFAA72', fg='black',
wraplength=180,
justify='center')
# show on screen
label3.pack()
root.mainloop() | true |
845282c41034ea8dd5595f6d9f41bc9dff50bfee | edu-athensoft/ceit4101python | /stem1400_modules/module_9_datetime/s93_strptime/s3_strptime/datetime_17_strptime.py | 420 | 4.1875 | 4 | """
datetime module
Python format datetime
Python has strftime() and strptime() methods to handle this.
The strptime() method creates a datetime object
from a given string (representing date and time)
"""
from datetime import datetime
date_string = "21 June, 2018"
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object, type(date_object))
| true |
7b97eec2bef56c7cdfc4577d5838ba2d7c1cd4b3 | edu-athensoft/ceit4101python | /stem1471_projects/p00_file_csv_processor_2/csv_append_row.py | 824 | 4.25 | 4 | """
csv processor
append a row
In this example, we first define the data that we want to
append to the CSV file, which is a list of values representing
a new row of data.
We then open the CSV file in append mode by specifying 'a'
as the file mode. This allows us to append data to the end of
the file rather than overwriting the entire file.
Finally, we use the csv.writer object to write the new row of
data to the CSV file using the writerow() method.
Note that we also specify newline='' when opening the file to
ensure that the correct line endings are used on all platforms.
"""
import csv
# data to append to CSV file
new_row = [6, 'Cathy', 'Saint Luc', 'G8']
# open CSV file in append mode
with open('data/output.csv', mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow(new_row)
| true |
7708fabec7e64fa51646e485729c1384f5283b63 | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_4_string/string_2_accessing.py | 425 | 4.375 | 4 | """
string - accessing char
"""
str1 = 'athensoft inc'
print('str = ', str1)
# accessing char in a string by index
# first character
print('str[0] = ', str1[0])
# last character
print('str[-1] = ', str1[-1])
# slicing - substring
# slicing 2nd to 5th character
print('str[1:5] = ', str1[1:5])
# slicing 6th to 2nd last character
print('str[5:-2] = ', str1[5:-2])
print('str[5:4] = ', str1[5:4]) # empty string
| false |
dfd2d8cedd22ab7f2bbba00f7013e3df8eb6bdd6 | edu-athensoft/ceit4101python | /evaluate/evaluate_1_exercise/m6_dictionary/ex_add_key_1.py | 279 | 4.15625 | 4 | """
module 6. datatype
chapter 6-6. dictionary
Question:
3. Write a program to add a key to a dictionary
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
Hints:
"""
mydict = {'a': 10, 'b': 20}
print(mydict)
mydict['c'] = 30
print(mydict)
| false |
9ba6f0b0303c1287bfc28a289e4afe878b85cd34 | edu-athensoft/ceit4101python | /stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo1_super_single/super_init_2c.py | 736 | 4.375 | 4 | """
super and init
child overrides init() of parent and use its own init()
child has its own property: age
parent has a property: name
child cannot inherit parent's property due to overriding,
properties defined in parent do not take effect to child.
"""
class Parent:
def __init__(self, name):
print('Parent __init__() called.')
self.name = name
class Child(Parent):
def __init__(self, age):
print('Child __init__() called.')
self.age = age
# main
# c1 = Child()
# TypeError: __init__() missing 1 required positional argument: 'age'
c1 = Child(16)
print(c1.age)
# print(c1.name)
# AttributeError: 'Child' object has no attribute 'name'
# there is no such attribute defined in Child
| true |
ba671e89c9244cd5969667d0f9aca6bec71a825d | edu-athensoft/ceit4101python | /stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo1_super_single/super_init_2e.py | 672 | 4.21875 | 4 | """
super and init
child overrides init() of parent and use its own init()
child has its own property: age
parent has a property: name
child inherit parent's property by super(),
child init() must accept all parameters
the order of parameter matters
"""
class Parent:
def __init__(self, name):
print('Parent __init__() called.')
self.name = name
class Child2(Parent):
def __init__(self, age, name):
print('Child __init__() called.')
self.age = age
super().__init__(name)
# main
# order of arguments do not match that of the declared parameters
c2 = Child2('Jack', 18)
print('age:',c2.age)
print('name:',c2.name)
| true |
aaba8ca8136fbb564b3c3a6869e57ec0be0b0fbf | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_1_capitalize.py | 761 | 4.46875 | 4 | """
string method - capitalize()
string.capitalize()
return a new string
"""
# case 1. capitalize a sentence
str1 = "pyThOn is AWesome."
result = str1.capitalize()
print(f"old string: {str1}")
print(f"new string: {result}")
print()
# case 2. capitalize two sentence
str1 = "pyThOn is AWesome. pyThOn is AWesome."
result = str1.capitalize()
print(f"old string: {str1}")
print(f"new string: {result}")
print()
# case 3. non-alphabetic first character
str1 = "+ pyThOn is AWesome."
result = str1.capitalize()
print(f"old string: {str1}")
print(f"new string: {result}")
print()
# case 4. whitespace as the first character
str1 = " pyThOn is AWesome."
result = str1.capitalize()
print(f"old string: {str1}")
print(f"new string: {result}")
print()
| true |
e8beb53f159933978745cec0d453798992e3c514 | edu-athensoft/ceit4101python | /stem1400_modules/module_12_oop/oop_11_classmember/s01_class_attribute/demo_4_add_property.py | 482 | 4.25 | 4 | """
adding properties by assignment
"""
class Tool:
count = 0
def __init__(self, name):
self.name = name
Tool.count += 1
# test
tool1 = Tool("hammer")
print(f'{tool1.count} tool(s) is(are) created.')
print()
tool1.count = 99
print(f'The instance tool1 has extra property: count')
print(f'{tool1.count} tools are created.')
print()
print(f'Now instance property has nothing to do with class property: count')
print(f'{Tool.count} tools are created.')
| true |
c958faae61b8d8a3f1a85cba789bbf87d87a1388 | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_7_array/array_2_add_2.py | 347 | 4.34375 | 4 | """
Python array
Adding Elements to a Array
append()
extend()
source:
"""
import array as arr
numbers = arr.array('i', [1, 2, 3])
numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])
# extend() appends iterable to the end of the array
numbers.extend([5, 6, 7])
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])
| true |
4a5ca15f00ebf97484032636a9bf7a10458bc914 | edu-athensoft/ceit4101python | /stem1400_modules/module_10_gui/s04_widgets/s0401_label/label_1_create.py | 342 | 4.3125 | 4 | """
Tkinter
place a label widget
Label(parent_object, options,...)
using pack() layout
ref: #1
"""
from tkinter import *
root = Tk()
root.title('Python GUI - Text Label')
root.geometry("{}x{}+200+240".format(640, 480))
# create a label widget
label1 = Label(root, text='Tkinter Label')
# show on screen
label1.pack()
root.mainloop()
| true |
c62f384b9f938f4ff0fcc96d8aec20ac81af479e | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_7_array/array_2_add.py | 725 | 4.21875 | 4 | """
Python array
Adding Elements to a Array
typecodes = 'bBuhHiIlLqQfd'
souce: https://www.geeksforgeeks.org/python-arrays/
"""
import array as arr
a = arr.array('i', [1, 2, 3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
# inserting array using
# insert() function
a.insert(1, 4)
print("Array after insertion : ", end=" ")
for i in a:
print(i, end=" ")
print()
# array with float type
b = arr.array('d', [2.5, 3.2, 3.3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
print()
# adding an element using append()
b.append(4.4)
print("Array after insertion : ", end=" ")
for i in b:
print(i, end=" ")
print()
| false |
13f90032c463121cc3494f8d168ae637ca43ebbb | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_11_isdecimal.py | 558 | 4.3125 | 4 | """
string method - isdecimal()
True - if all characters in the string are decimal characters.
False - if at least one character is not decimal character.
"""
str1 = "1234556"
print(str1.isdecimal())
str1 = "-1234556"
print(str1.isdecimal())
str1 = "123.4556"
print(str1.isdecimal())
str1 = "123abc"
print(str1.isdecimal())
str1 = "123,333"
print(str1.isdecimal())
str1 = "1233,33"
print(str1.isdecimal())
print()
str1 = "0123"
print(str1.isdecimal())
str1 = "000000"
print(str1.isdecimal())
str2 = '2\u00B2123'
print(str2)
print(str2.isdecimal())
| false |
efa832f38aeb306d6c721ba97ab39cc0746ff6c2 | edu-athensoft/ceit4101python | /stem1400_modules/module_3_flowcontrol/c2_for/forloop_5_nested.py | 946 | 4.25 | 4 | # print out a matrix
"""
out put like
11,12,13
21,22,23
31,32,33
(11,12,13)
(21,22,23)
(31,32,33)
matrix = ((11,12,13),(21,22,23),(31,32,33))
loop for each row
round 0: (11,12,13) -> row 0 -> matrix[0]
Loop for each column
round 0: 11 -> matrix[0][0]
round 1: 12 -> matrix[0][1]
round 2: 13 -> matrix[0][2]
round 1: (21,22,23) -> row 1 -> matrix[1]
Loop for each column
round 0: 21 -> matrix[1][0]
round 1: 22 -> matrix[1][1]
round 2: 23 -> matrix[1][2]
round 2: (31,32,33) -> row 2 -> matrix[2]
Loop for each column
round 0: 31 -> matrix[2][0]
round 1: 32 -> matrix[2][1]
round 2: 33 -> matrix[2][2]
"""
matrix = ((11,12,13),(21,22,23),(31,32,33))
for row in matrix:
# print(row)
for col in row:
print(col, end="\t")
print()
| false |
4543ea3f1dc6e723d7dfc265b3fe856dc787f186 | edu-athensoft/ceit4101python | /stem1400_modules/module_14_regex/s3_re/regex_9_search.py | 266 | 4.1875 | 4 | """
regex
"""
import re
mystr = "Python is fun"
pattern = r'\APython'
# check if 'Python' is at the beginning
match = re.search(pattern, mystr)
print(match, type(match))
if match:
print("pattern found inside the string")
else:
print("pattern not found")
| true |
0d3f250ba8d881ab75e3f043e905ec3425424496 | edu-athensoft/ceit4101python | /evaluate/evaluate_2_quiz/stem1401_python1/quiz313/q6.py | 1,290 | 4.4375 | 4 | """
Quiz 313
q6
A computer game company is developing a 3A-level role-playing game.
The character you are controlling will receive equipment items of
different tiers while adventuring in the big world. The system will
display different background and text colors according to the level
of the item to distinguish them. If the item is of the first tier,
the system uses gray; if the item is of the second tier, the system
uses green; if the item is of the tier level, the system uses blue;
if the item is of the fourth tier, the system uses purple; if the item
is of the fifth tier, the system uses gold(en).
Please write a program to determine what color should be used to
display the background and text of an item based on its tier when
you pick up an item and know its tier number.
Hint: Please save your code in the file naming as stem1401_quiz313_q6_yourname.py
"""
# tier numbers = 1, 2, 3, 4, 5
tier_num = int(input("Input a number of tier: "))
color = None
if tier_num == 1:
color = "gray"
elif tier_num == 2:
color = "green"
elif tier_num == 3:
color = "blue"
elif tier_num == 4:
color = "purple"
elif tier_num == 5:
color = "golden"
else:
print("Invalid input.")
if color:
print(f"The right color of tier number {tier_num} should be {color}.")
| true |
92d6114c1a38dc82151a67729905a625ef3f18ff | Mart1nDimtrov/Math-Adventures-with-Python | /01. Drawing Polygons with the Turtle Module/triangle.py | 373 | 4.53125 | 5 | # exerCise 1-3: tri anD tri again
# Write a triangle()
# function that will draw a triangle of a given “side length.”
from turtle import *
# encapsulate with a function
def triangle(sidelength=100):
# use a for loop
for i in range(3):
forward(sidelength)
right(120)
# set speed and shape
shape('turtle')
speed(0)
# create a square
triangle()
| true |
e8b911a5f1a2d7b8569d3636cc5bcc2b1d5382a1 | BH909303/py4e | /ex6_1.py | 490 | 4.1875 | 4 | '''
py4e, Chapter 6, Exercise 1: Write a while loop that starts at the last
character in the string and works its way backwards to the first character in
the string, printing each letter on a separate line, except backwards.
William Kerley, 21.02.20
'''
fruit = 'banana'
index = len(fruit)-1 #set index to last letter of string
while index >= 0: #print letters of words from last to first
letter = fruit[index]
print(letter)
index = index - 1
| true |
ceedc4cf9059a26d9544f553148abac5a5d39d2a | AccentsAMillion/Python | /Ten Real World Applications/Python Basics/Functions and Conditionals/PrintReturnFunction.py | 396 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 30 09:28:25 2020
@author: Chris
"""
#To create functions in python it starts with def function():
# Division (/) Function calculating the sum of myList taking in 3 parameters
def mean(myList):
print("Function mean started!")
the_mean = sum(myList) / len(myList)
return the_mean
myMean = mean([0 ,3 ,4])
print (myMean + 10)
print
| true |
cb12aca17df00ff174aa59c48f720b77c23e9026 | andrei-chirilov/ICS3U-assignment-05b-Python | /reverse.py | 406 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by: Andrei Chirilov
# Created on: November 2019
# This program reverses a digit
import math
def main():
number = int(input("Enter a number: "))
result = ""
if number == 0:
print(0)
exit(0)
while number != 0:
result += str(number % 10)
number = math.floor(number / 10)
print(result)
if __name__ == "__main__":
main()
| true |
9ca29631af7bc11b2128efe122862904346a05ec | oscarmrt/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 241 | 4.28125 | 4 | #!/usr/bin/python3
def uppercase(str):
for characters in str:
if ord(characters) >= 97 and ord(characters) <= 122:
characters = chr(ord(characters) - 32)
print('{:s}'.format(characters), end='')
print('')
| true |
181a7912a6a44a3887ee28c1a1af3276c9ca1609 | learsixela/logicaDiurno | /Funciones.py | 1,913 | 4.21875 | 4 |
#funcion
def funcionSaludo():
mensaje()
print("Esta es un mensaje desde otra funcion")
def mensaje():
print("mensaje")
print("mensaje2")
print("mensaje3")
print("***********")
#llamado a la funcion
#mensaje()
#funcionSaludo()
#mensaje()
def funcionSuma():
numero3 = 3
numero4 = 4
print("Resultado de la suma",numero1+numero2)
print("Resultado de la 2 suma", numero3 + numero4)
numero1 = int(input("Ingrese numero 1 "))
numero2 = int(input("Ingrese numero 2 "))
print(numero1+ numero2)
funcionSuma()
#definiendo un funcion que recibe parametros
def resta(num1, num2):
print("el resultado de la resta es :", num1-num2)
#llamar a la funcion con parametros
resta(numero1,numero2)
resta(8,4)
resta(numero2,numero2)
print("****** multiplicacion ******")
#funcion sin parametros
def multiplicacion():
print("Resultado de la multiplicacion es: ", numero1*numero2)
multiplicacion()
#sobre carga de un metodo o funcion
def multiplicacion(var1,var2):
print("Resultado de la multiplicacion 2 es: ", var1 * var2)
multiplicacion(numero2,numero1)
print("****** division ******")
def division(dividendo, divisor):
if divisor ==0 :
print("Error, no se puede dividir por cero")
else:
print("Resultado de la division es :", dividendo/divisor)
division(numero1,numero2)
print("****** funciones con retorno ******")
# funciones que retornan un valor
def funcionRetorno():
return "17"
valorRespuesta = funcionRetorno()
print(" el valor de retorno es: ",valorRespuesta)
print("llamado directo ",funcionRetorno())
if(funcionRetorno() ==1):
print("recibi un uno")
# solicitar al usuario el ingreso de 2 numeros
# crear funcion que valide:
# si el primer numero es mayor que el segundo, retornar un 1
# si el segundo es mayor que el primero, retornar un -1
# si son iguales retornar un cero
#imprimir el resultado
#utilizar funciones
| false |
37614a1f4ece39402e14fd4c73725151f8968339 | learsixela/logicaDiurno | /20201013_arreglos3.py | 1,321 | 4.15625 | 4 | #key, o palabra clave
#Diccionarios
numeros = {
"uno": 1,
"doscientos":200,
"gato":1234,
}
print(numeros["uno"])
print(numeros["doscientos"])
print(numeros["gato"])
print()
#agregar contenido a numeros
#crear variable para diccionario numeros
print(numeros)
numeros["cuatro"] = 4
print(numeros["cuatro"])
print(numeros)
#tamaño del diccionario
print(len(numeros))
numeros["cuatro"] = 5
print(numeros)
#si no existe y consultamos =>error (impresion)
#si no existe lo crea, asignacion
#si existe lo reemplaza
#matriz de diccionarios
matriz =[
[{"uno":"casa","dos":2},{"tres":3,"cuatro":4}],#0
#[a,b,c,d] #1, a=>{key:valor,key:valor}; b=>{key:valor,key:valor}
#[] #2,
#[] #3,
#[] #4,
]
print()
print(matriz)
print(matriz[0])#[{"uno":1,"dos":2},{"tres":3,"cuatro":4}]
print(matriz[0][0])#{'uno': 1, 'dos': 2}
print(matriz[0][0]["uno"])#casa
#matriz de diccionarios con :
# 5 arreglos internos
# cada arreglo debe tener 4 elementos
# cada elemento debe tener 2 key
#como imprimir con for de for
matriz2=[
[{"nombre":"israel"},{"apellido":"palma"},{"edad":40}],
[{"nombre":"Juan"},{"apellido":"Perez"},{"edad":30}],
[{"nombre":"Juan2"},{"apellido":"Perez2"},{"edad":20}],
[{"nombre":"Juan3"},{"apellido":"Perez3"},{"edad":25}],
]
## israel palma 40
## juan perez 30
| false |
d03cc6651d511fefa6af2adea4aa722df253f99d | gauthamikuravi/Python_challenges | /Leetcode/shift_zeros.py | 1,106 | 4.21875 | 4 |
#######################################################
#Write a program to do the following:Given an array of random numbers, push all the zeros of a given array to the start of the array.
# The order of all other elements should be same.
#Example
#1: Input: {1, 2, 0, 4, 3, 0, 5, 0}
#Output: {0, 0, 0, 1, 2, 4, 3, 5}
#Example
#2:Input: {1, 2, 0, 0, 0, -1, 6}
#Output: {0, 0, 0, 1, 2, -1, 6}
#Example
#3:Input: {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}
#Output: {0, 0, 0, 0, 1, 9, 8, 4, 2, 7, 6}
###########################################
# ran the loop through reverse order
# swap the elements in the same position until the first zero element was found
class Solution:
def shiftposition(self, nums):
pos = len(nums) - 1
for i in reversed(range(len(nums))):
el = nums[i]
if el != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos -= 1
return (nums)
if __name__ == '__main__':
array = [1, 2, 0, 0, 0, -1, 6]
sol = Solution()
a = sol.shiftposition(array)
print(a)
| true |
53a16f0432aa40c042ddb70f4bfc0b09a97227dc | sk1z0phr3n1k/Projects | /python projects/mbox.py | 1,483 | 4.15625 | 4 | # Author: Mark Griffiths
# Course: CSC 121
# Assignment: Lab: Lists (Part 2)
# Description: mbox module
# The mbox format is a standards-based email file format
# where many emails are put in a single file
def get_mbox_username(line):
"""
Get mbox email username
Parse username from the start of an email
Parameters:
line (str): line starting a new email in mbox format
Returns: (str) email username
"""
words=line.split()
email=words[1]
# use the double split strategy
pieces = email.split('@')
return(pieces[0])
def get_mbox_domain(line):
"""
Get mbox email domain
Parse domain from a new email in mbox format
Parameters:
line (str): line starting a new email in mbox format
Returns: (str) email internet domain
"""
words=line.split()
email=words[1]
# double split strategy
pieces = email.split('@')
return(pieces[1])
def get_mbox_day(line):
"""
Get mbox email day of the week
Parse the day of the week an email was sent from the start of an email
Parameters:
line (str): line starting a new email in mbox format
Returns: (str) day of the week abbreviation
"""
words=line.split()
return(words[2])
def get_mbox_minute(line):
"""
Get mbox email minute
Parse the minute an email was sent from the start of an email
Parameters:
line (str): line starting a new email in mbox format
Returns: (str) minute
"""
words=line.split()
time=words[5]
# double split strategy
pieces = time.split(':')
return(pieces[1])
| true |
320fba2a5627ea67e99b54abfae6315115e5c74b | Jamieleb/python | /challenges/prime_checker.py | 685 | 4.34375 | 4 | import math
def is_prime(num):
'''
Checks if the number given as an argument is prime.
'''
#first checks that the number is not even, 1 or 0 (or negative).
if num < 2 or num > 2 and not num % 2:
return False
#checks if all odd numbers up to the sqrt of num are a factor of num
for x in range(3, int(math.sqrt(num))+1, 2):
if not num % x:
return False
else:
return True #if no numbers are a factor, returns True (that the number is prime)
def prime_counter(num):
'''
Function returns the number of primes that exist in the range up to and including the given number.
'''
count = 0
for i in range(0,num+1):
if is_prime(i):
count += 1
return count
| true |
80ae08b7bf04d23b557a34f0dcd409c04b7e942a | 2ptO/code-garage | /icake/q26.py | 541 | 4.59375 | 5 | # Write a function to reverse a string in-place
# Python strings are immutable. So convert string
# into list of characters and join them back after
# reversing.
def reverse_text(text):
"""
Reverse a string in place
"""
if not text:
raise ValueError("Text is empty or None")
start = 0
end = len(text) - 1
chars = list(text)
while start <= end:
t = chars[start]
chars[start] = chars[end]
chars[end] = t
start += 1
end -= 1
return "".join(chars) | true |
908b37ef23e23156396a33582721faa92f816ddc | Akshaypokley/PYCHAMP | /src/SetConcepts.py | 2,816 | 4.25 | 4 | """Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets."""
setex={'java','python',True,False,45,2.3}
print(setex)
"""Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword."""
for x in setex:
print(x)
#if we want to check
print("java" in setex)
"""Change Items
Once a set is created, you cannot change its items, but you can add new items.
"""
"""Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method."""
setex.add("AKSHAY")
setex.update(["JAVA45",897,65.3])
print(setex)
#length of set
print(len(setex))
# @We can remove item from set using remove and descard method
setex.remove('AKSHAY')
setex.discard(2.3)
print(setex)
#Remove the last item by using the pop() method:
setex.pop()
print(setex)
#The clear() method empties the set:
#The del keyword will delete the set completely:
"""Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:"""
setex.clear()
print(setex)
#del setex
#print(setex)
set1={3.3,15,45,True,False,'Akshay'}
set2={'Java', 'Pokley',True}
set3=set1.union(set2)
print(set3)
set1.update(set2)
print(set1)
#It also make as constructor
set23=set((47,87,'ajksh'))
print(set23)
print(set2.symmetric_difference(set23))
"""Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others""" | true |
84d13c65e3b036f0887da9a009a67d65385b17e0 | aadroher/pingpong | /pingpong/models/calendar.py | 1,089 | 4.125 | 4 |
from datetime import datetime
"""
Este módulo representa el calendario general para la
aplicación. Puesto que es único y no hay que guardar
ninguna información sobre el mismo, se representa de
esta forma y no mediante una clase.
"""
def current_year():
"""
:return: El año en el que nos encontramos.
"""
return datetime.now().year
def current_week():
"""
:return: La representación numérica de la
semana del año en el que nos encontramos.
"""
week_num = datetime.now().strftime("%W")
return int(week_num)
def date_from_nums(year, week, week_day):
"""
Genera un objeto datetime.date a partir de los
siguientes parámetros numéricos.
:param year: El año de la fecha.
:param week: La semana del año.
:param week_day: El día de la semana.
:return:
"""
date_str = "{year} {week} {week_day}".format(year=year,
week=week,
week_day=week_day)
return datetime.strptime(date_str, "%Y %W %w").date()
| false |
b7c9deb2e1fd40b3b79343e8afd5f1978ffcb0ae | ayoblvck/Startng-Backend | /Python task 1.py | 225 | 4.5625 | 5 | # a Python program to find the Area of a Circle using its radius
import math
radius = float(input('Please enter the radius of the circle: '))
area = math.pi * radius * radius
print ("Area of the circle is:%.2f= " %area)
| true |
b6dd55f61795983858f76cbd06978865722c9850 | isolis1210/HW2-Python | /calculator.py | 1,487 | 4.5 | 4 | def calculator():
#These lines take inputed values from the user and store them in variables
number_1 = float(float(input('Please enter the first number: ')))
number_2 = float(float(input('Please enter the second number: ')))
operation = input('Please type in the math operation you would like to complete:+,-,*,/,//,** ')
#These conditional statements apply the desired math function
if operation == "+":
print(number_1 + number_2)
elif operation == '-':
print(number_1 - number_2)
elif operation == '*':
print(number_1 * number_2)
elif operation == '/':
print(number_1 / number_2)
elif operation == '//':
print(number_1 // number_2)
elif operation == '**':
print(number_1 ** number_2)
else:
print('FALSE')
#If the input for an operation is invalid, this message will appear
print('You have not typed a valid operator, please run the program again.')
input_output()
'''The calculator function takes two numbers and the desired math operation to calculate a solution'''
def input_output():
calc_again = input('Do you wish to exit? Please type Y for YES or N for NO. ')
if calc_again.upper() == 'N':
calculator()
elif calc_again.upper() == 'Y':
print('See you later.')
else:
input_output()
calculator()
''' This function asks if the user wants to calculate another expression, if so it calls on the calculator function'''
| true |
32a429bae97a0678517dff15dbce80bbd25ee46a | NSNCareers/DataScience | /Dir_OOP/classVariables.py | 1,374 | 4.3125 | 4 |
# Class variables are those shared by all instances of a class
class Employee:
raise_amount = 10.04
gmail = '@gmail.com'
yahoo = '@yahoo.com'
num_of_employees = 0
def __init__( self, fistName, lastName, gender, pay):
self.first = fistName
self.last = lastName
self.gender = gender
self.p = pay
self.email = fistName + '.' + lastName + self.gmail
Employee.num_of_employees += 1
def apply_raise(self):
self.p = int(self.p + self.raise_amount)
return self.p
# print(Employee.num_of_employees)
emp_1 = Employee('James','Hunter','Male',100000)
emp_2 = Employee('Luvas','Gasper','Female',300000)
print(emp_1.p)
print(emp_1.apply_raise())
print(emp_2.email)
# Shows you the class attributes and instance attributes
print(Employee.__dict__) # This prints out the name space of Employee
print(emp_1.__dict__) # This prints out the name space of emp_1
print(emp_2.__dict__) # This prints out the name space of emp_2
# change class variable using class instance empl_1
emp_1.raise_amount = 30
# change class variable using class its self
Employee.raise_amount = 20
print(emp_1.raise_amount)
print(Employee.raise_amount)
print(emp_1.__dict__) # This prints out the name space of emp_1
print(emp_2.__dict__) # This prints out the name space of emp_2
#print(Employee.num_of_employees)
| true |
e69539f58ab8f159c826d552d852c08cd79a022f | Developirv/PythonLab1 | /exercise-5.py | 512 | 4.25 | 4 | # DELIVERABLE LAB 03/05/2019 5/6
# exercise-05 Fibonacci sequence for first 50 terms
# Write the code that:
# 1. Calculates and prints the first 50 terms of the fibonacci sequence.
f = 1
current = 1
former = 0
for term in range (50):
if term == 0:
print(f"term: {term} / number: 0")
elif term == 1:
print(f"term: {term} / number: 1")
else:
f = current + former
print(f"term: {term} / number: {f}")
former = current
current = f
# 2. Print each term and number as follows:
# ^^ | true |
91bcd6886a825494f0013eb115ee3f8ac5871ec8 | LialinMaxim/Toweya | /league_table.py | 2,866 | 4.21875 | 4 | """
The LeagueTable class tracks the score of each player in a league.
After each game, the player records their score with the record_result function.
The player's rank in the league is calculated using the following logic:
* The player with the highest score is ranked first (rank 1). The player with the lowest score is ranked last.
* If two players are tied on score, then the player who has played the fewest games is ranked higher.
* If two players are tied on score and number of games played,
then the player who was first in the list of players is ranked higher.
Implement the player_rank function that returns the player at the given rank.
For example:
table = LeagueTable(['Mike', 'Chris', 'Arnold'])
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
print(table.player_rank(1))
All players have the same score.
However, Arnold and Chris have played fewer games than Mike, and as Chris is before Arnold in the list of players,
he is ranked first. Therefore, the code above should display "Chris".
"""
class LeagueTable:
__empty_player = {'scores': 0, 'games': 0, 'last_game': None}
__last_game = 0
def __init__(self, players: list):
self.players = {p: dict(LeagueTable.__empty_player) for p in players} # dict() need to make a new objs
def __srt__(self):
return f'<LeagueTable obj: {self.players}>'
def record_result(self, player: str, score: int):
data_player = self.players.get(player)
if data_player:
data_player['scores'] += score
data_player['games'] += 1
data_player['last_game'] = self.__get_last_game()
def player_rank(self, rank=None):
if rank and (rank > len(self.players) or rank < 0):
return None
ps = self.players
# List of Tuples [(player name, scores, games, game order) ... ]
table_rank = [(p, ps[p]['scores'], ps[p]['games'], ps[p]['last_game']) for p in ps]
table_rank = sorted(table_rank, key=lambda p: (-p[1], p[2], p[3]))
if rank:
return table_rank[rank - 1]
return table_rank
def add_player(self):
pass
@classmethod
def __get_last_game(cls, ):
cls.__last_game += 1
return cls.__last_game
if __name__ == '__main__':
table = LeagueTable(['Mike', 'Chris', 'Arnold', 'Nike', 'Max'])
table.record_result('Max', 2)
table.record_result('Nike', 2)
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
print('The leader:', table.player_rank(1), )
from pprint import pprint
print("\nRating of all players")
pprint(table.player_rank())
print("\nPlayers")
pprint(table.players)
| true |
91e32dc173b88a2cbdb441627633957137064961 | kunaljha5/python_learn_101 | /scripts/pyhton_list_operations_remove_pop_insert_append_sort.py | 1,554 | 4.25 | 4 | # https://www.hackerrank.com/challenges/python-lists/problem
#Consider a list (list = []). You can perform the following commands:
# insert i e: Insert integer at position.
# print: Print the list.
# remove e: Delete the first occurrence of integer.
# append e: Insert integer at the end of the list.
# sort: Sort the list.
# pop: Pop the last element from the list.
# reverse: Reverse the list.
#
#Initialize your list and read in the value of
#followed by lines of commands where each command will be of the type
# INPUT
# 12
# insert 0 5
# insert 1 10
# insert 0 6
# print
# remove 6
# append 9
# append 1
# sort
# print
# pop
# reverse
# prints listed above. Iterate through each command in order and perform the corresponding operation on your list.
# OUTPUT
# [6, 5, 10]
# [1, 5, 9, 10]
# [9, 5, 1]
if __name__ == '__main__':
N = int(input())
klist = []
for _ in range(N):
action =input().split()
# print(action)
if action[0] == "insert":
klist.insert(int(action[1]), int(action[2]))
elif action[0] == "print":
print(klist)
elif action[0] == 'remove':
klist.remove(int(action[1]))
elif action[0] == 'append':
klist.append(int(action[1]))
elif action[0] == 'sort':
klist.sort()
elif action[0] == 'pop':
klist.pop(-1)
#print(klist)
elif action[0] == 'reverse':
klist.reverse()
#print(klist)
else:
print("NA")
| true |
7d180da0bcf7f111d1d306897566ec129cd5ef0e | mebsahle/data-structure-and-algorithms | /sorting-algorithms/pancakeSort.py | 882 | 4.125 | 4 | # Python code of Pancake Sorting Algorithm
def maxNum(arr, size):
num = 0
for index in range(0, size+1):
if arr[index] > arr[num] :
num = index
return num
def flipArr(arr, index):
begin = 0
while begin < index :
temp = arr[begin]
arr[begin] = arr[index]
arr[index] = temp
begin = begin + 1
index = index - 1
def pancakeSort(arr, size):
for index in range(size-1, 0 ,-1):
index1 = maxNum(arr, index)
if index1 != index :
flipArr(arr, index1)
flipArr(arr, index)
def main():
arr = [56, 47, 9, 46, 70, 9, 25, 36]
size = len(arr)
print("Unsorted Array: ", arr)
pancakeSort(arr, size)
print("Sorted Array: ", arr)
if __name__ == "__main__":
main() | true |
0bb65cb9b5d9e6b30d70b2613cc224cb39c24d5e | balanalina/Formal-Languages-and-Compiler-Design | /Scanner/symbol_table/linked_list.py | 1,973 | 4.21875 | 4 | # class for a Node
class Node:
def __init__(self, val=None):
self.val = val # holds the value of the node
self.nextNode = None # holds the next node
# implementation of a singly linked list
class LinkedList:
def __init__(self, head=None):
self.headNode = head
self.size = 0
# inserts a new node at the end of the list, returns the position on which it was inserted
def insert(self, new_node):
# make sure that the new node is not linked to other nodes
new_node.nextNode = None
self.size += 1
if self.headNode is None:
self.headNode = new_node
return 1
else:
index = 1
current_node = self.headNode
while current_node.nextNode is not None:
current_node = current_node.nextNode
index += 1
current_node.nextNode = new_node
return index + 1
# searches for a value in the list and returns its position ( starting from 1), returns 0 if the value wasn't found
def search(self, token):
index = 1
current_node = self.headNode
while current_node is not None:
if current_node.val == token:
return index
else:
current_node = current_node.nextNode
index += 1
return 0
# returns true if the list is empty, false otherwise
def is_empty(self):
if self.headNode is None:
return True
return False
# returns the number of nodes in the list
def get_size(self):
return self.size
# returns the elements of the list as a string
def pretty_print(self):
current_node = self.headNode
list_as_string = ''
while current_node is not None:
list_as_string = list_as_string + str(current_node.val) + " "
current_node = current_node.nextNode
return list_as_string
| true |
b63fd63b6a381fd59a4e1f0eb1fef04bdc7886d7 | HurricaneSKC/Practice | /Ifelseproblem.py | 535 | 4.28125 | 4 | # Basic problem utilising if and elif statements
# Take the users age input and determine what level of education the user should be in
age = int(input("Enter your age: "))
# Handle under 5's
if age < 5:
print("Too young for school")
# If the age is 5 Go to Kindergarten
elif age == 5:
print ("Go to Kindergarten")
# Ages 6 through 17 goes to grades 1 through 12
elif age >= 6 and age<= 17:
print ("go to grade {}".format(age-5))
# If age is greater then 17 say go to college
elif age > 17:
print ("Go to college") | true |
56ff2ec0d608fe22ec4c4a8acf6d0f7789e61f91 | HurricaneSKC/Practice | /FunctionEquation.py | 614 | 4.1875 | 4 | # Problem 10: Create an equation solver, functions
# solve for x
# x + 4 = 9
# x will always be the first value recieved and you will only deal with addition
# Create a function that takes an input equation as a string to solve for x as above example
def string_function(equation):
# separate the function using the split operator
x, add, num1, equals, num2 = equation.split()
# convert the string into integers
num1 = int(num1)
num2 = int(num2)
# solve equation
x = num2 - num1
# return x
return("x = {}" .format(x))
# Run function
print(string_function(input("Input function: ")))
| true |
fc64ae88890dd66365a2ed43daa92b27cd503224 | Ronaldss/Python | /exercicios/operadores-logicos.py | 405 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# Cometários
# Operações matemáticas + - * / ** %
# Variáveis
# Operadores relacionais == != < > <= >=
# OPERADORES LOGICOS and or not
'''
x = 2
y = 3
print(x == y and x > y)
print(x != y or x < y)
'''
# Exemplo com NOT
nome = input('Qual o seu nome: ')
if not nome == 'Ronald':
print('Acesso liberado!')
else:
print("Acesso negado!")
| false |
01128016296190edce2e8c2a203fe2f40dda23c5 | Ronaldss/Python | /exercicios/revisao/string-metodos-geral2-review.py | 881 | 4.4375 | 4 | # Revisao: Strings - métodos mais usado em geral
print('Concatenando strings')
string1 = 'Estou estudando '
string2 = 'a linguagem de programacao Python'
print('Concatenacao: ' + string1 + string2)
print('\n')
print('Contar quantos caracteres existem no texto em questao: ')
texto = 'My name is Ronald.'
tamanho = len(texto)
print('Quantidade de caracteres: ' + str(tamanho))
print('\n')
print('Navengando entre a posicao dos caracteres de uma frase: ')
frase1 = 'Minha terra tem palmeiras onde canta o sabiar'
frase2 = 'As aves que aqui gorgeinha gorjeiam, nao gorjeiam como la...'
print('\n')
print('FRASES COMPLETAS: ')
print('')
print(frase1)
print(frase2)
print('')
print('Selecionando um caracter na frase 1: ' + str(frase1[0]))
print('Selecionando um caracter na frase 2: ' + str(frase2[9]))
print('\n')
print('IMPRIMIR PARTE DE UMA FRASE 1:')
print(frase1[5:11])
| false |
c3bd0685bcceacb2bee2ae1cc40bb24aff0cd71c | benjdj6/Hackerrank | /DataStructures/LinkedList/ReverseDoublyLinkedList.py | 533 | 4.125 | 4 | """
Reverse a doubly linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None, prev_node = None):
self.data = data
self.next = next_node
self.prev = prev_node
return the head node of the updated list
"""
def Reverse(head):
curr = head
while curr:
tmp = curr.prev
curr.prev = curr.next
curr.next = tmp
if not curr.prev:
break
curr = curr.prev
return curr
| true |
d2cb42f27bc8a03906e7f19d28a0bc75467053a3 | Harshad06/Python_programs | /py-programs/args-kwargs.py | 442 | 4.28125 | 4 |
# args/kwargs allows python functions to accept
# arbitary/unspecified amount of arguments & keyword arguments.
# Arguments
def print_args(*args):
print(f"These are my arguments : {args}")
print_args([1,2,3],(20,30),{'key': 4}, 'abc')
#---------------------------------------------------
# Keyword Arguments
def print_kwargs(**kwargs):
for key,value in kwargs.items():
print(key,value)
print_kwargs(x="Hello", y="world") | true |
a81393a5f71a79fcf1b9bcc44698fdd66ca24be1 | Harshad06/Python_programs | /PANDAS/joinsPandas.py | 739 | 4.125 | 4 | ## MERGE Function
# JOINS in PANDAS ----> [inner/outer/right/left/index]
# importing pandas
import pandas as pd
# Creating Dictionary 1
data1 = {'id': [1, 2, 10, 12],
'val1': ['a', 'b', 'c', 'd']}
a = pd.DataFrame(data1)
# print(a)
# Creating Dictionary 2
data2 = {'id': [1, 2, 9, 8],
'val2': ['p', 'q', 'r', 's']}
b = pd.DataFrame(data2)
# print(b)
# inner join
df = pd.merge(a, b, on='id', how='inner')
print("Inner Join: \n", df, end="\n")
# outer join
df = pd.merge(a, b, on='id', how='outer')
print("Outer Join: \n", df, end="\n")
# left join
df = pd.merge(a, b, on='id', how='left')
print("Left Join: \n", df, end="\n")
# right join
df = pd.merge(a, b, on='id', how='right')
print("Right Join: \n", df, end="\n") | false |
1b504b774f87f662641549baee8860ea34fd6fa7 | Harshad06/Python_programs | /useful-functions/accumulate.py | 389 | 4.1875 | 4 |
"""
accumulate() function
> accumulate() belongs to “itertools” module
> accumulate() returns a iterator containing the intermediate results.
> The last number of the iterator returned is operation value of the list.
"""
import itertools
import operator
n = [1,2,3,5,10]
print(list(itertools.accumulate(n, operator.add)))
print(list(itertools.accumulate(n, operator.mul))) | true |
e34ed0465a5fd22c905826be81eda95e1bba69d4 | Harshad06/Python_programs | /PANDAS/joinsIdenticalData.py | 740 | 4.21875 | 4 |
import pandas as pd
df1 = pd.DataFrame([1,1], columns=['col_A'] )
#print("DataFrame #1: \n", df1)
df2 = pd.DataFrame([1,1,1], columns=['col_A'] )
#print("DataFrame #2: \n", df2)
df3 = pd.merge(df1, df2, on='col_A', how='inner')
print("DataFrame after inner join: \n", df3)
# Output: 2x3 --> 6 times it will be printed. [one-many operation]
# It maybe any type of join ---> inner/outer/right/left
'''
DataFrame after inner join:
col_A
0 1
1 1
2 1
3 1
4 1
5 1
'''
# In case where any df data is "NaN" or "None", then value will be empty column-
# df1 = pd.DataFrame([NaN, NaN], columns=['col_A'] )
'''
DataFrame after inner join:
Empty DataFrame
Columns: [col_A]
Index: []
'''
| true |
c1ecf3355aadf69e8084b30d801024003c562702 | Harshad06/Python_programs | /Dictionary/sortDict.py | 471 | 4.46875 | 4 | # To sort a dictionary -
# this will sort by key
c={2:3, 1:89, 4:5, 3:0}
y = sorted(c.items())
#print(y)
#Another excampple of sort by key
d = { "John":36, "Lucy":24, "Albert":32, "Peter":18, "Bill":41 }
y = sorted(d.keys())
print(y)
x = sorted(d.values())
print(x)
z = sorted(d.items())
print(z)
for k,v in d.items(): # --------> Unordered
print(k,':',v)
#print('Key : Value')
for k,v in sorted(d.items()): # --------> Ordered
print(k,':',v) | false |
6824c7f37caca3e464bfacb3da444a075808cf09 | Harshad06/Python_programs | /string programs/longestString.py | 454 | 4.59375 | 5 |
# Python3 code to demonstrate working of
# Longest String in list
# using loop
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# Longest String in list using loop
max_len = -1
for element in test_list:
if len(element) > max_len:
max_len = len(element)
result = element
# printing result
print("Maximum length string is : " + result)
print(len(result))
| true |
4360b4921820bf5519f4a23e9300e51cf5a667d8 | Robbie-Wadud/-CS-4200-Project-3 | /List Comprehension Finding Jones.py | 483 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 7 20:22:17 2020
@author: Robbi
"""
print('Let\'s find the last name "Jones" within a list of tuples')
#Creating the list (firstName, lastName)
names = [('Robbie', 'Wadud'),('Matt', 'Jones'),('Lebron', 'James'),('Sarah', 'Jones'),('Serena', 'Williams'),('Ashley', 'Jones'),('Jessica', 'Jones')]
#Creating the new Jones tuple
jones = tuple(row for row in names if 'Jones' == row[1])
#Spacer
print('')
print(jones) | true |
77e6615697d2b92f1529259c16b8963f617187c2 | sharmasourab93/JustPython | /deepcopy.py | 1,028 | 4.53125 | 5 | """
Python: Copy
Deep Copy Vs Shallow Copy
"""
import copy
def deep_copy(array1):
array2 = copy.deepcopy(array1)
print("The original elements before deep copying")
for i in range(0, len(array1)):
print(array1[i], end=" ")
print('\r')
array2[2][0] = 7
# change reflected in l2
print("the new lis tof elements after deep copying")
for i in range(0, len(array1)):
print(array2[i], end=" ")
print("\r")
print("The original elements after deep copying")
for i in range(0, len(array1)):
print(array1[i], end=" ")
def shallow_copy(array1):
array2 = copy.copy(array1)
print("The original elements before shallow copying")
for i in range(0, len(array1)):
print(array1[i], end=" ")
array2[2][0] = 7
print("The original elements after shallow copying")
for i in range(0, len(array1)): print(array1[i], end=" ")
if __name__ == '__main__':
array1 = [1, 2, [3, 5], 4]
shallow_copy(array1)
deep_copy(array1)
| false |
fdca2f44051851ad10fb9ac34b4edf16afe46cb7 | sharmasourab93/JustPython | /tests/pytest/pytest_101/pytest_calculator_example/calculator.py | 1,470 | 4.3125 | 4 | """
Python: Pytest
Pytest 101
Learning pytest with Examples
Calculator Class's PyTest File test_calculator.py
"""
from numbers import Number
from sys import exit
class CalculatorError(Exception):
"""An Exception class for calculator."""
class Calculator:
"""A Terrible Calculator."""
def add(self, x, y):
try:
self._check_operand(x)
self._check_operand(y)
return x + y
except TypeError:
raise CalculatorError('Wrong')
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def _check_operand(self, operand):
if not isinstance(operand, Number):
raise CalculatorError(f'"{operand}" was not a number')
if __name__ == '__main__':
calculator = Calculator()
operations = [
calculator.add,
calculator.subtract,
calculator.multiply
]
print("Let's calculate!")
while True:
print("Pick an operation")
for i in enumerate(operations, start=1):
print(f"{i[0]}: {i[1].__name__}")
print("q for quit")
operation = input("Pick an operation:")
if operation == 'q':
exit()
op = int(operation)
a, b = input("What is a & b?").split()
a, b = int(a), int(b)
result = operations[op - 1]
print(result(a, b))
| true |
1be1e0530d028553e0099989161dc24ebc3e1d41 | sharmasourab93/JustPython | /decorators/decorator_example_4.py | 612 | 4.3125 | 4 | """
Python: Decorator Pattern In Python
A Decorator Example 4
Using Decorators with Parameter
Source: Geeksforgeeks.org
"""
def decorator_fun(func):
print("Inside Decorator")
def inner(*args):
print("Inside inner Function")
print("Decorated the Function")
print("Printing args:", None if args is None else args)
func()
return inner
@decorator_fun
def func_to():
print("Inside actual function ")
"""
The code above is equivalent to:
decorator_fun(func_to)()
"""
if __name__ == '__main__':
func_to()
| true |
937df73a2265bef32d2ba32ca222c47c8db247b9 | sharmasourab93/JustPython | /decorators/decorator_example_10.py | 950 | 4.21875 | 4 | """
Python: Decorator Pattern in Python
A Decorator Example 10
Func tools & Wrappers
Source: dev.to
(https://dev.to/apcelent/python-decorator-tutorial-with-example-529f)
"""
from functools import wraps
def wrapped_decorator(func):
"""Wrapped Decorator Docstring"""
"""
functools.wraps comes to our rescue in preventing
the function from getting replaced.
It takes the function used in the decorator
and adds the functionality of copying over
the function name, docstring, arguemnets etc.
"""
@wraps(func)
def inner_function(*args, **kwargs):
"""Inner Function Docstring"""
print(f"{func.__name__} was called")
return func(*args, **kwargs)
return inner_function
@wrapped_decorator
def foobar(x):
"""Foobar Docstring"""
return x**2
if __name__ == '__main__':
print(foobar.___name__)
print(foobar.__doc__)
| true |
d5320085808347ab18124a1886072b5b9cfdbe0f | sharmasourab93/JustPython | /oop/oop_iter_vs_next.py | 947 | 4.375 | 4 | """
Python: iter Vs next in Python Class
"""
class PowTwo:
"""Class to implement an iterator of powers of two"""
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
if __name__ == '__main__':
numbers = PowTwo(3)
i = iter(numbers)
while True:
try:
print(next(i))
except StopIteration:
print("Stop Iteration raised.")
break
# A simpler way to achieve this
# would be to use a for loop as given below:
print("Printing the same object value using for loop")
for i in PowTwo(3):
print(i)
# The advantage of using iterators is that they save resources.
| true |
332349a979045aa438f80f293690460e34ba8e19 | NicholasDowell/Matrix-Calculator | /Matrix.py | 2,856 | 4.375 | 4 | # This will be the fundamental matrix that is used for Matrix Operations
# it stores a 2d grid of values
# 11
# To DO: Restrict the methods so that they will not resize the matrix when they shouldnt
# CONVENTION is [ROW][COLUMN] BE CAREFUL
class Matrix:
def __init__(self, rows, columns):
self._data = [[0 for x in range(columns)] for y in range(rows)]
self._height = rows
self._width = columns
# returns the matrix's height (number of rows)
def get_height(self):
return self._height
def set_height(self, new_height):
self._height = new_height
# returns the matrix's width (number of columns)
def get_width(self):
return self._width
# replaces a row in the matrix with the passed new row
def replace_row(self, row_number, new_row):
self._data[row_number] = [column for column in new_row]
return
# replaces a column in the matrix with the passed new column
# Column_number represents the index of the column in the matrix that will be replaced.
# column_index represents the current index in the new column (the value that is being placed into the matrix)
# the passed column must have the same number of entries as the number of rows in the matrix
def replace_column(self, column_number, new_column):
# What do you do to replace a column?
column_index = 0
for x in self._data:
x[column_number] = new_column[column_index]
column_index += 1
return
# adds a new column on the rightmost side of the matrix.
def add_column(self, new_column):
self._width += 1
for x in range(self._height):
self._data[x].append(new_column[x])
return
# adds a new row to the bottom of the matrix
def add_row(self, new_row):
self._height += 1
self._data.append(new_row)
# replaces a single number in the matrix
def replace_value(self, new_value, row, column):
self._data[row][column] = new_value
def set_row(self, row_index, new_row):
self._data[row_index] = new_row
# returns a list containing all elements of one row of the matrix
def get_row(self, row_index):
return self._data[row_index]
# returns a list containing all elements of one column of the matrix
def get_column(self, column_index):
column = []
for x in range(self._height):
column.append(self._data[x][column_index])
return column
# returns the value stored at one coordinate of the matrix
def get_value(self, row, column):
return self._data[row][column]
def get_data(self):
return self._data
def set_width(self, new_width):
self._width = new_width
| true |
971383f0baa1427023b3884f19d11c9d1f590055 | AGKirby/InClassGit | /calc.py | 1,014 | 4.1875 | 4 | def calc():
# get user input
try:
num1 = int(input("Please enter the first number: ")) # get a number from the user
num2 = int(input("Please enter the second number: ")) # get a number from the user
except: # if the user did not enter an integer
print("Invalid input: integer expected. Exiting program.")
return
result = 0
# calculate the results
sum = num1 + num2
difference = num1 - num2
multiply = num1 * num2
try:
divide = num1 / num2
except: #divide by zero error!
divide = None
#put the results in a list
operation = ["Addition: ", "Subtraction: ", "Multiplication: ", "Division: "]
resultsList = [sum, difference, multiply, divide]
total = 0
# print the results and sum the list
for i in range(len(resultsList)):
print(operation[i] + str(resultsList[i]))
total += resultsList[i]
# print the sum of the list
print("The sum of the list is " + str(total))
calc() | true |
2a09f466b0eb647e577bf0835a4d55e4cbae1792 | iambillal/inf1340_2015_asst1 | /exercise2.py | 1,212 | 4.46875 | 4 | def name_that_shape():
"""
For a given number of sides in a regular polygon, returns the shape name
Inputs: user input 3-10
Expected Outputs: triangle, quadrilateral, pentagon, hexagon, heptagon, octagon, nonagon, decagon.
Errors: 0,1,2, any number greater than 10 and any other string
"""
name_that_shape = raw_input("How many sides? ")
if (name_that_shape == "3"):
print("triangle")
elif (name_that_shape == "4"):
print("quadrilateral")
elif (name_that_shape == "5"):
print("pentagon")
elif (name_that_shape == "6"):
print("hexagon")
elif (name_that_shape == "7"):
print("heptagon")
elif (name_that_shape == "8"):
print("octagon")
elif (name_that_shape == "9"):
print("nonagon")
elif (name_that_shape == "10"):
print("decagon")
else:
print("Error")
#name_that_shape()
"""
Test cases:
How many sides? 3
triangle
How many sides? 4
quadrilateral
How many sides? 5
pentagon
How many sides? 6
hexagon
How many sides? 7
heptagon
How many sides? 8
octagon
How many sides? 9
nonagon
How many sides? 10
decagon
How many sides? 2
Error
How many sides? 11
Error
"""
| true |
a6e83344a0aea87e35d4cca71c27eb2c8e4db307 | LeoImenes/SENAI | /1 DES/FPOO/python rafa/conv.py | 982 | 4.125 | 4 | print("Digite 1 para converter um número decimal\nDigite 2 para converter um número bínario\nDigite 3 para converter um número octal\nDigite 4 para converter um número hexadecimal")
a=int(input())
if a==1:
a = int(input("Qual o seu número decimal? "))
b = bin(a)
c = oct(a)
d = hex(a)
print(f"Seu número decimal é {a}\nBinário: {b}\nOctal: {c}\nHexadecimal: {d}\n")
elif a==2:
x = input("Qual o seu número binário? ")
y = int(x, 2)
z = oct(y)
z1 = hex(y)
print(f"Seu número binário é {x}\nDecimal: {y}\nOctal: {z}\nHex: {z1}\n")
elif a==3:
a1 = input("Qual seu número octal?")
a2 = int(a1, 8)
a3 = bin(a2)
a4 = hex(a2)
print(f"Seu número octal é {a1}\nDecimal: {a2}\nBinário: {a3}\nHexadecimal: {a4}\n")
else:
b1 = input("Qual seu número hexadecimal? ")
b2 = int(b1, 16)
b3 = bin(b2)
b4 = oct(b2)
print(f"Seu número hexadecimal é {b1}\nDecimal: {b2}\nBinário: {b3}\nOctal: {b4}") | false |
e7d5e6065d6645662ddd07ed34d242631b7bd686 | robinchew/misc | /interview/Edward/test.py | 565 | 4.125 | 4 | import time
import datetime
def test(add):
print "current date"
now = datetime.date.today()
print now
print add, "days after current time"
print now + datetime.timedelta(days=add)
test(4)
def test2(date):
print "current date test2"
now = datetime.datetime.now()
difference = date - now
print difference
test2(datetime.datetime.strptime('2009-2-28','%Y-%m-%d'))
def test3(str):
print "test3"
now = datetime.datetime.today()
difference = datetime.datetime.strptime(str,'%Y/%m-%d') - now
print difference
test3('2009/2-27')
| false |
3674c62c670327d324a08a2bb13a6cc111b9b973 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab4Problem4.py | 1,143 | 4.34375 | 4 | __author__ = 'Michele'
#How to test either a string or numeric
#Initial age question and valid entry test
age = int(input('Enter the child\'s age: '))
BooleanValidAge = age <= 200
#Is age entry valid
while BooleanValidAge == False:
print('Invalid entry. Please re-enter a valid age for the child.')
age = int(input('Enter the child\'s age: '))
BooleanValidAge = age <= 200
#end valid age entry loop
#Initial weight question and valid entry test
weight = int(input('Enter the child\'s weight: '))
BooleanValidWeight = weight <= 1000
#Is the entry valid
while BooleanValidWeight == False:
print('Invalid entry. Please re-enter a valid weight for the child.')
weight = int(input('Enter the child\'s weight: '))
BooleanValidWeight = weight <= 1000
#end valid weight entry loop
BooleanAgeWeight = age < 8 or weight < 70
if BooleanAgeWeight == True:
print('The child is required to ride in a booster seat according to North Carolina state law.')
#There is extra sunlight
else:
print('The child is no longer required to ride in a booster seat according to North Carolina state law.') | true |
2c330237b90116e7f55075a360f4290fe334d533 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab9Problem3.py | 2,927 | 4.375 | 4 | __author__ = 'Michele Johnson'
# Write a program to play the rock-paper-scissors game.
# A single player is playing against the computer.
# In the main function, ask the user to choose rock, paper or scissors.
# Then randomly pick a choice for the computer.
# Pass the choices of the player and the computer to a find_winner function,
# which determines and displays the outcome of the game.
# Imported Modules
import random
def InfoToUser():
# Information to the user
print('Welcome to Rock Paper Scissors!!!')
print()
print('This is a single player game against the computer.')
print('The player will select a weapon from the list below.')
print('The computer will then select a weapon.')
print('The most powerful weapon WINS!!!')
print()
print(' Weapons List')
print()
print('Weapon Code Weapon')
print('R Rock')
print('P Paper')
print('S Scissors')
print()
print()
def GetPlayer1():
##User enters input
global Player1
Player1 = input('Player 1, please enter your weapon of choice from the list above: ')
print()
Player1 = Player1.upper()
if Player1 != "R" and Player1 != "P" and Player1 != "S":
print('The player did not enter a valid weapon from the list above.')
else:
if Player1 == "R":
print("The Player's weapon of choice is Rock.")
if Player1 == "P":
print("The Player's weapon of choice is Paper.")
if Player1 == "S":
print("The Player's weapon of choice is Scissors.")
def GetComputer():
# Randomly select either R, P, or S
global Computer
Computer = ["R", "P", "S"]
Computer = random.choice(Computer)
if Computer == "R":
print("The Computer's weapon of choice is Rock.")
elif Computer == "P":
print("The Computer's weapon of choice is Paper.")
elif Computer == "S":
print("The Computer's weapon of choice is Scissors.")
def DetermineWinner(Player1, Computer):
if Player1 == Computer:
print("It's a Tie!!!")
elif Player1 == "R" and Computer == "S":
print("Rock beats Scissors. Player 1 Wins!!!")
elif Player1 == "S" and Computer == "P":
print("Scissors beat Paper. Player 1 Wins!!!")
elif Player1 == "P" and Computer == "R":
print("Paper beats Rocks. Player 1 Wins!!!")
elif Computer == "R" and Player1 == "S":
print("Rock beats Scissors. The Computer Wins!!!")
elif Computer == "S" and Player1 == "P":
print("Scissors beat Paper. The Computer Wins!!!")
else:
print("Paper beats Rocks. The Computer Wins!!!")
def main():
# Call Functions
InfoToUser()
GetPlayer1()
GetComputer()
print()
DetermineWinner(Player1,Computer)
main()
| true |
ba9e9753af0ce41ee2b220db1dc202677a8d73e7 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab5Problem1.py | 1,570 | 4.25 | 4 | __author__ = 'Michele'
print('It is time to select your health plan for the year.')
print('You will need to select from the table below:')
print('')
print('Health Plan Code Coverage Premium')
print('E Employee Only $40')
print('S Employee & Spouse $160')
print('C Employee & Children $200')
print('F Whole Family $250')
print('')
#User entry; 1st pass
Choice = str(input('Please enter your health plan choice code from the table above: '))
Choice = Choice.upper()
UserEntryValid = Choice == 'E' or Choice == 'S' or Choice == 'C' or Choice == 'F'
#Test valid user entry
while UserEntryValid == False:
print('Your entry is invalid. Please select a valid code from the table above.')
Choice = str(input('Please enter your health plan choice code from the table above: '))
Choice = Choice.upper()
UserEntryValid = Choice == 'E' or Choice == 'S' or Choice == 'C' or Choice == 'F'
#print(Choice)
#print(UserEntryValid)
#Begin program
if Choice == 'E':
print('You have selected the Employee Only health plan. Your premium is $40.')
elif Choice == 'S':
print('You have selected the Employee & Spouse health plan. Your premium is $160.')
elif Choice == 'C':
print('You have selected the Employee & Children health plan. Your premium is $200.')
else:
print('You have selected the Whole Family health plan. Your premium is $250.')
| true |
c3bec77407894ad0425a6c44b57733ff67beb1d7 | EtienneBrJ/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,210 | 4.21875 | 4 | #!/usr/bin/python3
""" Module Square
"""
from models.rectangle import Rectangle
class Square(Rectangle):
""" Square class inherits from Rectangle
"""
def __init__(self, size, x=0, y=0, id=None):
""" Initialize an instance square from the class Rectangle.
"""
super().__init__(size, size, x, y, id)
@property
def size(self):
""" Retrieves the size of the square.
"""
return self.width
@size.setter
def size(self, size):
""" Sets the size of the Square.
"""
self.width = size
self.height = size
def update(self, *args, **kwargs):
""" Public method:
assigns an argument to each attribute
"""
if args and len(args) != 0:
i = 0
for arg in args:
if i == 0:
if arg is None:
self.__init__(self.size, self.x, self.y)
else:
self.id = arg
elif i == 1:
self.size = arg
elif i == 2:
self.x = arg
elif i == 3:
self.y = arg
i += 1
elif kwargs and len(kwargs) != 0:
for k, v in kwargs.items():
if k == 'id':
if v is None:
self.__init__(self.size, self.x, self.y)
else:
self.id = v
elif k == 'size':
self.width = v
elif k == 'x':
self.x = v
elif k == 'y':
self.y = v
def to_dictionary(self):
""" Public method:
Returns the dictionary representation of a Rectangle
"""
return {
"id": self.id,
"size": self.size,
"x": self.x,
"y": self.y
}
def __str__(self):
""" Return the print() and str() representation
of the Square.
"""
return '[Square] ({}) {}/{} - {}'.format(self.id, self.x, self.y,
self.width)
| true |
64c8a33693b8db0533a3baa275c47a7d4b8e8e38 | GokoshiJr/algoritmos2-py | /src/modular/invertir.py | 246 | 4.125 | 4 | # 3. Invertir un numero
numero = int(input('Ingrese un numero: '))
digito = result = 0
aux = numero
while (aux > 0):
digito = aux % 10
result = (result * 10) + digito
aux //= 10
print('Su inverso es:', result)
| false |
366b54996d3152ac7bee13e218f167480699acd8 | rutujak24/crioTryout | /swapCase.py | 707 | 4.4375 | 4 | You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
'''For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
Input Format
A single line containing a string
.
Constraints
Output Format
Print the modified string
.
Sample Input 0
HackerRank.com presents "Pythonist 2".
Sample Output 0
hACKERrANK.COM PRESENTS "pYTHONIST 2".
'''
def swap_case(s):
a = ""
for let in s:
if let.isupper() == True:
a+=(let.lower())
else:
a+=(let.upper())
return a
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
| true |
a14c5a0c660b421fd79e09766fcd924bd76b60c6 | hoang-ph/Othello-with-Python-Processing | /Othello/computer.py | 2,964 | 4.25 | 4 | class Computer:
"""A class represent AI's move for Othello game"""
def __init__(self, board, game_controller, tile_color):
self.gc = game_controller
self.board = board
self.tile_color = tile_color
self.legal_moves = []
def place_tile(self):
"""
:rtype: void
Choose a suitable move from the available-move list
"""
self.legal_moves = self.board.get_legal_moves(self.tile_color)
if len(self.legal_moves) == 0:
self.gc.computer_no_move = True
self.gc.swap_turn()
print("No move available, your turn")
if self.gc.computer_turn:
if self.get_corner_move():
index = self.get_corner_move()
elif self.get_edge_move():
index = self.get_edge_move()
else:
index = self.get_best_move()
i, j = index
if self.board.check_legal_move(i, j, self.tile_color):
self.board.place_tile(i, j, self.tile_color)
self.board.flip_tiles(i, j, self.tile_color)
self.gc.swap_turn()
print("Your turn")
def get_corner_move(self):
"""
:rtype: Tuple(int i, int j) or None
Return an index for corner move from the available legal moves list
return None if not found a corner move available
"""
corner_indexes = [(0, 0), (0, self.board.SIZE-1),
(self.board.SIZE-1, 0),
(self.board.SIZE-1, self.board.SIZE-1)]
for index in corner_indexes:
if index in self.legal_moves:
return index
return None
def get_edge_move(self):
"""
:rtype: Tuple(int i, int j) or None
Return a tuple of [i,j] index if an edge move exist,
otheweise, return None
"""
edge_move_list = []
for i in range(self.board.SIZE):
edge_move_list.append((i, 0))
edge_move_list.append((i, self.board.SIZE-1))
edge_move_list.append((0, i))
edge_move_list.append((self.board.SIZE-1, i))
for index in edge_move_list:
if index in self.legal_moves:
return index
return None
def get_best_move(self):
"""
:rtype: Tuple(int i, int j)
Return a tuple of [i,j] index for the move with
the most flippable tiles
"""
count = 0
i_best = 0
j_best = 0
for i, j in self.legal_moves:
if (count
< len(self.board.get_flip_tile_list(i, j, self.tile_color))):
i_best, j_best = i, j
count = len(self.board.get_flip_tile_list(i, j,
self.tile_color))
return (i_best, j_best)
| false |
b585acc6820a2a013d1dacf883fc961d618f78a3 | mlarva/projecteuler | /Project1.py | 743 | 4.1875 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
def multipleFinder(min, max, *multiples):
multiplesSet = set()
if min >= max:
print("Minimum is not smaller than maximum")
return
if min < 0 or max < 1:
print("Cannot enter negative numbers")
return
for x in range(min,max):
for y in multiples:
if x % y == 0:
multiplesSet.add(x)
return multiplesSet
def sumSet(setToSum):
sum = 0
for x in setToSum:
sum += x
return sum
multiplesSet = multipleFinder(1,1000, 3, 5)
print(sumSet(multiplesSet))
| true |
6205ce04a990b36d3a18e04968ebdadf9a62f29a | LisaVysochyn/lab-3 | /1.py | 702 | 4.15625 | 4 | """
The Fibonacci numbers are the sequence below, where the first two numbers are 1, and each number thereafter is the sum of the two preceding numbers. Write a program that asks the user how many Fibonacci numbers to print and then prints that many.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
>>> Введіть скільки чисел Фібоначчі Ви хочете отримати: 8
[1, 1, 2, 3, 5, 8, 13, 21]
"""
n = int(input("Введіть скільки чисел Фібоначчі Ви хочете отримати: "))
if n == 0:
f = []
elif n == 1:
f = [1]
elif n >= 2:
f = [1, 1]
while len(f) != n:
f.append(f[-1] + f[-2])
print(f)
| false |
7696267a751e50ff101e20be49ae26ebf036222d | soedjais/dodysw-hg | /ProjectEuler/Problem45.py | 1,201 | 4.3125 | 4 | import math
def is_pentagonal(y):
"""
y = x(3x-1)/2.
y is the input, we need to find x, and whether it's an positive integer. Using quadratic equation, we convert to the following:
x = (-b +- sqrt(b^2-4ac))/2a
since y = x(3x-1)/2 is 1.5*x^2 - 0.5*x - y = 0, then a = 1.5, b = 0.5, c = -y
x = (0.5 +- sqrt(0.25+6y)/3. Since x must be positive integer, then -1.5 must be added with positive number. so:
x = (0.5 + sqrt(0.25+6y)/3
"""
x = (0.5 + math.sqrt(0.25+6*y))/3
if x % int(x) == 0:
return x
return False
def is_triangle(t):
"""
t = n(n+1)/2 => 0.5*n^2 + 0.5*n - t = 0
x = -0.5 +- sqrt(0.25+2*t) / 1
= -0.5 + sqrt(0.25+2*t)
"""
t = -0.5 + math.sqrt(0.25+2*t)
return t % int(t) == 0
def is_hexagonal(h):
"""
h = n(2n-1) => 2*n^2 - n - h = 0
x = (1 +- sqrt(1 + 8*h)) / 4
= 0.25 + sqrt(1 + 8*h)/4
"""
h = 0.25 + math.sqrt(1 + 8*h)/4
if h % int(h) == 0:
return h
return False
n = 1
while 1:
T = n*(n+1)/2
if is_hexagonal(T) and is_pentagonal(T):
print "T(%s)=%s is hexagonal(%s) and pentagonal(%s)" % (n,T, is_hexagonal(T), is_pentagonal(T))
n += 1 | false |
b1953a6b8652ea8744c6ca9c935a7ec9d04ac4b6 | MikeCullimore/project-euler | /project_euler_problem_0001.py | 2,131 | 4.3125 | 4 | """
project_euler_problem_0001.py
Worked solution to problem 1 from Project Euler:
https://projecteuler.net/problem=1
Problem title: Multiples of 3 and 5
Problem: if we list all the natural numbers below 10 that are multiples of 3 or
5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Break the problem down further:
1) Find the largest multiple of 3: e.g. for 10, it is 9 = 3 x 3.
2) Likewise for 5: e.g. for 10, it is 5 = 1 x 5.
3) Factorise each sum e.g. 3 + 6 + 9 = 3*(1 + 2 + 3).
4) Use Gauss's trick for the sums 1 + 2 + ... + n = n*(n - 1)/2.
5) Multiply the sums by 3 or 5 as appropriate then add together.
TODO: use example above as test case.
TODO: input validation.
"""
import numpy as np
def sum_gauss_trick(number):
"""Calculate the sum 1 + 2 + 3 + ... + number using Gauss's trick."""
sum = int(number*(number+1)/2)
print('The sum of the natural numbers up to {} is {}.'.format(number, sum))
return sum
def find_largest_multiplier(number, divisor):
"""Find the largest multiple of divisor below the given number.
I.e. return largest multiplier such that multiplier*divisor < number.
"""
multiplier = int(np.floor((number - 1)/divisor))
print('The largest multiple of {} below {} is {} x {} = {}.'.format(
divisor, number, multiplier, divisor, multiplier*divisor))
return multiplier
def find_sum_multiples_3_or_5(upper):
"""Find the sum of all multiples of 3 or 5 below the given upper bound.
E.g. if upper=10: multiples of 3 or 5 are 3, 5, 6 and 9; sum is 23.
"""
multiplier_3 = find_largest_multiplier(upper, 3)
multiplier_5 = find_largest_multiplier(upper, 5)
sum_3 = sum_gauss_trick(multiplier_3)
sum_5 = sum_gauss_trick(multiplier_5)
solution = 3*sum_3 + 5*sum_5
print('The sum of all multiples of 3 or 5 below {} is:'.format(upper))
print('3*{} + 5*{} = {}.'.format(upper, sum_3, sum_5, solution))
return solution
def main():
# find_sum_multiples_3_or_5(10)
find_sum_multiples_3_or_5(1000)
if __name__ == '__main__':
main()
| true |
256b3cf6e6919388e85f3e16fd025c4fc1c3b688 | suspectpart/misc | /cellular_automaton/cellular_automaton.py | 1,787 | 4.28125 | 4 | #!/usr/bin/python
'''
Implementation of the Elementary Cellular Automaton
For an explanation of the Elementary Cellular Automaton, read here:
http://mathworld.wolfram.com/ElementaryCellularAutomaton.html
The script takes three parameters:
- A generation zero as a starting pattern, e.g. 1 or 101 or 1110111
- A rule from 0 to 255 by which to evolve the generations
- A maximum generation
Sample usage:
./cellular_automaton.py 010 30 30
./cellular_automaton.py 1110111 255 30
'''
import sys
def rule(i):
return "".join(reversed(list("{0:08b}".format(i)))) # 00111001 becomes [1,0,0,1,1,1,0,0], so that rule[1], rule[2].. work
def cellular_automaton(generation_zero, rule, max_generations):
generations = evolve_all(generation_zero, rule, max_generations)
width = len(generations[-1])
for i, generation in enumerate(generations):
padded_zeros = (width - len(generation)) / 2
padded_generation = "0" * padded_zeros + generation + "0" * padded_zeros
print "".join(map(str, padded_generation)).replace("0", " ").replace("1", "X")
def evolve_all(generation_zero, rule, max_generation):
generations = [generation_zero]
for i in range(max_generation):
generations.append(evolve(generations[i], rule))
return generations
def evolve(generation, rule):
next_generation = ""
generation = "00" + generation + "00"
for i, cell in enumerate(generation[1:-1]):
left_neighbour, right_neighbour = str(generation[i]), str(generation[i+2])
binary_value_of_cell = int(left_neighbour + cell + right_neighbour, 2)
next_generation += rule[binary_value_of_cell]
return next_generation
if __name__ == "__main__":
generation_zero = str(sys.argv[1])
r = rule(int(sys.argv[2]))
max_generation = int(sys.argv[3])
cellular_automaton(generation_zero, r, max_generation) | true |
86cf4cb652c0c62011f157bfd98259d7a092d005 | anaruzz/holbertonschool-machine_learning | /math/0x06-multivariate_prob/0-mean_cov.py | 564 | 4.125 | 4 | #!/usr/bin/env python3
"""
A function that calculates the mean and covariance of a data set
"""
import numpy as np
def mean_cov(X):
"""
Returns mean of the data set
and covariance matrix of the data set
"""
if type(X) is not np.ndarray or len(X.shape) != 2:
raise TypeError("X must be a 2D numpy.ndarray")
if X.shape[0] < 2:
raise ValueError("X must contain multiple data points")
n, d = X.shape
mean = X.mean(axis=0, keepdims=True)
xi = X - mean
cov = np.matmul(xi.T, xi) / (n - 1)
return mean, cov
| true |
3a904d372a32c4d10dbf04e2e0f8653bf6c0d995 | anaruzz/holbertonschool-machine_learning | /math/0x00-linear_algebra/3-flip_me_over.py | 398 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Script that returns the transpose of a 2D matrix
"""
def matrix_transpose(matrix):
"""
function that returns
the transpose of a 2D matrix,
"""
i = 0
new = [[0 for i in range(len(matrix))] for j in range(len(matrix[i]))]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
new[j][i] = matrix[i][j]
return new
| true |
5ebd7f954d1ebf345d87d7cb8afa11bfbb9846a8 | whatarthurcodes/Swedish-Test | /swedishtest.py | 1,843 | 4.125 | 4 | import sys
import random
import csv
def swedishtest():
word_bank = select_module()
lang = choose_lang()
questions(word_bank, lang)
def select_module():
file_found = False
while file_found is False:
try:
module_choice = raw_input('Enter the file name. ex. module1.csv \n')
module = open(module_choice)
csv_f = csv.reader(module)
file_found = True
except Exception:
print ("Cannot Find file ") + module_choice + ("\n")
word_bank =[]
for row in csv_f:
word_bank.append(row)
return word_bank
def choose_lang():
lang = False
while lang is False:
lang = input('For Swedish to English enter 0 For English to Swedish enter 1 \n')
if lang == 0 or lang == 1:
return lang
else:
print ('Please enter 0 for English to Swedish or 1 for Swedish to English \n')
lang = False
def questions(word_bank, lang):
answer = 'answer'
quit = False
number_of_words = len(word_bank)
print number_of_words
correct_answers = 0
number_of_questions =0
print ('\nTo quit, enter q or quit')
if lang == 0:
print ('The word is given in Swedish, please type in the English word \n')
lang_answer = 1
if lang == 1:
print ('The word is given in English, please type in the Swedish word \n')
lang_answer = 0
while quit is False:
rand = random.randint(0, number_of_words-1)
question = word_bank[rand]
answer = raw_input(question[lang] + '\n')
if answer == 'q' or answer == 'quit':
quit = True
print "You got " + str(correct_answers) + " correct out of " + str(number_of_questions)
elif question[lang_answer] == answer:
print "Correct! \n"
correct_answers = correct_answers + 1
number_of_questions = number_of_questions + 1
else:
print "Wrong! The answer is: " + question[lang_answer] + "\n"
number_of_questions = number_of_questions + 1
swedishtest() | true |
9028afe374d90a565b23cf9ff102d7dd70025ba1 | mfaria724/CI2691-lab-algoritmos-1 | /Laboratorio 05/Laboratorio/Lab05Ejercicio3r.py | 1,265 | 4.125 | 4 | #
# Lab05Ejercicio3r.py
#
# DESCRIPCIÓN: Programa que dada una secuencia de N números naturales
# pertenecientes al conjunto {1,2,3,4} devuelve el número de ocurrencias
# de cada elemento del conjunto en la secuencia dada.
#
# Autor:
# Manuel Faria 15-10463
#
# Ultima modificacion: 22/02/2018
#
import sys # Se importa la libreria sys para poder utilizar sys.exit()
# VARIABLES:
# N: int // ENTRADA: Número actual de la secuencia.
# Valores iniciales:
ocurrencias = [0,0,0,0]
while True:
while True: # Verificación del valor cuando es introducido.
try:
N = int(input("Ingrese un número que pertenezca al conjunto {1,2,3,4}: "))
assert(0<=N<5)
break
except:
print("Debe introducir un número que pertenezca al conjunto {1,2,3,4}")
print("Ingrese otro número")
if N == 0: # Termina el programa.
break
elif N == 1:
ocurrencias[0] += 1
elif N == 2:
ocurrencias[1] += 1
elif N == 3:
ocurrencias[2] += 1
elif N == 4:
ocurrencias[3] += 1
# Salida:
print("Las ocurrencias del numero 1 son: " + str(ocurrencias[0]))
print("Las ocurrencias del numero 2 son: " + str(ocurrencias[1]))
print("Las ocurrencias del numero 3 son: " + str(ocurrencias[2]))
print("Las ocurrencias del numero 4 son: " + str(ocurrencias[3])) | false |
257ecb3f0097ccf743b102462cb4f14c37b5cc2d | mlawan/lpthw | /ex39/ex39.py | 1,591 | 4.3125 | 4 | # creates a mapping to state to abbreviation
states ={
'Oregon': 'OR',
'Florida' : 'FL',
'CAlifornia' : 'CA',
'Konduga' : 'KDG',
'Maiduguri': 'Mag'
}
#creats a babsic set of states and some cities in them
cities = {
'CA': 'SanfranCisco',
'KDG': 'Sandiya',
'FL': 'Florida',
'Mag': 'MMC'
}
#ADD SOME MORE cities
cities['NY'] = 'New York'
cities ['OR'] = 'Portland'
#print out some cities
print('*'* 20)
print("NY State has:", cities ['NY'])
print("OR State has:", cities['OR'])
print("Borno state has:", cities['KDG'])
#print("Borno State has:", states)
#print some states
print('*' * 20)
print("Maiduguri's abbreviation is:" , states['Maiduguri'])
print("Florida's abbreviation is:" , states['Florida'])
#do it by using the state then cities dict
print('-' * 20)
print("Maiduguiri has:", cities [states['Maiduguri']])
print ("Florida has:" , cities[states['Florida']])
#print every state abbreviation
print('*' *20)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
#print every city in states
print("+" *20)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
#now do both at the same time
print('=' * 20)
for state, abbrev in list(states.items()):
print(f"{state} state abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('~'*20)
# safely get a abbreviatedby state that might not be There
state = states.get("Texas")
if not state:
print("Sorry , no Texas")
#get a city with a defalut value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX'is {city}")
| false |
28a5ceae1d0b29e00c0a7e657c5ea9f3ce3ab08f | mlawan/lpthw | /ex30/ex30.py | 518 | 4.15625 | 4 | people = 30
cars = 40
trucks = 40
if cars > people or trucks < cars:
print("We should take the cars")
elif cars< people:
print("We should not take the cars")
else:
print(" We cant decide.")
if trucks > cars and cars == trucks:
print("Thats too much of trucks")
elif trucks <cars:
print("Maybe we could take the trucks")
else:
print(" We still can't decide")
if cars == trucks and cars > people:
print("Alrifht, lets jsut take the trucks")
else:
print("fine, lets stay home then.")
| true |
8950ac176813b900f3f4e7a4d3358e977987552e | andrewn488/5061-entire-class | /Week 05/pec1_decimal_to_binary.py | 741 | 4.21875 | 4 | """PEC1: Decimal to Binary
Author: Andrew Nalundasan
For: OMSBA 5061, Seattle University
"""
print('When you enter a non negative integer a string in binary representation will be shown')
n = int(input('Enter a non- negative integer: '))
if n < 0:
print('You must enter a non- negative integer: ')
print('Please try again')
n = int(input('Enter a non- negative integer: '))
def decimalToBinary (n):
""" Returns a string with the binary number representation
for any non- negative ineger
"""
if n == 0:
n = '0'
while n > 0:
if n % 2 != 0:
n = (([n / 2]) + '1')
elif n % 2 == 0:
n = (([n / 2]) + '0')
return n
print ('{:b}'.format (n))
| false |
0a3c8d459722962a4cf49d524456b76d2069fc9a | python4kidsproblems/Operators | /comparison_operators.py | 1,266 | 4.28125 | 4 | # Comarison Operators Practice Problems
# How to use this file:
# Copy this to your python (.py) file, and write your code in the given space
################################### Q1 ###################################
# Write a program that asks the user, #
# "Are you older than 15? Answer True or Flase." #
# Convert the user response to Bool and then check its type using the #
# type function. #
# See what happpens if the user does not repond with True or False, #
# and replies with Yes or No instead. Will this program still work? #
##########################################################################
# your code goes here
################################### Q2 ###################################
# Write a Truth Detector program that gives the User two numbers to #
# compare and tell which one is bigger. If the User answers correctly #
# print True and if not print False. #
# Hint: Notice that print(1==1) prints True and print(4<3) prints False. #
##########################################################################
# your code goes here
| true |
fc09bc969303a4bddf367fc3748ffb53e20e7ba0 | rsurpur20/ComputerScienceHonors | /Classwork/convertor.py | 1,114 | 4.25 | 4 | # convert dollars to other currencies
import math
import random
#
# dollars=float(input("Dollars to convert: \n $")) #gets the input of how many dollars, the user wants to convert
#
# yen=dollars*111.47 #the conversion
# euro=dollars*.86
# peso=dollars*37.9
# yuan=dollars*6.87
#
# print("$"+str(dollars) + " in yen is", str(yen)) #prints the result. a comma is
# #the same as a plus in string cancatination. a comma will add a space, where a plus lets you munipulate the spacing
# print("$"+str(dollars) + " in euros is", str(euro)) #prints the result. a comma is
# print("$"+str(dollars) + " in pesos is", str(peso)) #prints the result. a comma is
# print("$"+str(dollars) + " in yuan is", str(yuan)) #prints the result. a comma is
# print(random.randrange(0,101,10)) #starts, end, step. so it starts and includes zero,
# #ends with and doesn't include 101, and it is a multiple of 10
#this code is to get an input as theta and do the following: sin^2(theta)+cos^2(theta)
theta=math.radians(float(input("pick a random number \n")))
# print(theta)
print(float((math.sin(theta)**2)+(math.cos(theta)**2)))
| true |
111c5346ca6f32e8f25608a1d2cf2ea143056ed6 | rsurpur20/ComputerScienceHonors | /minesweeper/minesweepergame.py | 2,394 | 4.25 | 4 | # https://snakify.org/en/lessons/two_dimensional_lists_arrays/
#Daniel helped me,and I understand
import random
widthinput=int(input("width?\n"))+2 #number or colomns
heightinput=int(input("height ?\n"))+2 #number of rows
bombsinput=int(input("number of bombs?\n"))#number of bombs
width=[]
height=[]
# j=[]
# # for x in range(len(j)): #len(j) gives you the number of rows
# # print(*j[x]) #putting a * right before a list gets rid of synatx
#
# width=[0]*widthinput
# height=[0]*heightinput
# # print(width)
# # print(height)
# list=[width[]height[]]
# for x in range(0, len(height)):
# # print(width[x])
# # print()#print on new line
# for x in range(0,len(width)):
# print(width[x], end=' ') #prints on same line
# print()#print on new line
#
index=[]
# for every row in the height, make an empty row:
for x in range(heightinput):
#height +2 gives you number of rows
width=[0]*(widthinput)
index.append(width)
# print(index)
# print(*index[x])
area=heightinput*widthinput
# for x in range(0,bombsinput):
# position=random.randint(0,area)
# print(position)
i=1
while i<=bombsinput:
x=random.randint(1,widthinput-2)
y=random.randint(1,heightinput-2)
index[y][x]="*"
# print(y,x)
i+=1
#adds one to the area around the bomb
z=0
# print(bombsinput)
# for z in range(bombsinput):
if index[y+1][x]!="*": #right
index[y+1][x]+=1
if index[y-1][x]!="*": #left
index[y-1][x]+=1
if index[y][x+1]!="*":#down
index[y][x+1]+=1
if index[y][x-1]!="*":#up
index[y][x-1]+=1
#diagonals
if index[y-1][x+1]!="*":
index[y-1][x+1]+=1
if index[y+1][x-1]!="*":
index[y+1][x-1]+=1
if index[y-1][x-1]!="*":
index[y-1][x-1]+=1
if index[y+1][x+1]!="*":
index[y+1][x+1]+=1
# index[y][x+2]=+1
# index[y][x-2]=+1
z+=1
for x in range(1,heightinput-1): #every row except the buffer rows
for y in range(1,widthinput-1): #for every colomn except the buffer colomns
# print(*index[y])
print(index[x][y], end=' ')
print()
# height.append(width)
# j.append(width) #list j will have ten zeros
# print(height)
# print(width[x])
# gives you a ten by ten list of 100 zeros
#
# for i in range(height):
# for j in range(width):
# print(width[i][j], end=' ')
# print()
| true |
bac4234eb3635e084517cab020e5b8761e77967f | joelstanner/codeeval | /python_solutions/HAPPY_NUMBERS/happy_numbers.py | 1,485 | 4.3125 | 4 | """
A happy number is defined by the following process. Starting with any positive
integer, replace the number by the sum of the squares of its digits, and repeat
the process until the number equals 1 (where it will stay), or it loops
endlessly in a cycle which does not include 1. Those numbers for which this
process ends in 1 are happy numbers, while those that do not end in 1 are
unhappy numbers.
INPUT SAMPLE:
The first argument is the pathname to a file which contains test data,
one test case per line. Each line contains a positive integer. E.g.
7
22
OUTPUT SAMPLE:
If the number is a happy number, print out 1. If not, print out 0. E.g
1
1
0
For the curious, here's why 7 is a happy number: 7->49->97->130->10->1.
Here's why 22 is NOT a happy number:
22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...
"""
import sys
def parse_input(input_file):
with open(input_file, mode="r") as file:
for line in file:
happiness(line.rstrip())
def happiness(num):
"""Return 1 if number is happy, 0 if not
num is a string and is converted into single digit integers
"""
happys = [int(j) for j in num]
last = 0
for digit in happys:
last += digit ** 2
if last == 1:
print(1)
elif last == 89: # all unhappy numbers become 89 at some point
print(0)
return
else:
happiness(str(last))
if __name__ == '__main__':
INPUT_FILE = sys.argv[1]
parse_input(INPUT_FILE)
| true |
9668ba9aad876675efe26dc644d08c3f8cb049a1 | joelstanner/codeeval | /python_solutions/NUMBER_PAIRS/NUMBER_PAIRS.py | 2,563 | 4.3125 | 4 | """
You are given a sorted array of positive integers and a number 'X'. Print out
all pairs of numbers whose sum is equal to X. Print out only unique pairs and
the pairs should be in ascending order
INPUT SAMPLE:
Your program should accept as its first argument a filename. This file will
contain a comma separated list of sorted numbers and then the sum 'X',
separated by semicolon. Ignore all empty lines. If no pair exists, print the
string NULL e.g.
1,2,3,4,6;5
2,4,5,6,9,11,15;20
1,2,3,4;50
OUTPUT SAMPLE:
Print out the pairs of numbers that equal to the sum X. The pairs should
themselves be printed in sorted order i.e the first number of each pair should
be in ascending order. E.g.
1,4;2,3
5,15;9,11
NULL
"""
from sys import argv
def number_pairs(num_list, minuend):
"""Return a list of number pairs that sum to the minuend.
This is accomplished by iterating a list of integers and
subtracting the number from the minuend. If the difference from
that operation is also in our list of numbers, then we have a pair.
Remove the second number (diff) from the list so we don't duplicate.
Args:
num_list: A sorted list of integers.
minuend: The number we are looking to find sums of in our num_list.
Returns:
A list of tuples that sum to the minuend.
"""
pairs = []
for subtrahend in num_list:
diff = minuend - subtrahend
if diff in num_list:
pairs.append((subtrahend, diff))
num_list.remove(diff)
return pairs
def parse_line(line):
"""Returns a list of ints and a minuend integer.
The line needs to be in the form '1,2,3,...;5' as described in the module
docstring
"""
num_list, minuend = line.split(';')
num_list = [int(num) for num in num_list.split(',')]
minuend = int(minuend)
return num_list, minuend
def parse_output(output_list):
"""Return a string formed like so: '1,4;2,3'"""
output = []
for pair in output_list:
temp = ",".join([str(num) for num in pair])
output.append(temp)
return ";".join(output)
def main(input_file):
"""Iterate the lines of a text file and print the results."""
with open(input_file, 'r') as file:
for line in file:
num_list, minuend = parse_line(line)
pairs = number_pairs(num_list, minuend)
out_line = parse_output(pairs)
if not out_line == '':
print(out_line)
else:
print('NULL')
if __name__ == '__main__':
main(argv[1])
| true |
a73717e0842d17d44f275aeafba71950e88e5b55 | joelstanner/codeeval | /python_solutions/PENULTIMATE_WORD/PENULTIMATE_WORD.py | 583 | 4.4375 | 4 | """
Write a program which finds the next-to-last word in a string.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following:
some line with text
another line
Each line has more than one word.
OUTPUT SAMPLE:
Print the next-to-last word in the following way:
with
another
"""
from sys import argv
def penultimate(input_file):
with open(input_file, 'r') as file:
for line in file:
words = line.rstrip().split()
print(words[-2])
if __name__ == '__main__':
penultimate(argv[1])
| true |
0dc79dcc5c3b026ad10e1328ed2ef84a12514fb1 | joelstanner/codeeval | /python_solutions/UNIQUE_ELEMENTS/unique_elements.py | 809 | 4.4375 | 4 | """
You are given a sorted list of numbers with duplicates. Print out the sorted
list with duplicates removed.
INPUT SAMPLE:
File containing a list of sorted integers, comma delimited, one per line. E.g.
1,1,1,2,2,3,3,4,4
2,3,4,5,5
OUTPUT SAMPLE:
Print out the sorted list with duplicates removed, one per line.
E.g.
1,2,3,4
2,3,4,5
"""
from sys import argv
INPUT_FILE = argv[1]
def unique_elements(input_file):
"""Print out the sorted list with duplicates removed, one per line"""
with open(input_file, mode="r") as file:
for line in file:
# Create a new, unique list that is a set from orig list.
u_list = sorted(list(set([int(x) for x in line.split(',')])))
print(*u_list, sep=",")
if __name__ == '__main__':
unique_elements(INPUT_FILE)
| true |
3b9c14de993878342e89d659c501c39b27078042 | joelstanner/codeeval | /python_solutions/SIMPLE_SORTING/SIMPLE_SORTING.py | 873 | 4.53125 | 5 | """
Write a program which sorts numbers.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following
70.920 -38.797 14.354 99.323 90.374 7.581
-37.507 -3.263 40.079 27.999 65.213 -55.552
OUTPUT SAMPLE:
Print sorted numbers in the following way. Please note, that you need to print
the numbers till the 3rd digit after the dot including trailing zeros.
-38.797 7.581 14.354 70.920 90.374 99.323
-55.552 -37.507 -3.263 27.999 40.079 65.213
"""
from sys import argv
def sorter(input_file):
with open(input_file, 'r') as file:
for line in file:
line = line.rstrip()
sort_list = sorted([float(x) for x in line.split()])
for item in sort_list:
print("{:.3f}".format(item), end=" ")
print()
if __name__ == '__main__':
sorter(argv[1])
| true |
66a16d29f30d44d93ca5f219d6d51752633364e2 | jDavidZapata/Algorithms | /AlgorithmsInPython/stack.py | 329 | 4.125 | 4 |
# Stack implementation in Python
stack = []
# Add elements into stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Stack')
print(stack)
# Popping elements from stack
print('\nAfter popping an element from the stack:')
print(stack.pop())
print(stack)
print('\nStack after elements are poped:')
print(stack)
| true |
40b59d22b13152532166e69e31b4168a177d53c3 | fanya85/lesson2 | /if-2.py | 1,126 | 4.25 | 4 | """
Домашнее задание №1
Условный оператор: Сравнение строк
* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая строка 'learn', возвращает 3
* Вызвать функцию несколько раз, передавая ей разные праметры
и выводя на экран результаты
"""
def main():
one = input()
two = input()
if not one.isdigit() and not two.isdigit():
if one == two:
print(1)
elif len(one) > len(two):
print(2)
elif two == "learn":
print(3)
else:
print(666)
else:
print(0)
if __name__ == "__main__":
main()
| false |
b6a6ac69c4730e0f7ee4e2bf889271812d5f168d | ogrudko/leetcode_problems | /easy/count_prime.py | 804 | 4.15625 | 4 | '''
Problem:
Count the number of prime numbers less than a non-negative number, n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5000000
'''
# Solution
class Solution:
def count_primes(self, n: int) -> int:
is_prime = True
primes_list = []
if n < 2:
return len(primes_list)
elif n == 2:
return 1
for i in range (2, n + 1, 1):
for j in range (1, i, 1):
if i % j == 0 and j != 1:
is_prime = False
if is_prime == True:
primes_list.append(i)
is_prime = True
return len(primes_list) | true |
06aab6ad1bc538a8dbc0435ee7bd2d1f25c6d143 | AspiringOliver/kkb | /1 基础语法/课后作业/13-类与对象 练习题.py | 2,325 | 4.34375 | 4 | #self的作用:self会在类的实例化中接收传入的数据, 在代码中运行。
#类中的一个类方法需要调用另一个类方法或类属性,都需要使用self。
#总结:类方法中调用类内部属性或者是其他方法时,需要使用self来代表实例。
#1.1.0
# class Information(object): #object是所有类的父类
# def __init__(self, name):
# #初试化方法无需调用,对象实例化时自动执行
# print(name)
# self.n = name
# #此时的self.n可以理解为Information这个类的‘全局变量’
#
# def other(self, constellation, age):#累赘
# print('''
# My name is %s,
# my constellation is %s,
# Im %s years old.
# ''' % (self.n, constellation, age))
#
#
# liu = Information('Oliver')
# liu.other( 'virgo', 18) #self属性只会在方法创建的时候出现,方法调用时就不需出现
#1.2.0
# class Information(object): #object是所有类的父类
# def __init__(self, name, constellation, age):
# #初试化方法无需调用,对象实例化时自动执行
# #利用init初始化方法的特点,我们可以在初始化方法中完成类属性的创建及类属性的赋初值。
# print(name) #此时name不算类属性
# self.n = name #‘类属性’的赋初值
# self.c = constellation #‘类属性’的赋初值
# self.a = age #‘类属性’的赋初值
#
# def other(self):
# print('''
# My name is %s,
# my constellation is %s,
# Im %s years old.
# ''' % (self.n, self.c, self.a))
# #只要在othor()方法内部调用类属性(在初始化方法中)
# # ,就可以实现同样的功能,没有必要把参数再传递一遍。
#
# liu = Information('Oliver', 'virgo', 18)
# liu.other()
class Inf(object): #object是所有类的父类
def __init__(self, name, age):
self.n = name #‘类属性’的赋初值
self.a = age #‘类属性’的赋初值
def na(self):
print('''
My name is %s,
'''%self.n)
def ag(self):
print('''
Im %s years old.
'''%self.a)
ol = Inf('Oliver', 23)
ol.na(),ol.ag()
| false |
393fe94266faade066b3ca0112a434622e2dff22 | rawatsushil/datastructure | /code/DP/tushar/staircase.py | 473 | 4.15625 | 4 | # Given a staircase and give you can take 1 or 2 steps at a time, how many ways you can reach nth step.
class StairCase:
def __init__(self, steps):
self.steps = steps
self.step_arr = []
def find_steps(self):
self.step_arr.append(1)
self.step_arr.append(2)
for i in range(2, self.steps):
self.step_arr.append(self.step_arr[i-2]+self.step_arr[i-1])
return self.step_arr[self.steps-1]
if __name__ == '__main__':
s = StairCase(5)
print (s.find_steps())
| false |
b93e6ff80e0e807a8da0739d03b8a04317532fc4 | herisson31/Python-3-Exercicios-1-ao-104 | /ex017 - Catetos e Hipotenusa.py | 352 | 4.125 | 4 | '''Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo.
Calcule e mostre o comprimento da hipotenusa.'''
import math
co = float(input('Digite o cateto oposto: '))
ca = float(input('Digite o cateto adjacente: '))
h = co**2 + ca**2
hi= math.sqrt(h)
print('O valor da Hipotenusa é {}'.format(hi))
| false |
965ad1a766be9f89266e37e53b1b559864004c64 | herisson31/Python-3-Exercicios-1-ao-104 | /ex022 - Analisador de Textos.py | 533 | 4.25 | 4 | '''022: Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas e minúsculas.
- Quantas letras ao todo (sem considerar espaços).
- Quantas letras tem o primeiro nome'''
nome = input('Digite seu nome completo: ')
print('Seu nome com todas as letras Maiuscula: {}'.format(nome.upper()))
print('Seu nome com todas as letras minusculas: {}'.format(nome.lower()))
print('Seu nome tem {} letras'.format(len(nome.strip())))
print('Seu Primeiro nome tem {} letras'.format(len(nome[:9]))) | false |
0958494baedd0b356df208926b34a4a0c9c0a961 | herisson31/Python-3-Exercicios-1-ao-104 | /ex063 - Sequência de Fibonacci v1.0.py | 494 | 4.21875 | 4 | '''063: Escreva um programa que leia um número N inteiro qualquer e mostre na tela
os N primeiros elementos de uma Sequência de Fibonacci.
Ex: 0 - 1 - 1 - 2 - 3 - 5 - 8'''
print('-'*30)
print('Sequencia de Fibonacci')
print('-'*30)
n = int(input('Digite o termo da sequencia: '))
t1 = 0
t2 = 1
print('~'*30)
print('{} --> {}'.format(t1,t2), end='')
cont = 3
while cont <= n:
t3 = t1 + t2
print(' --> {}'.format(t3), end='')
t1 = t2
t2 = t3
cont += 1
print(' --> Fim')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.