blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
f48ad084c38a7023a5850dc1452b2534e620e776
|
Anku-0101/Python_Complete
|
/DataTypes/03_TypeCasting.py
| 229
| 4.1875
| 4
|
a = "3433"
# Typecasting string to int
b = int(a)
print(b + 1)
'''
str(31) --> "31" => Integer to string conversion
int("32") --> 32 => string to integer conversion
float(32) --> 32.0 => Integer to float conversion
'''
| false
|
1d8479254cbe4a936f1b7c21715fc58638f61f84
|
Anku-0101/Python_Complete
|
/DataTypes/02_Operators.py
| 591
| 4.15625
| 4
|
a = 3
b = 4
print("The value of a + b is", a + b)
print("The value of a*b is", a * b)
print("The value of a - b is", a - b)
print("The value of a / b is", a / b)
print("The value of a % b is", a % b)
print("The value of a > b is", a > b)
print("The value of a == b is", a == b)
print("The value of a != b is", a != b)
print("The value of a < b is", a < b)
flagA = True
flagB = False
print("The value of flagA and flagB is", flagA and flagB)
print("The value of flagA or flagB is", flagA or flagB)
print("The value of not flagB is", not flagB)
print("The value of not flagA is", not flagA)
| true
|
05f486e4dac5d903bd5ec01c15c0835caa59a8b2
|
Weenz/software-QA-hw2
|
/bmiCalc.py
| 1,631
| 4.3125
| 4
|
import math
#BMI Calculator function
def bmiCalc():
print ("")
print ("BMI Calculator")
print ("------------------")
#Loop to verify integer as input for feet
while True:
try:
feet = int(input("Enter your feet part of your height: "))
except ValueError:
print("Incorrect value, must be a number.")
continue
else:
break
#Loop to verify integer as input for inches
while True:
try:
inches = int(input("Enter the inches part of your height: "))
except ValueError:
print("Incorrect value, must be a number.")
continue
else:
break
#Loop to verify integer as input for weight
while True:
try:
weight = int(input("Enter your weight (in pounds): "))
except ValueError:
print("Incorrect value, must be a number.")
continue
else:
break
weight = weight * 0.45 #metric conversion
height = feet * 12 + inches #total height in inches
height = height * 0.025 #metric conversion
height = height * height #square height
bmi = weight / height #bmi calculation
bmi = math.ceil(bmi * 10) / 10 #keep one decimal place
if (bmi <= 18.5):
value = "Underweight"
elif ( (bmi > 18.5) and (bmi <= 24.9) ):
value = "Normal Weight"
elif( (bmi >= 25) and (bmi <= 29.9) ):
value = "Overweight"
else:
value = "Obese"
return (bmi, value)
| true
|
12491cc31c5021a38cb40799492171c2d5b6b978
|
muneel/url_redirector
|
/redirector.py
| 2,194
| 4.25
| 4
|
"""
URL Redirection
Summary:
Sends the HTTP header response based on the code received.
Converts the URL received into Location in the response.
Example:
$ curl -i http://127.0.0.1:5000/301/http://www.google.com
HTTP/1.0 301 Moved Permanently
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:11 GMT
Location: http://www.google.com
$ curl -i http://127.0.0.1:5000/302/http://www.google.com
HTTP/1.0 302 Found
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:17 GMT
Location: http://www.google.com
$ curl -i http://127.0.0.1:5000/303/http://www.google.com
HTTP/1.0 303 See Other
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:22 GMT
Location: http://www.google.com
"""
import BaseHTTPServer
import time
import sys
HOST_NAME = ''
PORT_NUMBER = 5000
class RedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
"""Sends only headers when HEAD is requested
Args:
None:
Returns:
None
"""
s.end_headers()
def do_GET(s):
"""GET request from getting URL Redirection with return status code
Args:
None
Returns:
None
"""
print s.path
try:
temp = str(s.path)
code = int(temp[1:4])
url = temp[5:]
if code in (301, 302, 303, 307):
s.__send_redirect(code, url)
else:
s.send_response(400)
s.end_headers()
except:
s.send_response(400)
s.end_headers()
def __send_redirect(s, code, url):
s.send_response(code)
s.send_header("Location", url)
s.end_headers()
if __name__ == '__main__':
if len(sys.argv) == 2:
PORT_NUMBER = int(sys.argv[1])
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), RedirectHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
| true
|
94c39abb57532962ca90b9df933800cfa6d1b3b3
|
AswinT22/Code
|
/Daily/Vowel Recognition.py
| 522
| 4.1875
| 4
|
# https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/
def count_vowel(string,):
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
count = 0
length=len(string)
for i in range(0, length):
if(string[i] in vowel):
number=(length-i)
count += (number+(number*(i)))
return count
for _ in range(int(input())):
string = input()
print(count_vowel(string))
| true
|
8299f3f9b8ae5f7f1781d56037247da67de61ddd
|
Cpano98/Ejercicios-Clase
|
/PruebaWhile.py
| 329
| 4.125
| 4
|
#encoding: UTF-8
#Autor: Carlos Pano Hernández
#Prueba ciclo while
import turtle
def main():
radio=int(input("Radio:"))
while radio>0:
x=int(input("x:"))
y = int(input("y:"))
turtle.goto(x,y)
turtle.circle(radio)
radio=int(input("Radio:"))
turtle.exitonclick()
main()
| false
|
d9816ac73df50f5676313824859a15b10485a7c4
|
affreen/Python
|
/pyt-14.py
| 511
| 4.28125
| 4
|
"""demo - script that converts a number into an alphabet and then
determines whether it is an uppercase or lowercase vowel or consonant"""
print("Enter a digit:")
var=input()
var=int(var)
new_var=chr(var)
#if(new_var>=97 and new_var<=122):
if (new_var in ['a','e','i','o','u']):
print("You have entered a lowercase vowel:", new_var)
elif(new_var in ['A','E','I','O','U']):
print("You have entered an uppercase vowel:", new_var)
else:
print("You have entered a consonant:", new_var)
| true
|
f33786d90ed22092a69a7114e274fd8610c4d278
|
admcghee23/RoboticsFall2019GSU
|
/multiCpuTest.py
| 2,198
| 4.3125
| 4
|
#!/usr/bin/env python
'''
multiCpuTest.py - Application to demonstrate the use of a processor's multiple CPUs.
This capability is very handy when a robot needs more processor power, and has processing elements
that can be cleaved off to another CPU, and work in parallel with the main application.
https://docs.python.org/2/library/multiprocessing.html describes the many ways the application parts
can communicate, beyond this simple example
Copyright (C) 2017 Rolly Noel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
from multiprocessing import cpu_count, Process, Value, Array
import time
secondCpuToRun = Value('i', False) #Shared memory designation for an integer
timeLastSaw = Value('d', 0.) #Shared memory designation for a decimal number
def watchTheTime(timeLastSaw): #THIS FUNCTION RUNS ON ITS OWN CPU
print()
while secondCpuToRun.value:
now = time
timeLastSaw.value = time.time() #
print('2nd CPU reporting the time: %d' % timeLastSaw.value)
time.sleep(5) #Sleep for 5 seconds
print('Second CPU task shutting down')
if __name__ == '__main__':
print("System has %d CPUs" % cpu_count())
secondCpuToRun.value = True
proc = Process(target=watchTheTime, args=(timeLastSaw,)) #Consume another cpu - TRAILING COMMA NEEDED
proc.daemon = True
proc.start()
x = raw_input("Hit Enter to shut 2nd CPU down") #This CPU is blocked till user hits Enter
secondCpuToRun.value = False #Tell second CPU process to shut down
time.sleep(1) #Give it a chance
print("Last time 2nd CPU captured was %d" % timeLastSaw.value) #Show work 2nd CPU did
| true
|
18646e411b6caf292796e43014e8093d9c818655
|
Mahe7461/Python
|
/Python IDEL/comparison operator.py
| 257
| 4.25
| 4
|
#comparison operator
a=10
b=20
if a==b:
print('equal')
elif a!=b:
print('not equal')
elif a>b:
print('greater than')
elif a<b:
print('less than')
elif a>=b:
print('greater than or equal to')
elif a<=b:
print('less than or equal to')
| false
|
c7d0404c184ff42bd90467f8aebe5c6d1ac185a9
|
csuzll/PyDesignPattern
|
/创建型/SimpleFactory.py
| 1,093
| 4.4375
| 4
|
"""
简单工厂模式: 集中式生产
"""
# 斧头: 产品抽象类
class Axe(object):
def __init__(self, name):
self.name = name
def cutTree(self):
print("%s斧头砍树" % self.name)
# 花岗岩石斧头: 子产品类
class StoneAxe(Axe):
def cutTree(self):
print("使用%s砍树" % self.name)
# 铁斧头: 子产品类
class SteelAxe(Axe):
def cutTree(self):
print("使用%s砍树" % self.name)
# 工厂类
class Factory(object):
@staticmethod
def create_axe(type):
if type == "Stone":
axe = StoneAxe("花岗岩斧头")
return axe
elif type == "Steel":
axe = SteelAxe("铁斧头")
return axe
else:
print("输入类型错误,没有此类型的斧头")
class Person(object):
def __init__(self,name):
self.name = name
def work(self, axe_type):
print("%s开始工作" % self.name)
axe = Factory.create_axe(axe_type)
axe.cutTree()
if __name__ == '__main__':
p1 = Person("lili")
p1.work("Steel")
| false
|
7fb846cef384bf05421502c4602add3a30f2c889
|
mahespunshi/Juniper-Fundamentals
|
/Comprehensions.py
| 1,006
| 4.53125
| 5
|
# List comprehension example below. notes [] parenthesis. Comprehensions can't be used for tuple.
x =[x for x in range(10)]
print(x)
# create comprehension and it can creates for us, but in dict we need to create it first and then modify it.
# so, we can't create auto-dict, we can just modify dict, unlike list.
# Dictionary comprehension is implement after list comprehension
# Keys should be unique in dict, guess keys are tuples ()
dict1 = {'a': 5, 'b': 10, 'c': 15}
triple = {k:v**3 for (k,v) in dict1.items()}
print(triple)
triple = {k:v**3 for (k,v) in {'a': 3, 'b': 6}.items()}
print(triple)
# in dict, keys should be any immutable type tuple,set, so number or letters both are fine.
# read cha 1,
# Use enumerate in list or string when you want to store index values instead of using while loop with i counter
city = 'Boston'
for index, char in enumerate(city):
print(index, char)
# or using while loop instead of enumerate
i = 0
while i < len(city):
print(i, city[i])
i = i + 1
| true
|
19e0975c0f0f0df045b2c1a1e6ff13ad97a3aee6
|
BaDMaN90/COM404
|
/Assessment_1/Q7functions.py
| 1,429
| 4.3125
| 4
|
#file function have 4 functions that will do a cool print play
#this function will print piramids on the left of the face
def left(emoji):
print("/\/\/\\",emoji)
#this function will print piramids on the right of the face
def right(emoji):
print(emoji,"/\/\/\\")
#this function will print face between piramids
def both(emoji):
print("/\/\/\\",emoji,"/\/\/\\")
#this function will creat the grid of faces betweein piramids
#size of the grid will depend on the deifined size by the user
def grid(emoji,grid_size):
#2 loops will helo to create a nice grid
#first loop will define the height of the grid f.e. grid_size = 3 means that loop will creat 3 rows
#second loop will print the correct patternt in the raw
for x in range(grid_size):
for operator in range(-1,grid_size):
#operator range is from -1 to grid_size
#program will print piramids followed by face only on the first print. this will make sure that if grid size is 1 then the print still work.
#else the program will print 5 piramids followed by a face
if operator <= -1 or operator == grid_size-1:
print("/\/\/\\ ", end ="")
if operator != grid_size-1:
print(emoji,"", end='')
operator +=1
else:
print("/\/\/\/\/\\",emoji,"", end ="")
operator +=1
print("")
| true
|
3f7d577aacbb73da5406b3676fb12d9947c98e51
|
BaDMaN90/COM404
|
/Basic/4-repetition/1-while-loop/2-count/bot.py
| 684
| 4.125
| 4
|
#-- importing the time will allow the time delay in the code
#-- progtram will print out the message and ask for input
#-- 2 variables are created to run in the while loop to count down the avoided live cables and count up how many have avoided
import time
print("Oh no, you are tangle up in these cables :(, how many live cables are you wrpped in?")
no_cables = int(input())
live_cable = 1
#-- while loop will run as long as no_cables are different then 0
while no_cables !=0:
print("Avoiding...")
no_cables = no_cables - 1
time.sleep(1)
print(str(live_cable) + " live cable avoided")
live_cable = live_cable + 1
time.sleep(1)
print("All live cable avoided")
| true
|
5996714a292cf5902cefb2830c497c7d81959b54
|
RPadilla3/python-practice
|
/python-practice/py-practice/greeter.py
| 407
| 4.1875
| 4
|
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\n Hello, " + name + "!")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
| true
|
5d10bf344a26b484e373e93cd734b9c405d3076c
|
rexrony/Python-Assignment
|
/Assignment 4.py
| 2,548
| 4.25
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
#Question 1
firstname = input("Your First Name Please ");
lastname = input("Your Last Name Please ");
age = int(input("Your Age Please "));
city = input("Your City Please ");
userdata = {
'first_name': firstname,
'last_name': lastname,
'age': age,
'city': city,
}
print("\n----------------\n")
print(userdata['first_name'])
print(userdata['last_name'])
print(userdata['age'])
print(userdata['city'])
# In[3]:
#Question 2
dubai = {
'country': 'UAE',
'population': '3.137 million',
'fact': 'The total population of Dubai is 3.1 million. Arabic is the official language. The currency is UAE dirham (AED).',
}
karachi = {
'country': 'PAKISTAN',
'population': '14.91 million',
'fact': 'In 1729, real settlements were founded, and it was named Kolachi after the name of an old woman, Mai Kolachi (Auntie Kolachi). She was the head of a village and was known for her fair decisions. However, there are many other tales about this city’s former name ‘Kolachi.’',
}
Mumbai = {
'country': 'INDIA',
'population': '13 million',
'fact': 'Every day in Mumbai, more than 200 trains make over 2,000 trips along 300 kilometres of track, carrying more passengers per kilometre than any railway on earth.',
}
#for key, value in Mumbai.items():
# print(key, "=", value)
print("DUBAI");
for key, value in dubai.items():
print(key, "=", value)
print("\n----------------\n")
print("PAKISTAN");
for key, value in karachi.items():
print(key, "=", value)
print("\n----------------\n")
print("Mumbai");
for key, value in Mumbai.items():
print(key, "=", value)
# In[1]:
#Question 3
ask_age = "How old are you?"
ask_age += "\nType 'end' when you are finished adding age. "
while True:
age = input(ask_age)
if age == 'end':
break
age = int(age)
if age < 18:
print(" You get in free!")
elif age <= 19:
print(" Your ticket is $10.")
else:
print(" Your ticket is $15.")
# In[2]:
#Question 4
def favorite_book(title):
print(title + " is one of my favorite books.");
fvrt_book = input("Enter your Favorite Book Name : ");
favorite_book(fvrt_book)
# In[2]:
#Question 5
import random
it=random.randint(1, 30)
def main():
x=int(input('Guess a number between 1 and 30 = '))
if x == it:
print("You got it!")
elif x > it:
print("too high")
main()
else:
print("too low")
main()
main()
# In[ ]:
# In[ ]:
| true
|
8536c9d42de73a7e2b426c38df271740c51f79e2
|
HarshHC/DataStructures
|
/Stack.py
| 1,819
| 4.28125
| 4
|
# Implementing stack using a linked list
# Node Class
class Node(object):
# Initialize node with value
def __init__(self, value):
self.value = value
self.next = None
# Stack Class
class Stack(object):
# Initializing stack with head value and setting default size to 1
def __init__(self, head=None):
self.head = head
if head:
self.size = 1
else:
self.size = 0
# Function to print the entire stack as string
def printStack(self):
current = self.head
while current:
print(str(current.value) + " -> ", end="")
current = current.next
print(str(current))
# Function to get current size of the stack
def getSize(self):
return self.size
# Function to check if the stack is empty
def isEmpty(self):
return self.size == 0
# Function to get the top item in the stack
def peek(self):
if self.isEmpty():
raise Exception("Peeking from an empty stack")
print(self.head.value)
# function to add an item to the top of the stack
def push(self, item):
item.next = self.head
self.head = item
self.size+=1
# function to remove an item from the top of the stack
def pop(self):
if self.isEmpty():
raise Exception("Popping from an empty stack")
self.head = self.head.next
self.size-=1
# Create a Stack
stack = Stack()
# Print current stack size
print(stack.getSize())
# Push Data to the top
stack.push(Node('head'))
stack.push(Node(1))
stack.push(Node(2))
stack.push(Node(3))
stack.push(Node(4))
stack.push(Node(5))
# Display the stack
stack.printStack()
# Pop Data from the top
stack.pop()
stack.printStack()
# Peek top item
stack.peek()
| true
|
82bc520ff6d2ea345f94e190032a06296eb89b77
|
SugeilyCruz/edd_1310_2021
|
/adts/Funcion Recursiva/tarea.py
| 1,547
| 4.1875
| 4
|
print("Crear una lista de enteros en Python y realizar la suma con recursividad, el caso base es cuando la lista este vacia.")
def suma_lista_rec(lista):
if len(lista) == 1:
return lista[0]
else:
return lista.pop() + suma_lista_rec(lista)
def main():
datos= [4,2,3,5]#14
dt= [4,2,3,5]
res=suma_lista_rec(datos)
print(f"\tLista: {dt} Suma total: {res}\n")
main()
print("Hacer una función recurso que dado un número entero positivo,imprima a la salida una cuenta regresiva hasta cero.")
def regresiva(num):
if num >=0:
print(f"\t\t\t{num}")
regresiva(num-1)
def main2():
num=5
print(f"\t\tNumero ingresado: {num}")
regresiva(num)
main2()
print("Hacer una función recursiva que reciba de entrada una pila con al menos 3 elementos y con recursividad elimine el elemento en la posición media.")
def deleteMid(pila, curr=1) :
middle=round((pila.length()+curr) /2)
if (pila.is_empty()):
return
else:
if (curr != middle):
n = pila.peek()
pila.pop()
deleteMid(pila, curr= curr+1)
pila.push(n)
else:
print(f"Valor medio de la pila: {pila.peek()}")
pila.pop()
from pilas import Stack
def main3():
st = Stack()
st.push('q')
st.push('u')
st.push('e')
st.push('s')#eliminar
st.push('i')
st.push('t')
st.push('o')
print("---Pila inicial---")
st.to_string()
print("---Pila Nueva---")
deleteMid(st)
st.to_string()
main3()
| false
|
dec63d4f99825d1934be4b81836d5a3728b8038e
|
DKanyana/Code-Practice
|
/ZerosAndOnes.py
| 372
| 4.25
| 4
|
"""
Given an array of one's and zero's convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
"""
def binary_array_to_number(arr):
binNum = 0
for cnt,num in enumerate(arr):
binNum += num * (2 ** (len(arr)-1-cnt))
return binNum
print(binary_array_to_number([0,0,1,0]))
| true
|
67588905fa64b3e7efa93541b569769688d1600f
|
krrish12/pythonCourse
|
/Day-4/DecisionMaking.py
| 1,578
| 4.125
| 4
|
var,var1 = 100,110
if ( var == 100 ) : print("Value of expression is 100 by Comparison operator")
#output: Value of expression is 100
if ( var == 10 ): print("Value of expression is 10 by Comparison operator")
elif(var1 == 50): print("Value of expression is 50 by Comparison operator")
else:print("Value of expression is 110 by Comparison operator")
#output: Value of expression is 100
if ( var or var1 ) : print("Result of expression is True by Logical operator")
#output: Result of expression is True by Logical operator
if ( var and var1 ) : print("Result of expression is False by Logical operator")
#output: Result of expression is False by Logical operator
if (not(var and var1)) : print("Result of expression is False by Logical operator")
else: print("Result of expression is True by Logical operator")
#output: Result of expression is True by Logical operator
if(var is 100): print("Value of expression is 100 by identity operator")
#output Value of expression is 100
if(var is not 100): print("Value of expression is 100 by identity operator")
else: print("Value of expression is 100 by identity operator by else ")
#output Value of expression is 100 by identity operator by else
obj,obj1 = 2,[1,2,10]
if(obj in obj1): print("Value of expression is 100 by membership operator")
#output Value of expression is 100 by membership operator
if(obj not in obj1): print("Value of expression is 100 by membership operator")
else :print("Value of expression is 100 by membership operator by else")
#output Value of expression is 100 by membership operator by else
| true
|
982cdcd7b9d77313def824ed2540e1d4f609f0ab
|
krrish12/pythonCourse
|
/Day-3/operators.py
| 1,463
| 4.21875
| 4
|
obj=10+4
print(obj)#int type
#output: 14
obj=10+3.0
print(obj)#float type
#output:13.0
obj=10-4
print(obj)#int type
#output: 6
obj=10-3.0
print(obj)#float type
#output:7.0
obj=2*2
print(obj)#int type
#output: 4
obj=4.0*2
print(obj)#float type
#output: 8.0
obj=2/2
print(obj)#float type
#output: 1.0
obj=2%2
print(obj)#int type
#output:0
obj=2%2.0
print(obj)#float type
#output: 0.0
obj=2.0%2
print(obj)#float type
#output: 0.0
obj=10+4j
print(obj)#complex type
#output:(10+4j)
obj = 2**3
print(obj)#int type
#output: 8
obj = 3//2
print(obj)#int type
#output: 1
obj = 3//2.0
print(obj)#float type
#output: 1.0
#Comparison Operators
obj,obj1 = 2,3
print(obj == obj1)#boolean type
#output: False
print(obj is obj1)
#output: False
print(obj != obj1)
#output: True
print(not(obj == obj1))
#output: True
print(not(obj != obj1))
#output: False
print(obj > obj1)
#output: False
print(obj < obj1)
#output: False
print(obj >= obj1)
#output: True
print(obj <= obj1)
#output: False
#Logical Operators
print(obj and obj1)
#output: 3
print(obj or obj1)
#output: 2
#Bitwise Operators
print(obj & obj1)
#output: 2
print(obj | obj1)
#output: 3
print(~obj)
#output: -3
print(obj ^ obj1)
#output: 1
print(obj>> 2)
#output: 0
print(obj << 5)
#output: 64
#Identity Operators
print(obj is not obj1)
#output: True
print(obj is obj1)
#output: False
#Membership Operators
a,b = 2,[1,2,3]
print(a in b)
#output: True
print(a not in b)
#output: False
| false
|
56af4680b7f68a43096c0c8d8a9d81a318b3ceea
|
Tom0497/BCS_fuzzy
|
/src/FuzzyFact.py
| 2,097
| 4.46875
| 4
|
class FuzzyFact:
"""
A class to represent a fuzzy fact, i.e. a fact or statement with a value of certainty in the range [-1, 1],
where -1 means that the fact is a 100% not true, whereas a value of 1 means that the fact is a 100% true,
finally, a value of 0 means ignorance or lack of knowledge in terms of the fact or statement considered.
In specific, this application considers facts or statements about animals, therefore, the facts must match
one of these next formats:
* el animal tiene [attribute]
* el animal es [adjective]
Where both of these sentences are in spanish, and so must the objects created be.
"""
def __init__(self, obj: str, atr: str, val: str, cv: float = 0):
"""
Creates a new FuzzyFact object, from a fact or statement in the form of a three-part
sentence whose parts are:
* object
* attribute
* value
Also, a certainty value can be assigned to the object as specified before.
:param obj: the object of the sentence
:param atr: the attribute in the sentence
:param val: the value in the sentence
:param cv: the certainty value, a float in the range [-1, 1], default value is 0
"""
self.obj: str = obj
self.atr: str = atr
self.val: str = val
self.cv: float = 0.0
self.assign_cv(cv)
def assign_cv(self, cv: float):
"""
Assigns the certainty value to the FuzzyFact object. It makes sure the value is in the range [-1, 1]
"""
assert -1 <= cv <= 1, 'Certainty value is not in the range [-1, 1]'
self.cv: float = cv
def __repr__(self):
"""
Put the object together for printing.
Magic method for print(object) command.
"""
sentence = ' '.join([self.obj, self.atr, self.val])
sentence = f'(({sentence}) {self.cv})'
return sentence
if __name__ == "__main__":
fact1 = FuzzyFact('el animal', 'tiene', 'pelo')
fact1.assign_cv(0.9)
print(fact1)
| true
|
6048b803d984e8837f31aaa7c31667e396f4b0b0
|
yogesh1234567890/insight_python_assignment
|
/completed/Data3.py
| 384
| 4.21875
| 4
|
'''3. Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t' '''
user=input("Enter a word: ")
def replace_fun(val):
char=val[0]
val=val.replace(char,'$')
val=char + val[1:]
return val
print(replace_fun(user))
| true
|
12d6c22a4cdacef7609f965d1f682213f06d25d1
|
yogesh1234567890/insight_python_assignment
|
/completed/Data22.py
| 267
| 4.1875
| 4
|
#22. Write a Python program to remove duplicates from a list.
mylist=[1,2,3,4,5,4,3,2]
mylist = list(dict.fromkeys(mylist))
print(mylist)
##here the list is converted into dictionaries by which all duplicates are removed and its well again converted back to list
| true
|
c0874441b6ae538e3be713d71015ec626f04272f
|
yogesh1234567890/insight_python_assignment
|
/functions/Func14.py
| 498
| 4.4375
| 4
|
#14. Write a Python program to sort a list of dictionaries using Lambda.
models = [{'name':'yogesh', 'age':19, 'sex':'male'},{'name':'Rahsit', 'age':70, 'sex':'male'}, {'name':'Kim', 'age':29, 'sex':'female'},]
print("Original list:")
print(models)
sorted_models = sorted(models, key = lambda x: x['name'])
print("\nSorting the List on name basis::")
print(sorted_models)
sorted_models = sorted(models, key = lambda x: x['age'])
print("\nSorting the List on age basis::")
print(sorted_models)
| true
|
93705ba1b2d202737fa5f9f9852ed9814f768eb4
|
yogesh1234567890/insight_python_assignment
|
/functions/Func5.py
| 313
| 4.40625
| 4
|
""" 5. Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument. """
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
n=int(input("Insert a number to calculate the factiorial : "))
print(fact(n))
| true
|
7d701dbeb4a04cda556c0bc2da03de589a1d26e9
|
yogesh1234567890/insight_python_assignment
|
/completed/Data39.py
| 206
| 4.1875
| 4
|
#39. Write a Python program to unpack a tuple in several variables.
a = ("hello", 5000, "insight")
#here unpacking is done
(greet, number, academy) = a
print(greet)
print(number)
print(academy)
| true
|
93d2d0026b5d737c60049229091c9c01faedf0f0
|
yogesh1234567890/insight_python_assignment
|
/functions/Func7.py
| 666
| 4.25
| 4
|
""" 7. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12 """
string="The quick Brow Fox"
def check(string):
upper=0
lower=0
for i in range(len(string)):
if ord(string[i])>=97 and ord(string[i])<=122:
lower+=1
else:
if ord(string[i])==32:
continue
upper+=1
print("No. of Upper case characters: "+str(upper))
print("No. of Lower case characters: "+str(lower))
check(string)
| true
|
45c4e66f0dba9851ea5539d2c98e6076ed1ad8fd
|
sk-ip/coding_challenges
|
/December_2018/stopwatch.py
| 734
| 4.125
| 4
|
# program for stopwatch in python
from datetime import date, datetime
def stopwatch():
ch=0
while True:
print('stopwatch')
print('1. start')
print('2. stop')
print('3. show time')
print('4. exit')
ch=input('enter your choice:')
if ch=='1':
start=datetime.now()
print('time started at',start)
elif ch=='2':
stop=datetime.now()
print('time stopped at',stop)
elif ch=='3':
time_taken=start-stop
print('your timing is:',divmod(time_taken.days * 86400 + time_taken.seconds, 60))
else:
print('exiting')
exit()
if __name__=="__main__":
stopwatch()
| true
|
888537ae81ac1f0a4b2b1452d32bd86b004c610c
|
B001bu1at0r81/Home-Work
|
/Home_Work4/Home_Work4_Task_3.py
| 664
| 4.125
| 4
|
###################################
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
#!!!_______Orest Danysh________!!!#
#!!!________Home-work_4________!!!#
#!!!___________Task_3__________!!!#
#!!!_____Fibonacci_number______!!!#
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
###################################
quantity_of_numbers = int(input("Input number of members : "))
fibonacci = [0, 1]
temp = 0
i = 2 #оскільки пеших два числа Фібоначчі у нас вже є, то починаємо з третього
while i < quantity_of_numbers:
temp = fibonacci[i-1] + fibonacci[i-2]
fibonacci.insert(i, temp)
i += 1
for item in fibonacci:
print(item)
| false
|
9f34a088a4d0a61f2af65fa911222eb2d3372dd8
|
mbramson/Euler
|
/python/problem016/problem016.py
| 488
| 4.125
| 4
|
# -*- coding: utf-8 -*-
## Power Sums
## 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
## What is the sum of the digits of the number 2**1000?
## This is actually a very simple problem in python, because Python automatically deals with large numbers.
## Returns the Power Sum of n. As in it sums the digits of 2^n
def PowerSum(n):
sumstring = str(2**n)
total = 0
for s in sumstring:
total += int(s)
return total
print(PowerSum(1000))
| true
|
a4382447caa1d2c2e4bfd9ddedef88a7063bf943
|
valerienierenberg/holbertonschool-low_level_programming
|
/0x1C-makefiles/5-island_perimeter.py
| 1,421
| 4.1875
| 4
|
#!/usr/bin/python3
"""This module contains a function island_perimeter that returns
the perimeter of the island described in grid
"""
def island_perimeter(grid):
"""island_perimeter function
Args:
grid ([list of a list of ints]):
0 represents a water zone
1 represents a land zone
One cell is a square w/ side length 1
Grid cells are connected horiz/vertically (not diagonally).
Grid is rectangular, width and height don’t exceed 100
The island is one contiguous land mass
"""
perim = 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 1: # value is 1 at that cell
if row == 0 or grid[row - 1][col] == 0:
# outer rows always 0s, OR one cell above it is 0
perim += 1
if col == 0 or grid[row][col - 1] == 0:
# outer cols always 0s, OR one cell to the left is 0
perim += 1
if row == len(grid) - 1 or grid[row + 1][col] == 0:
# if row is one above bottom OR value below curr pos. is 0
perim += 1
if col == len(grid) - 1 or grid[row][col + 1] == 0:
# col is one to left of end OR value left of curr pos. is 0
perim += 1
return perim
| true
|
74a62d228dbd2ce456d09211bea6f15d822ca3f7
|
James-E-Sullivan/BU-MET-CS300
|
/sullivan_james_lab3.py
| 2,052
| 4.25
| 4
|
# Eliza300
# Intent: A list of helpful actions that a troubled person could take. Build 1
possible_actions = ['taking up yoga.', 'sleeping eight hours a night.',
'relaxing.', 'not working on weekends.',
'spending two hours a day with friends.']
'''
Precondition: possible_actions is the list defined above
Postconditions:
1. (Welcome): A welcome message is on the console
2. (user_complaint): user_complaint is the user's response to a prompt for the
user's complaint
3. (how_long): how_long is the user's string response to "How many months have
you experience ...?" AND Eliza300 sympathized, mentioning duration
4. (Advice):
EITHER how_long < 3 AND "Please return in * months" is on the console where *
is 3-how_long
OR how_long >= 3 AND The phrases in possible_actions are on separate lines
on the console, each preceded by "Try ".
'''
# Welcome message from Eliza300 is printed on the console
print("Thank you for using Eliza300, a fun therapy program.")
# User prompted to input their emotional complaint
# User complaint stored as string in variable 'user_complaint'
print("Please describe your emotional complaint--in one punctuation-free line:")
user_complaint = input()
# User prompted to input number of months they have experienced their complaint
# User input stored as string in variable 'how_long'
print("How many months have you experienced '" + user_complaint + "'?")
how_long = input()
# Eliza300 sympathetic response, mentioning during, printed to console
print(how_long + " months is significant. Sorry to hear it.")
# Eliza advice, which is dependent on value of how_long, printed to console
# If how_long < 3, Eliza suggests user comes back when how_long is 3
# Otherwise, Eliza provides suggestions from list of possible_actions
if int(how_long) < 3:
print("Please return in " + str(3 - int(how_long)) + " months.")
else:
for possible_actions_index in range(5):
print("Try " + possible_actions[possible_actions_index])
| true
|
91e5fa35bc4ea64c7cc65e096d10ed0d91d8d88b
|
bperard/PDX-Code-Guild
|
/python/lab04-grading.py
| 320
| 4.125
| 4
|
score = int(input('On a scale of 0-100, how well did you?'))
grade = ''
if score > 100:
grade = 'Overachiever'
elif score > 89:
grade = 'A'
elif score > 79:
grade = 'B'
elif score > 69:
grade = 'C'
elif score > 59:
grade = 'D'
elif score >= 0:
grade = 'F'
else:
grade = 'Leave'
print(grade)
| true
|
21ab8c793589afe2c8f984db02ca2b5650be962b
|
bperard/PDX-Code-Guild
|
/python/lab08-roshambo.py
| 1,309
| 4.25
| 4
|
'''
Rock, paper, scissors against the computer
'''
import random
throws = ['rock', 'paper', 'scissors'] #comp choices
comp = random.choice(throws)
player = input('Think you can beat me in a game of Roshambo? I doubt it, but let\'s give it a shot.\n Choose your weapon: paper, rock, scissor.').lower() #player prompt
while player == comp: #check for tie, and replay
player = input('It\'s a tie, we can\'t end without a loser. Type "done," or throw again.').lower()
comp = random.choice(throws)
if player == 'done':
break
# rock outcome
if player == 'rock':
if comp == 'scissors':
print('You must be very proud of yourself, you win.')
else:
print('Computers are the future, this is just the beginning; you lose.')
# scissors outcome
elif player == 'scissors':
if comp == 'paper':
print('You must be very proud of yourself, you win.')
else:
print('Computers are the future, this is just the beginning; you lose.')
# paper outcome
elif player == 'paper':
if comp == 'rock':
print('You must be very proud of yourself, you win.')
else:
print('Computers are the future, this is just the beginning; you lose.')
# horrible person outcome
else:
print('There were three choices... how did you mess that up; you lose.')
| true
|
75566c13a5e09874a1ea4ff64c7f198b7f4218fc
|
bperard/PDX-Code-Guild
|
/python/lab31-atm.py
| 2,865
| 4.21875
| 4
|
'''
lab 31 - automatic teller machine machine
'''
transactions = [] # list of deposit/withdraw transactions
class ATM: # atm class with rate and balance attribute defaults set
def __init__(self, balance = 0, rate = 0.1):
self.bal = balance
self.rat = rate
def __str__(self): # format when returned as a string
return 'BAL=' + str(self.bal) + '\nRAT=' + str(self.rat)
def check_balance(self): # return balance attribute
return self.bal
def deposit(self, amount): # add deposit parameter to ATM balance attribute, add transaction to list
self.bal += amount
transactions.append('User deposited $' + str(amount))
def check_withdrawal(self, amount): # return True if balance greater than amount parameter
return self.bal - amount >= 0
def withdraw(self, amount): # subtract parameter amount from balance attribute, add transaction, and return amount
self.bal -= amount
transactions.append('User withdrew $' + str(amount) + '\n')
return amount
def calc_interest(self): # return interest rate
return self.rat
def print_transactions(self): # print transaction history in separate lines
for lines in transactions:
print(lines)
print('Welcome, I am an ATM, feed me money!\n' # intro and user input stored in teller variable
'Just kidding, that was my humor function, hopefully I haven\'t offended you.\n'
'Now that you are done laughing, what would you like to do?\n'
'Enter "done" at any time to exit your account.')
teller = input('Choose "deposit", "withdraw", check "balance", and "history":')
account = ATM() # account variable initialized as ATM type
while teller != 'done': # while loop until teller == 'done'
if teller.lower() == 'deposit': # user input amount, call deposit function
amount = int(input('Enter how much you would like to deposit: $'))
account.deposit(amount)
elif teller.lower() == 'withdraw': # user input amount, call check_withdraw, call withdraw if True, notify user if False
amount = int(input('Enter how much you would like to withdraw: $'))
if account.check_withdrawal(amount):
account.withdraw(amount)
else:
print('Can\'t withdraw $' + str(amount) + ', balance is $' + str(account.bal) + '.')
elif teller.lower() == 'balance': # show user balance
print('Your balance is $' + str(account.bal) + '.')
elif teller.lower() == 'history': # call print_transactions
account.print_transactions()
if teller != 'done': # ask user for new mode
teller = input('Choose "deposit", "withdraw", check "balance", and "history":')
print('Work to live, don\'t live to work... okay, goodbye.') # pass knowledge and love to user
| true
|
e5a8eae58dc45a0259309b867eeac974b3dc7d62
|
bperard/PDX-Code-Guild
|
/python/lab09-change.py
| 838
| 4.25
| 4
|
'''
Making change
'''
# declaring coin values
quarters = 25
dimes = 10
nickles = 5
pennies = 1
# user input, converted to float
change = float(input('Giving proper change is key to getting ahead in this crazy world.\n'
'How much money do you have? (for accurate results, use #.## format)'))
# convert float to int for math
change = int(change * 100)
# proper coinage math
#first line determins amount, second passes remaining change forward
quarters = int(change // quarters)
change -= quarters * 25
dimes = int(change // dimes)
change -= dimes * 10
nickles = int(change // nickles)
change -= nickles * 5
pennies = int(change // pennies)
# print proper coinage
print('Proper change is: ' + str(quarters) + ' quarters, ' + str(dimes) + ' dimes, ' + str(nickles) + ' nickles, and ' + str(pennies) + ' pennies.')
| true
|
07de036683eeaf643caaa7e140c8959af82703e7
|
RobertCochran/connect4
|
/user_input.py
| 1,148
| 4.25
| 4
|
import random
def user_input():
""" This function allows the user to choose where their red piece goes. """
print "We're going to play Connect Four."
print " I'll be black and you'll be red. "
print "You go first and choose where you want to put your piece. There are seven columns in total."
valid_move = False
while not valid_move:
col = input(" Choose a column to put your piece in (1-7): ")
for row in range (6,0,-1):
if (1 <= row <= 6) and (1 <= col <= 7) and (board[row-1][col-1] == "."):
board[row-1][col-1] = 'r'
valid_move = True
break
else:
print "Error, please restart game and try again."
def computer_choice():
""" this function has the computer randomly choose where it will set its
piece """
valid_move = False
while not valid_move:
row = random.randint(0,6)
col = random.randint(0,7)
for row in range (6,0,-1):
if board[row][col] == ".":
board[row][colum] == "b"
valid_move = True
break
| true
|
eb7cb4ffdec2e4c5790db0c1d1b407ed5b8a2930
|
galgodon/astr-119-hw-1
|
/operators.py
| 1,641
| 4.5
| 4
|
#!/usr/bin/env python3 # makes the terminal know this is in python
x = 9 #Set variables
y = 3
#Arithmetic Operators
print(x+y) # Addition
print(x-y) # Subtraction
print(x*y) # Multiplication
print(x/y) # Division
print(x%y) # Modulus (remainder)
print(x**y) # Exponentiation (to the power of)
x = 9.191823 # Make x into a complicated float to show the effect of floor division
print(x//y) # Floor Division (divide but get rid of the decimal will ALWAYS round down)
# how many whole times does y go into x
# Assignment Operators
x = 9 # set x back to 9. Single equal ASSIGNS the value. Double equals is boolean
x += 3 # take the previous value of x and add 3. So x is now 12
print(x)
x = 9 # set x back to 9.
x -= 3 # take the previous value of x and subtract 3. So x is now 6
print(x)
x = 9 # set x back to 9
x *= 3 # take the previous value of x and multiply by 3. x = 27
print(x)
x = 9 # set x back to 9
x /= 3 # take the previous value of x and divide 3. x = 3
print(x)
x = 9 # set x back to 9
x **= 3 # take the previous value of x and put it to the power of 3. x = 9^3
print(x)
# Comparison Operators - Booleans
x = 9
y = 3
print(x==y) # is x the same as y? In this case False
print(x!=y) # is x different than y? In this case True
print(x>y) # is x greater than y? In this case True
print(x<y) # is x less than y? In this case False
print(x>=y) # is x greater than or equal to y? In this case True
print(x<=y) # is x less than or equal to y? In this case False
| true
|
9bdfa82561a8638beb7caa171e52f717cc3bb89e
|
galgodon/astr-119-hw-1
|
/functions.py
| 1,209
| 4.1875
| 4
|
#!/usr/bin/env python3
import numpy as np # import numpy and sys
import sys
def expo(x): # define a function named expo that needs one input x
return np.exp(x) # the function will return e^x
def show_expo(n): # define a subroutine (does not return a value)
# n needs to be an integer
for i in range(n): # loop i values from 0 to n
print(expo(float(i))) # call the expo function. also convert i to a
# float to be safe
def main(): # define main function, no input needed
n = 10 # provide a default value for n
if (len(sys.argv)>1): # sys.argv is the command line arguements.
n = int(sys.argv[1]) # if a command line arguement is provided, use it for n
# in cmd: python3 functions.py [insert argv here]
show_expo(n) # call the show_expo subroutine with the input n
# if there are no command line arguements, n is the default 10
if __name__ == '__main__': # run the main() function
main()
| true
|
3ad1a7fcb0a7b6d2c7ba0e1f639d396c6adf6fe7
|
Peter-Moldenhauer/Python-For-Fun
|
/If Statements/main.py
| 502
| 4.3125
| 4
|
# Name: Peter Moldenhauer
# Date: 1/12/17
# Description: This program demonstrates if statements in Python - if, elif, else
# Example 1:
age = 12
if age < 21:
print("Too young to buy beer!")
# Example 2:
name = "Rachel"
if name is "Peter": # you can use the keword is to compare strings (and also numbers), it means ==
print("Hello Peter!")
elif name is "Rachel":
print("Good afternoon Rachel")
elif name is "Bob":
print("Yo Bob what up!")
else:
print("Um I don't know your name!")
| true
|
b26499e29901a2733e78fc344d500378924488e6
|
python-programming-1/homework-3-kmc89
|
/HW3.py
| 310
| 4.1875
| 4
|
num = 0
try:
num_input = input('Enter a number: ')
except:
print('Invalid input!')
num = int(num_input)
def collatz(num):
if (num)%2 == 0:
col_num = int(num /2)
print(col_num)
return (col_num)
else:
col_num = num * 3 + 1
print(col_num)
return (col_num)
while num > 1:
num = collatz(num)
| false
|
971e882b734c6217358ea3c384e58b0554206a3b
|
FA0AE/Mision-04
|
/Triangulos.py
| 1,519
| 4.3125
| 4
|
#Francisco Ariel Arenas Enciso
#Determinación de un triángulo de acuerdo a la medida de sus lados
'''
Mediante el uso de operadores lógicos y relacionales, y de los datos enviados por "main()",
la función decide que tipo de triángulo es.
'''
def decidirTriangulo(lado1, lado2, lado3):
if lado1 == lado2 and lado1 == lado3:
return "forman un triángulo equilatero"
elif lado1 == lado2 or lado1 == lado3:
return "forman un triángulo isósceles"
elif lado2 == lado3:
return "forman un triángulo isósceles"
elif ((lado1**2)+(lado2**2))**0.5 == lado3:
return "forman un triángulo rectángulo"
elif ((lado2 ** 2) + (lado3** 2)) ** 0.5 == lado1:
return "forman un triángulo rectángulo"
elif ((lado1 ** 2) + (lado3 ** 2)) ** 0.5 == lado2:
return "forman un triángulo rectángulo"
else:
return "no pertenecen a ningún triángulo"
'''
Función main, la cual controla todo el programa, envía las medidas de los lados a la función "decidirTriangulo"
e imprime el mensaje de acuerdo al resultado obtenido de la función.
'''
def main():
lado1 = int(input("Escribe la medida del primer lado de tu figura: "))
lado2 = int(input("Escribe la medida del segundo lado de tu figura: "))
lado3 = int(input("Escribe la medida del tercer lado de tu figura: "))
mensaje = decidirTriangulo(lado1, lado2, lado3)
print("---------------------------------")
print("Las medidas dadas %s" % (mensaje))
main()
| false
|
86148c0044b69aea97ee2609548116160898a6bb
|
Douglas1688/Practices
|
/operaciones_matematicas/calculos_generales.py
| 549
| 4.1875
| 4
|
"""Este módulo permite realizar operaciones matemáticas"""
def sumar(x,y):
print("El resultado de la suma es: ",x+y)
def restar(x,y):
print("El resultado de la suma es: ",x-y)
def multiplicar(x,y):
print("El resultado de la suma es: ",x*y)
def dividir(x,y):
print("El resultado de la suma es: ",x//y)
def potencia(x,y):
print("El resultado de la suma es: ",x**y)
def raiz_cuadrada(x,y):
print("El resultado de la suma es: ",x**(1/2))
def factorial(x):
if x==0:
return 1
else:
return x*factorial(x-1)
| false
|
bda62fab31e84c7569144db7354b0072603f52b4
|
seashore001x/PythonDataStructure
|
/BinarySearchTree.py
| 1,514
| 4.21875
| 4
|
class BinaryTree:
def __init__(self):
self.tree = EmptyNode()
def __repr__(self):
return repr(self.tree)
def lookup(self, value):
return self.tree.lookup(value)
def insert(self, value):
self.tree = self.tree.insert(value)
class EmptyNode:
def __repr__(self):
return '*'
def lookup(self, value):
return False
def insert(self, value):
return BinaryNode(self, value, self)
class BinaryNode:
def __init__(self, left, value, right):
self.data, self.left, self.right = value, left, right
def lookup(self, value):
path = []
if self.data == value:
return self.data
elif self.data > value:
print(self.data, end='->') # print the root path
return self.left.lookup(value)
else:
print(self.data, end='->') # print the root path
return self.right.lookup(value)
def insert(self, value):
if self.data > value:
self.left = self.left.insert(value)
elif self.data < value:
self.right = self.right.insert(value)
elif self.data == value:
print('Data already exist')
return self
def __repr__(self):
return '(%s, %s, %s)' % (repr(self.left), repr(self.data), repr(self.right))
if __name__ == '__main__':
y = BinaryTree()
print(y)
for i in [3, 1, 9, 2, 7]:
y.insert(i)
print(y)
print(y.lookup(7)) # test lookup
| false
|
df41b52417f3f769d2e6bfe452a76c7e9a67d886
|
su6i/masterIpsSemester1
|
/HMIN113M - Système/tp's/factoriel.py
| 316
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import sys, os
os.system("clear")
r=1
if len(sys.argv) == 2:
n = int(sys.argv[1])
if n<0:
print("Please enter a number superior than 2")
elif n<2 and n>0:
print(n,"!= 1")
else:
while n >= 2:
r *=n
n -=1
print(sys.argv[1]+"! = ",r)
| false
|
26cdf3876507195bf2db3deb50b2bee7eb316483
|
JatinBumbra/neural-networks
|
/2_neuron_layer.py
| 1,059
| 4.15625
| 4
|
'''
SIMPLE NEURON LAYER:
This example is a demonstration of a single neuron layer composed of 3 neurons. Each neuron has it's own weights that it
assigns to its inputs, and the neuron itself has a bias. Based on these values, each neuron operates on the input vector
and produces the output.
The below program demonstrates the ouput of a layer.
NOTE: This example does not combine the result into a single value, like the final output layer which has one
output(in simplest case)
'''
inputs = [1, 2, 3, 2.5]
weights1 = [0.2, 0.8, -0.5, 1.0]
weights2 = [0.5, -0.91, 0.26, -0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
output = [inputs[0]*weights1[0] + inputs[1] * weights1[1] + inputs[2]*weights1[2] + inputs[3]*weights1[3] + bias1,
inputs[0]*weights2[0] + inputs[1] * weights2[1] +
inputs[2]*weights2[2] + inputs[3]*weights2[3] + bias2,
inputs[0]*weights3[0] + inputs[1] * weights3[1] + inputs[2]*weights3[2] + inputs[3]*weights3[3] + bias3, ]
print(output)
| true
|
8eb8573aacab9bc276179414ebd75e4cf664cf47
|
sankalp-sheth/FSDP2019
|
/day3/weeks.py
| 252
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon May 13 13:22:14 2019
@author: KIIT
"""
week_days=('Monday', 'Wednesday', 'Thursday', 'Saturday')
new_days=(week_days[0],)+("Tuesday",)+week_days[1:3]+("Friday",)+(week_days[-1],)+("Sunday",)
print(new_days)
| false
|
12284512b8af388e4ed161a00fea411dfead3100
|
sakura-fly/learnpyqt
|
/src/布局/绝对定位.py
| 1,054
| 4.21875
| 4
|
"""
程序指定了组件的位置并且每个组件的大小用像素作为单位来丈量。当你使用了绝对定位,我们需要知道下面的几点限制:
如果我们改变了窗口大小,组件的位置和大小并不会发生改变。
在不同平台上,应用的外观可能不同
改变我们应用中的字体的话可能会把应用弄得一团糟。
如果我们决定改变我们的布局,我们必须完全重写我们的布局,这样非常乏味和浪费时间。
"""
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lable1 = QLabel("111", self)
lable1.move(15, 10)
lable2 = QLabel("222", self)
lable2.move(35, 40)
lable3 = QLabel("333", self)
lable3.move(55, 70)
self.resize(250, 150)
self.setWindowTitle("绝对定位")
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
| false
|
144e54ba2157096c8d6e9076129d00022ad1bd93
|
Dgustavino/Taller_01-Python
|
/python_1.py
| 1,103
| 4.59375
| 5
|
""" EJERCIO 1:
EJERCIO 2:
"""
lista_nombres = [
'nombre1', # this is list
'nombre2' ]
lista_apellidos = ('apell1',
'apell2') # this is tuplet
# imprimo los ejemplos de la parte superior
print(lista_nombres)
print(lista_apellidos)
# ejemplos de la estructurada de datos set()
set1 = {123456789}
set2 = {1645}
print(set1,set2) # puedo enviar multiples paramentros al print()
resultado_set = set1.union(set2)
print(resultado_set)
numero = 5
"""This is DocString
The next lines are conditional block If statement
and recieves the variable numero int() and returns True / False
"""
if numero == 5:
print("soy un numero")
else:
print("seguro soy un texto")
palabra = 'soyUnalineadeCaracteres'
print(type(numero), type(palabra))
num1 = 100
num2 = 5
# referencias en memoria
print(id(num1) , id(num2))
num3 = 100 # almacena la misma referencia si apunta al mismo objeto
print(id(num3))
# example of a try except: // finally - else:
try:
variable = numero+palabra
except:
print("Soy un Error en el try de multiplicar: " + str(numero) + " " + palabra)
| false
|
0823b6486c60bccbed17ff96778b88ec46a3d113
|
ScoltBr/PythonProjetos
|
/escopo_de_variaveis.py
| 990
| 4.40625
| 4
|
"""
Escopo de variavel
Dois casos de escopo:
1 - Variáveis globais:
- Variáveis globais são reconhecidas, ou seja, seu escopos compreendem, todo a o programa.
2 - Variáveis locais:
- Variáveis locais ~soa reconhecidas apenas no bloco onde foram declarades, ou seja, seu escopo
esta limitado ao seu bloco onde foi declarada
Para declarar variáveis em Python fazemos:
nome_da_variavel = valor_da_variavel
Python é uma linguagem de tipagem dinâmica. Isso significada que
ao declararmos a variável, nos não colocamos o tipo de dado dela.
Este tipo é inferido ao atribuirmos o valor a mesma.
Exemplo em C:
int numero = 42;
Exemplo em Java:
int numero = 42;
"""
numero = 42
print(numero)
print(type(numero))
numero = 'Luiz'
print(numero)
print(type(numero))
nao_existo = 'Oi'
print(nao_existo)
numero =42
if numero > 10:
novo = numero + 10 # A variavel 'novo' esta declarada localmente dentro do bloco do if. Portanto, é local
print(novo)
print(novo)
| false
|
8034b3dcc454c0570bbf301ed92a7d9ee3100260
|
ScoltBr/PythonProjetos
|
/tipo_float.py
| 726
| 4.125
| 4
|
""""
Tipo float
Tipo real, dicimal
Casas decimais
OBS: o separados de casas de cimais na programação é o ponto e não a virgula. [1.5F,0.9F,1.123F]
"""
# Errado do ponto de vista do Float, mas gera uma tupla
from builtins import int
valor = 1, 44 #Tuple
print(valor)
print(type(valor))
# Certo
valor = 1.44
print(valor)
print(type(valor))
# É possivel
valor1, valor2 = 1,44
print(type(valor1))
print(type(valor2))
# Podemos converter um float para um int
"""
OBS: Ao converter valores float para inteiros, nos perdemos precisão.
"""
res = int(valor)
print(res)
print(type(res))
# Podemos trabalhar com numeros complexos
varialvel = 5j
| false
|
d8fb565e7a39ebb7a200514407b2ffb49e07b19d
|
adharmad/project-euler
|
/python/commonutils.py
| 2,794
| 4.34375
| 4
|
import functools
from math import sqrt
@functools.lru_cache(maxsize=128, typed=False)
def isPrime(n):
"""
Checks if the number is prime
"""
# Return false if numbers are less than 2
if n < 2:
return False
# 2 is smallest prime
if n == 2:
return True
# All even numbers are not prime
if not n & 1:
return False
# Now start at 3, go upto the square root of the number and check
# for divisibility. Do this in steps of two so that we consider
# only odd numbers
for i in range(3, int(n**0.5)+1, 2):
if n%i == 0:
return False
# number is prime
return True
def getPrimeFactors(n):
"""
Return a list having the prime factors of the number including the
number itself
"""
factors = []
for i in range(n+1):
if isPrime(i) and n%i == 0:
factors.append(i)
return factors
def getAllFactors(n):
"""
Return a list having all the factors of a number
"""
factors = []
for i in range(n+1):
if isPrime(i) and n%i == 0:
tmpnum = n
while tmpnum % i == 0:
factors.append(i)
tmpnum = tmpnum / i
return factors
def getAllFactorsWithCount(n):
"""
Return a map having the prime factors of the number and the number
of times the prime factor can divide the number
"""
allFactors = {}
factors = getPrimeFactors(n)
for f in factors:
tmpnum = n
count = 0
while tmpnum % f == 0:
tmpnum = tmpnum / f
count += 1
allFactors[f] = count
return allFactors
def isPalindrome(s):
"""
Checks if the given string is a palindrome and returns true
"""
i = 0
j = len(s) - 1
while i < j:
if s[i] == s[j]:
i += 1
j -= 1
continue
else:
return False
return True
def listToDictWithCount(lst):
"""
Convert a list of elements into a dictionary with the values
being the number of times the element occurs in the list.
For example,
[1, 2, 2, 3, 3, 3, 4, 4]
will return
{1:1, 2:2, 3:3, 4:2}
"""
retDict = {}
for elem in lst:
if elem in retDict.keys():
retDict[elem] = retDict[elem] +1
else:
retDict[elem] = 1
return retDict
def isPythagoreanTriplet(a, b, c):
x = [a, b, c]
x.sort()
if x[0]*x[0] + x[1]*x[1] == x[2]*x[2]:
return True
return False
def getAllDivisors(num):
"""
Returns a list having all the divisors of a number, including 1
"""
div = []
for i in range(1, int(num/2)):
if num % i == 0:
div.append(i)
return div
| true
|
97fee167a426b404694914d45e69b493b6f07a72
|
patrebert/pynet_cert
|
/class9/ex8/mytest/world.py
| 885
| 4.15625
| 4
|
#!/bin/env python
def func3():
print "world.py func3"
class MyClass:
def __init__(self,arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def hello(self):
print "hello"
print " %s %s %s" %(self.arg1, self.arg2, self.arg3)
def not_hello(self):
print "not_hello"
print " %s %s %s" %(self.arg1, self.arg2, self.arg3)
class MyChildClass(MyClass):
def hello(self):
print "This is the overridden 'hello' method of MyChildClass speaking"
print " %s %s %s" %(self.arg3, self.arg2, self.arg1)
def testclass():
hell = MyClass('1', '2', '3')
hell.hello()
hell.not_hello()
def main():
func3()
hell = MyClass('1','2','3')
hell.hello()
hell.not_hello()
hell2 = MyChildClass('1','2','3')
hell2.hello()
if __name__ == '__main__':
main()
| false
|
96de7caab2ee2c486df92f38a6b207376173bc01
|
jackyxugz/myshop
|
/coupons/tests.py
| 814
| 4.28125
| 4
|
class Cat:
"""定义一个猫类"""
def __init__(self, new_name, new_age):
"""在创建完对象之后 会自动调用, 它完成对象的初始化的功能"""
self.name = new_name
self.age = new_age # 它是一个对象中的属性,在对象中存储,即只要这个对象还存在,那么这个变量就可以使用
def __str__(self):
"""返回一个对象的描述信息"""
return "名字是:%s , 年龄是:%d" % (self.name, self.age)
def eat(self):
return "%s在吃鱼...." % self.name
def drink(self):
print("%s在喝可乐..." % self.name)
def introduce(self):
print("名字是:%s, 年龄是:%d" % (self.name, self.age))
# 创建了一个对象
tom = Cat("汤姆", 30)
tom1 = Cat('1', 2)
print(tom)
print(tom1)
| false
|
779d06833f0b30281c71242196a77f9ff08ce094
|
abhay-rana/python-tutorials.
|
/DATA STRUCTURE AND ALGORITHMS/INSERRTION_ SORT.py
| 397
| 4.15625
| 4
|
#INSERTION SORT IS SIMILAR TO E WE PLAYING CARDS
# THE WAY WE SORT THE CARDS
def insertion_sort(arr):
for e in range(1,len(arr)):
temp=arr[e]
j=e-1
while j>=0 and temp<arr[j]:
arr[j+1]=arr[j] # we are forwarding the elements
j=j-1
else:
arr[j+1]=temp
return arr
arr=[40,55,33,20,35,1,5]
print(insertion_sort(arr))
| true
|
6cc03c6e49891cacfa4ff2824caf9718994e1811
|
Avinint/Python_musicfiles
|
/timeitchallenge.py
| 1,006
| 4.375
| 4
|
# In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number of iterations to 1,000 or 10,000. The default
# of one million will take a long time to run.
import timeit
from statistics import mean, stdev
def fact(n):
result = 1
if n > 1:
for f in range(2, n + 1):
result *= f
return result
def factorial(n):
# n! can also be defined as n * (n-1)!
if n <= 1:
return 1
else:
return n * factorial(n-1)
res = timeit.repeat("fact(200)", setup="from __main__ import fact", number=1000, repeat=6)
res2 = timeit.repeat("factorial(200)", setup="from __main__ import factorial", number=1000, repeat=6)
print(f"Iterative: {mean(res)} {stdev(res)}")
print(f"Recursive: {mean(res2)} {stdev(res2)}")
| true
|
f348334cc86f5d86e66be05fa2aaaab5da2460c6
|
cyrus-raitava/SOFTENG_364
|
/ASSIGNMENT_2/SOLUTIONS/checksum.py
| 1,406
| 4.125
| 4
|
# -*- coding: utf-8 -*-
def hextet_complement(num):
'''
Internet Checksum of a bytes array.
Further reading:
1. https://tools.ietf.org/html/rfc1071
2. http://www.netfor2.com/checksum.html
'''
# Create bitmask to help calculate one's complement
mask = 0xffff
# Use the invert operator, alongside the bitmask, to calculate result
return (~num & mask)
def internet_checksum(data, total=0x0):
'''
Internet Checksum of a bytes array.
Further reading:
1. https://tools.ietf.org/html/rfc1071
2. http://www.netfor2.com/checksum.html
'''
# Create temp array to hold/manipulate data from data input
temp = []
# If number of bytes is odd, append extra zero byte
# For every even-numbered element in the array, shift it to the right
# by 8 bits, to allow for the final summing
for x in range(0, len(data)):
if (x % 2 == 0):
temp.append(data[x] << 8)
else:
temp.append(data[x])
# Sum all of the elements in the now edited array
checksum = sum(temp)
# take only 16 bits out of the 32 bit sum and add up the carries
while (checksum >> 16) > 0:
checksum = (checksum & 0xffff) + (checksum >> 16)
# Return the hextet_complement of the sum of the checksum and total
return hextet_complement(checksum + total)
| true
|
cfd0d212f68d0be4b2caca1cf3df6c5a7ce645c5
|
toasterbob/review
|
/Object_Oriented/polymorphism.py
| 1,195
| 4.1875
| 4
|
# Polymorphism
class Animal:
name = ""
location = ""
def __init__(self, name, location):
self.name = name
self.location = location
def talk(self):
pass
def move(self):
pass
def breathe(self):
pass
class Bird(Animal):
def talk(self):
print "Squawk"
def move(self):
print "Flying through the %s" % (self.location)
def breathe(self):
print "Take in air through beak"
class Dog(Animal):
def talk(self):
print "Woof"
def move(self):
print "Running on the %s" % (self.location)
def breathe(self):
print "Pant"
class Whale(Animal):
def talk(self):
print "Woooooeeeeeaaaowww"
def move(self):
print "Swimming in the %s" % (self.location)
def breathe(self):
print "Blow hole"
animals = [
Bird("Polly", "sky"),
Dog("Roger", "ground"),
Whale("Moby", "sea")
]
for animal in animals:
animal.talk()
animal.move()
animal.breathe()
# This function overloading is what we mean when we refer to Polymorphism.
# Having said that, there are other forms of Polymorphism, other than function overloading.
| false
|
82b50126fd52145f1d863a61ca57c592bf13b297
|
carlosflrslpfi/CS2-A
|
/class-08/scope.py
| 1,521
| 4.21875
| 4
|
# Global and local scope
# The place where the binding of a variable is valid.
# Global variable that can be seen and used everywhere in your program
# Local variable that is only seen/used locally.
# Local analogous to within a function.
# we define a global variable x
x = 5
def some_function():
x = 10 # local variable
# print('local x is {}'.format(x))
return x + 5
y = some_function() # Global variable y
# function call: some_function(), no input
# evaluate: x = 10, return x + 5, return 10 + 5
# output: 15
print('global x is {}'.format(x))
# 5, 10, or 15?
print(y)
def other_function():
a = "hello!"
print(a)
other_function()
# print(a)
outside_variable = 10
def another_function(x):
x = x + outside_variable # x = x + outside_variable
print(x)
return x + 1
x = 5
print(another_function(x))
# function call: another_function(x), x = 5
# evaluate: x = x + outside_variable, x = 5 + 10 = 15, print(x)
# output: x + 1, 15 + 1, 16
print(x)
def even_yet_another_function(word):
word = word + ' more letters'
return word
word = 'hello'
w = even_yet_another_function(word)
# function call: even_yet_another_function(word), word = 'hello'
# evaluate: word = 'hello' + ' more letters' -> word = 'hello more letters'
# return: 'hello more letters'
print(w)
print(word)
# strings are also immutable
# if the data type is an immutable type this works differently.
def make_first_one(lst):
lst[0] = 1
l = [0, 1]
make_first_one(l)
print(l)
# lists are mutable types
| true
|
1f561cbd24991690d041d444eae5cc96a110e06d
|
bronyamcgrory1998/Variables
|
/Class Excercises 5.py
| 724
| 4.21875
| 4
|
#Bronya McGrory
#22/09/2014
#Both a fridge and a lift have heights, widths and depths. Work out how much space is left in the lift once the fridge
fridgeheight= int (input("fridge height"))
fridgewidth= int (input("fridge width"))
fridgedepth= int (input("fridge depth"))
volume_of_fridge_answer= fridgeheight * fridgewidth * fridgedepth
print (volume_of_fridge_answer)
liftheight= int (input("lift height"))
liftwidth= int (input("lift width"))
liftdepth= int (input("lift depth"))
volume_of_lift_answer= liftheight * liftwidth * liftdepth
print (volume_of_lift_answer)
space_left= volume_of_fridge_answer-volume_of_lift_answer
print("the amount of space left in the lift is".format(space_left))
| true
|
2d8881cef624299204688eee1fbe091c8f32fab0
|
mariia-iureva/code_in_place
|
/group_coding_sections/Section2/8ball.py
| 991
| 4.375
| 4
|
"""
Simulates a magic eight ball.
Prompts the user to type a yes or no question and gives
a random answer from a set of prefabricated responses.
"""
import random
# make a bunch of random answers
ANSWER_1 = "Ask again later."
ANSWER_2 = "No way."
ANSWER_3 = "Without a doubt."
ANSWER_4 = "Yes."
ANSWER_5 = "Possibly."
def main():
# Fill this function out!
number = random.randint(1,5)
# ask the user
# name: question, type: string
question = input("Ask a yes or no question: ")
# is question (string) the same as 0 (number)
while question != "":
# pick a random answer and tell the user the answer
if number == 1:
print(ANSWER_1)
if number == 2:
print(ANSWER_2)
if number == 3:
print(ANSWER_3)
if number == 4:
print(ANSWER_4)
if number == 5:
print(ANSWER_5)
question = input("Ask a yes or no question: ")
if __name__ == "__main__":
main()
| true
|
009c1adc7155346cdebdf136237a9f00d6a4b4a5
|
Ace139/PythonAlgorithms
|
/pysort.py
| 1,942
| 4.125
| 4
|
__author__ = 'ace139'
__email__ = 'soumyodey@live.com'
"""
This program is implementation of different sorting algorithms,
also could be imported as a module in other programs.
"""
def insertion_sort(arr):
for p in range(1, len(arr)):
key = arr[p]
c = p - 1
while c >= 0 and arr[c] > key:
arr[c + 1] = arr[c]
c -= 1
arr[c + 1] = key
return arr
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_arr = arr[:mid]
right_arr = arr[mid:]
merge_sort(left_arr)
merge_sort(right_arr)
i, j, z = 0, 0, 0
while i < len(left_arr) and j < len(right_arr):
if left_arr[i] < right_arr[j]:
arr[z] = left_arr[i]
i += 1
else:
arr[z] = right_arr[j]
j += 1
z += 1
while i < len(left_arr):
arr[z] = left_arr[i]
i += 1
z += 1
while j < len(right_arr):
arr[z] = right_arr[j]
j += 1
z += 1
return arr
def bubble_sort(arr):
l = len(arr)
for i in range(l - 1):
for j in range(l - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def driver(c, arr):
option = {
0: insertion_sort,
1: bubble_sort,
2: merge_sort
}
func = option.get(c)
result = func(arr)
for r in result:
print(r, end=" ")
if __name__ == '__main__':
print("Select any Sorting Algorithm")
choices = {
"0": "insertion sort",
"1": "bubble sort",
"2": "merge sort"
}
for k, v in sorted(choices.items()):
print("%s : %s" % (k, v))
ch = int(input("Enter your choice : "))
var = input("Enter the array to perform sorting : ")
array = list(map(int, var.split(" ")))
driver(ch, array)
| false
|
410cd4eae846e5f36fdf76230a5e64afd7cfaa81
|
qcymkxyc/JZoffer
|
/main/question51/book1.py
| 1,438
| 4.40625
| 4
|
#!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 19-1-30 上午10:49
@Author: qcymkxyc
@File: book1.py
@Software: PyCharm
"""
def _merge(nums1, nums2):
"""合并两个数组
:param nums1: List[int]
数组一
:param nums2: List[int]
数组二
:return: List[int], int
合并数组, 反转统计
"""
merge_num = list()
reverse_count = 0
while len(nums1) != 0 and len(nums2) != 0:
if nums1[-1] > nums2[-1]:
reverse_count += len(nums2)
merge_num.insert(0, nums1.pop(-1))
# merge_num.append(nums1.pop(-1))
else:
# merge_num.append(nums2.pop(-1))
merge_num.insert(0, nums2.pop(-1))
merge_num = nums1 + merge_num
merge_num = nums2 + merge_num
return merge_num, reverse_count
def reverse_tuple(nums):
"""逆序对
:param nums: List[int]
数组
:return: List[int],int
排序序列,逆序对的个数
"""
if len(nums) == 0:
return nums, 0
if len(nums) == 1:
return nums, 0
middle = len(nums) // 2
left_nums = nums[:middle]
right_nums = nums[middle:]
left_nums, left_reverse = reverse_tuple(left_nums)
right_nums, right_reverse = reverse_tuple(right_nums)
merge_nums, reverse_count = _merge(left_nums, right_nums)
return merge_nums, reverse_count + left_reverse + right_reverse
| false
|
a57612a005864e361ebf18274fc62a76f97618d1
|
duonglong/practice
|
/magicalRoom.py
| 2,880
| 4.15625
| 4
|
# --*-- coding: utf-8 --*--
"""
You're an adventurer, and today you're exploring a big castle.
When you came in, you found a note on the wall of the room.
The note said that the castle contains n rooms, all of which are magical.
The ith room contains exactly one door which leads to another room roomsi.
Because the rooms are magical, it is possible that roomsi = i.
The note indicated that to leave the castle, you need to visit all the rooms,
starting from the current one, and return to the start room without visiting any room twice (except start one).
The current room has the number 0. And to make things more interesting,
you have to change the exit of exactly one door, i.e. to change one value roomsi.
Now you need to figure out how to leave the castle.
You need to return an array of two numbers numbers result[0] and result[1],
where result[0] is the number of the room with the exit you're going to change
and result[1] is the new room number to which the door from result[0] leads.
The new exit shouldn't be equal to the old one,
and after this operation is done it should be possible to visit all the rooms,
starting from 0, without visiting any room twice, and return to room 0 afterall.
If there is no answer, return [-1, -1] (and you're stuck in the castle forever).
Example
For rooms = [0, 1, 2], the output should be
magicalRooms(rooms) = [-1, -1];
For rooms = [0, 2, 0], the output should be
magicalRooms(rooms) = [0, 1].
After changing the exit of room 0 to 1, we have the following scheme of exits:
Room 0 leads to room 1;
Room 1 leads to room 2;
Room 2 leads to room 0.
As we can see, path 0 -> 1 -> 2 is valid and visits all the rooms exactly once.
Input/Output
[execution time limit] 4 seconds (py)
[input] array.integer rooms
An array of integers, where roomsi represents the 0-based exit from the room number i.
Guaranteed constraints:
3 ≤ rooms.length ≤ 10^5,
0 ≤ rooms[i] < rooms.length.
[output] array.integer
An array containing exactly 2 numbers, result[0] and result[1],
where result[0] is the room with the exit that's changing and result[1] is the number of the new exit of this room. result[1] shouldn't be equal to the old exit, and it should be possible to visit all rooms starting from 0 without visiting any room twice, and return to room 0 afterall. If this is impossible, return [-1, -1]
"""
def magicalRooms(rooms):
n = len(rooms) - 1
x = n * (n + 1) / 2 - sum(rooms)
s = set(range(n + 1)) - set(rooms)
r = list(s)[0] - x
print r, list(s)[0]
if x == 0 or len(s) > 1:
return [-1, -1]
if rooms[0] == 0 and len(s):
return [-1, -1]
for i in rooms:
pass
# import random
# test = range(0, 100001)
# random.shuffle(test)
tests = [
[3, 0, 4, 6, 5, 2, 5], # [4, 1]
[0, 2, 0], # [0, 1]
[4, 5, 0, 1, 4, 2] # [4, 3]
]
for t in tests:
magicalRooms(t)
| true
|
1cd204b6f3b4a171e9625b8d2a3db9c04e472b84
|
duonglong/practice
|
/acode.py
| 2,098
| 4.25
| 4
|
"""
Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages:
Alice: 'Let's just use a very simple code: We'll assign 'A' the code word 1, 'B' will be 2, and so on down to 'Z' being assigned 26.'
Bob: 'That's a stupid code, Alice. Suppose I send you the word 'BEAN' encoded as 25114. You could decode that in many different ways!'
Alice: 'Sure you could, but what words would you get? Other than 'BEAN', you'd get 'BEAAD', 'YAAD', 'YAN', 'YKD' and 'BEKD'. I think you would be able to figure out the correct decoding. And why would you send me the word 'BEAN' anyway?'
Bob: 'OK, maybe that's a bad example, but I bet you that if you got a string of length 5000 there would be tons of different decodings and with that many you would find at least two different ones that would make sense.'
Alice: 'How many different decodings?'
Bob: 'Jillions!'
For some reason, Alice is still unconvinced by Bob's argument, so she requires a program that will determine how many decodings there can be for a given string using her code.
Input
Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of '0' will terminate the input and should not be processed.
Output
For each input set, output the number of possible decodings for the input string. All answers will be within the range of a 64 bit signed integer.
Example
Input:
25114
1111111111
3333333333
0
Output:
6
89
1
"""
def solve(n, i):
if int(n) == 0:
return 0
if i == len(n) - 1:
return 1
if i == len(n) - 2:
if int(n[i:]) > 26 or int(n[i+1]) == 0:
return 1
else:
return 2
if int(n[i]+n[i+1]) > 26 or int(n[i]) == 0:
return solve(n, i + 1)
return solve(n, i + 1) + solve(n, i + 2)
print solve('0', 0)
print solve('10', 0)
print solve('101', 0)
print solve('25114', 0)
print solve('1111111111', 0)
print solve('3333333333', 0)
| true
|
b3fbacf8e7c5a5fd61a833c04a2b4e87899dc127
|
KRiteshchowdary/myfiles
|
/Calculator.py
| 394
| 4.15625
| 4
|
a = float(input('number 1 is '))
function = input('desired function is ')
b = float(input('number 2 is '))
if (function == '+'):
print(a + b)
elif (function == '-'):
print(a - b)
elif (function == '*'):
print(a*b)
elif (function == '/' and b != 0):
print(a/b)
elif (function == '/' and b==0):
print('b cannot be equal to zero')
else:
print('give proper functions')
| true
|
0ee672d520f8a915f269215ac12d78738e46ed33
|
bilun167/FunProjects
|
/CreditCardValidator/credit_card_validator.py
| 1,036
| 4.1875
| 4
|
"""
This program uses Luhn Algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm) and works with most credit card numbers.
1. From the rightmost digit, which is the check digit, moving left, double the value of every second digit.
2. If the result is greater than 9 (e.g., 7 * 2 = 14), then sum the digits of it (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5).
This procedure can be alternatively described as: num - 9
3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid.
"""
if __name__ == '__main__':
number = raw_input('Enter the credit card number of check: ')\
.replace(' ', '')
digits = [int(ch) for ch in number]
digits = digits[::-1]
# double alternate digits (step 1)
double = [(digit * 2) if (i % 2) else digit \
for (i, digit) in enumerate(digits)]
# subtract 9 which >= 10 (step 2)
summ = [num if num < 10 else num - 9 \
for num in double]
# step 3
if sum(summ) % 10 == 0:
print 'The number is valid'
else:
print 'The number is invalid'
| true
|
de4352cd7d651055e3204be3f1c06dfb4ba75d83
|
DarlanNoetzold/P-versus-NP
|
/P versus NP.py
| 2,233
| 4.15625
| 4
|
# Simulação de tempo que o computador que está executando o programa
# levaria para calcular algumas rotas para o caixeiro viajante sem
# utilizar Otimização Combinatória
import time
# Calcula o tempo que o processador da máquina leva para fazer 10 milhões
# de adições, cada edição é o calculo de um caminho (ligação entre duas
# cidade)
tempo = time.time()
i = sum(range(1, 10000000))
tempo = time.time() - tempo
print("Tempo para processar 10 milhões de adicoes (segundos): ", tempo)
adicoes = 10000000 / tempo
print("Adicoes por segundo: ", int(adicoes))
# Simula quanto tempo levaria para calcular a menor rota para o caixeiro
# passar por 5, 10, 15, 20 e 25 cidades e retornar a cidade origem
for contador in range(5,30,5):
print("\nCidades", contador)
rotasSeg = (adicoes / (contador -1))
# Rotas são quantos caminhos completos são testados por segundo
print("Rotas por segundo: ", int(rotasSeg))
rotas = 1
for i in range(contador - 1,1,-1):
rotas = rotas * i
print("Rotas possiveis: ", rotas)
#Armazena o tempo em segundos
tempoCalculo = (rotas / rotasSeg)
if tempoCalculo < 0.001:
print("Tempo para calculo: insignificante")
elif tempoCalculo < 1:
print("Tempo para calculo: ", int(tempoCalculo * 1000), " milisegundos")
elif tempoCalculo < 1000:
print("Tempo para calculo: ", int(tempoCalculo), " segundos")
elif tempoCalculo < 60 * 60:
print("Tempo para calculo: ", (tempoCalculo / 60), " minutos")
elif tempoCalculo < 60 * 60 * 24:
print("Tempo para calculo: ", tempoCalculo / (60 * 60), " horas")
elif tempoCalculo < 60 * 60 * 24 * 365:
print("Tempo para calculo: ", int(tempoCalculo / (60 * 60 * 24)), " dias")
elif tempoCalculo < 60 * 60 * 24 * 365 * 1000 * 1000:
print("Tempo para calculo: ", int(tempoCalculo / ( 60 * 60 * 24 * 365)), " anos")
elif tempoCalculo < 60 * 60 * 24 * 365 * 1000 * 1000 * 1000:
print("Tempo para calculo: ", int(tempoCalculo / ( 60 * 60 * 24 * 365 * 1000 * 1000)), " milhões de anos")
else:
print("Tempo para calculo: ", int(tempoCalculo / ( 60 * 60 * 24 * 365 * 1000 * 1000 * 1000)), " bilhões de anos")
| false
|
8153b4cfc2169b781bc16d1ad06e2ca4233b3ea9
|
osagieomigie/foodWebs
|
/formatList.py
| 1,572
| 4.21875
| 4
|
## Format a list of items so that they are comma separated and "and" appears
# before the last item.
# Parameters:
# data: the list of items to format
# Returns: A string containing the items from data with nice formatting
def formatList(data):
# Handle the case where the list is empty
if len(data) == 0:
return "(None)"
# Start with an empty string that we will add items to
retval = ""
# Handle all of the items except for the last two
for i in range(0, len(data) - 2):
retval = retval + str(data[i]) + ", "
# Handle the second last item
if len(data) >= 2:
retval += str(data[-2]) + " and "
# Handle the last item
retval += str(data[-1])
# Return the result
return retval
# Run some tests if the module has not been imported
if __name__ == "__main__":
# Test the empty list
values = []
print(values, "is formatted as", formatList(values))
# Test a list containing a single item
values = [1]
print(values, "is formatted as", formatList(values))
# Test a list containing two items
values = [3, 4]
print(values, "is formatted as", formatList(values))
# Test a list containing three items
values = [-1, -2, -3]
print(values, "is formatted as", formatList(values))
# Test a list containing four items
values = ["Alice", "Bob", "Chad", "Diane"]
print(values, "is formatted as", formatList(values))
# Test a list containing lots of items
values = [3, 1, 4, 1, 5, 9, 2, 6, 5, 9]
print(values, "is formatted as", formatList(values))
| true
|
d87ae28da2b3a113e2891241fddd47595525417f
|
margueriteblair/Intro-To-Python
|
/more-loops.py
| 1,001
| 4.125
| 4
|
#counting in a loop,
zork = 0
print('Before', zork)
for thing in [9, 42,12, 3, 74, 15]:
zork = zork+1
print(zork, thing)
print('After', zork)
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 42,12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', sum, count, sum/count)
#we can also use Boolean values to search for things
found = False
print('Before', found)
for value in [9, 42,12, 3, 74, 15]:
if value == 3:
found = True
print(found, value)
print('After', found)
#none type has one marker None, it's a constant
# is is stronger than equal sign
smallest = None
print('Before')
for value in [9, 41, 12, 3, 74, 15]:
if smallest is None :
smallest = value
elif value < smallest:
smallest = value
print (smallest, value)
print('AFTER', smallest)
#python has an is operator that can be used in logical expressions
#is implies 'is the same as'
#is not is also a logical operator
| true
|
c3bce9a9f83075deeb2e20c609676b26e669840e
|
murffious/pythonclass-cornell
|
/coursework/working-with-data-file/samples/unit4/convert.py
| 956
| 4.15625
| 4
|
"""
Module showing the (primitive) way to convert types in a CSV files.
When reading a CSV file, all entries of the 2d list will be strings, even if you
originally entered them as numbers in Excel. That is because CSV files (unlike
JSON) do not contain type information.
Author: Walker M. White
Date: June 7, 2019
"""
def numify(table):
"""
Modifies table so that all non-header rows contains numbers, not strings.
The header row is assumed (as in all CSV files) to be names. It will not
be altered.
Parameter table: The table to convert
Precondition: table is a rectangular 2d list of strings. Every row after
the first contains strings that can all be converted to numbers.
"""
# Altering, so must loop over positions
for rpos in range(1,len(table)): # Ignore the header
# Loop over columns
for cpos in range(len(table[rpos])):
table[rpos][cpos] = float(table[rpos][cpos])
| true
|
30be17d0390482768e1351980180136f55087a9e
|
murffious/pythonclass-cornell
|
/coursework/programming-with-objects/exercise2/funcs.py
| 1,793
| 4.15625
| 4
|
"""
Module demonstrating how to write functions with objects.
This module contains two versions of the same function. One version returns a new
value, while other modifies one of the arguments to contain the new value.
Author: Paul Murff
Date: Feb 6 2020
"""
import clock
def add_time1(time1, time2):
"""
Returns the sum of time1 and time2 as a new Time object
DO NOT ALTER time1 or time2, even though they are mutable
Examples:
The sum of 12hr 13min and 13hr 12min is 25hr 25min
The sum of 1hr 59min and 3hr 2min is 4hr 1min
Parameter time1: the starting time
Precondition: time1 is a Time object
Parameter time2: the time to add
Precondition: time2 is a Time object
"""
sum_time_h = int(str(time1).split(':')[0]) + int(str(time2).split(':')[0])
sum_time_m = int(str(time1).split(':')[1]) + int(str(time2).split(':')[1])
if sum_time_m > 60:
sum_time_m -=60
sum_time_h += 1
return clock.Time(sum_time_h,sum_time_m)
def add_time2(time1, time2):
"""
Modifies time1 to be the sum of time1 and time2
DO NOT RETURN a new time object. Modify the object time1 instead.
Examples:
The sum of 12hr 13min and 13hr 12min is 25hr 25min
The sum of 1hr 59min and 3hr 2min is 5hr 1min
Parameter time1: the starting time
Precondition: time1 is a Time object
Parameter time2: the time to add
Precondition: time2 is a Time object
"""
sum_time_h = int(str(time1).split(':')[0]) + int(str(time2).split(':')[0])
sum_time_m = int(str(time1).split(':')[1]) + int(str(time2).split(':')[1])
if sum_time_m > 60:
sum_time_m -=60
sum_time_h += 1
time1.hours = sum_time_h
time1.minutes = sum_time_m
| true
|
5aa45d78764eb9ca62abc1f4d6bfd82b7056d90d
|
ellafrimer/shecodes
|
/lists/helper.py
| 549
| 4.46875
| 4
|
print("Accessing just the elements")
for letter in ['a', 'b', 'c']:
print(letter)
print("Accessing the elements and their position in the collection")
for (index, letter) in enumerate(['a', 'b', 'c']):
print("[%d] %s" % (index, letter))
print("A string is also a collection...")
for (index, letter) in enumerate("banana"):
print("iteration no. %d" % (index+1))
print("[%d] %s" % (index, letter))
dict = {
'first_key': 'first value'
}
dict['hi'] = 'hello'
dict['anyword'] = 23
print(dict)
"""
ABCDEFG
CDEFGHI
BAD -> DCF
"""
| true
|
2883dec0109abec67805f361b8bc7c8748b70a7f
|
ellafrimer/shecodes
|
/loops/geometric_shape.py
| 282
| 4.1875
| 4
|
"""
making a triangle
"""
def print_asterisks(num):
print("*" * num)
# for number in range(1, 6):
# print_asterisks(number)
"""
making a trapeze
"""
a_number = 8
for number in range(int(a_number/2), a_number+1):
print_asterisks(number)
"""
making a diamond
"""
| false
|
6276c03f5933147d623376818f96cfa35f07f8e8
|
shahamran/intro2cs-2015
|
/ex3/findLargest.py
| 410
| 4.46875
| 4
|
#a range for the loop
riders=range(int(input("Enter the number of riders:")))
high_hat=0
gandalf_pos=0
#This is the loop that goes through every hat size and
#checks which is the largest.
for rider in riders:
height=float(input("How tall is the hat?"))
if height>high_hat:
high_hat=height
gandalf_pos=rider+1
print("Gandalf's position is:",gandalf_pos)
| true
|
8552969c9e3f4e2764951ac3914572d1b9744a36
|
Lumexralph/python-algorithm-datastructures
|
/trees/binary_tree.py
| 1,471
| 4.28125
| 4
|
from tree import Tree
class BinaryTree(Tree):
"""Abstract base class representing a binary tree structure."""
# additional abstract methods
def left_child(self, p):
"""Return a Position representing p's left child.
Return None if p does not have a left child
"""
raise NotImplementedError('must be implemented by the subclass')
def right_child(self, p):
"""Return a Position representing p's right child.
Return None if p does not have a right child
"""
raise NotImplementedError('must be implemented by the subclass')
# concrete methods that got implemented in this class
def sibling(self, p):
"""Return a Position representing p's sibling or None if no sibling."""
parent = self.parent(p)
if parent is None: # p must be the root
return None # a root has no sibling
else:
if p == self.left_child(parent): # if it is the left child
return self.right_child(parent)
else:
return self.left_child(parent)
def children(self, p):
"""Generate an iteration of Positions representing p's children."""
if self.left_child(p) is not None:
yield self.left_child(p)
if self.right_child(p) is not None:
yield self.right_child(p)
| true
|
caf308fc4385c102d25e0dd35bd132017822a166
|
Kevinvanegas19/lps_compsci
|
/misc/calculateDonuts.py
| 360
| 4.15625
| 4
|
print("How many people are coming to the party?")
people = int(raw_input())
print("How many donuts will you have at your party?")
donuts = int(raw_input())
donuts_per_person = donuts / people
print("Our party has " + str(people) + " people and " + str(donuts) + " donuts.")
print("Each person at the party gets " + str(donuts_per_person) + " donuts.")
| false
|
bf12f927c2d684699f41b48c1191ea956205a41c
|
km-aero/eng-54-python-basics
|
/exercise_103.py
| 433
| 4.3125
| 4
|
# Define the following variables
# name, last_name, species, eye_color, hair_color
# name = 'Lana'
name = 'Kevin'
last_name = 'Monteiro'
species = 'Alien'
eye_colour = 'blue'
hair_colour = 'brown'
# Prompt user for input and Re-assign these
name = input('What new name would you like?')
# Print them back to the user as conversation
print(f'Hello {name}! Welcome, your eyes are {eye_colour} and your hair color is {hair_colour}.')
| true
|
f693e45eab8cfcc4ab449149fcba829e8e4f0b02
|
khadtareb/class_assignments1
|
/pythonProject6/Assignment_62.py
| 351
| 4.1875
| 4
|
#62. Python | Ways to remove a key from dictionary Ways to sort list of dictionaries by values in
d=[{ "name" : "Nandini", "age" : 22},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
print(sorted(d,key=lambda i:i['age']))
print(sorted(d,key=lambda i:i['age'],reverse=True))
print(sorted(d,key=lambda i:(i['age'],i['name'])))
| false
|
1736fa54bb0aa30ff931ced7e8fc61c104a3aa5d
|
CheshireCat12/hackerrank
|
/eulerproject/problem006.py
| 544
| 4.21875
| 4
|
#!/bin/python3
def square_of_sum(n):
"""Compute the square of the sum of the n first natural numbers."""
return (n*(n+1)//2)**2
def sum_of_squares(n):
"""Compute the sum of squares of the n first natural numbers."""
return n*(n+1)*(2*n+1)//6
def absolute_diff(n):
"""
Compute the absolute difference between the square of sum
and the sum of squares.
"""
return square_of_sum(n) - sum_of_squares(n)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(absolute_diff(n))
| true
|
dd5140fad8067d9c49215aa6a3600281770c22ff
|
marsdev26/python_exercises
|
/hello_turtle.py
| 1,085
| 4.28125
| 4
|
import turtle
#Function to draw 1 petal of a flower
def draw_petal():
turtle.down()
turtle.forward(30)
turtle.right(45)
turtle.forward(30)
turtle.right(135)
turtle.forward(30)
turtle.right(45)
turtle.forward(30)
turtle.right(135)
#Function to draw a flower
def draw_flower():
turtle.down()
turtle.left(45)
draw_petal()
turtle.left(90)
draw_petal()
turtle.left(90)
draw_petal()
turtle.left(90)
draw_petal()
turtle.left(135)
turtle.forward(150)
#Function that draws flower and advance on the map
def draw_flower_and_advance():
draw_flower()
turtle.right(90)
turtle.up()
turtle.forward(150)
turtle.right(90)
turtle.forward(150)
turtle.left(90)
turtle.down()
#Function that draw the 3 flowers required
def draw_flower_bed():
turtle.up()
turtle.forward(200)
turtle.left(180)
turtle.down()
draw_flower_and_advance()
draw_flower_and_advance()
draw_flower_and_advance()
if __name__ == "__main__" :
draw_flower_bed()
turtle.done()
| false
|
99e02fa63b997cb3156d5427da3833584a99d3c3
|
stogaja/python-by-mosh
|
/12logicalOperators.py
| 534
| 4.15625
| 4
|
# logical and operator
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan.')
# logical or operator
high_income = False
good_credit = True
if high_income or good_credit:
print('Eligible for a loan.')
# logical NOT operator
is_good_credit = True
criminal_record = False
if is_good_credit and not criminal_record:
print('Eligible for a loan.')
# AND both conditions must be true
# OR at least one condition is true
# NOT reverses any boolean value given
| true
|
fa537f900f5a5f23c8573e1965895df2dd3b3706
|
jhreinholdt/caesar-cipher
|
/ceasar_cipher.py
| 1,693
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 15:33:33 2017
@author: jhreinholdt
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "monoalphabetic substitution cipher" provides almost no security,
because an attacker who has the encoded message can either use frequency analysis to guess the key,
or just try all 25 keys.
"""
from types import *
import string
def encode(key, plaintext):
assert type(key) is int, "key is not an integer: %r" % key
ciphertext = ''
for char in plaintext:
# print((ord(char)+key)-97)
cipherchr = chr((((ord(char) + key) - 97) % 26) + 97)
ciphertext += cipherchr
# print("Plaintext: ", char, " Ciphertext: ", cipherchr)
# print("Ciphertext: ", ciphertext)
return ciphertext
def decode(key, ciphertext):
assert type(key) is int, "key is not an integer: %r" % key
plaintext = ''
for char in ciphertext:
plainchr = chr((((ord(char) - key) - 97) % 26) + 97)
plaintext += plainchr
# print("Plaintext: ", plaintext)
return plaintext
def main():
ciphertext = encode(25, input("Enter plaintext: "))
print("Ciphertext: ", ciphertext)
for key in range(1,26):
plaintext = decode(key, ciphertext)
print("Decoded plaintext with key#", key, ":", plaintext)
if __name__ == '__main__':
main()
| true
|
fd5d0602a635cc7f492c76ed2df9548da2ec29dc
|
madhuriagrawal/python_assignment
|
/swapTwoNumbers.py
| 231
| 4.25
| 4
|
def swapingUsingThirdVariable():
x=2
y=6
z=x
x=y
y=z
print(x,y)
def swapingWithoutThirdVariable():
x = 2
y = 6
x,y=y,x
print(x,y)
swapingUsingThirdVariable()
swapingWithoutThirdVariable()
| false
|
58185c8ed1fbceae5dbb44fc547712f101f17e21
|
Meenal-goel/assignment_7
|
/fun.py
| 2,238
| 4.28125
| 4
|
#FUNCTIONS AND RECURSION IN PYTHON
#1.Create a function to calculate the area of a circle by taking radius from user.
rad = float(input("enter the radius:"))
def area_circle (r):
res = (3.14*pow(r,2))
print("the area of the circle is %0.2f"%(res) )
area_circle(rad)
print("\n")
#Write a function “perfect()” that determines if parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.
#[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
#function to determine number is a perfect number
def perf_num (n):
sum = 0
for i in range (1,n):
rem = n % i
if( rem == 0 ):
sum = sum +i
if(sum == n):
print("%d"%(n))
else :
return()
print("in the given range i.e between 1 to 1000 are:")
#loop to make use of function perf_num in given range
for j in range(1,1000) :
perf_num(j)
print("\n")
#3.Print multiplication table of 12 using recursion
def multi_twelve( multiplicand, multiplier=1):
if(multiplier <= 10):
print(multiplicand ,"x", multiplier,"=", multiplicand * multiplier)
multi_twelve(multiplicand,multiplier+1)
else:
return()
m = int(input("enter the multiplicand:"))
print("the multiplication table of %d is:"%(m))
(multi_twelve(m))
print("\n")
#4. Write a function to calculate power of a number raised to other ( a^b ) using recursion.
a = int(input("enter a number:"))
b = int(input("enter the power:"))
def pwr ( num1 , num2):
if(num2 !=0):
return(num1*pow(num1,num2-1))
else :
return(1)
print("%d^%d is:"%(a,b))
print(pwr(a,b))
print("\n")
#5. Write a function to find factorial of a number but also store the factorials calculated in a dictionary
numx = int(input("enter a countof numbers:"))
f=0
def fact ( numbr ):
if (numbr == 0):
return(1)
else :
#print("the factorial of the number %d is "%(numbr))
y=((numbr*fact(numbr-1)))
return(y)
num = numx
factorial = fact(numx)
dict = {num:factorial}
print(dict)
| true
|
833994a2e77655b22525d4cf4e8d3d3a6ab93cc4
|
JustineRobert/TITech-Africa
|
/Program to Calculate the Average of Numbers in a Given List.py
| 284
| 4.15625
| 4
|
n = int(input("Enter the number of elements to be inserted: "))
a =[]
for i in range(0,n):
elem = int(input("Enter the element: "))
a.append(elem)
avg = sum(a)/n
print("The average of the elements in the list", round(avg, 2))
input("Press Enter to Exit!")
| true
|
6f6baad65328395fc7a61d1dbf7f0e981ff9ec9a
|
caoxiang104/DataStructuresOfPython
|
/Chapter3_Searching_Sorting_and_Complexity_Analysis/example4.py
| 745
| 4.21875
| 4
|
# coding=utf-8
"""
expo函数的一个可替代的策略是,使用如下的递归定义:
expo(number, exponent)
=1, 当exponent=0
=number*expo(number, exponent-1) 当exponent是基数的时候
=(expo(number,exponent/2))^2, 当exponent是偶数的时候
使用这一策略定义一个递归的expo函数,并且使用大O表示法表示其复杂度。
"""
# O(nlogn)
def expo(number, exponent):
if exponent == 0:
return 1
elif exponent % 2 == 1:
return number * expo(number, exponent - 1)
else:
return expo(number, exponent//2) ** 2
def main():
num = 2
times = 128
out = expo(num, times)
print("{} 的 {} 次幂是:".format(num, times), out)
if __name__ == '__main__':
main()
| false
|
787f852dd458b854945dd7e5fc9da154c0f3351d
|
caoxiang104/DataStructuresOfPython
|
/Chapter11_Sets_and_Dicts/item.py
| 614
| 4.125
| 4
|
class Item(object):
"""Represents a dictionary item."""
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return str(self.key) + ":" + str(self.value)
def __eq__(self, other):
if type(self) != type(other):
return False
return self.key == other.key
def __lt__(self, other):
if type(self) != type(other):
return False
return self.key < other.key
def __le__(self, other):
if type(self) != type(other):
return False
return self.value <= other.key
| false
|
c9edd541c68a693e72eb35e48e24701e862a23a4
|
IfWell/MSG-Algorithm
|
/p1-3.py
| 464
| 4.1875
| 4
|
#문제(1) ppt의 문제 3번
# """로 둘러싸인 코드들은 없는 걸로 처리됨. 지우고 사용할 것
#for을 이용한 풀이
"""
for i in range(1, 10):
for j in range(1, 10):
print("{0} x {1} = {2}".format(i, j, i*j))
"""
#while을 이용한 풀이
"""
i,j = 1,1
while(i <= 9):
j = 1 #j를 다시 1로 초기화
while(j <= 9):
print("{0} x {1} = {2}".format(i, j, i*j))
j+=1
i+=1
"""
| false
|
4dbd156acd668c70d2c6b1426c9a80a2843dbfdc
|
Struggling10000/try
|
/Hw_1.py
| 525
| 4.125
| 4
|
import string
'''
题目:有这么一串字符串 str = “my Name is alex”想要将每一个单词首字母大写,其他不变str = “My Name Is Alex”
'''
s = 'my Name is alex.'
print('原字符串:s='+s)
print('直接调用函数结果:'+string.capwords(s))
s1=s.split(' ')
print('切分后的字符串列表是:')
print(s1)
def normallize(name):
return name.capitalize()
s2=list(map(normallize,s1))
print('处理后的列表是:')
print(s2)
a=' '
print('应用第二种方法的结果:'+ a.join(s2))
| false
|
597653d108f0c38033a862126f529a959c0afd2d
|
OlegMeleshin/Lubanovic-Exercises
|
/Chapter 3/Chapter_3_part_4.py
| 836
| 4.5
| 4
|
# 10. Create an English-French dictionary called "e2f" and print it.
# Here are your words: dog/chien, cat/chat and walrus/morse.
e2f = {'dog' : 'chien', 'cat' : 'chat', 'walrus' : 'morse'}
print(f'''English to French Dictionary
{e2f}\n''')
# 11. Print french for walrus using your dictionary.
print(f"French for walrus is {e2f['walrus']}\n")
# 12. Create French-English dictionary based on e2f dictionary using
# "items" method.
f2e = {}
for key in e2f:
f2e[e2f[key]] = key
print(f'''French to English Dictionary
{f2e}\n''')
# 13. Print English word for "chien".
print(f'''Chien is a French word for {f2e['chien']}\n''')
# 14. Create and print a set of English words of e2f dictionary
eng_words = set(list(e2f.keys()))
print(f"Set of English words:\n{eng_words}")
| false
|
0f498dc435ba20d7cace60400c5439d12a0546e4
|
OlegMeleshin/Lubanovic-Exercises
|
/Chapter_4/Chapter_4_part_6.py
| 270
| 4.28125
| 4
|
'''6. Use Set comprehension to create the 'odd' set containing even numbers in range(10).
Так и написано ODD, в котором ЧЕТНЫЕ числа. Опечатка возможно.'''
odd = {even for even in range(10) if even % 2 == 0}
print(odd)
| false
|
5f5106c85c99ffa303151c793d5d490844b92977
|
rajatsachdeva/Python_Programming
|
/UpandRunningwithPython/Working with files/OS_path_utilities.py
| 1,241
| 4.125
| 4
|
#
# Python provides utilities to find if a path is file or directory
# whether a file exists or not
#
# Import OS module
import os
from os import path
from datetime import date, time , datetime
import time
def main():
# print the name of os
print "Os name is " + os.name
# Check for item existence and type
print "Item Exists: " + str(path.exists("textfile.txt"))
print "Item is a file: " + str(path.isfile("textfile.txt"))
print "Item is a directory: " + str(path.isdir("textfile.txt"))
# Work with file paths
print "Item's path: " + str(path.realpath("textfile.txt"))
print "Item's path and name: " + str(path.split(path.realpath("textfile.txt")))
# Get the modification time of the file
t = time.ctime(path.getmtime("textfile.txt"))
print "Modification time for 'textfile.txt' is : " + t
print datetime.fromtimestamp(path.getmtime("textfile.txt"))
# Calculate how long ago the file was modified
td = datetime.now() - datetime.fromtimestamp(path.getmtime("textfile.txt"))
print "It has been " + str(td) + " since the file was updated"
print "Or, " + str(td.total_seconds()) + " seconds"
if __name__ == "__main__":
main()
| true
|
f848e3d507aaad9c30b0042a17542dc6225e5945
|
rajatsachdeva/Python_Programming
|
/Python 3 Essential Training/04 Syntax/object.py
| 921
| 4.25
| 4
|
#!/bin/python3
# python is fundamentally an object oriented language
# In python 3 everything is an object
# class is a blueprint of an object
# encapsulation of variables and methods
class Egg:
# define a constructor
# with special name __init__
# All methods within classes have first argument as self
# which is the reference to object itself
def __init__(self, kind = "fired"):
self.kind = kind
def whatKind(self):
return self.kind
def main():
print("Main starts")
# Creates an Object of Egg class and
# Constructor is called whenever an object is created
# Here kind will be initialized with default value as fried
fried = Egg()
print("fried egg has %s"%(fried.whatKind()))
# Create another object
scrambled = Egg("scrambled")
print("scrambled egg has %s"%(scrambled.whatKind()))
if __name__ == "__main__":
main()
| true
|
377c78d18db40dd93bd16b65a9a1a4547c508216
|
rajatsachdeva/Python_Programming
|
/Python 3 Essential Training/16 Databases/databases.py
| 896
| 4.3125
| 4
|
#!/usr/bin/python3
# Databases in python
# Database used here is SQLite 3
# row factory in sqlite3
import sqlite3
def main():
# Connects to database and creates the actual db file if not exits already
db = sqlite3.connect('test.db')
# Interact with the database
db.execute('drop table if exists test')
db.execute('create table test(t1 text, i1 int)')
db.execute('insert into test (t1, i1) values(?, ?)', ('one', 1))
db.execute('insert into test (t1, i1) values(?, ?)', ('two', 2))
db.execute('insert into test (t1, i1) values(?, ?)', ('three', 3))
db.execute('insert into test (t1, i1) values(?, ?)', ('four', 4))
# commit the changes in database
db.commit()
cursor = db.execute('select i1, t1 from test order by i1')
# Data comes in tuple
for row in cursor:
print (row)
if __name__ == "__main__": main()
| true
|
33d9a7cc53d070f8575fa5b3b044edd4eb5e9fe4
|
rajatsachdeva/Python_Programming
|
/Python 3 Essential Training/12 Classes/generator.py
| 1,218
| 4.46875
| 4
|
#!/usr/bin/python3
# A generator object is an object that can be used in the context of an iterable
# like in for loop
# Create own range object with inclusive range
class inclusive_range:
def __init__(self, *args):
numargs = len(args)
if numargs < 1 :
raise TypeError('Requries at least one argument')
elif numargs == 1:
self.start = 0
self.stop = args[0]
self.step = 1
elif numargs == 2:
self.start = args[0]
self.stop = args[1]
self.step = 1
elif numargs == 3:
(self.start, self.stop, self.step) = args
else:
raise TypeError('Number of arguments should be 3, but they are {}'.format(numargs))
# Generator
def __iter__(self):
i = self.start
while i <= self.stop:
yield i
i += self.step
def main():
# generator object
o = range(0, 25, 1) # start, stop
for i in o: print(i, end = ' ')
print()
mygen = inclusive_range(1,18)
for i in mygen: print(i, end = ' ')
print()
for i in inclusive_range(10): print (i , end = ' ')
if __name__ == "__main__": main()
| true
|
b572c312a1314e7048b1f596650a724d215b0a63
|
rajatsachdeva/Python_Programming
|
/Python 3 Essential Training/11 Functions/generator.py
| 1,290
| 4.125
| 4
|
#!/usr/bin/python3
# Generator functions
def main():
for i in inclusive_range(0, 10):
print(i, end = ' ')
print()
for i in inclusive_range2(18):
print(i, end = ' ')
print()
for i in inclusive_range2(0, 25):
print(i, end = ' ')
print()
for i in inclusive_range2(0, 50, 2):
print(i, end = ' ')
print()
for i in inclusive_range2(7, 50, 2):
print(i, end = ' ')
print()
def inclusive_range(start = 0, stop = 0, step = 1):
i = start
while i <= stop:
# You can return the value
# using yield
yield i
i += step
def inclusive_range2(*args):
numargs = len(args)
if numargs < 1:
raise TypeError("requires atleast one argument")
elif numargs == 1:
stop = args[0]
start = 0
step = 1
elif numargs == 2:
start = args[0]
stop = args[1]
step = 1
elif numargs == 3:
(start, stop, step) = args
else:
raise TypeError("inclusive_range expected at most 3 arguments, got {}".format(numargs))
i = start
while i <= stop:
yield i
i += step
if __name__ == "__main__": main()
# yield returns each time the next item in the sequence.
| false
|
d2d7d34fa745243c91ab891f0fdd3e28ba8b16d0
|
rajatsachdeva/Python_Programming
|
/Python 3 Essential Training/14 Containers/dictionary.py
| 1,397
| 4.28125
| 4
|
#!/usr/bin/python3
# Organizing data with dictionaries
def main():
d1 = {'one' : 1, 'two' : 2, 'three' : 3}
print(d1, type(d1))
# dictionary using dict constructor
d2 = dict(one = 1, two = 2, three = 3)
print(d2, type(d2))
d3 = dict(four = 4, five = 5, six = 6)
print(d3, type(d3))
# Using keyword arguments
# ** this denots the kwargs
d4 = dict(one = 1, two = 2, three = 3, **d3)
print(d4, type(d4))
# check if a value is in dictionary
print('four' in d3)
print('three' in d3)
# Iterate over dict elements
# to print all the keys
for key in d4:
print(key, end = ' ')
print()
# Iterate over dict elements to print all the keys and values
for key,value in d4.items():
print(key, "=", value)
print()
# Get a particular item from a dictionary
print("d4['three'] =", d4['three'])
# get method to get a value for a key from a dict object
print(d3.get('three'))
print(d4.get('three'))
# Set a default return value in case key is not present
print(d3.get('three', 'Not Found'))
# delete an item from a dict
del d3['four']
print(d3, type(d3))
# pop an item from a dict
# In dictionary it requires atleast one argument
d3.pop('five')
print(d3, type(d3))
if __name__ == "__main__": main()
| true
|
f33362d646b39360d8bdc20d346a369fdf7d6a19
|
rajatsachdeva/Python_Programming
|
/Python 3 Essential Training/05 Variables/Finding_type_identity.py
| 1,300
| 4.3125
| 4
|
#!/bin/python3
# Finding the type and identity of a variable
# Everything is object and each object has an ID which is unique
def main():
print("Main Starts !")
x = 42
print("x:",x)
print("id of x:",id(x))
print("id of 42:",id(42))
print("type of x:", type(x))
print("type of 42:", type(42))
# ID of x and 42 is same as the object x references to
# integer 42 and thus have the same ID
# So, Number 42 is an object
y = 42
print("y:",y)
print("id of y:",id(y))
print("id of 42:",id(42))
print("type of y:", type(y))
print("type of 42:", type(42))
# == operator compares the value
print("x == y:", x == y)
# They are exactly the same objects
# As they have the same id
# 'is' compares the id rather than the value
print("x is y:", x is y)
z = dict(x = 42)
print(type(z))
print(z)
print(id(z))
z2 = dict(x = 42)
print(type(z2))
print(z2)
print(id(z2))
print("z == z2:", z == z2) # True
print("z is z2:", z is z2) # False as they are differnt objects
# All muttable objects gets unique ID
# Whereas the immutable objects get different ID
# Variables in python are references to objects
if __name__ == "__main__": main()
| true
|
20a46b2b8f01f34c9cced37bd810309cf4808858
|
lucioeduardo/cc-ufal
|
/APC/Listas/02 - Estruturas de Decisão/q6.py
| 783
| 4.125
| 4
|
"""
Escreva um algoritmo que recebe três valores para os lados de um
triângulo (a,b e c) e decide se a forma geométrica é um triângulo ou não e em
caso positivo, classifique em isósceles, escaleno ou equilátero.
– O valor de cada lado deve ser menor que' a soma dos outros dois
– Isósceles: dois lados iguais e um diferente
– Escaleno: todos os lados diferentes
– Equilátero: todos os lados iguais
"""
a = int(input("Valor de A:"))
b = int(input("Valor de B:"))
c = int(input("Valor de C:"))
if((a < b+c) and (b < a+c) and (c < a+b)):
if(a == b and b == c):
print("Triângulo Equilátero")
elif(a == b or b == c or a == c):
print("Triângulo Isósceles")
else:
print("Triângulo Escaleno")
else:
print("Não é triângulo")
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.