blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8ee0d69f0c65d0eee9408aec3ee934678bf0c0cd | SapirLastimoza-Dooley/webgis | /gis_programming/Example_Code/If_Else/if_else_while.py | 423 | 4.3125 | 4 | # # 3. if else within while loop, give reminders to guess magic number
magic_number = 12
user_input = int(input('Guess the magic number: '))
while user_input != magic_number:
if user_input > magic_number:
print('its greater than the magic number')
else:
print('its less than the magic number')
user_input = int(input('Guess the magic number: '))
print('Congratulations, you got it!') | true |
12ada0203b4602a1226e8b93c39ed7de14054bc8 | ijpq/CMU15213 | /attacklab/rec_attack/rec5/inputs/hex2raw | 2,819 | 4.59375 | 5 | #!/usr/bin/env python3
"""
This program converts hex-encoded bytes into raw bytes, or "binary form".
For example, the character "a" is represented in ASCII by 0x61, so in order
to output that raw byte, you would provide the input "61" to this program.
This program provides the same functionality as "xxd -r -p", but it also
supports comments, and provides relevant error messages. To perform the
reverse operation (displaying a binary file as hex), use "xxd" for
human-formatted output, and "xxd -p" for plain output.
Sample usage:
$ ./hex2raw
61 62 63
^D
123
$ ./hex2raw < sample.txt > sample.bin
$ ./hex2raw sample.txt sample.bin
Authors:
Kevin Geng (khg), February 2020
"""
import argparse
import binascii
import re
import sys
def convert_hex_string(text):
# Remove all comments in the text: /* */, //, and #
# Note: this needs to be in one regex for correctness
text = re.sub(r'(/\*[\s\S]*?\*/)|(//.*$)|(#.*$)', '', text, flags=re.M)
# Search for invalid characters (not hex or whitespace)
matches = re.findall(r'[^\s0-9a-fA-F]+', text)
if matches:
print('ERROR: invalid characters in input:', file=sys.stderr)
print(', '.join(map(repr, matches)), file=sys.stderr)
print('Please use only hex characters: 0-9 and a-f.', file=sys.stderr)
exit(1)
# Remove all whitespace
text = re.sub(r'\s+', '', text)
# Make sure length is correct
if len(text) % 2 != 0:
print('ERROR: input length is odd.', file=sys.stderr)
print('Make sure each byte is represented by two hex characters.',
file=sys.stderr)
exit(1)
# Use binascii to convert and catch any errors
try:
result = binascii.unhexlify(text)
except binascii.Error as e:
print("ERROR: couldn't parse hex: {}".format(e), file=sys.stderr)
exit(1)
return result
def main():
parser = argparse.ArgumentParser(
description='Convert hex-encoded bytes into raw bytes.')
parser.add_argument('infile',
nargs='?',
type=argparse.FileType('r'),
default='-',
help='specify an input file to read from')
parser.add_argument('outfile',
nargs='?',
type=argparse.FileType('wb'),
default='-',
help='specify an output file to write to')
args = parser.parse_args()
# Make sure we write to stdout as binary, not text
if args.outfile == sys.stdout:
args.outfile = sys.stdout.buffer
text = args.infile.read()
args.infile.close()
result = convert_hex_string(text)
args.outfile.write(result)
args.outfile.close()
if __name__ == '__main__':
main()
| true |
f8571425d6fe4534638fd8350dccecb984a82598 | chazkiker2/code-challenges | /misc/capitalization_and_mutability/capitalization_and_mutability.py | 358 | 4.1875 | 4 | """
Challenge: Correct a function that takes a string and returns the first character capitalized in the string.
Difficulty: Easy
Examples:
capitalize_word("hello") ➞ "Hello"
capitalize_word("i") ➞ "I"
capitalize_word("lambda") ➞ "Lambda"
Author: @joshrutkowski
"""
def capitalize_string(word):
return "".join(char.isupper() for char in word)
| true |
47a2c81101f448b8dc46f6250c0f886c4e7dc96b | yaoxin502/Homework | /接口第1天/作业第2题.py | 678 | 4.15625 | 4 | '''
2、小明爱跑步,爱吃东西。
1)小明体重75.0公斤
2)每次跑步会减肥0.5公斤
3)每次吃东西体重会增加1公斤
4)小美的体重是45.0公斤
'''
'''
分析:
类:人
属性:姓名,体重
方法:跑步,吃东西
'''
class People():
def __init__(self,name,weight):
self.name = name
self.weight = weight
def run(self):
self.weight -= 0.5
print(f'{self.name}跑步后体重是{self.weight}')
def eat(self):
self.weight += 1
print(f'{self.name}吃东西后体重是{self.weight}')
p1 = People('小明',75.0)
p1.run()
p1.eat()
p2 = People('小美',45.0)
p2.run()
p2.eat()
| false |
455b9b26a4925da0a23c178dfe866eaa2dae507f | run22sagar/python_assignment_dec1 | /formula_(a+b).py | 302 | 4.125 | 4 | def LHS(a,b):
c=(a+b)**2
return c
def RHS(a,b):
c=(a**2)+(2*a*b)+(b**2)
return c
num1=int(input("Enter value of a"))
num2= int(input ("Enter value of b"))
X =LHS(num1,num2)
Y =RHS(num1,num2)
if X==Y:
print("LHS=RHS Hence Proved")
else :
print("LHS is not equals to RHS")
| true |
79c56d6213b41773282fb77eb46e4cdec654333e | Kirill0684/Python_GitHUB | /1/task_5.py | 418 | 4.21875 | 4 | revenue = int(input('revenue: '))
costs = int(input('costs: '))
if revenue < costs:
print('the company is unprofitable.')
elif revenue == costs:
print('zero profit company.')
else:
profitability = (revenue - costs) / revenue
print('the company is profitable. Profitability: ', profitability)
size = int(input('size of the company: '))
print('profit per 1 employee: ', (revenue - costs) / size)
| true |
d090088c0ded4d8d4c480e421c45f27628df190d | VitorBrandaoS/python-blue | /#04-For.py | 2,013 | 4.15625 | 4 | # Até agora a gente aprendeu a desviar das coisas, agora vmaos aprender a repetir elas!
# Imagina que nós queremos escrever na telá olá 5 vezes, nós teriamos que colcoar:
print('Olá')
print('Olá')
print('Olá')
print('Olá')
print('Olá')
# Mas e se eu quiser escrever isso 500 vezes? Seria inviável, por isso temos o laço for, podemos substituir o código de cima por:
for c in range(1, 6): # De 1 a 6 porque o range ignora o ultimo número.
print('Olá')
print('Fim')
# O laço for é chamado de laço com variável de controle, caso acima, o c é a variável de controle.
# Outro exemplo, pra entendermos variáveis de controle:
for c in range(0, 5):
print(c) # Vai mostrar uma contagem crescente
# Para contagens descrescentes utilize:
for c in range(5, 0, -1): # começa no 5, tira 1 (-1), até o 1 (pois o útimo é ignorado)
print(c)
# Para pular de dois em dois:
for c in range(0, 7, 2): # começa no 0, pula de 2 em 2, até o 6 (pois o útimo é ignorado)
print(c)
# Vamos a mais um exemplo:
n = int(input('Digite um número: '))
for c in range(0, n+1): # Li o n e utilizei dentro do range para contagem.
print(c)
print('Fim')
# Agora vamos receber o incio do range, o fim e o passo:
i = int(input('Digite o inicio: '))
f = int(input('Digite o fim: '))
p = int(input('Digite o passo: '))
for c in range(i, f+1, p):
print(c)
print('Fim')
# Vamos pedir varios valores no for, através do input e somar todos eles:
s = 0
for c in range(0, 4):
n = int(input('Digite um número: '))
s += n
print(f'A soma de todos os numeros é {s}')
# O in pode ser usado para Strings
for letra in 'Thiago Veiga Lima':
if letra == 'e':
print(f'Achei a letra {letra}')
print('Fim')
# EXERCÍCIOS
# Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artifício, indo de 10 até 0, com uma pausa de 1 segundo entre eles.
from time import sleep
for cont in range(10, -1, -1):
print(cont)
sleep(1)
print('FELIZ ANO NOVOOO!')
| false |
6f034a62a4a767c3962f0bd9f12f1915a28ad5bd | BasicProbability/InClassExercises2016 | /classes/exercises_solutions.py | 1,603 | 4.25 | 4 | import math
from classes.Account_solution import Account
# 1) Get all numbers whose square roots are integers (mathematical integers, not necessarily Python ints)
# from the following list. result should be assigned a list that contains the numbers and their square roots
# in tuples. That is result should be [(1,1),(4,2),....]. Only use filters and maps for this exercise!
numbers = list(range(1,10001))
result = list(map(lambda x : (x, math.sqrt(x)) ,filter(lambda x : math.sqrt(x).is_integer(), numbers)))
print("Exercise 1 seems to be correct: {}".format(len(result) == 100 and result[81] == (6724, 82.0)))
# 2) Implement the methods in the Account class.
my_account = Account(123, 1234)
your_account = Account(897, 5555, 1000)
print('Funding account works: {}'.format(my_account.deposit(100) == 100))
print('Withdrawal crashes on wrong pin: {}'.format(isinstance(my_account.withdraw(50, 1235), str)))
print('Withdrawal crashes when funds not sufficient: {}'.format(isinstance(my_account.withdraw(1000, 1234), str)))
print('Withdrawal works: {}'.format(my_account.withdraw(50,1234) == 50))
print('Equality works: {}'.format(my_account != your_account and my_account == my_account and my_account != 123))
print('Transaction crashes on wrong pin: {}'.format(isinstance(your_account.transfer_money(my_account,200,1111), str)))
print('Transaction crashes when funds not sufficient: {}'.format(isinstance(my_account.transfer_money(your_account,2000,1234), str)))
print('Transaction works: {}'.format(your_account.transfer_money(my_account,200,5555) == 800 and my_account.show_balance() == 250))
| true |
a6e0ab1b333ade81fd359a86593cdb0127d4daef | zengln/BasePY | /base.py.zln/base_variable.py | 1,350 | 4.25 | 4 | # -*- coding:utf-8 -*-
# python 基础变量
# 字符串
# '' 与 "" 只是 python 中字符串表达的不同的两种方式,除了在字符串中要对相同的字符进行转义以外,并没有任何的区别
print('I\'m "OK"')
print("I'm \"OK\"")
# 除了上述的方式外, python 中也可以使用 r''表示字符串不需要转移
print(r'\n')
print('\n')
print(r'I\'m Ok')
# 多行内容
print('''1.第一行
2.第二行
3.第三行''')
print(r'''1.第一行\n
2.第二行
''')
# 布尔值, 布尔值只有 True 和 False 两种, 可以直接使用 True 和 False 表示或者使用运算标识
print(True)
print(False)
print(1>3)
print(3>1)
# 布尔值可以用 and、or 和 not 运算
# and 运算与运算, 必须全部为 True, 结果才是 True
# or 运算或运算, 只需要有一个为 True, 结果就是 True
# not 运算非运算, 是单目运算符, 后面只能跟一个值, 结果与值相反
print(True and True)
print(False and True)
print(False and False)
print(False or True)
print(not False)
print(not 1 > 2)
# 空值
None
# 第一种以 / 作为运算符, 结果是浮点数
print("以 / 作为运算符")
print(10/3)
# 第二种以 // 作为运算符, 结果是整数
print("以 // 作为运算符")
print(10//3)
str = "Hello World!"
print(str[1:3])
print(str[1:-3])
print(str[-2:-1])
print(str + "Test")
| false |
365297f9e20527d0fc9c86f6740291cb36f1f93a | AminooZ/coding_interview | /src/coding_interview/stacks_and_queues/queue.py | 1,603 | 4.25 | 4 | from coding_interview.linked_lists.linked_lists import Node
class Queue:
def __init__(self):
self.first = None
self.last = None
def remove(self):
# Remove the first item from the queue
assert self.first is not None, "Can not remove the top item from an empty queue"
self.first = self.first.next
if self.first is None:
self.last = None
def add(self, item):
# Add an item at the end of the queue
if self.first is None:
self.first = Node(value=item)
else:
node = self.first
while node.next:
node = node.next
node.next = Node(value=item, next=None)
self.last = Node(value=item, next=None)
def peek(self):
# Return the first of the queue
assert self.first is not None, "Can not return the top item from an empty queue"
return self.first.value
def is_empty(self):
# Return True if and only if the queue is empty
return self.first is None
@classmethod
def from_list(cls, items):
# Build a queue from a list of items
queue = cls()
for item in items:
queue.add(item=item)
return queue
def to_list(self):
items = []
while not self.is_empty():
items.append(self.peek())
self.remove()
return items
def display(self):
items = []
node = self.first
while node is not None:
items.append(node.value)
node = node.next
print(items)
| true |
1773ba3f43750dd0ca6abd85060f760324756a7d | AminooZ/coding_interview | /src/coding_interview/arrays_and_strings/string_rotation.py | 501 | 4.40625 | 4 | # Assume you have a method isSubstring which checks if one word is a substring of
# another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1
# using only one call to isSubstring (e.g.,"waterbottle" is a rotation of"erbottlewat").
def is_substring(sub_string, string):
return sub_string in string
def string_rotation(string1, string2):
return is_substring(
sub_string=string1,
string=string2 + string2[:-1]
) and len(string1) == len(string2)
| true |
06e1c27e729a61de67b57441352b405c01743b4b | bokhaus/ProgrammingPortfolio | /PythonProjects/Lion/Exponent_Function.py | 1,017 | 4.8125 | 5 | # Exponents
# 2^3
print("2^3")
print(2**3)
print()
print("======================= Using a Function to calculate a power =======================")
print()
base = input("Enter number to be raised: ")
power = input("Enter to what power:")
def raise_to_power(base_num, pow_num):
result = base_num ** pow_num
return result
print(raise_to_power(int(base), int(power)))
print()
print("======================= Using a Function/For Loop to calculate a power =======================")
print()
base = input("Enter number to the base number: ")
power = input("Enter to what power:")
def raise_to_power(base_num, pow_num):
result = 1 # stores result of math
# Loop through range of numbers from 0 up to but not including the power number
# Loop through power number of times
for index in range(pow_num):
result = result * base_num # multiplying result by base number
return result # return the result of the function
print(raise_to_power(int(base), int(power)))
| true |
43ed7931e1fd98e80481eec92fed86c3fa82fec4 | bokhaus/ProgrammingPortfolio | /PythonProjects/Lion/IF_Statements.py | 1,290 | 4.40625 | 4 | # IF_Statements
# Create a Boolean Variable
is_male = False
is_tall = True
print()
print("=============================")
print("The boolean variables are set to " + str(is_male) + " = Male, " + str(is_tall) + " = Tall")
print()
print("============ Simple IF-Else Statement =================")
# Simple IF-Else Statement
if is_male:
print("You are a male")
else:
print("You are not a male")
print()
print("============== IF Statement using OR ===============")
# Simple IF-Else Statement using OR
if is_male or is_tall:
print("Your are a male or tall or both")
else:
print("You are neither male nor tall")
print()
print("============== IF Statement using AND ===============")
# Simple IF-Else Statement using AND
if is_male and is_tall:
print("Your are a tall male")
else:
print("You are either not a male or not tall or both")
print()
print("============== IF Statement using If-Elseif-Else ===============")
# Simple IF-ElseIf-Else Statement using AND
if is_male and is_tall:
print("Your are a tall male")
elif is_male and not is_tall: # not negates parameter
print("You are a short male")
elif not is_male and is_tall: # not negates parameter
print("You are not a male, but are tall")
else:
print("You are not a male and not tall")
| true |
d869f54ba1fc7e4845ebd477977b47aa8f70f684 | bokhaus/ProgrammingPortfolio | /PythonProjects/Lion/GuessingGame.py | 810 | 4.3125 | 4 | # Guessing Game
# Declare and intialize variables
secret_word = "lion"
guess = ""
# Prompt user for secret word using WHILE loop
while guess != secret_word:
guess = input("Enter guess: ")
print("You WIN!")
print("==========================================================")
print()
# Limit number of guesses a user can try before they lose
secret_word = "lion"
guess = ""
guess_count = 0
guess_limit = 3 # Guess limit is 3
out_of_guesses = False
# Prompt user for secret word using WHILE loop
while guess != secret_word and not (out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1 # increment guess count
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses, You LOSE!!!!")
else:
print("You WIN!")
| true |
04a47692d05f2038edaee951c95b3dce8b327650 | jdht1992/PythonScript | /list/exercises/list1.py | 558 | 4.21875 | 4 | weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# # Check the first letter of the attibutes in the list and if match the storage
day = []
for d in weekdays:
if d[0] == "T":
day.append(d)
else:
day.append(0)
print(day)
day = [d if d[0] == "T" else 0 for d in weekdays]
print(day)
# In this example we check if the word is in the list
day = []
for d in weekdays:
if d == "Wednesday":
day.append(d)
print(day)
day = [d for d in weekdays if d == "Wednesday"]
print(day)
| false |
aa316e388f956d300cc03ffd39a198f62be6983e | jdht1992/PythonScript | /dictionary/method_dictionaty/method_update.py | 352 | 4.15625 | 4 | car = {
"brand": "Ford",
"model": "Mustang",
"year": 1994
}
print(car)
car.update({"year": 1990})
print(car)
# The update() method insert the specifed items to the dictionary.
car.update({"color": "red"})
print(car)
# The specified items can be dictionary, or an iterable object.
car.update({"year": 1989, "color": "blue"})
print(car)
| true |
1a961ade02a71521947e5ac9bac8fc4a5b1909ee | jdht1992/PythonScript | /for/for_continues.py | 680 | 4.125 | 4 | fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
for x in fruits:
if x == "banana":
print(f"found {x}")
continue
print(x)
for x in fruits:
if x == "banana":
print(f"found {x}")
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
else:
print("Found a number", num)
| false |
9d4a346a20185b7f31f946ed69ee0dcd781c4f04 | jdht1992/PythonScript | /decorators/decorator.py | 2,061 | 4.59375 | 5 | # # Assingning function to variable
# def append_somehting(name):
# return "Appending to {}".format(name)
# #Assiging function to a variable
# append_var = append_somehting
# print(append_somehting("Diego"))
# #Output Appending to "Diego"
# # calling one function as a parameter of another function
# def append_something(name):
# return "Appending to {}".format(name)
# def calling_function(func):
# name = "Diego"
# return func(name)
# print(calling_function(append_somehting))
# #Output: Appending to Diego
# # def out_func():
# # def inner_func():
# # return "This function will be return by out_func"
# # return inner_func
# # out = out_func()
# # print(out())
# def out_func(name):
# def inner_func():
# return f"We are using the name {name} inside inner_func"
# return inner_func
# out = out_func("Diego")
# print(out())
# #Decorating function using another function
# def get_txt(name):
# return f"My name is {name}"
# def lets_decorate(func):
# def func_wrapper(name):
# return f"Hi there {name}. How are you?"
# return func_wrapper
# my_outout = lets_decorate(get_txt)
# print(my_outout("Diego"))
# Creating and using decoratirs in python using syntactic sugar
# def lets_decorate(func):
# def func_wrapper(name):
# return f"Hi there {name}. How are you"
# return func_wrapper
# @lets_decorate
# def get_txt(name):
# return f"My name is {name}"
# print(get_txt("Diego"))
# # Using decorators on method
# def lets_decorate(func):
# def func_wrapper(self):
# print("Something before the method execution")
# print(func(self))# print(func(*args, **kwargs))
# print("Something after the method execution")
# return func_wrapper
# class Example:
# def __init__(self):
# self.firststr = "first"
# self.secondstr = "second"
# @lets_decorate
# def concat_string(self):
# return f"Full string is {self.firststr} {self.secondstr}"
# out = Example()
# out.concat_string()
| false |
14682e4372c3fd0152fbccb87820b5b3dee79610 | mahnaz-ahmadi/pythonClass | /tamrin2-jalase7.py | 1,436 | 4.21875 | 4 | import sqlite3
class Person:
def __init__(self, first_name, last_name, email, age):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.age = age
def create(self):
connection = sqlite3.connect("testDb.sqlite")
cursor = connection.cursor()
query = f'CREATE TABLE IF NOT EXISTS Person (first_name TEXT,last_name TEXT,email TEXT,age INTEGER)'
cursor.execute(query)
connection.commit()
connection.close()
def save(self):
self.create()
print("hello my name is {} and {} years old. my email address is {} ".format(self.first_name + " " + self.last_name, self.age, self.email))
connection = sqlite3.connect("testDb.sqlite")
cursor = connection.cursor()
query = f'insert into person values("{self.first_name}", "{self.last_name}", "{self.email}", "{self.age}")'
cursor.execute(query)
connection.commit()
connection.close()
print("data saved in db")
connection = sqlite3.connect("testDb.sqlite")
cursor = connection.cursor()
query = f'select * from person'
result = cursor.execute(query)
for item in result:
print(item[0], item[1], item[2], item[3])
connection.commit()
connection.close()
new_person = Person("baran", "ahmadi", "baran.ahmadi@gmail.com", 4)
new_person.save();
| true |
2daf803ef8161b7f4d8d7297ea3d17168c9d09c8 | brianchiang-tw/UD1110_Intro_to_Python_Programming | /L4_Control flow/Practice_For loops.py | 550 | 4.34375 | 4 | # Practice_#1
# Quick Brown Fox
# Use a for loop to take a list and print each element of the list in its own line.
sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
# Method_#1
for word in sentence:
print(word)
# Method_#2
'''
for index in range(0, len(sentence) ):
print( sentence[index] )
'''
# Practice_#2
# Multiples of 5
# Write a for loop below
# that will print out every whole number that is a multiple of 5 and less than or equal to 30.
for number in range( 5, 31, 5):
print(number) | true |
6a9da5627643ccbdae42dcef931793605e6f29ff | brianchiang-tw/UD1110_Intro_to_Python_Programming | /L5_Functions/Quiz_Check for understanding_functions.py | 1,031 | 4.4375 | 4 |
# Q1:
# Below are some types of statements you have used.
# Can you match each piece of code with the type of statement?
size = 8
# Assignment statement
42
# Not a statement
for i in [1, 2, 3, 4, 5]:
print(i)
# for loop
string2 = "demo"
string2.lower()
# Method call
n = 3
while n > 2:
print(n)
# while loop
# Q2:
# Match each term with its description.
# A block of code that has a name, but doesn't run until we tell it to
# => Function
# A statement that makes a function run
# => Function call
# A value that we can pass to a function when we call that function
# => Argument
# A function associated with an object
# => Method
# Q4:
# Here is a call to a function named print_list_elements:
# print_list_elements(list)
# Which part of this code is referred to as an argument?
# Answer:
# list
# Q5:
# Here is a call to a function named print_list_elements:
# print_list_elements()
# Which part of this code is referred to as an argument?
# Answer:
# There is no argument in this function call. | true |
9a12978914adff618dd5df0bfada2940ab6afa6f | vaishu1312/Python-lab | /EX 3 A/EX 3 B/prime r compo.py | 275 | 4.15625 | 4 | n=int(input('enter number '))
if n>1:
for j in range(2,n):
if(n%j==0):
print(n,'is composite')
break
else:
print(n,'is prime')
elif n==1:
print('1 is neither prime nor composite')
| false |
386656e8de619be9cd788a4f0ca28598ec79d493 | vaishu1312/Python-lab | /prime comp.py | 2,902 | 4.125 | 4 | #recursion-range
def prime(n,div=None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
return False
else:
return prime(n, div-1)
else:
print(n,'is prime')
return 'True'
l=int(input('enter lower range '))
u=int(input('enter upper range '))
print('Prime nos between',l,'and',u,'are: ')
for i in range(l,u+1):
prime(i)
#recursion
def prime(n,div=None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print("Number is composite")
return False
else:
return prime(n, div-1)
else:
print("Number is prime")
return True
n=int(input('enter number '))
prime(n)
#
n=int(input('enter number '))
if n>1:
for j in range(2,n):
if(n%j==0):
print(n,'is composite')
break
else:
print(n,'is prime')
elif n==1:
print('1 is neither prime nor composite')
#FIRST N PRIME NOS-1
n=int(input('enter no '))
count=0
potentialprime = 2
def primetest(n):
for j in range(2,n):
if(n%j==0):
return False
else:
return True
while count<n:
if primetest(potentialprime) == True:
#print (potentialprime,'is prime')
print ('Prime',count + 1, 'is', potentialprime)
count += 1
potentialprime += 1
else:
#print (potentialprime,'is composite')
#count+=1
potentialprime += 1
#FIRST N PRIME NOS-2
n=int(input('enter no '))
count=0
potentialprime = 2
while count<n:
for j in range(2,potentialprime):
if(potentialprime%j==0):
break
else:
print('Prime',count + 1, 'is', potentialprime)
count += 1
potentialprime += 1
#list
l=int(input('Enter lower range '))
u=int(input('Enter upper range '))
list=[]
prime=[]
comp=[]
for k in range(l,u+1):
list.append(k)
print('the list of nos is',list)
for num in list:
for j in range(2,num):
if(num%j==0):
comp.append(num)
break
else:
prime.append(num)
print('The prime nos in the range are',prime)
print('The composite nos in the range are',comp)
l=int(input('enter lower range '))
u=int(input('enter upper range '))
print('Prime nos between',l,'and',u,'are: ')
for i in range(l,u+1):
if i>1:
for j in range(2,i):
if(i%j==0):
break
else:
print(i)
elif i==1:
print('1 is neither prime nor composite')
l=int(input('enter lower range'))
u=int(input('enter upper range'))
for i in range(l,u+1):
counter=0
for j in range(2,i):
if(i%j==0):
counter=counter+1
if(counter==0):
print(i,'is prime')
else:
print(i,'is composite')
| false |
beff566e9981606c6f4c2d93f530e6a2d33e8442 | vaishu1312/Python-lab | /EX 3 A/intbin.py | 1,040 | 4.125 | 4 |
#integer to binary conversion
num=int(input('enter num '))
if num < 0:
print('Must be a positive integer')
elif num==0:
print ('the binary no of',num,'is','0')
else:
b=0
i=1
a=num
while num>0:
r=num%2
num=num//2
b+=i*r
i=i*10
print ('the binary no of',a,'is',b)
#integer to binary conversion-function
def dec2bin(num):
if num < 0:
return 'Must be a positive integer'
elif num==0:
print ('the binary no of',num,'is',end='')
return '0'
else:
b=0
i=1
a=num
while num>0:
r=num%2
num=num//2
b+=i*r
i=i*10
print('the binary no of',a,'is ',end='')
return b
n=int(input('enter num '))
print(dec2bin(n))
#integer to binary conversion-recursion
def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2,end = '')
num=int(input('enter num '))
print ('the binary no of',num,'is ',end='')
convertToBinary(num)
#binary rep of n is binary rep of n//2 and 0 if n is divisible by 2 or else 1
| false |
df8da8a0734dd6601719e7e0e77226fdd3441dc9 | vaishu1312/Python-lab | /matrix addition.py | 1,335 | 4.15625 | 4 | # Matrix Addition
# Function - Read Matrix
def fn_read(r, c):
M = []
print("Enter values of Matrix : ")
for i in range(0,r):
M.append([])
for j in range(0,c):
print('Enter element for ','row',i+1,'and column',j+1,': ')
e=int(input())
M[i].append(e)
return M
# Function - Display Matrix
def fn_display(M):
for row in M:
for ele in row:
print(ele, end=" ")
print()
# Function - Matrix Addition
def fn_add(MA, MB, r, c):
M = []
for i in range(0,r):
M.append([])
for j in range(0,c):
ele = MA[i][j] + MB[i][j]
M[i].append(ele)
return M
# Main Program
print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))
# Addition
if ( (r1 != r2) or (c1 != c2) ):
print("Rows and columns of given matrices do not match.")
print("Cannot Add the matrices.")
else:
Mat_A = fn_read(r1, c1)
Mat_B = fn_read(r2, c2)
print("Given matrix 1 : ")
fn_display(Mat_A)
print("Given matrix 2 : ")
fn_display(Mat_B)
Mat_Add = fn_add(Mat_A, Mat_B, r1, c1)
print("Sum of given matrices : ")
fn_display(Mat_Add)
| false |
52e0613e60d1e0ae16051da197216f8afd2d51fa | SureshKrishnanSrinivasan/Python-Practise | /Regex_6.py | 226 | 4.34375 | 4 | # match a lower case string joined using underscore
import re
string = input('Please enter a number: ')
pattern = r"[a-z]+_[a-z]+$"
match = re.match(pattern, string)
if match:
print ("Match")
else:
print ("No match") | true |
b821946cfa0840068d7761a1a32e825a876075ca | SureshKrishnanSrinivasan/Python-Practise | /Regex_14.py | 245 | 4.1875 | 4 | # Write a Python program where a string will start with a specific number.
import re
string = input('Please enter a word: ')
pattern = r"\d+(\w)+"
match = re.search(pattern, string)
if match:
print (match.group())
else:
print ("No match") | true |
c22c0561c01f4452adbc6dc9c25c2ca43e3d04ae | ariasamandi/python_OOP_2 | /bike_2.py | 828 | 4.21875 | 4 | class Bike(object):
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = 0
def display_info(self):
print "Price: ", self.price
print "max speed: ", self.max_speed
print "miles: ", self.miles
return self
def ride(self):
print "Riding"
self.miles += 10
return self
def reverse(self):
print "Reversing"
if self.miles <= 5:
self.miles = 0
else:
self.miles -= 5
return self
bike1 = Bike('200', '20', '0')
bike2 = Bike('100', '10', '0')
bike3 = Bike('1', '1', '0')
print bike1.ride().ride().ride().display_info()
print bike2.ride().ride().reverse().reverse().display_info()
print bike3.reverse().reverse().reverse().display_info() | false |
c28f4bf947237bdf2cf7ed3f416599bc0c5ad9ad | kranthikar/Guvi | /python/778.py | 429 | 4.15625 | 4 | '''You are provided with a number "N", Find the Nth term of the series: 1, 4, 9, 25, 36, 49, 64, 81, .......
(Print "Error" if N = negative value and 0 if N = 0).
Input Description:
An integer N is provided to you as the input.
Output Description:
Find the Nth term in the provided series.
Sample Input :
18
Sample Output :
324'''
code
N=int(input())
a=N*N
if(N==0):
print("0")
elif(N>0):
print(a)
else:
print("Error")
| true |
8086a0aeb19502000892c8a4503bce8e24c3756d | kranthikar/Guvi | /python/776.py | 591 | 4.59375 | 5 | '''You are provided with the radius of a circle "A". Find the length of its circumference.
Note: In case the output is coming in decimal, roundoff to 2nd decimal place. In case the input is a negative number, print "Error".
Input Description:
The Radius of a circle is provided as the input of the program.
Output Description:
Calculate and print the Circumference of the circle corresponding to the input radius up to two decimal places.
Sample Input :
2
Sample Output :
12.57'''
code
import math
A=float(input())
a=2*math.pi*A
b=round(a,2)
if(A>=0):
print(b)
else:
print("Error")
| true |
a3fd42a75c0f0f092a03c08af2655549ea8f605a | s1len0eye/python_learning | /Chapter 4/4.13buffet.py | 247 | 4.1875 | 4 | foods = ('rice', 'tomato', 'potato', 'carrot', 'meat')
print("Original foods:")
for food in foods:
print(food)
#foods[1] = 'fake'
foods = ('rice', 'apple', 'potato', 'orange', 'meat')
print("\nNew foods:")
for food in foods:
print(food)
| false |
c4b2ea76546d0c3e5f5ccf7a214d9a82c96cd125 | sadOskar/courses | /lesson_4/calculator.py | 561 | 4.15625 | 4 |
number_1 = int(input('Введите первое число: '))
operation = input('Введите одну из операций +, -, *, /: ')
number_2 = int(input('Введите второе число: '))
if operation == '+':
print('total:', number_1 + number_2)
elif operation == '-':
print('total:', number_1 - number_2)
elif operation == '*':
print('total:', number_1 * number_2)
elif operation == '/':
if number_2 != 0:
print('total:', number_1 / number_2)
else:
print('На ноль делить нельзя!') | false |
1053b8e19974f68db93c2bdf3f5528d0addc073c | Indrashish/Python-Projects | /Calculator.py | 1,964 | 4.46875 | 4 | # Python script to implement the basic functionality of a scientific calculator
# Below methods defining the following functionality respectively
# 1.Add 2.Subtract 3.Multiply 4.Divide
class Calculator:
# Add
def add(self, num1, num2):
return num1 + num2
# Subtract
def sub(self, num1, num2):
return num1 - num2
# Multiply
def mul(self, num1, num2):
return num1 * num2
# Divide
def div(self, num1, num2):
try:
return num1 / num2
except Exception as err:
raise Exception("Division by zero not possible!")
return 0
# performoperation: Method which performs operation as per user input
def performoperation(self, option, num1, num2):
print("Option =", option)
if option == 1:
print("Ready to add")
print(self.add(self, num1, num2))
elif option == 2:
print("Ready to subtract")
print(self.sub(self, num1, num2))
elif option == 3:
print("Ready to multiply")
print(self.mul(self, num1, num2))
elif option == 4:
print("Ready to divide")
print(self.div(self, num1, num2))
else:
print("Operation not valid")
# Main function
def main(self):
while True:
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
option = int(input("What do you want to do? 1. Add 2. Subtract 3. Multiply 4. Divide. Enter your choice: "))
self.performoperation(self, option, num1, num2)
# We ask user if they want to use the calculator further
user_input = int(input("Do you want to continue? 1. Yes 2. No"))
if(user_input != 1):
print("Exiting Calculator.....")
break
cal = Calculator
Calculator.main(cal)
#main()
#if __name__ == '__main__':
# main()
| true |
7b69c95987b167b894fe1c29cea6cd87ae8a2d47 | rRiks/spectrumTask1 | /q6.py | 975 | 4.15625 | 4 | #Program to create simple calculator in Python which on input of 1,2,3,4 should add , subtract , multiply and divide respectively.
def addition(a , b):
return a + b
def subtraction(a , b):
return a - b
def multiplication(a , b):
return a * b
def division(a , b):
return a / b
print('select an operation :')
print('1.Addition')
print('2.Subtraction')
print('3.Multiplication')
print('4.Division')
while True:
choice = input('enter operation type(1 or 2 or 3 or 4 ) : ')
if choice in ('1' , '2' , '3' , '4'):
n1 = float(input('enter the first number : '))
n2 = float(input('enter the second number : '))
if choice == '1' :
print(n1 , '+' , n2 , ' = ' ,addition(n1,n2))
elif choice == '2' :
print(n1 , '-' , n2 ,' = ' ,subtraction(n1 , n2))
elif choice == '3' :
print(n1 , '*' , n2 , ' = ' ,multiplication(n1 , n2))
elif choice == '4' :
print(n1 , '/' , n2 , ' = ' ,division(n1 , n2))
else:
print('invalid choice') | false |
a2b6e3a5c22996d0f30fba405fe0658df8741bca | rRiks/spectrumTask1 | /q4.py | 605 | 4.21875 | 4 | #Get the key corresponding to the minimum value from the following dictionary using appropriate python logic.
def minimums(givenDictionary):
positions = []
min_value = float("inf")
for k, v in givenDictionary.items():
if v == min_value:
positions.append(k)
if v < min_value:
min_value = v
positions = []
positions.append(k)
return positions
sample = {'physics' : 88 , 'maths' : 75 , 'chemistry' : 72 , 'Basic electrical' : 89 }
minKey = minimums(sample)
print('The minimum valued key in the dictionary is : ' ,minKey) | true |
bdd36b6746294e4cf3c1684f8837392b755eef44 | elclass1co/basic_python | /lesson_1/task1_1.py | 847 | 4.375 | 4 | # Реализовать вывод информации о промежутке времени в зависимости от его продолжительности duration в секундах:
# до минуты: <s> сек;
# * до часа: <m> мин <s> сек;
# * до суток: <h> час <m> мин <s> сек;
# * *до месяца, до года, больше года: по аналогии.
duration = int(input('Введите продолжительность в секундах: '))
days = duration // 86400
if days > 0:
duration = duration - (86400 * days)
hours = duration // 3600
if hours > 0:
duration = duration - (3600 * hours)
minutes = duration // 60
if minutes > 0:
duration = duration - (60 * minutes)
seconds = duration
print(f"Дн {days}, час {hours}, мин {minutes}, сек {seconds}")
| false |
6c9a428a93d0bf7faad3c41e667938d8d8376475 | reks93/Python | /day5_Python_Lists.py | 837 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 22:46:11 2020
@author: Rekha
"""
#Question 5: Given a two list. Create a third list by picking an odd-index element from the first list and even index elements from second.
print("My Program to append 2 lists")
list1len = int(input("Enter length of list 1"))
list2len = int(input("Enter length of list 2"))
list1= []
list2= []
list3 = []
print("Enter list1 elements")
for i in range(list1len):
v = int(input("Element"))
list1.append(v)
print(list1)
print("Enter list2 elements")
for j in range(list2len):
y = int(input("Element"))
list2.append(y)
print(list2)
list1 = list1[1::2]
list2 = list2[0::2]
print("odd index list :", list1)
print("even index list :", list2)
list3.extend(list1)
list3.extend(list2)
print("consolidted list :", list3) | true |
2ae4631bff7582ce4f81b5483f0652faa5799356 | reks93/Python | /day36_astrologicalsign.py | 1,745 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 16:44:40 2020
@author: rekha
"""
#Question 36: Write a Python program to display astrological sign for given date of birth. The input date of birth should be a single string in the format “dd-mm-yyyy”.
def zodiac_sign(day, month):
astro_sign = ''
if month == '12':
astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'
elif month == '01':
astro_sign = 'Capricorn' if (day < 20) else 'aquarius'
elif month == '02':
astro_sign = 'Aquarius' if (day < 19) else 'pisces'
elif month == '03':
astro_sign = 'Pisces' if (day < 21) else 'aries'
elif month == '04':
astro_sign = 'Aries' if (day < 20) else 'taurus'
elif month == '05':
astro_sign = 'Taurus' if (day < 21) else 'gemini'
elif month == '06':
astro_sign = 'Gemini' if (day < 21) else 'cancer'
elif month == '07':
astro_sign = 'Cancer' if (day < 23) else 'leo'
elif month == '08':
astro_sign = 'Leo' if (day < 23) else 'virgo'
elif month == '09':
astro_sign = 'Virgo' if (day < 23) else 'libra'
elif month == '10':
astro_sign = 'Libra' if (day < 23) else 'scorpio'
elif month == '11':
astro_sign = 'scorpio' if (day < 22) else 'sagittarius'
return astro_sign
print("FIND your Astro sign based on birth date:\n")
dob = input("Enter you dob in the format “dd-mm-yyyy” ")
dayarr = dob.split("-")
day = int(dayarr[0])
month = dayarr[1]
print(zodiac_sign(day, month) )
| false |
832610e16fb6e81e1e4bb7be1b6e6f43511f4094 | reks93/Python | /day21_classes.py | 1,893 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 23:07:49 2020
@author: rekha
"""
#Question 21: Create a Parent Class “Vehicle” and 3 child classes “Bus”, “Car” and “Motorcycle”. All child classes should inherit all the properties of parent class and also has its own specific properties. Print one specific brand in each vehicle with specific property values.
#Vehicle Properties:
#Name:
#No of seats:
#Number of tyres:
#Child Class specific property:
#Brand:
class Vehicle:
def __init__(self , name , seats , tyres):
self.Vname = name
self.Vseats = seats
self.Vtyres = tyres
class Bus(Vehicle):
def __init__(self, name , seats , tyres , brand):
super().__init__(name , seats , tyres)
self.VBrand = brand
def printBus(self):
print("Name :" , self.Vname , "\nType:" , type(self).__name__ ,"\nBrand:" , self.VBrand , "\nNo of seats:" , self.Vseats , "\nNo of tyres:" , self.Vtyres ,"\n")
class Car(Vehicle):
def __init__(self, name , seats , tyres , brand):
super().__init__(name , seats , tyres)
self.VBrand = brand
def printCar(self):
print("Name :" , self.Vname , "\nType:" , type(self).__name__ ,"\nBrand:" , self.VBrand , "\nNo of seats:" , self.Vseats , "\nNo of tyres:" , self.Vtyres,"\n")
class Motorcycle(Vehicle):
def __init__(self, name , seats , tyres , brand):
super().__init__(name , seats , tyres)
self.VBrand = brand
def printmotorcycle(self):
print("Name :" , self.Vname , "\nType:" , type(self).__name__ ,"\nBrand:" , self.VBrand , "\nNo of seats:" , self.Vseats , "\nNo of tyres:" , self.Vtyres,"\n")
bus = Bus("Traveller" , 28 , 6 ,"Volvo" )
car = Car("Swift" , 5 , 4 ,"Maruti" )
MC = Motorcycle("Pulsar" , 2 , 2 ,"Bajaj" )
bus.printBus()
car.printCar()
MC.printmotorcycle() | true |
01d4eed2028d7ead90a0d013d9a5b13961a30424 | reks93/Python | /day29_Infinitenumber.py | 436 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 22:31:17 2020
@author: rekha
"""
#Question29:check if a given number is infinite or not
import math
def isinfinite(num):
if(math.isinf(num)):
print("The number {} is infinite:" .format(num))
else:
print("The number {} is not infinite:" .format(num))
a = -300
b = float(math.inf)
c= float(-math.inf)
isinfinite(a)
isinfinite(b)
isinfinite(c) | false |
ba3525121ce729194ed6018bee208146ae097a06 | reks93/Python | /Day11_Arraylengthreverse.py | 645 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 21:08:42 2020
@author: Rekha
"""
#Question11:Printing the length of an array in reverse order
#For this problem, you need to print the length of the arrays provided to you in the test cases in reverse order, i.e. the length of the last array provided as input will be printed first.
n = int(input("Enter the length of the array"))
#lists = [ [] for i in range(n)]
stringlist = []
listoflist = []
for i in range(n):
inp = input().split()
stringlist = [int(j) for j in inp]
listoflist.append(stringlist)
for j in listoflist[len(listoflist)::-1]:
print(len(j)) | true |
4beda0efe4f7559fcaf419b2df13468152adbc94 | Parth1906/Arithmetic-operators | /arithmeticoperators | 395 | 4.21875 | 4 | # Examples of Arithmetic Operator
a = 9
b = 4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
| true |
446dce061272ed8afa428fad2d208d0751e94e0a | RainbowLegend/my_first_binary_converter | /other/4-bit.py | 946 | 4.15625 | 4 | print('Welcome to my first converter!!!!')
num = input('Whats your number???')
if '0000' == num:
print('The number is 0!!!')
if '0001' == num:
print('The number is 1!!!')
if '0010' == num:
print('The number is 2!!!')
if '0011' == num:
print('The number is 3!!!')
if '0100' == num:
print('The number is 4!!!')
if '0101' == num:
print('The number is 5!!!')
if '0110' == num:
print('The number is 6!!!')
if '0111' == num:
print('The number is 7!!!')
if '1000' == num:
print('The number is 8!!!')
if '1001' == num:
print('The number is 9!!!')
if '1010' == num:
print('The number is 10!!!')
if '1011' == num:
print('The number is 11!!!')
if '1100' == num:
print('The number is 12!!!')
if '1101' == num:
print('The number is 13!!!')
if '1110' == num:
print('The number is 14!!!')
if '1111' == num:
print('The number is 15!!!')
print('Thanks for using my calculator!!!!')
| true |
8322ee1f2d360cf57d56bce09d1a4f66296abb27 | MateoMinghi/Data_Structures_and_Algorithms | /Data_Structures/singly_linked_list.py | 894 | 4.28125 | 4 | #implementation of a linked list
#further explanation in the README file
class Node: #The objects will be the nodes that go into the list
def __init__(self, data):
self.data = data
self.next = None
class LinkedList: #this class contains the methods to insert, remove, traverse or sort the list
# Function to initialize head
def __init__(self):
self.head = None
def printList(self): # This function prints contents of linked list
temp = self.head
while (temp):
print (temp.data)
temp = temp.next
if __name__=='__main__':
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second; # Link first node with second
second.next = third; # Link second node with the third node
llist.printList()
| true |
827851b29754d981b7157071eb0977a36ec85df0 | MateoMinghi/Data_Structures_and_Algorithms | /Data_Structures/Hash_Tables.py | 796 | 4.25 | 4 | #more info on hash tables in README file
#the equivalent to a hash table in python is the dictionary
dictionary = { 'Food': 'Pizza',
'Dessert': 'Ice Cream'}
print(dictionary)
#program to implement a hash function
#create the class
class HashTable(object):
def __init__(self): #initialize instance
self.table = [None]*10000
#this function calculates the hash value by using the built-in method ord()
#adding a numeric values to a character. Multiplies that by 100 and adds the ord() value of the second character in the string
def calculate_hash_value(self, string):
value = ord(string[0])*100 + ord(string[1])
return value
if __name__ == '__main__':
hash_table = HashTable()
print(hash_table.calculate_hash_value('Pizza'))
| true |
a1cf6e48ab33c3c0495b6afd832dd538b54b227b | dabarre/etsinf3 | /SAR/P1/SAR_p1_piglatin.py~ | 2,614 | 4.25 | 4 | #!/usr/bin/env python
#! -*- encoding: utf8 -*-
"""
1.- Pig Latin
Nombre Alumno: Alberto Romero Fernández
Nombre Alumno: David Barbas Rebollo
"""
import sys
legalChar='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
vocal='aeiouyAEIOUY'
punctuation=',.;?!'
def piglatin_word(word):
"""
Esta función recibe una palabra en inglés y la traduce a Pig Latin
:param word: la palabra que se debe pasar a Pig Latin
:return: la palabra traducida
"""
# COMPLETAR
#
# DiN'T MODIFY STRINGS
#
isupper = ""
#Remove punctuation
p = 0
for i in range(len(word)-1,-1,-1) :
if (word[i] in punctuation) :
p += 1
else :
break
ending = word[(len(word)-p):]
word = word[:(len(word)-p)]
if (word.isalpha()) :
if (word.isupper()) :
isupper = "all"
elif (word[0].isupper()) :
isupper = "first"
#Traducir
word = word.lower()
aux = 0
for i in range(len(word)) :
if (word[i] in vocal) :
break
aux += 1
if (i == 0) :
word += "y"
word = word[i:] + word[:i] + "ay"
if (isupper == "all") :
word = word.upper()
if (isupper == "first") :
word = word[0].upper() + word[1:]
return word + ending
def piglatin_sentence(sentence):
"""
Esta función recibe una frase en inglés i la traduce a Pig Latin
:param sentence: la frase que se debe pasar a Pig Latin
:return: la frase traducida
"""
# COMPLETAR
lista = []
for word in sentence.split() :
lista.append(piglatin_word(word))
sentence = " ".join(lista)
return sentence
if __name__ == "__main__":
if len(sys.argv) > 1:
# CMPLETAR
if (sys.argv[1] != "-f") :
print(piglatin_sentence(sys.argv[1]))
else :
filename = sys.argv[2]
if (not filename.endswith(".txt")) :
print("Error! file " + filename + " does not exist.")
exi()
newfilename = filename[:-4] + "_piglatin.txt"
fr = open(filename, "r")
fw = open(newfilename, "w")
lines = fr.read()
for line in lines.split("\n") :
fw.write(piglatin_sentence(line) + "\n")
fw.close()
fr.close()
else:
while True:
# COMPLETAR
text = input("English: ")
if (text == "") :
break
print("Piglatin: " + piglatin_sentence(text)) | false |
c5d8b33cfe68916fbb74d71f259fb1dd6d8c4478 | BryantCabrera/python-func-lab | /function_product.py | 321 | 4.375 | 4 | """
4. Write a function named product() that takes an arbitrary number of parameters, multiplies them all together, and returns the product. (HINT: Review your notes on *args).
"""
def product(*parameters):
product = 1
for parameter in parameters:
product *= parameter
print(product)
product(1, 5, 4) | true |
fc3d0562cc23062840549bda53501c10335983ec | amirtha4501/PythonExercises | /decbincon.py | 696 | 4.1875 | 4 | # Decimal to binary conversion without using recursion
li = []
def dec_bin(val):
print("Binary number without using recursion")
while val > 1:
a = val % 2
li.append(a)
val = val//2
li.append(val)
for i in range(len(li)-1, -1,-1):
print(li[i],end=" ")
# Decimal to binary conversion using recursion
l = []
def dec_bin_recursion(val):
if val > 1:
dec_bin_recursion(val//2)
a = val % 2
l.append(a)
elif val == 1:
l.append(val)
else:
pass
n = int(input("Decimal Number : "))
dec_bin(n)
print("")
dec_bin_recursion(n)
print("Binary number using recursion")
for i in l:
print(i,end=" ")
| false |
6205c890ed3777060a6c075395f627ee351e1c83 | Liudeimiao/LearnPythonGithub | /jingxiao/01list&tuple/list_tuple.py | 1,833 | 4.15625 | 4 |
#列表和元组
#
l = [1, 2, 3, 4]
l[3] = 40 # 和很多语言类似,python 中索引同样从 0 开始,l[3] 表示访问列表的第四个元素
print(l)
[1, 2, 3, 40]
#模仿
list_01 = [5,6,7,8]
list_01[3] = 50
print(list_01)
tup = (1, 2, 3, 4)
new_tup = tup + (5, ) # 创建新的元组 new_tup,并依次填充原元组的值
print(new_tup[-1])
(1, 2, 3, 4, 5)
l = [1, 2, 3, 4]
l.append(5) # 添加元素 5 到原列表的末尾
l
[1, 2, 3, 4, 5]
##切片操作
list_01 = [1, 2, 3, 4]
l[1:3] # 返回列表中索引从 1 到 2 的子列表
print(list_01[1:3])
tup = (1, 2, 3, 4)
tup[1:3] # 返回元组中索引从 1 到 2 的子元组
print(tup[1:3])
#随意嵌套
l = [[1, 2, 3], [4, 5]] # 列表的每一个元素也是一个列表
print(l)
tup = ((1, 2, 3), (4, 5, 6)) # 元组的每一个元素也是一元组
print(tup)
# 3.4 列表和元组可以通过 list_01() 和 tuple() 互相转换
# 如果list_01变量和list_01函数重名 TypeError: 'list_01' object is not callable
list((1,2,3))
print(list((1, 2, 3)))
#tuple([1, 2, 3])
#print(tuple([1, 2, 3]))
#常用内置函数
l = [3, 2, 3, 7, 8, 1]
print(l.count(3)) # # count(item) 表示:统计列表/元组中 item 出现的次数
t = ("L",7,"L",77);
print(t.count("L"))
print(l.index(7)) # index(item) 表示:返回列表/元组 中 item 第一次出现的索引
# 2
# l.index(7)
# 3
l.reverse() # 原地反转列表
print(l)
l.sort()# 排序列表
print(l)
# l
# [1, 8, 7, 3, 2, 3]
# l.sort()
# l
# [1, 2, 3, 3, 7, 8]
#
tup1 = (3, 2, 3, 7, 8, 1)
# tup.count(3)
# 2
# tup.index(7)
# 3
tup2 = reversed(tup1) # reversed() 和sorted() 都能对元组和列表进行反转和排序。但是会生成一个新的元组和列表
print(list(tup2))
# [1, 8, 7, 3, 2, 3]
tup4 = sorted(tup1) #
print(tup4)
# [1, 2, 3, 3, 7, 8]
| false |
a0a36b65fc7725fbb7aeb2125de360525380fdab | DeepaShrinidhiPandurangi/Problem_Solving | /HackerRank/Interview_Preparation_Kit/Warmup_1_List_Match_Socks.py | 2,781 | 4.28125 | 4 | ''' Warm-up 1:
John works at a clothing store. He has a large pile of socks that he must pair by color for sale.
Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are n=7 socks with colors ar = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 .
There are three odd socks left, one of each color. The number of pairs is 2.
Function Description
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers describing the colors of the socks in the pile.
Constraints
1<=n<=100
1<=ar[i]<= 100 where 0<=i<=n
where
Output Format
Return the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
'''
# Without function
ar = list(map(int, input("Enter the integers with a space in between: ").split()))# Note this step. Converts input with spaces into list
print(ar)
unique=[]
pairs=0
extras=0
# To find out unique elements of a list
for i,j in enumerate(ar):
if j not in unique:
unique.append(ar[i])
#print(unique)
for i,j in enumerate(unique):
counter= ar.count(unique[i])
#print("The count of",unique[i],"is:",counter)
if counter%2 == 0:
pairs = pairs+counter//2
else:
pairs= pairs+counter//2
extras= extras+1
print(pairs)
print(extras)
'''
# The code that worked on the website:
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
unique=[]
pairs=0
extras=0
# To find out uniue elements of a list
for i,j in enumerate(ar):
if j not in unique:
unique.append(ar[i])
#print(unique)
for i,j in enumerate(unique):
counter= ar.count(unique[i])
#print("The count of",unique[i],"is:",counter)
if counter%2 == 0:
pairs = pairs+counter//2
else:
pairs= pairs+counter//2
extras= extras+1
return pairs
#print(extras)
# Given by them: ****Note this procedure****
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()'''
| true |
29a6346034363784bac6008033889553ef3ef403 | DeepaShrinidhiPandurangi/Problem_Solving | /Programs/Tuples_Lists_Dictionaries_Sets/All_the_same.py | 1,946 | 4.375 | 4 | #Check if all the elements of the list are the same.
# Note : Print True if yes. Else print False. It is True if the number of elements are 0 or 1.
def all_the_same(List):
# identify the distinct elements of the list. If the distinct elements > 1 , then the list elements are not equal
List1 =[] # empty list, here we compare the given list to an empty list to get the distinct elements
for i in List:
if i not in List1:
List1.append(i)
if len(List1)> 1:
return False
else:
return True
print(all_the_same([1, 1, 1, 1]))
print(all_the_same([1, 2, 1 ,2]))
print(all_the_same(['b','a', 'a', 'a','b']))
print(all_the_same([]))
print(all_the_same(['c']))
# Soln.2
def all_the_same(List):
count=0
if len(List) == 0 or len(List) == 1:
return True
else:
for i in range(0,len(List)):
for j in range (0,len(List)): # if you set the range 0,i or 0,i+1 ,do not use break as it will terminate after i = 0
if List[i]!= List[j]: # left side element should remain the same,and compared with different right side elements .
count = count+1
break # Outer most loop break.Can break cause 1 iteration of i is enough.
#print(count)
if count == 0:
return True
else:
return False
print(all_the_same([1, 1, 1, 1]))
print(all_the_same([1, 2, 1 ,2]))
print(all_the_same(['b','a', 'a', 'a','b']))
print(all_the_same([]))
print(all_the_same(['c']))
# Soln 3
# Check io soln
def all_the_same(elements):
return all(x == y for x, y in zip(elements, elements[1:])) #The all() function returns True if all items in an iterable are true, otherwise it returns False.
print(all_the_same([1, 1, 1, 1]))
print(all_the_same([1, 2, 1 ,2]))
print(all_the_same(['b','a', 'a', 'a','b']))
print(all_the_same([]))
print(all_the_same(['c']))
'''
o/p:
True
False
False
True
True
''' | true |
f30c2d91a514082dc2f57c63a73e142208bda684 | DeepaShrinidhiPandurangi/Problem_Solving | /HackerRank/Algorithms/Strings/CamelCase.py | 1,167 | 4.65625 | 5 | # CamelCase
'''
There is a sequence of words in CamelCase as a string of letters,s , having the following properties:
It is a concatenation of one or more words consisting of English letters.
All letters in the first word are lowercase.
For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase.
Given , determine the number of words in .
Example :oneTwoThree
There are words in the string: 'one', 'Two', 'Three'.
Function Description
Complete the camelcase function in the editor below.
camelcase has the following parameter(s):
string s: the string to analyze
Returns
int: the number of words in
Input Format
A single line containing string .
Constraints : string len greater than 1, less than 10^5
Sample Input
saveChangesInTheEditor
Sample Output
5
'''
import string
s = "saveChangesInTheEditor"
if len(s) == 0:
print(0)
else:
count = 1
for i in range(0,len(s)):
if s[i] in string.ascii_uppercase: # The other way (searching a smaller string in bigger one doesn't work.
count+=1
print(count)
# Using regex
import sys
import re
s = input().strip()
print(len(re.findall(r'[A-Z]', s)) + 1) | true |
20097cc56e7e019c4728252b8c46444ab81c2083 | DeepaShrinidhiPandurangi/Problem_Solving | /HackerRank/Strings/Making anagrams shorter code.py | 2,131 | 4.21875 | 4 | #Making anagrams,shorter code
'''Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.
Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?
Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings.
For example, if a=cde and b=dcf , we can delete e from a string and f from b string so that both remaining strings are cd and dc which are anagrams.
Function Description
Complete the makeAnagram function in the editor below. It must return an integer representing the minimum total characters that must be deleted to make the strings anagrams.
makeAnagram has the following parameter(s):
a: a string
b: a string
Input Format
The first line contains a single string, .
The second line contains a single string, .
Constraints
The strings and consist of lowercase English alphabetic letters ascii[a-z].
Output Format
Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.
Sample Input
cde
abc
Sample Output
4
We delete the following characters from our two strings to turn them into anagrams of each other:
Remove d and e from cde to get c.
Remove a and b from abc to get c.
We must delete characters to make both strings anagrams, so we print on a new line.'''
a="fcrxzwscanmligyxyvym"
b="jxwtrhvujlmrpdoqbisbwhmgpmeoke"
import string
L_a =[]
L_b =[]
alpha = string.ascii_lowercase
for i in alpha:
L_a.append(a.count(i))
L_b.append(b.count(i))
res = [ abs(a-b) for a,b in zip(L_a,L_b)]
print(sum(res))
| true |
0effbda54d0a6e4837895b2e51dbcf69ec227d0d | Hyper-Devil/learn-python3 | /10.inherit.py | 2,746 | 4.25 | 4 | class Animal(object):
def run(self):
print('Animal is running...')
alan = Animal()
alan.run()
class Dog(Animal):
pass
# *对于Dog来说,Animal就是它的父类,对于Animal来说,Dog就是它的子类。
# *子类获得了父类的全部功能,自动拥有了run()方法
class Cat(Animal):
def run(self):
print('Cat is running...')
def eat(self):
print('Catching mouse...')
Bob = Dog()
Bob.run()
Jack = Cat()
Jack.run()
# *子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这就是:多态。
'''
要理解什么是多态,我们首先要对数据类型再作一点说明。当我们定义一个class的时候,我们实际上就定义了一种数据类型。
我们定义的数据类型和Python自带的数据类型,比如str、list、dict没什么两样
因为Dog是从Animal继承下来的,当我们创建了一个Dog的实例c时,我们认为c的数据类型是Dog没错,但c同时也是Animal也没错,Dog本来就是Animal的一种
所以,在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行
'''
def run_twice(animal):
# ?这里理解为函数还是方法?
animal.run()
animal.run()
run_twice(Animal())
run_twice(alan)
run_twice(Jack)
class Tortoise(Animal):
def run(self):
print('Tortoise is running slowly...')
run_twice(Tortoise())
# *新增一个Animal的子类,不必对run_twice()做任何修改
# *实际上,任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态。
'''
多态的好处就是,当我们需要传入Dog、Cat、Tortoise……时,我们只需要接收Animal类型就可以了,因为Dog、Cat、Tortoise……都是Animal类型,
然后,按照Animal类型进行操作即可。由于Animal类型有run()方法,因此,传入的任意类型,只要是Animal类或者子类,就会自动调用实际类型的run()方法,这就是多态的意思:
对于一个变量,我们只需要知道它是Animal类型,无需确切地知道它的子类型,就可以放心地调用run()方法,
而具体调用的run()方法是作用在Animal、Dog、Cat还是Tortoise对象上,由运行时该对象的确切类型决定,
这就是多态真正的威力:调用方只管调用,不管细节,而当我们新增一种Animal的子类时,只要确保run()方法编写正确,不用管原来的代码是如何调用的。
这就是著名的“开闭”原则:
对扩展开放:允许新增Animal子类;
对修改封闭:不需要修改依赖Animal类型的run_twice()等函数。
'''
| false |
c31748577b65e0370c41485b6c47d9a06f2c5274 | Hyper-Devil/learn-python3 | /old/fx.py | 550 | 4.1875 | 4 | # 无参数
def print_hello():
print("hello")
print_hello()
# 带参数 fuckfuck
def print_str(s):
print(s)
return s * 2
r = print_str("fuck")
print(r)
# 带默认参数
def print_default(s="hello"):
print(s)
print_default()
print_default("default")
# 不定长参数
def print_args(s, *arg):
print(s)
for a in arg:
print(a)
return
print_args("hello")
print_args("hello", "world", "1")
# 参数次序可以变
def print_two(a, b):
print(a, b)
print_two(a="a", b="b")
print_two(b="b", a="a")
| false |
0333124d038af0d77d32eabf7c1955ebf81bdfe4 | Hyper-Devil/learn-python3 | /sample/6.listtuple.py | 943 | 4.28125 | 4 | classmates = ['Michael', 'Bob', 'Tracy']
# list是一种有序的集合,可以随时添加和删除其中的元素。使用方括号[]
print(len(classmates))
print(classmates)
print(classmates[0])
print(classmates[1])
# 索引从0开始
print(classmates[-1])
# 倒数第一个元素
classmates.append('Adam')
print(classmates)
classmates.insert(1, 'Jack')
# 插入‘Jack’到第二个位置
print(classmates)
classmates.pop()
# 删除末尾元素
print(classmates)
classmates.pop(1)
# 删除索引位置元素
print(classmates)
classmates[1] = 'Sarah'
# 通过直接赋值来替换索引位置元素
print(classmates)
classmates = ('Michael', 'Bob', 'Tracy')
# 元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改,使用圆括号()
print(classmates)
# 可以同名
t = (1,)
# 如果定义的tuple只有一个元素,需要加上逗号,与小括号区分开
print(t)
# 输出的时候也会显示逗号
| false |
78c05ae2a4983fdf927d3f89363767305f64ddd7 | khasherr/SummerOfPython | /InsertionSort.py | 695 | 4.3125 | 4 | #Sher Khan
#insertion sort - just like sorting deck of cards with hands 1) pile sorted and second pile not sorted
#always compare to previous one elements in the deck.
def InsertionSort(array):
length = len(array)
#compare it with previous index, can not start at 0 because nothing previous to it.
for index in range(1,length):
j = index -1 #compare to the previous index
value = array[index] # value at index
while(j>= 0 and array[j] > value): #shifting elements till this condition holds
array[j+1] = array[j]
j = j -1
array[j+1] = value #correct position
array = [3,1,2,0,5]
InsertionSort(array)
print(array) | true |
57cc509320520e1f457a0d7614e8d87626e03c3a | khasherr/SummerOfPython | /MergeTwoSortedArrays.py | 1,444 | 4.15625 | 4 | #Sher Khan
#Merge Sort - 2 arrays - 1) sort them 2) compare i & j 3) append to the new array 4) append the left overs
def mergeSort(array1, array2):
i = 0 #pointer for array 1
j = 0 #pointer for array 2
len1 = len(array1)
len2 = len(array2)
finalArray = [] #finalarray is empty
while((i < len1) & (j < len2)):
if (array1[i] < array2[j]): #checks if value at array1 is less than value at array 2
finalArray.append(array1[i]) #add the the value to the new array
i = i+1
else:
finalArray.append(array2[j]) #else add the j value in the second array
j = j+1 #increment j
while(i < len1): # condition for dont want left over elements
finalArray.append(array1[i]) #append the left over elements to array
i = i+1 #increment
while(j < len2): #condition for dont want left over elment in array2
finalArray.append(array2[j]) #append the element in array2 to the final array
j = j +1 #increment
return finalArray
n1 = int(input())
array1 = list(int(i)for i in input().strip().split(' '))
n2 = int(input())
array2 = list(int(i)for i in input().strip().split(' '))
# array1.sort()
# array2.sort()
finalArray = mergeSort(array1, array2)
print(*finalArray)
#test
# array1 = [1,4,9,10]
# array2 = [2,3,6,7,8]
# finalArray = mergeSort(array1,array2)
# print(*finalArray) #the star removes the brackets | true |
e530257a5a4cc575650a22252f0f6e47dbfdd32a | khasherr/SummerOfPython | /CountingVCDS.py | 1,189 | 4.28125 | 4 | #Sher Khan
#This program finds vowels, consonants, digits and special character in string
def countInString(str):
vowels,consonants, digits,specialChar = 0,0,0,0, #initialized it to 0
for letters in str: #interate every character in string
#checks if letters is a lower or upper case vowels
if ((letters >= 'a' and letters <='z' ) or (letters >= "A" and letters <= "Z")):
if ((letters == "a" or letters == "e" or letters =="i" or letters == "o" or letters == "u") or
(letters =="A" or letters == "E" or letters =="I" or letters == "O" or letters =="U")):
vowels+=1 #increments vowels
else:
consonants+=1 #if not vowel then its consonant so increment consonants
elif(letters >= "0" and letters <= "9" ): #if letter is a digit
digits+=1; #increments
else:
specialChar+=1 #if not vowels or digit or consonant then its a specialcharacter so increment
return vowels,consonants, digits,specialChar
str = "aisdhckscjasJSSHER123!@# aei ^&"
vowels,consonants,digits,specialChar = countInString(str)
print(vowels,consonants, digits,specialChar)
| true |
c13150910abf220a07ba710173d33c4ef0b6ae2e | khasherr/SummerOfPython | /VariableArguments.py | 742 | 4.34375 | 4 | #tuples
#motivation suppose we have
def sum(a,b):
return a+b
print(sum(1,3)) #passed two arguments and prints 4
# print(sum(1,2,3,4)) #error because it only accept 2 arguments
#What if we have variable length of arguments like 6 or 7 how would you do that ?
def sum(c,d, *morearg):
# return c+d+morearg
# print(sum(1,2,3,4,10,10)) #will not work ! error because int and tuple
answer = c+d #integer addtion
for i in morearg: #iterating through each user input args
answer = answer + i #adding it to asnwer
return answer
print(sum(2,4,5,6,10,11,20)) #variable length of arguments
#
def sum_diff_prod(a,b):
return a+b, a-b, a*b
c = sum_diff_prod(1,3)
j,d,e = sum_diff_prod(1,3)
print(c)
print(j,d,e) | true |
5f92e2103ae8da883570d102af67e2c49f719c4a | gulshan25/python | /Day3/ifStatement1.py | 1,753 | 4.40625 | 4 | """
if condition 1:
true statement
else:
false statement
"""
mango=25
banana=27
if mango>=banana:
print("mango is bigger or equal than")
else:
print("banana is bigger or equal than")
mango=25
banana=27
if mango>banana:
print("mango is bigger")
else:
print("banana is bigger")
mango=25
banana=27
if mango<=banana:
print("mango is smaller or equal than")
else:
print("banana is smaller or equal than")
mango=25
banana=27
if mango<banana:
print("mango is smaller")
else:
print("banana is smaller")
mango=25
banana=27
if mango!=banana:
print("mango is not equal to")
else:
print("banana is not equal to")
mango=25
banana=27
if mango==banana:
print("mango is equal to")
else:
print("banana is equal to")
a=25
b=27
if a>b:
print("a is bigger")
else:
print("b is bigger")
a=25
b=27
if a>=b:
print("a is bigger")
else:
print("b is bigger")
a=25
b=27
if a<b:
print("a is smaller")
else:
print("b is smaller")
a=25
b=27
if a<=b:
print("a is smaller")
else:
print("b is smaller")
a=25
b=27
if a!=b:
print("a isn't equal")
else:
print("b isn't equal")
# b is bigger than a. so, why not equal to!= result is coming a
a=25
b=27
if a==b:
print("a is equal")
else:
print("b is equal")
# mango=25
# banana=27
# if mango=banana:
# print("mango is assignment operator")
# else:
# print("banana is assignment operator")
"""
relational operator
===================
greater than >
greater than or equal to >=
less than <
less than or equal to <=
not equal to !=
equal to ==
assignment operator =
""" | false |
29351d04847fc64e2e6609482c79a7422130fc26 | gulshan25/python | /Day10/classExample.py | 952 | 4.1875 | 4 | """"
class
A class is a blueprint for the object
An object has two characteristics
1. Attributes/Properties
2. Behavior/Method
Syntax -
class className(object):
--snip--
Creating class object
objectName = className(arguments)
"""
class myClass(object):
'''
Document String
This is my first Class
'''
a = 20
def myFunc(self):
print('Hello')
# obj = myClass()
# obj.myFunc()
print(myClass.a)
print(myClass.__doc__)
print(myClass.__name__)
print(myClass.__base__)
class Parrot():
# class attribute
species = "Bird"
# instance attribute
def __init__(self, n, a):
# pass
print('This is Parrot Class')
self.name = n
self.age = a
tiya = Parrot('Mitu',2)
print(f'{tiya.name} is {tiya.age} years old')
print(f'{tiya.name} is {tiya.species}')
print(tiya.__class__)
# tota = Parrot()
# doel = Parrot()
| true |
46d671600d12b122b076eebd127c55f9bb92e371 | gulshan25/python | /Day5/listExample.py | 1,620 | 4.125 | 4 | #print("Hallo Shahin Rahim")
motorcycles=['Honda','Yamaha','Suzuki']
print(motorcycles)
print(motorcycles[0])
print(motorcycles[1])
print(motorcycles[2])
#Change Data
motorcycles[1]='ducati'
fruits=[]
fruits.append('Mango')
fruits.append('Banana')
fruits.append('Orange')
fruits.insert(1,'Apple')
fruits.insert(3,'Grape')
print(fruits)
del fruits[3] # Using Index
print (fruits)
fruits.pop() # LIFO
print(fruits)
fruits.remove('Apple') # Using Item Name
print(fruits)
cars=['bmw','audi','subaru','toyota','audi','audi','toyota']
print(cars)
# cars.sort() # ascending way sorting
# print(cars)
# cars.sort(reverse=True) # Descending Way Sorting
# print(cars)
# print(sorted(cars))
# print(cars) # temporary Sorting
# cars.reverse()
# print(cars)
print('Total Number of cars: ', len(cars))
print('Total Number of cars: %s' % (len(cars)))
print(f'Total Number of cars: {len(cars)}' )
print('Total Number of cars: {0}'.format(len(cars)))
# Slicing
print(cars[-1])
print(cars[-2])
print(cars[0:3])
print(cars[2:5])
print(cars[3:])
print(cars[:4])
print(cars.index('audi'))
print(cars.index('toyota'))
# print(cars.index('Toyota'))
print('Toyota ache : ', cars.count('toyota'))
print('Audi ache : ', cars.count('audi'))
print(type(cars))
print(dir(cars))
cars.extend(['a','b','c','d'])
print(cars)
gari=cars.copy()
print(gari)
gari.clear()
print(gari)
# Common method of list
# --------------------------------
# 'append', 'clear', 'copy', 'count', 'extend', 'index',
# 'insert', 'pop', 'remove', 'reverse', 'sort'
| false |
d03b35fd189199bc527c1d9c8ea774c15628d408 | Srinivasaraghavansj/Python-Programs | /max_list_elements.py | 576 | 4.1875 | 4 | # Write a function that accepts a list of numbers, finds the greatest number in the list and replaces the entire list with that number and returns the new list
# my_new_list([6,4,8,9,7]) should return [9,9,9,9,9]
#Solution 1
def max_func(l):
return [max(l)]*len(l)
print(max_func([6,4,8,9,7]))
#Solution 2
lst = [10, 5, 12, 299, 135, 75, 98, 2]
length = len(lst)
max = 0
for i in range(length):
if max < lst[i]:
max = lst[i]
print(f'maximum value in list is {max}')
for i in range(length):
lst[i] = max
print(f'Updated list {lst}')
| true |
8b5939a27bfae3e7aff3c03c7b4ef02064b907cd | Benjamin-Douglas/Astro119_Fundamentals_Library | /Python_Operators.py | 845 | 4.28125 | 4 | x = 9
y = 3 #integers
#arithmetic operators
print(x+y) #addition
print(x-y) #subtraction
print(x*y) #Multiplication
print(x/y) #division
print(x%y) #modulus
print(x**y) #exponentiation
x = 9.1918123
print(x//y) #floor division [gives the number without the remainder]
#assignment operators
x = 9 #sets x equal to 9
x += 3 #adds three to the current value of x
print(x)
x = 9
x -= 3
print(x)
x = 9
x *= 3
print(x)
x = 9
x /= 3
print(x)
x = 9
x **= 3
print(x)
#comparison operators
x = 9
y = 3
print(x==y) #will print True if x = y, will print False if otherwise
print(x!=y) #true if x does not equal y, False otherwise
print(x>y) #True if x is greater than y, False otherwise
print(x<y) #True if x is less than y, False if otherwise
print(x>=y) #True if x is greater than or equal to y
print(x<=y) #True if x is less than or equal to y | true |
8ebf8b536f2722f55ace8f47e60b15d6e39df672 | 1530426574/practices-of-Data-Structures-and-Algorithms | /排序算法/counting_sort.py | 1,023 | 4.15625 | 4 | # counting sort
def counting_sort(array):
length = len(array)
output = [0] * length
# initialize count array
count = [0] * 256
# store the count of each elements in count array
# [4, 2, 2, 8, 3, 3, 1]
for i in range(0, length):
count[array[i]] = count[array[i]] + 1
# find the index of each element of the original array
# place the elements in output array
# store the cummulative count
for i in range(1, 256):
count[i] += count[i - 1]
for i in range(length):
output[count[array[i]] - 1] = array[i]
count[array[i]] -= 1 # 个数-1
# i = length - 1
# while i >= 0: #关键在于理解 count[array[i]] ,值的个数
# output[count[array[i]] - 1] = array[i]
# count[array[i]] -= 1 #个数-1
# i = i - 1
# copy the original array
for i in range(0, length):
array[i] = output[i]
data = [4, 2, 2, 8, 3, 3, 1]
counting_sort(data)
print("Sorted Array in Ascending Order: ")
print(data)
| false |
a160e82e7075a92985dc7543aade5f8cf82c3802 | supvolume/adventofcode_2020 | /aoc2020_day3_part1_and_part2.py | 839 | 4.34375 | 4 | """Count the number of tree (#) when starting at the top-left corner of the map and following a slope
https://adventofcode.com/2020/day/3"""
def count_hash(x_increase, y_increase):
# Count the number of "#"
hash_num = 0
x_coor = x_increase
y_coor = y_increase
while x_coor <= len(input_list) - 1:
if input_list[x_coor][y_coor] == "#":
hash_num += 1
x_coor += x_increase
y_coor = ((y_coor + y_increase) % len(input_list[0]))
return hash_num
# ===Part 1===
# Read input from file
input_file = open("day3_input.txt", "r")
input_list = input_file.read().split("\n")
# Slope in part 1 is right 3 and down 1
print("Answer of part 1: ", count_hash(1,3))
# ===Part 2===
print("Answer of part 2: ", count_hash(1,1)*count_hash(1,3)*count_hash(1,5)*count_hash(1,7)*count_hash(2,1))
| true |
2c8763f5f0a0de5df970cf2d16943d0799a00d08 | Cosdaman/BSYS2065-Lab | /Lab5/Lab5Q7-6.py | 569 | 4.3125 | 4 | # Write a function findHypot. The function will be given the length of two sides of a right-angled triangle
# and it should return the length of the hypotenuse.
# (Hint: x ** 0.5 will return the square root, or use sqrt from the math module)
import math
def findHypot(xside, yside):
hypotenuse = xside**2 + yside**2
hypotenuse = math.sqrt(hypotenuse)
return hypotenuse
x = int(input("Input the first side of the triangle: "))
y = int(input("Input the second side of the triangle: "))
print("The hypotenuse of the triangle is: ", findHypot(x, y))
| true |
b5ce86f7d4963a1949f325af3047d187e13be8de | Cosdaman/BSYS2065-Lab | /Lab7/LAB7Q9-12.py | 374 | 4.15625 | 4 | # Write a function that removes all occurrences of a string from another string.
def removestring(stringthing, stringremovething):
x = stringthing.replace(stringremovething, "")
return x
stringitem = str(input("Enter a string: "))
lettertoremove = str(input("Enter a smaller string to remove from the string: "))
print(removestring(stringitem, lettertoremove))
| true |
d74e7f0dde8c61043649889fc3ea900537a968a0 | stefansilverio/hangman_repo | /randomhangman.py | 1,407 | 4.28125 | 4 | # attribute is an action that an object can perform - "The cat can jump".
# attributes of an object refer to the given data and abilities of that object
# an object is just a collection of associated attributes
import random
def hangman(word):
word_list = ["butter", "bubble", "smoke", "shield"]
random_number = random.randint(0, 4)
word = word_list[random_number]
wrong = 0
stages = ["",
"_________ ",
"| ",
"| | ",
"| 0 ",
"| /|\ ",
"| / \ ",
"| ",
]
remaining_letters = list(word)
board = ["____"] * len(word)
win = False
print("Welcome to Hangman")
while wrong < len(stages) - 1:
print("\n")
msg = "guess a letter"
char = input(msg)
if char in remaining_letters:
cind = remaining_letters.index(char)
board[cind] = char
remaining_letters[cind] = '$'
else:
wrong += 1
print((" ".join(board))
e=wrong + 1
print("\n".join(stages[0: e]))
if "__" not in board:
print("you win!")
print(" ".join(board))
win=True
break
if not win:
print("\n".join(stages[0: wrong]))
print("you lose! It was {}.".format(word)
| true |
9b515666e26b9c4960d6cfcda5fd0f31abfeb202 | DevAhmed-py/Pirple.py | /Dictionaries and Sets.py | 656 | 4.25 | 4 |
#List and Dictionary
CountryList = []
for i in range(3):
Country = input("Enter country: ")
CountryList.append(Country)
print(CountryList)
CountryDictionary = {}
for country in CountryList:
if country in CountryDictionary:
CountryDictionary[country] += 1
else:
CountryDictionary[country] = 1
print(CountryDictionary)
#Using while loop in Dictionary
BlackShoes = {40:3, 42:4, 37:0, 54:0}
print(BlackShoes)
while(True):
Size = int(input("\nEnter your shoe size: "))
if Size < 0:
break
if Size > 0:
BlackShoes[Size] -= 1
else:
print("Size NOT available")
print(BlackShoes)
| true |
d3da0cd4fd213a4fffdce16d6117ba2a15ac5a61 | Gerson-Rodrigues/Python---Projetos-do-Curso | /desafio22.py | 1,299 | 4.3125 | 4 | # Crie um programa que leia o nome completo de uma pessoa e mostre:
# O nome com todas as letras maiúsculas.
# O nome com todas minúsculas.
# Quantas letras ao todos (sem considerar espaços)
# Quantas letras tem o primeiro nome.
#minha resolução do problema
"""nome = str(input('Escreva um nome completo:'))
print(nome.upper())
print(nome.lower())
#print(nome.title())
nome1 = nome.split()
n = len(nome1)
if (n==2):
print('Aotodo tem {} letras o nome '.format(len(nome)-1))
elif(n==3):
print('Aotodo tem {} letras o nome '.format(len(nome)-2))
elif(n==4):
print('Aotodo tem {} letras o nome '.format(len(nome)-3))
elif(n==5):
print('Aotodo tem {} letras o nome '.format(len(nome)-4))
else:
print('Aotodo tem {} letras o nome '.format(len(nome)))
print('O primeiro nome tem {} letras.'.format(len(nome1[0])))
"""
# resolução do Professor
nome = str(input('Digite seu nome completo: '))
nome1 = nome.split()
print("Analisando seu nome...")
print('Seu nome em maiúsculas é {}'.format(nome.upper()))
print('Seu nome em minúsculas é {}'.format(nome.lower()))
print('Seu nome ao todo tem {} letras'.format(len(nome) - nome.count(' ')))
#print('Seu primeiro nome tem {} letras.'.format(nome.find(' ')))
print('O primeiro nome tem {} letras.'.format(len(nome1[0])))
| false |
38d6468ed0e9a1cb1a345505e325fb10815e2392 | Gerson-Rodrigues/Python---Projetos-do-Curso | /desafio29.py | 1,550 | 4.125 | 4 | # Escreva um programa que leia a velocidade de um carro.
# Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele
# foi multado.
# A multa vai custar R$7,00 por cada Km acima do limite.#
#minha resolução do desafio
velo = float(input('Digite a velocidade de um veículo no qual costuma dirigir: '))
if velo <= 80.0 and velo > 74.0:
print('Uma boa velocidade para viagens, segurança sempre!')
elif velo < 75:
print('Velocidade abaixo do habitual da pista, suba sua velocidade ou poderá \n'
'receber uma multa por congestionar a via!!')
else:
multa = (velo - 80)*7+50
if velo >80.0 and velo < 100.0:
ponto = 5
elif velo >99.0 and velo < 150.0:
ponto = 12; multa = multa + 250
elif velo >149.0:
ponto = 30; multa = multa + 1000
print('Você passou o limite de velocidade, você receberá uma multa.\n'
'o valor da multa aplicada será relativo a sua velocidade, ficando R${:.2f} \n'
'e {} pontos na carteira'.format(multa, ponto))
if ponto == 30:
print('Por exceder demais a velocidade, terá a carteira suspensa.')
print('Sempre Dirija com Cuidado, e não Beba se for dirijir...')
# Resolução do Professor Guanabara
"""
velocidade = float(input('Qual é a valocidade atual do carro? '))
if velocidade > 80:
print('MULTADO! Você excedeu o limite permitido que é de 80Km/h')
multa = (velocidade - 80) * 7
print('Você deve pagar uma multa de R${:.2f}'.format{multa))
print('Tenha um bom dia! Dirija com Segurança!')
""" | false |
b7e658717af668f406bbe8620830eec5501c1a31 | mitant127/Python_Algos | /Урок 1. Практическое задание/task_5.py | 1,300 | 4.40625 | 4 | """
Задание 5.
Пользователь вводит две буквы. Определить,
на каких местах алфавита они стоят, и сколько между ними находится букв.
Подсказка:
Вводим маленькие латинские буквы.
Обратите внимание, что ввести можно по алфавиту, например, a,z
а можно наоборот - z,a
В обоих случаях программа должна вывести корректный результат.
В обоих случаях он 24, но никак не -24
"""
print('Вводите маленькие латинские буквы.!')
LEFT = int(ord(input("Введите первый символ: ")))
RIGHT = int(ord(input("Введите второй символ: ")))
if LEFT > RIGHT:
LEFT, RIGHT = RIGHT, LEFT
POSITION_1 = LEFT - 96
POSITION_2 = RIGHT - 96
DISTANCE = POSITION_2 - POSITION_1 - 1
print("------------------------------------")
print(f"Символ {chr(LEFT)} находится на {POSITION_1}")
print(f"Символ {chr(RIGHT)} находится на {POSITION_2}")
print(f"Дистанция между символами {chr(LEFT)} и {chr(RIGHT)} равна {DISTANCE}")
| false |
5fcfeb186947c79f03a6801bf58d6b6b77c2c473 | saa419/LPTHW | /ex22.py | 1,046 | 4.15625 | 4 | '''
print: prints the variable or string that follows
+: Adds or concatenates two things
/: divides two things
-: subtracts two things
*: multiplies or repeats thing 1 by thing 2
%: modulo: provides the remainder of a division. Also used for placing strings and numbers into statements
<: less than
>: greater than
>=: greater than or equal to
<=: less than or equal to
#: Makes a comment
=: assigns a value to a variable
%s: represents a string variable
%d: represents a digit variable
%r: represents a raw data variable
\n: new line
\t: tab
\\: one backslash
""": block of text
int: makes something an integer
raw_input: takes the raw input from the user and passes it to something
from: from a particular module,
import: import something from somewhere else to be used in the program
open: open a file
read: read a file
close: close a file
truncate: truncates (erases) a file
write: writes to a file
def: defines a function
while: while something is true, do something
+=: add something to an existing variable, make that the new variable
''' | true |
4e85d82e054feee0f7d414e26d53ca6e5c4482c5 | Sathyacool/Python3_Basics_Tutorial | /example_programs/pythagoras.py | 313 | 4.34375 | 4 |
print "Find out whether a triangle is straight-edged."
a = float(input("length of edge a: "))
b = float(input("length of edge b: "))
c = float(input("length of edge c: "))
if a ** 2 + b ** 2 == c ** 2:
print "This is a straight-edged triangle."
else:
print "This is not a straight-edged triangle."
| true |
547fdf6577e07144e74ba1c66a019fddd5f615ed | Tiki92/small_python-projects | /Python3/Guess_number/Guess_the_number.py | 952 | 4.21875 | 4 | """A game where you have to guess the sum of a pair of rolled dice"""
from random import randint
from time import sleep
def get_user_guess():
guess = int(input("Guess the Number: "))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print("The max value is %d" % (max_val))
guess = get_user_guess()
if guess > max_val:
print("The Number that you entered is to high!")
else:
print("Rolling...")
sleep(2)
print("The first roll is %d" % (first_roll))
sleep(1)
print("The second roll is %d" % (second_roll))
sleep(1)
total_roll = first_roll + second_roll
print("The total roll is %d" % (total_roll))
print("Result...")
sleep(1)
if guess == total_roll:
print("Congratulation you guessed the number!")
else:
print("You didn't guess the number!")
roll_dice(6)
| true |
0d32b4e4912543721e16f9542aee95e8728cc876 | howie1329/Calculator | /Calc.py | 1,400 | 4.1875 | 4 | # Created and Finished by Howard Thomas
calculator_usage = "yes"
# Adding
def add(x, y):
print(int(x + y))
# Sub
def sub(x, y):
print(int(x - y))
# Multi
def multi(x, y):
print(int(x * y))
# Dividing
def div(x, y):
print(int(x / y))
# Printing
def printing(x):
print("The total is" + x)
def heading():
print("Calculator")
print("Created by Howard Thomas in python")
def start():
global calculator_usage
heading()
while calculator_usage == "yes":
calculator_usage = input("Would you like to use the calculator? (yes/no) ")
choices()
calculator_usage = input("would you like to use the calculator again? (yes/no) ")
# Calculations
def calc(user_input, num1, num2):
if user_input == 1:
add(num1, num2)
elif user_input == 2:
sub(num1, num2)
elif user_input == 3:
multi(num1, num2)
elif user_input == 4:
div(num1, num2)
else:
print("Wrong input")
choices()
# Choices
def choices():
num1 = int(input("What is your first number: "))
num2 = int(input("What is your second number: "))
print("Please pick a option 1 - 4")
print("1.) Adding")
print("2.) Subtraction")
print("3.) Multiplication")
print("4.) Dividing")
user_input = int(input("What is your choice? "))
calc(user_input, num1, num2)
if __name__ == "__main__":
start()
| true |
7cab28f14579adb930a4b67cbd8072ac6148c471 | SarahAlkhalawi/guessing-game | /guessing.py | 386 | 4.21875 | 4 | import random
number = random.randint(1, 20)
guess = 0
while guess != number:
guess = int(input("Guess a number between 1 and 20: "))
if (guess < number):
print("The number is greater than your number. Try again")
elif (guess > number):
print("The number is smaller than your number. Try again")
else:
print("This is the number!") | true |
f74912473a8fc8e649310182fd06909614fdb0ac | alphaomegos/pylesson5 | /Task 02.py | 840 | 4.34375 | 4 | # Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке.
'''
Как я понял это задание, можно вполне воспользоваться файлом из предыдущего задания.
Я назвал его Text01.txt и он прилгается к этой работе.
'''
file = open("Text01.txt", "r")
Line_Count = 0
Word_Count=0
for Line in file:
if Line != "\n":
Line_Count += 1
f1 = Line.split()
Word_Count = len(f1)
print(f'Words in line: {Line_Count} is {str(Word_Count)}')
file.close()
print(f'Total number of lines is: {Line_Count}') | false |
6134065ad996bce421f4cfd4ec9cd5e4b7675896 | Ankita-Dake/PythonExceptionHandling | /ExceptionHandling.py | 757 | 4.28125 | 4 | # application without exception handling
# print(10/0)
# using exception handling
try:
print(10 / 0)
except:
print("division by zero")
#
try:
print(10 / 0)
except:
print('division by zero')
print("hello")
#
try:
print(10 / 0)
except NameError:
print("Invalid error")
except ZeroDivisionError:
print("division by zero")
print("Hello")
# else keyword in exception
try:
print(i+j)
except NameError:
print("variable not defined")
else:
print("code is running well")
# finally keyword
try:
print(i+j)
except NameError:
print("variable not defined")
finally:
print("This line is always executed")
# throw an exception
x = int(input("enter number"))
if x<10:
raise Exception("value must be above 10")
| true |
a1d1612320d106e197815fc4071d72aabb856fcf | nkmk/python-snippets | /notebook/zip_example.py | 881 | 4.21875 | 4 | names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for name, age in zip(names, ages):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
points = [100, 85, 90]
for name, age, point in zip(names, ages, points):
print(name, age, point)
# Alice 24 100
# Bob 50 85
# Charlie 18 90
names = ['Alice', 'Bob', 'Charlie', 'Dave']
ages = [24, 50, 18]
for name, age in zip(names, ages):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
# for name, age in zip(names, ages, strict=True):
# print(name, age)
# ValueError: zip() argument 2 is shorter than argument 1
names = ['Alice', 'Bob', 'Charlie']
ages = (24, 50, 18)
z = zip(names, ages)
print(z)
print(type(z))
# <zip object at 0x1038b0980>
# <class 'zip'>
l = list(zip(names, ages))
print(l)
print(type(l))
print(type(l[0]))
# [('Alice', 24), ('Bob', 50), ('Charlie', 18)]
# <class 'list'>
# <class 'tuple'>
| false |
1c287f359f9a4250634c933f4fa53cdab55624f6 | nkmk/python-snippets | /notebook/arithmetic_operator_num.py | 1,411 | 4.21875 | 4 | print(10 + 3)
# 13
print(10 - 3)
# 7
print(10 * 3)
# 30
print(10 / 3)
# 3.3333333333333335
print(0.1 / 0.03)
# 3.3333333333333335
print(10 // 3)
# 3
print(0.1 // 0.03)
# 3.0
print(10 % 3)
# 1
print(0.1 % 0.03)
# 0.010000000000000009
print(10**3)
# 1000
print(2**0.5)
# 1.4142135623730951
print(10**-2)
# 0.01
print(0**0)
# 1
# print(10 / 0)
# ZeroDivisionError: division by zero
# print(10 // 0)
# ZeroDivisionError: integer division or modulo by zero
# print(10 % 0)
# ZeroDivisionError: integer modulo by zero
# print(0**-1)
# ZeroDivisionError: 0.0 cannot be raised to a negative power
a = 10
b = 3
c = a + b
print(f'{a = }')
print(f'{b = }')
print(f'{c = }')
# a = 10
# b = 3
# c = 13
a = 10
b = 3
a += b
print(f'{a = }')
print(f'{b = }')
# a = 13
# b = 3
a = 10
b = 3
a %= b
print(f'{a = }')
print(f'{b = }')
# a = 1
# b = 3
a = 10
b = 3
a **= b
print(f'{a = }')
print(f'{b = }')
# a = 1000
# b = 3
print(2 + 3.0)
print(type(2 + 3.0))
# 5.0
# <class 'float'>
print(10 / 2)
print(type(10 / 2))
# 5.0
# <class 'float'>
print(2**3)
print(type(2**3))
# 8
# <class 'int'>
print(2.0**3)
print(type(2.0**3))
# 8.0
# <class 'float'>
print(25**0.5)
print(type(25**0.5))
# 5.0
# <class 'float'>
print(0.01**-2)
print(type(0.01**-2))
# 10000.0
# <class 'float'>
print(100 / 10**2 + 2 * 3 - 5)
# 2.0
print(100 / (10**2) + (2 * 3) - 5)
# 2.0
print((100 / 10) ** 2 + 2 * (3 - 5))
# 96.0
| false |
638ce259a020b47221b4689823ea4dd9a4750cae | nkmk/python-snippets | /notebook/conditional_expressions.py | 1,453 | 4.1875 | 4 | a = 1
result = 'even' if a % 2 == 0 else 'odd'
print(result)
# odd
a = 2
result = 'even' if a % 2 == 0 else 'odd'
print(result)
# even
a = 1
result = a * 10 if a % 2 == 0 else a * 100
print(result)
# 100
a = 2
result = a * 10 if a % 2 == 0 else a * 100
print(result)
# 20
a = 1
print('even') if a % 2 == 0 else print('odd')
# odd
a = 1
if a % 2 == 0:
print('even')
else:
print('odd')
# odd
a = -2
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result)
# negative and even
a = -1
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result)
# positive or odd
a = 2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# positive
a = 0
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# zero
a = -2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# negative
result = 'negative' if a < 0 else ('positive' if a > 0 else 'zero')
print(result)
# negative
result = ('negative' if a < 0 else 'positive') if a > 0 else 'zero'
print(result)
# zero
l = ['even' if i % 2 == 0 else i for i in range(10)]
print(l)
# ['even', 1, 'even', 3, 'even', 5, 'even', 7, 'even', 9]
l = [i * 10 if i % 2 == 0 else i for i in range(10)]
print(l)
# [0, 1, 20, 3, 40, 5, 60, 7, 80, 9]
get_odd_even = lambda x: 'even' if x % 2 == 0 else 'odd'
print(get_odd_even(1))
# odd
print(get_odd_even(2))
# even
| false |
19fcf106a16b157200bc64028c242c3aed5f794b | Ashwinbicholiya/Python | /Python/3(2Darray)/3darray.py | 295 | 4.625 | 5 | #create 3d array from 2d array
#function use reshape()
from numpy import *
arr1=array([
[1,2,3,4,5,6],
[5,6,7,8,9,1]
])
arr2=arr1.flatten()
arr3=arr2.reshape(2,2,3)
print(arr3)
#we got 1 big 3d array which has 2 2d array and which has 2 single array
#and then which has 3 values | true |
5ca850475eb72423c872440df937e707a6bfab49 | Ashwinbicholiya/Python | /Python/assignment/1ELIF.py | 313 | 4.15625 | 4 | x=int(input('Enter a number : '))
if x==2 :
print('Prime number')
elif x>1:
for i in range(2,x):
if x%2==0:
print(x, 'Not a prime number ')
break
else:
print(x, 'Prime number ')
break
elif x<=1:
print(x, 'Not a Prime Number')
| false |
93ad46ec022d287254c08092b6e84dab3c98d050 | Ashwinbicholiya/Python | /Python/assignment/37Functionassgn1.py | 336 | 4.1875 | 4 | #Create a list and print how many even and odd numbers in the list by using function
def count(lst):
even=0
odd=0
for i in lst:
if i%2==0:
even +=1
else:
odd +=1
return even,odd
lst= [1,2,3,4,5,6,7,8,9,10]
even,odd = count(lst)
print("Even : {} and odd : {} ".format(even,odd)) | true |
d4a664964b5a110fdca47ddcc13f83f526874c57 | alex652/X0 | /altele/board.py | 797 | 4.15625 | 4 | size=3
table={}
for a in range(size):
for b in range(size):
table[a,b]="-"
##def print_table (table):
## for a in range(size):
## for b in range(size):
## print(table[a][b])
#create_table()
for a in range(size):
for b in range(size):
print(table[a,b] ,end="")
print("",end="\n")
class Game:
def __init__(self,name,size):
self.name=name
self.size=size
def createBoard(self)
table={}
for a in range(size):
for b in range(size):
table[a,b]="-"
def displayBoard(self):
for a in range(size):
for b in range(size):
print(table[a,b] ,end="")
print("",end="\n")
| true |
5a3a2a494309a0f8569dcb80aa325aa8d1786969 | harsh1915/Machine_Learning | /Python/01_My_Programs_Hv/03_Loops/52_Check_Empty_Or_Not.py | 393 | 4.34375 | 4 | name= "Harsh"
if name:
print( "String is not empty !") #checks string is empty or not
else:
print( "String is empty !")
name1= ""
if name1:
print( "String is not empty !") #checks string is empty or not
else:
print( "String is empty !")
uname= input( "Enter your name = ")
if uname:
print( f"Your name is {uname}")
else:
print( "You didn't Enter your name !") | true |
d1db867734564cf21b9812357c93088f7793d066 | harsh1915/Machine_Learning | /Python/01_My_Programs_Hv/09_List_Comprehention/132_E1.py | 315 | 4.15625 | 4 | name= ["Harsh", "Karan", "Krunal", "Rohan", "Bhargav"]
def reverse_name(name):
return [i[::-1] for i in name]
print(f"name = {name}")
print(f"reverse of your name = {reverse_name(name)}")
def reverse_name2(name):
ls= []
for i in name:
ls.append(i[::-1])
return ls
print(reverse_name2(name)) | false |
b3fe6cd62707e3c508ad3aeca5cb4965a9b725f9 | harsh1915/Machine_Learning | /Python/02_Practice_Programce/01_Basic_Programs/03_factorial_of_a_number.py | 391 | 4.125 | 4 | import math
while True:
num1= int(input("Enter Any number = "))
fact= 1
if num1> 0:
for i in range(1, num1+ 1):
fact= fact* i
print(f"Factorial of {num1} = {fact}")
break
print("Invalid input !\nTry Again")
# using math.factoril() function
# num1= int(input("Enter Any number = "))
# print(f"Factorial of {num1} = {math.factorial(num1)}") | true |
9e03ab59f89e392512dc600f3703f7344da3f9f0 | huotong1212/mylearnpy | /code/day08/描述符优先级测试/类属性大于数据描述符.py | 1,558 | 4.21875 | 4 | #描述符Str
class Str:
def __get__(self, instance, owner):
print('Str调用')
def __set__(self, instance, value):
print('Str设置...')
def __delete__(self, instance):
print('Str删除...')
class People:
name=Str()
def __init__(self,name,age): #name被Str类代理,age被Int类代理,
self.name=name
self.age=age
#基于上面的演示,我们已经知道,在一个类中定义描述符它就是一个类属性,存在于类的属性字典中,而不是实例的属性字典
# p1 = People('mitchal',20)
# del p1.name
# print(p1.name)
#那既然描述符被定义成了一个类属性,直接通过类名也一定可以调用吧,没错
People.name #恩,调用类属性name,本质就是在调用描述符Str,触发了__get__()
print('0',People.__dict__)
People.name='egon' #那赋值呢,我去,并没有触发__set__()
print('1',People.__dict__)
del People.name #赶紧试试del,我去,也没有触发__delete__()
#结论:描述符对类没有作用-------->傻逼到家的结论
print('2',People.__dict__)
'''
原因:描述符在使用时被定义成另外一个类的类属性,因而类属性比二次加工的描述符伪装而来的类属性有更高的优先级
People.name #恩,调用类属性name,找不到就去找描述符伪装的类属性name,触发了__get__()
People.name='egon' #那赋值呢,直接赋值了一个类属性,它拥有更高的优先级,相当于覆盖了描述符,肯定不会触发描述符的__set__()
del People.name #同上
''' | false |
5aeb370ae7da9dd9fc79aff36719a7aa6ba0782d | huotong1212/mylearnpy | /code/day11/进程与线程/线程/futures模块/进程池异步调用.py | 1,616 | 4.1875 | 4 | #介绍
# The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.
#
# class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None)
# An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is lower or equal to 0, then a ValueError will be raised.
#用法
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import os,time,random
def task(n):
print('%s is runing' %os.getpid())
time.sleep(random.randint(1,3))
return n**2
if __name__ == '__main__':
executor=ProcessPoolExecutor(max_workers=3)
futures=[]
for i in range(11):
'''
submit(fn, *args, **kwargs)
异步提交任务
'''
future=executor.submit(task,i)
futures.append(future)
'''
shutdown(wait=True)
相当于进程池的pool.close()+pool.join()操作
wait = True,等待池内所有任务执行完毕回收完资源后才继续
wait = False,立即返回,并不会等待池内的任务执行完毕
但不管wait参数为何值,整个程序都会等到所有任务执行完毕
'''
executor.shutdown(True)
print('+++>')
for future in futures:
print(future.result())
| true |
34149a240273c3c3905cdd841413f453add2a205 | huotong1212/mylearnpy | /code/day08/描述符的应用/example2.py | 1,630 | 4.3125 | 4 | '''
class Str:
def __init__(self,name):
self.name=name
def __get__(self, instance, owner):
print('get--->',instance,owner)
return instance.__dict__[self.name]
def __set__(self, instance, value):
print('set--->',instance,value)
instance.__dict__[self.name]=value
def __delete__(self, instance):
print('delete--->',instance)
instance.__dict__.pop(self.name)
class People:
name=Str('name')
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary
#疑问:如果我用类名去操作属性呢
People.name #报错,错误的根源在于类去操作属性时,会把None传给instance
'''
#修订__get__方法
class Str:
def __init__(self,name):
self.name=name
def __get__(self, instance, owner):
print('get--->',instance,owner)
if instance is None:
return self
return instance.__dict__[self.name]
# def __set__(self, instance, value):
# print('set--->',instance,value)
# instance.__dict__[self.name]=value
# def __delete__(self, instance):
# print('delete--->',instance)
# instance.__dict__.pop(self.name)
class People:
name=Str('name')
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary
# print(People.name) #完美,解决
p1 = People('張三',12,321) # 这段代码可以证明实例属性的优先级大于只实现了get方法的非数据描述符
print(p1.name)
print(p1.__dict__) | false |
74ddad50ca5c0ed15eac1e2837c08cf902e622ca | EudesG/dobraduras_de_mordidas | /Principal.py | 1,969 | 4.28125 | 4 | ############ Função de entrada #############
#ADICIONAR ENTRADA COMO FUNÇÂO DE X
#Pedir as dimensões do plano a ser modulado
#funcao = input('Digite sua função com variável x, usando '**' como expoente e '*' como multiplicação: ')
#comprimento = int(input('Digite o comprimento do seu plano a ser modulado: '))
#largura = int(input('Digite a largura do seu plano a ser modulado: '))
#dobras = int(input('Digite a quantidade de desdobramentos a ser computado: '))
## ADICIONAR CONDIÇÕES COMO A FUNÇÃO TER VARIÁVEL X E O COMPRIMENTO E A LARGURA SEREM INTEIROS ##
dobras = 3
#####################################
# aqui diz que se a quantidade de dobras for ímpar
# será feitos "N" nobras em y e "N-1" dobras em x
if dobras % 2 !=0:
dobra_y = dobras
x = 0
fim = 10*dobra_y
coord_y = []
coord_x = []
desdobras = 0
while desdobras <= dobras:
desdobras += 1
############### essa parte se dedica a pegar os valores num intervalo 'x' e aplica na função y ###############
while x <= fim :
x += 1
coordenada_x=coord_x.append(x)
y = -x ** 1.76 + 2 * x * 2 - 10 #### Adicionar a função aqui como sendo y = - funcao #####
coordenada_y=coord_y.append(y)
#################### Essa parte se dedica a salvar num arquivo os pontos x ##########################
arquivo_coord = open('coordenadas_x.txt', 'a', encoding='utf8')
arquivo_coord.write(str(x) + '\n')
arquivo_coord.close()
#################### Essa parte se dedica a salvar num arquivo os pontos f(x) ##########################
# for y in coord_y:
arquivo_coord = open('coordenadas_y.txt', 'a', encoding='utf8')
arquivo_coord.write(str(y) + '\n')
arquivo_coord.close()
| false |
ea3096d6af9cd7db24c4913c22bc87b42c1daac9 | danrgonzalez/dsp | /python/q8_parsing.py | 1,595 | 4.28125 | 4 | #The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
import csv
parsed_data = []
def read_data(data):
with open(data, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print row
parsed_data.append(row)
def get_min_score_difference(parsed_data):
#print parsed_data[0][5], parsed_data[0][6]
diff = []
for i in range(1,len(parsed_data)):
#print int(parsed_data[i][5]), int(parsed_data[i][6])
d = int(parsed_data[i][5]) - int(parsed_data[i][6])
#print d
diff.append(d)
#print diff
print min(diff)
def get_team(parsed_data):
diff = []
for i in range(1,len(parsed_data)):
#print int(parsed_data[i][5]), int(parsed_data[i][6])
d = int(parsed_data[i][5]) - int(parsed_data[i][6])
#print d
diff.append(d)
#print diff
print diff.index(min(diff))+1
print parsed_data[diff.index(min(diff))+1][0]
read_data('football.csv')
get_min_score_difference(parsed_data)
get_team(parsed_data)
| true |
2e8ccc4400430fa04b687c53add26ca0d168e716 | m-01101101/udacity-datastructures-algorithms | /3. data_structures/linked_list/linked_lists_reversed.py | 2,153 | 4.3125 | 4 | # Helper Code
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
def __repr__(self):
return str([v for v in self])
def insert_at_head(linked_list, value):
position_tail_continuity = linked_list.head
linked_list.head = Node(value)
linked_list.head.next = position_tail_continuity
return linked_list
# Time complexity O(N)
def reverse(linked_list):
"""
Reverse the inputted linked list
Args:
linked_list(obj): Linked List to be reversed
Returns:
obj: Reveresed Linked List
"""
new_list = LinkedList()
prev_node = None
"""
A simple idea - Pick a node from the original linked list traversing from the beginning, and
prepend it to the new linked list.
We have to use a loop to iterate over the nodes of original linked list
"""
# In this "for" loop, the "value" is just a variable whose value will be updated in each iteration
for value in linked_list:
# create a new node
new_node = Node(value)
# Make the new_node.next point to the
# node created in previous iteration
new_node.next = prev_node
# This is the last statement of the loop
# Mark the current new node as the "prev_node" for next iteration
prev_node = new_node
# Update the new_list.head to point to the final node that came out of the loop
new_list.head = prev_node
return new_list
llist = LinkedList()
for value in [4, 2, 5, 1, -3, 0]:
llist.append(value)
flipped = reverse(llist)
is_correct = list(flipped) == list([0, -3, 1, 5, 2, 4]) and list(llist) == list(
reverse(flipped)
)
print("Pass" if is_correct else "Fail")
| true |
477f8502bb9059c4a7fa61488e87f9b3b91dc385 | m-01101101/udacity-datastructures-algorithms | /2. python_refresher/factorials.py | 510 | 4.21875 | 4 | def prod(a: int, b: int) -> int:
return a * b
def fact_gen():
"""generates factorials for a number n
using a recursive function"""
i = 1
n = i
while True:
output = prod(n, i)
yield output
i += 1
n = output
# TODO: update i and n
# Hint: i is a successive integer and n is the previous product
# Test block
my_gen = fact_gen()
num = 5
for i in range(num):
print(next(my_gen))
# Correct result when num = 5:
# 1
# 2
# 6
# 24
# 120
| true |
71fea20fdbe0d71312a82d862428bad1dcf98c9e | m-01101101/udacity-datastructures-algorithms | /3. data_structures/stack/balanced_parantheses.py | 1,781 | 4.75 | 5 | """
In this exercise you are going to apply what you learned about stacks with a real world problem.
We will be using stacks to make sure the parentheses are balanced in mathematical expressions such as:
((3^2 + 8)*(5/2))/(2+6)
In real life you can see this extend to many things such as text editor plugins
and interactive development environments for all sorts of bracket completion checks.
Take a string as an input and return `True` if it's parentheses are balanced or `False` if it is not.
"""
from typing import List
class Stack:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
if self.size() == 0:
return None
else:
return self.items.pop()
def equation_checker(equation):
"""
Check equation for balanced parentheses
Args:
equation(string): String form of equation
Returns:
bool: Return if parentheses are balanced or not
"""
opening_parenthesis = Stack()
closing_parenthesis = Stack()
for _ in equation:
if _ == "(":
opening_parenthesis.push(_)
elif _ == ")":
closing_parenthesis.push(_)
return opening_parenthesis.size() == closing_parenthesis.size()
def _equation_checker(equation):
"""
Check equation for balanced parentheses
"""
# not in the the spirit
return equation.count("(") == equation.count(")")
def udacity_equation_checker(equation):
stack = Stack()
for char in equation:
if char == "(":
stack.push(char)
elif char == ")":
if stack.pop() == None:
return False
return stack.size() == 0
| true |
e95f2c78096aafb265b8c0d6bb88420316a5ab6d | m-01101101/udacity-datastructures-algorithms | /5. basic_algorithms/trie_defaultdict.py | 1,786 | 4.25 | 4 | """
A cleaner way to build a trie is with a Python default dictionary
"""
from collections import defaultdict
from typing import List
class TrieNode:
def __init__(self):
self.children = defaultdict(
TrieNode
) # we're defining children as a dict of nodes
self.is_word = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def add(self, word):
"""
Add `word` to trie
"""
node = self.root
for char in word:
node = node.children[
char
] # because it remembers the order you can add it as a dictionary
node.is_word = True
def add_many(self, words: List[str]):
"""
Add multiple words at once
"""
for word in words:
self.add(word)
def exists(self, word): # no change in this implementation
"""
Check if word exists in trie
"""
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_word
valid_words = ["the", "a", "there", "answer", "any", "by", "bye", "their"]
word_trie = Trie()
word_trie.add_many(valid_words)
"""
word_trie.root.children
>>> defaultdict(__main__.TrieNode,
{'t': <__main__.TrieNode at 0x105d8ba60>,
'a': <__main__.TrieNode at 0x105d8bdc0>,
'b': <__main__.TrieNode at 0x1064e7e20>})
same implemention when validating a word:
word_trie.root.children["t"].children["h"].children["e"].is_word
>>> True
"""
assert word_trie.exists("the")
assert word_trie.exists("any")
assert not word_trie.exists("these")
assert not word_trie.exists("zzz")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.