blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
226ceeac8256bb567d21dade909a9f24b3369e53 | AlexPlatin/Grokking_Algorithms_book | /tests/test_recursive.py | 764 | 3.5 | 4 | import unittest
from Recursive_tryings import recursive_factorial, loop_factorial, recursive_sum, recursive_max
class Recursive(unittest.TestCase):
def test_recursive_algorithm(self):
self.assertEqual(recursive_factorial(5), 120)
def test_loop_algorithm(self):
self.assertEqual(loop_factorial(5), 120)
class Recursive_Sum(unittest.TestCase):
def test_sum_simple_right_values(self):
self.assertEqual(recursive_sum([1, 2, 3, 4]), 10)
def test_sum_right_type(self):
with self.assertRaises(TypeError):
recursive_sum(1)
class Recursive_max(unittest.TestCase):
def test_simple_values(self):
self.assertEqual(recursive_max([1, 7, 5, 3, 8]), 8)
if __name__ == '__main__':
unittest.main() |
0513b455aaf0f5c2289790507c7782b3465b56d3 | jl532/BME547-TSHTestData | /tsh.py | 6,620 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 20:54:03 2019
@author: Mars
"""
def nameParser(inputDictionary, inputString):
"""Splits full name string into First and Last name and parses into dict
nameParser takes an input String with a full name ("First Last") and
splits the string to a list of ["First","Last"]. This list is parsed
into the inputDictionary patient dictionary. This updated dictionary is
then returned.
Args:
inputDictionary (dict): patient dictionary
inputString (String): patient's full name
Returns:
inputDictionary (dict): patient dictionary with first and last name
"""
firstAndLast = inputString.split(" ")
inputDictionary["First Name:"] = firstAndLast[0]
inputDictionary["Last Name: "] = firstAndLast[1]
return inputDictionary
def ageParser(inputDictionary, inputString):
"""typesets the input String into an int and records in patient dictionary
Nothing special is done here... it just takes the input string, turns it
into an int, and then makes the "age" entry in the patient dictionary.
Then outputs the patient dictionary after the age is entered. Simple
Args:
inputDictionary (dict): patient dictionary
inputString (String): patient's age
Returns:
inputDictionary (dict): patient dictionary populated with age data
"""
inputDictionary["Age"] = int(inputString)
return inputDictionary
def genderParser(inputDictionary, inputString):
"""Directly enters inputString of Gender into patient dictionary
Nothing special done here either. Takes input string, and places "gender"
entry into the patient dictionary. Then outputs the patient dictionary
after the age is entered. Simplest.
Args:
inputDictinoary (dict): patient dictionary
inputString (String): patient's gender
Returns:
inputDictionary (dict): patient dictionary populated with gender data
"""
inputDictionary["Gender"] = inputString
return inputDictionary
def testDataParser(inputDictionary, inputString):
""" Parses TSH data line into a list for input into patient dictionary
Splits the TSH data line by commas, ignoring the first entry "TSH" and
appending all other entries between commas into a list. This list is then
sorted (extra credit) and appended in the patient dictionary under
"TSHData". The populated patient dictionary is then returned.
Args:
inputDictionary (dict): patient dictionary
inputString (String): patient's TSH data unformatted
Returns:
inputDictinoary (dict): patient dictionary populated with TSH data
"""
testDataSplit = inputString.split(",")
testDataTagRm = testDataSplit[1:]
newData = []
for eachEntry in testDataTagRm:
newData.append(float(eachEntry))
inputDictionary["TSHData"] = sorted(newData)
return inputDictionary
def fileParser(fileName):
"""Parses patient information from txt input into a list of dictionaries
This file Parser opens the given text file and parses it line-by-line,
which corresponds to the particular piece of patient information in order.
The pre-determined order of data is as follows: First Name/Last Name, Age,
Gender, and TSH test data. Given this order, the modulo command can be used
with the lineNumber within the text file to send the line to the proper
String parsing function. These functions append dictionary entries for
each patient, in order. In the sequence, the first line corresponding to
a new patient initializes a new dictionary, the lines of data are parsed in
dictionary key/value pairs, and then the function appends the fully
populated dictionary into the list of patients. This list of dictionaries
with patient data is then returned.
Args:
fileName (String): name of the .txt file containing patient info
Returns:
listOfPatients (list): list of dictionaries with patient information
"""
fileData = open(fileName, "r")
listOfPatients = []
lineNumber = 0
for eachLine in fileData:
if lineNumber % 4 == 0:
if eachLine != "END":
person = {}
person = nameParser(person, eachLine.rstrip())
if lineNumber % 4 == 1:
person = ageParser(person, eachLine.rstrip())
if lineNumber % 4 == 2:
person = genderParser(person, eachLine.rstrip())
if lineNumber % 4 == 3:
person = testDataParser(person, eachLine.rstrip())
listOfPatients.append(person)
lineNumber = lineNumber + 1
fileData.close()
return listOfPatients
def saveData(outFile, inputDictionaries):
"""Generates the json formatted file including all patient data
saveData takes the input list of dictionaries and dumps them in json format
into the target "outFile" .json file.
Args:
outFile (String): file name of the json output file
inputDictionaries (list): list including all patient dictionaries
"""
import json
fileWriter = open(outFile, "w")
for eachPatient in inputDictionaries:
json.dump(eachPatient, fileWriter)
fileWriter.close()
def diagnoseTSH(inputPatients):
"""Runs the TSH data of each patient through predetermined diagnostic logic
The function iterates through each patient in the input list, checking
each TSH reading against the specifications for diagnostic cutoffs for
Thyroid Stimulating Hormone (TSH). If a hit is found, the corresponding
diagnosis is appended in the patient dictionary. Else, a normal status is
appended. The full list of dictionaries with the diagnostic status is
returned.
Args:
inputPatients (list): list of patient dictionaries
Returns:
inputPatients (list): list of patient dictionaries with diagnosis
"""
for eachPatient in inputPatients:
tshData = eachPatient["TSHData"]
print(tshData)
if any(tshReading > 4 for tshReading in tshData):
eachPatient["TSH Diagnosis"] = "hypothyroidism"
elif any(tshReading < 1 for tshReading in tshData):
eachPatient["TSH Diagnosis"] = "hyperthyroidism"
else:
eachPatient["TSH Diagnosis"] = "normal thyroid function"
print(eachPatient["TSH Diagnosis"])
return inputPatients
def main():
patients = fileParser("test_data.txt")
patients = diagnoseTSH(patients)
outFile = "patients.json"
saveData(outFile, patients)
if __name__ == "__main__":
main()
|
42d43aa23b28fe2b95cf6f7063a90d465ecbbcc2 | hhoangphuoc/data-structures-and-algorithms | /cracking_the_coding_interview/trees_and_graphs/linked_list.py | 2,052 | 4.375 | 4 | # -*- coding: UTF-8 -*-
from __future__ import print_function
'''
Linked list is a dynamic linear data structure where each element is represented as an object.
Each element is comprised of two items - the data and the reference to next element or next node.
'''
# Class to initialize a node for a linked list
class Node(object):
def __init__(self, data):
self.data = data
self.nextnode = None
# Class to create a Linked List
class LinkedList(object):
def __init__(self, head=None):
self.head = head
# Function to search an element in a linked list and print it's index
def search(self, head, data, index):
if head.data == data:
print (index)
else:
# Search for the element by calling itself recursively
if head.nextnode:
return self.search(head.nextnode, data, index+1)
else:
raise ValueError("Node not in linked list")
# Function to print all the nodes in a linked list starting from first node
def print_list(self):
if self.head == None:
raise ValueError("List is empty")
current = self.head
while(current):
print (current.data, end=" ")
current = current.nextnode
print ('\n')
# Function to get the length of the linked list
def size(self):
if self.head == None:
return 0
size = 0
current = self.head
while(current):
size += 1
current = current.nextnode
return size
# Function to insert a node in a linked list
def insert(self, data):
node = Node(data)
if not self.head:
self.head = node
else:
node.nextnode = self.head
self.head = node
# Function to delete a node in a linked list
def delete(self, data):
if not self.head:
return
temp = self.head
# Check if head node is to be deteled
if head.data == data:
head = temp.nextnode
print ("Deleted node is " + str(head.data))
return
while(temp.nextnode):
if (temp.nextnode.data == data):
print ("Node deleted is " + str(temp.nextnode.data))
temp.nextnode = temp.nextnode.nextnode
return
temp = temp.nextnode
print ("Node not found")
return
|
bd22c2d7321eefbaecc25497b4fec2bcbfb651b0 | chloe-wong/pythonchallenges | /AS23.py | 609 | 3.5 | 4 | #1
file= open("textfile.txt", "r")
a = []
for line in file:
a.append(line.strip('\n')
a = reverse(a)
for x in range(len(a)):
print(a[x])
#2
file= open("textfile.txt", "r")
a = []
for line in file:
if "snake" in line:
print(line.strip('\n')
#3
with open("textfile.txt","w") as file:
x = 1
for line in file:
a = []
a.append(x)
a.append(line)
a = " ".join(a)
file.write(a)
x = x+1
#4
with open("textfile.txt","w") as file:
for line in file:
a = line.split()
a.pop(0)
a = " ".join(a)
file.write(a)
|
9f7d9b898b8e61ba20b8a554529e2b00a1dd78a7 | 6ftunder/open.kattis | /py/Stacking Cups/stacking_cups.py | 856 | 4.21875 | 4 | cups = [] # list of cups with tuple (color, radius)
for i in range(int(input())):
# go through i test cases and add the cups into the cups list
# if we get data as diameter color we convert it to color radius
# if we get data as color raius we just enter the data as is
a, b = input().split() # split the input data at ' '
try:
a = int(a)//2 # try to convert into int and divide by 2(diamater/2=radius)
cups.append((b, a))
except ValueError:
# since first input was a string we can safely assume that b is a radius
# that's if the input was even entered correctly
cups.append((a, int(b)))
# print out the result
for cup in sorted(cups, key=lambda x: x[1]):
# go through sorted cups and print out the order from smallest to largest cup
print(cup[0]) # print out the current cup
|
1b531d0a6dc207cdc84528075cc60d2c97a0bb49 | trivelt/academic-projects | /Python/lab3/zad3_4.py | 220 | 3.6875 | 4 | #!/usr/bin/python
import re
while(True):
inp = raw_input(">>")
if inp == "stop":
break
if re.findall(r"\D", inp):
print "Nalezy podawac liczby, nie tekst!"
continue
x = int(inp)
print x, pow(x,3)
|
9dff520a84aec044429e0fb6e40544ec72631ab0 | Ikigai-pt/interview | /python/src/matrix/rotateMatrix.py | 2,166 | 3.78125 | 4 | # rotate a give nxn matrix clockwise
# eg: m[5,4] = > [1,2,3,4]
# [5,6,7,8]
# [a,b,c,d]
# [e,f,g,h]
# */
# op: m[5,4] = > [e,a,5,1]
# [f,b,6,2]
# [g,c,7,3]
# [h,d,8,4]
#
from random import randint
def prettyPrint(M):
for r in range(len(M)):
print(M[r])
print("\n")
def rotateMatrix90degree(M):
# if(direction == 'clockwise'):
O = M;
rowLen = len(M);
colLen = len(M[0]);
for d in range(0,rowLen/2):
for y in range(0,colLen):
start = M[y][y];
# O[rowLen-y-1][colLen-x-1] = M[x][rowLen-y-1]
for r in range(0,rowLen):
if(r%2 == 0):
O[r][y]= M[rowLen-d-1][r]
else:
O[rowLen-d-1][y]= M[rowLen-d-1:][rowLen-d-1]
prettyPrint(O)
return O
def rotateMatrix(M):
#let the matrix be arranged in x & y coordinates
rowLen = len(M)
colLen = len(M[0])
firstVal = M[0][0]
print("Col len %d Row Len %d", colLen,rowLen )
for y in range(0,1):
colLen -=1
for x in range(1,5):
print(x)
if(x % 2 > 0):
rowLen -=1
print(M[rowLen -x +1][x-1])
print(M[colLen -rowLen +x -1 ][colLen -rowLen -x])
M[colLen - rowLen][colLen - rowLen] = M[rowLen -x +1][x-1]
else:
print(M[rowLen][rowLen])
M[rowLen][x-2] = M[rowLen][rowLen]
prettyPrint(M)
M[0][rowLen] = firstVal
return M
def rotateAnyMatrix(M):
# base case M[1,1]
if(len(M) == len(M[0]) == 1):
return M
rows = len(M)
columns = len(M[0])
for r in range(1,rows):
for c in range(0,columns):
fromR = rows - r
fromC = c
toR = r
toC = c
print("from position %d ,%d" %(fromR, fromC))
print("to position %d, %d"%(toR,toC))
data = 0;
M = [[ randint(1,100) for r in range(4)] for c in range(4)]
prettyPrint(M)
rotateAnyMatrix(M)
#prettyPrint(rotateMatrix(M))
|
ea0d274b566d564a266efb7c23de78c3b3221a6d | nbiederbeck/Advent-Of-Code | /aoc/aoc12.py | 1,256 | 3.765625 | 4 | class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"<x={self.x:3d}, y={self.y:3d}, z={self.z:3d}>"
def __iter__(self):
for i in [self.x, self.y, self.z]:
yield i
class Moon:
def __init__(self, position: Vector, velocity: Vector):
self.position = position
self.velocity = velocity
def __repr__(self):
return f"pos={self.position}, vel={self.velocity}"
def kinetic(self):
return sum(map(abs, self.velocity))
def potential(self):
return sum(map(abs, self.position))
def total(self):
return self.kinetic() * self.potential()
class Jupiter:
def __init__(self, moons):
self.moons = moons
def potential(self):
return
def kinetic(self):
return 0
def total(self):
return self.potential * self.kinetic
p = Vector(2, 2, -2)
v = Vector(-1, -1, 1)
moon = Moon(position=p, velocity=v)
def test_moon_kinetic():
assert moon.kinetic() == 3
def test_moon_potential():
assert moon.potential() == 6
def test_moon_total():
assert moon.total() == 18
def main():
pass
if __name__ == '__main__':
main()
|
76438dea0f1d490dbcfae2d7206d16594d4c92c7 | subhane/TP_python1 | /verif.py | 254 | 3.734375 | 4 | def verif(nombre):
if nombre % 2 == 0:
print("Ce nombre est pair")
elif nombre % 3 == 0:
print("Ce nombre est impair, mais est multiple de 3")
else:
print("Ce nombre n'est ni pair ni multiple de 3")
print(verif(3))
|
ccc3461e3e362b590796198a26b154302a8f1071 | Engineervinay/Face-Recognition-Based-Attendance-System | /train.py | 10,144 | 3.546875 | 4 |
import tkinter as tk
from tkinter import Message ,Text
import cv2,os
import shutil
import csv
import numpy as np
from PIL import Image, ImageTk
import pandas as pd
import datetime
import time
import tkinter.ttk as ttk
import tkinter.font as font
window = tk.Tk()
#helv36 = tk.Font(family='Helvetica', size=36, weight='bold')
window.title("Face_Recogniser")
dialog_title = 'QUIT'
dialog_text = 'Are you sure?'
#answer = messagebox.askquestion(dialog_title, dialog_text)
#window.geometry('1280x720')
window.configure(background='blue')
#window.attributes('-fullscreen', True)
window.grid_rowconfigure(0, weight=1)
window.grid_columnconfigure(0, weight=1)
#path = "profile.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
#img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
#panel = tk.Label(window, image = img)
#panel.pack(side = "left", fill = "y", expand = "no")
#cv_img = cv2.imread("img541.jpg")
#x, y, no_channels = cv_img.shape
#canvas = tk.Canvas(window, width = x, height =y)
#canvas.pack(side="left")
#photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))
# Add a PhotoImage to the Canvas
#canvas.create_image(0, 0, image=photo, anchor=tk.NW)
#msg = Message(window, text='Hello, world!')
# Font is a tuple of (font_family, size_in_points, style_modifier_string)
message = tk.Label(window, text="Face-Recognition-Based-Attendance-Management-System" ,bg="Green" ,fg="white" ,width=50 ,height=3,font=('times', 30, 'italic bold underline'))
message.place(x=200, y=20)
lbl = tk.Label(window, text="Enter ID",width=20 ,height=2 ,fg="red" ,bg="yellow" ,font=('times', 15, ' bold ') )
lbl.place(x=400, y=200)
txt = tk.Entry(window,width=20 ,bg="yellow" ,fg="red",font=('times', 15, ' bold '))
txt.place(x=700, y=215)
lbl2 = tk.Label(window, text="Enter Name",width=20 ,fg="red" ,bg="yellow" ,height=2 ,font=('times', 15, ' bold '))
lbl2.place(x=400, y=300)
txt2 = tk.Entry(window,width=20 ,bg="yellow" ,fg="red",font=('times', 15, ' bold ') )
txt2.place(x=700, y=315)
lbl3 = tk.Label(window, text="Notification : ",width=20 ,fg="red" ,bg="yellow" ,height=2 ,font=('times', 15, ' bold underline '))
lbl3.place(x=400, y=400)
message = tk.Label(window, text="" ,bg="yellow" ,fg="red" ,width=30 ,height=2, activebackground = "yellow" ,font=('times', 15, ' bold '))
message.place(x=700, y=400)
lbl3 = tk.Label(window, text="Attendance : ",width=20 ,fg="red" ,bg="yellow" ,height=2 ,font=('times', 15, ' bold underline'))
lbl3.place(x=400, y=650)
message2 = tk.Label(window, text="" ,fg="red" ,bg="yellow",activeforeground = "green",width=30 ,height=2 ,font=('times', 15, ' bold '))
message2.place(x=700, y=650)
def clear():
txt.delete(0, 'end')
res = ""
message.configure(text= res)
def clear2():
txt2.delete(0, 'end')
res = ""
message.configure(text= res)
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def TakeImages():
Id=(txt.get())
name=(txt2.get())
if(is_number(Id) and name.isalpha()):
cam = cv2.VideoCapture(0)
harcascadePath = "haarcascade_frontalface_default.xml"
detector=cv2.CascadeClassifier(harcascadePath)
sampleNum=0
while(True):
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
#incrementing sample number
sampleNum=sampleNum+1
#saving the captured face in the dataset folder TrainingImage
cv2.imwrite("TrainingImage\ "+name +"."+Id +'.'+ str(sampleNum) + ".jpg", gray[y:y+h,x:x+w])
#display the frame
cv2.imshow('frame',img)
#wait for 100 miliseconds
if cv2.waitKey(100) & 0xFF == ord('q'):
break
# break if the sample number is morethan 100
elif sampleNum>60:
break
cam.release()
cv2.destroyAllWindows()
res = "Images Saved for ID : " + Id +" Name : "+ name
row = [Id , name]
with open('StudentDetails\StudentDetails.csv','a+') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
csvFile.close()
message.configure(text= res)
else:
if(is_number(Id)):
res = "Enter Alphabetical Name"
message.configure(text= res)
if(name.isalpha()):
res = "Enter Numeric Id"
message.configure(text= res)
def TrainImages():
recognizer = cv2.face_LBPHFaceRecognizer.create()#recognizer = cv2.face.LBPHFaceRecognizer_create()#$cv2.createLBPHFaceRecognizer()
harcascadePath = "haarcascade_frontalface_default.xml"
detector =cv2.CascadeClassifier(harcascadePath)
faces,Id = getImagesAndLabels("TrainingImage")
recognizer.train(faces, np.array(Id))
recognizer.save("TrainingImageLabel\Trainner.yml")
res = "Image Trained"#+",".join(str(f) for f in Id)
message.configure(text= res)
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#print(imagePaths)
#create empth face list
faces=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert('L')
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,'uint8')
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces.append(imageNp)
Ids.append(Id)
return faces,Ids
def TrackImages():
recognizer = cv2.face.LBPHFaceRecognizer_create()#cv2.createLBPHFaceRecognizer()
recognizer.read("TrainingImageLabel\Trainner.yml")
harcascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(harcascadePath);
df=pd.read_csv("StudentDetails\StudentDetails.csv")
cam = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
col_names = ['Id','Name','Date','Time']
attendance = pd.DataFrame(columns = col_names)
while True:
ret, im =cam.read()
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
faces=faceCascade.detectMultiScale(gray, 1.2,5)
for(x,y,w,h) in faces:
cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
if(conf < 50):
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
aa=df.loc[df['Id'] == Id]['Name'].values
tt=str(Id)+"-"+aa
attendance.loc[len(attendance)] = [Id,aa,date,timeStamp]
else:
Id='Unknown'
tt=str(Id)
if(conf > 75):
noOfFile=len(os.listdir("ImagesUnknown"))+1
cv2.imwrite("ImagesUnknown\Image"+str(noOfFile) + ".jpg", im[y:y+h,x:x+w])
cv2.putText(im,str(tt),(x,y+h), font, 1,(255,255,255),2)
attendance=attendance.drop_duplicates(subset=['Id'],keep='first')
cv2.imshow('im',im)
if (cv2.waitKey(1)==ord('q')):
break
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
Hour,Minute,Second=timeStamp.split(":")
fileName="Attendance\Attendance_"+date+"_"+Hour+"-"+Minute+"-"+Second+".csv"
attendance.to_csv(fileName,index=False)
cam.release()
cv2.destroyAllWindows()
#print(attendance)
res=attendance
message2.configure(text= res)
clearButton = tk.Button(window, text="Clear", command=clear ,fg="red" ,bg="yellow" ,width=20 ,height=2 ,activebackground = "Red" ,font=('times', 15, ' bold '))
clearButton.place(x=950, y=200)
clearButton2 = tk.Button(window, text="Clear", command=clear2 ,fg="red" ,bg="yellow" ,width=20 ,height=2, activebackground = "Red" ,font=('times', 15, ' bold '))
clearButton2.place(x=950, y=300)
takeImg = tk.Button(window, text="Take Images", command=TakeImages ,fg="red" ,bg="yellow" ,width=20 ,height=3, activebackground = "Red" ,font=('times', 15, ' bold '))
takeImg.place(x=200, y=500)
trainImg = tk.Button(window, text="Train Images", command=TrainImages ,fg="red" ,bg="yellow" ,width=20 ,height=3, activebackground = "Red" ,font=('times', 15, ' bold '))
trainImg.place(x=500, y=500)
trackImg = tk.Button(window, text="Track Images", command=TrackImages ,fg="red" ,bg="yellow" ,width=20 ,height=3, activebackground = "Red" ,font=('times', 15, ' bold '))
trackImg.place(x=800, y=500)
quitWindow = tk.Button(window, text="Quit", command=window.destroy ,fg="red" ,bg="yellow" ,width=20 ,height=3, activebackground = "Red" ,font=('times', 15, ' bold '))
quitWindow.place(x=1100, y=500)
copyWrite = tk.Text(window, background=window.cget("background"), borderwidth=0,font=('times', 30, 'italic bold underline'))
copyWrite.tag_configure("superscript", offset=10)
copyWrite.insert("insert", "Developed by Ashish","", "TEAM", "superscript")
copyWrite.configure(state="disabled",fg="red" )
copyWrite.pack(side="left")
copyWrite.place(x=800, y=750)
window.mainloop()
|
78248dcf33c6b1d7b01054ee809b48206b068089 | rjugalde/Tareas-1-2018 | /Taller/tarea taller 4.3.18.py | 472 | 3.609375 | 4 | #tarea taller 04/03/2018
def p1(n1,n2):
x=n1
y=n2
negativo=False
l1=[]
l2=[]
result=0
if x == 0 or y==0:
print("El resultado es--> 0")
else:
if x<0 or y<0:
negativo= True
while x!=0:
l1=l1+[x]
l2=l2+[y]
x=int(x/2)
y=y*2
print(l1,l2)
for i in range(0,len(l1)):
if (l1[i]%2)==1:
result+=l2[i]
#print ("gohuer",l1[i])
if negativo:
result=result*(-1)
print("Resultado de multiplicacion-->",result)
p1(90,3)
p1(,)
p1(,)
p1(,)
|
ea17f7ef90efb23c55573b0fd249b0555e11d1a6 | AnGela-CoDe/Task-one | /Start.py | 869 | 4.28125 | 4 | print("Давайте узнаем площадь данного прямоугольника!")
#выводим свойство данной программы
a=float(input("Введите длину прямоугольника"))
#присваеваем переменной а запрашиваемое и введённое с клавиатуры дробное число
b=float(input("Введите ширину прямоугольника"))
#присваиваем переменной b запрашиваемое и введённое с клавиатуры дробное число
s=a*b
#присваиваем переменной s произведение a и b
print("Площадь данного прямоугольника = " , s)
#и наконец, с помощью print выводим на экран полученное число |
06783cb22a658db7f8323c9d188889f46b0e785e | Slothfulwave612/Coding-Problems | /Data Structure/07. Strings/08. minimum_window_substring.py | 2,027 | 4.375 | 4 | '''
Find the smallest window in a string containing all characters of another string
Given two strings string1 and string2, the task is to find the smallest substring
in string1 containing all characters of string2 efficiently.
Examples:
Input: string = “this is a test string”, pattern = “tist”
Output: Minimum window is “t stri”
Explanation: “t stri” contains all the characters of pattern.
'''
def find_substring(string_1, string_2):
'''
Function to find the smalled window in string_1.
Arguments:
string_1 -- str, the original string from when the window is to be found.
string_2 -- str, the characters to be found in the string_1.
Returns:
str, the smallest window in a string.
'''
if len(string_2) > len(string_1):
return 'No window can be found.'
hash_pattern = [0] * 256
hash_string = [0] * 256
## 256, for all the ASCII characters
for char in string_2:
hash_pattern[ord(char)] += 1
start, start_index, min_length = 0, -1, float('inf')
count = 0
for j in range(len(string_1)):
hash_string[ord(string_1[j])] += 1
if hash_pattern[ord(string_1[j])] != 0 and hash_string[ord(string_1[j])] <= hash_pattern[ord(string_1[j])]:
count += 1
if count == len(string_2):
while hash_pattern[ord(string_1[start])] == 0 or hash_pattern[ord(string_1[start])] < hash_string[ord(string_1[start])]:
if hash_string[ord(string_1[start])] > hash_pattern[ord(string_1[start])]:
hash_string[ord(string_1[start])] -= 1
start += 1
len_window = j - start + 1
if len_window < min_length :
start_index = start
min_length = len_window
if start_index == -1:
return 'No window found.'
return string_1[start_index: start_index + min_length]
string_1 = 'this is a test string'
string_2 = 'tist'
print(find_substring(string_1, string_2))
|
2c75da7ae72d957c7b332c35234727db83788e07 | Marcfeitosa/listadeexercicios | /ex050.py | 377 | 3.75 | 4 | """Exercício 50
Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares.
Se o valor digitado for ímpar, desconsidere-o"""
s = 0
c = 0
for i in range(0,8):
n = int(input('Digite um valor: '))
if n % 2 == 0:
s += n
c += 1
print('A soma de todos os {} números pares é igual a {}.'.format(c,s)) |
a24db43644e281b46b5cd34bc68a92ee824acd52 | neriphy/temperaturas | /temperatura.py | 618 | 4 | 4 | #Programa para convertir de Celsius a Fahrenheit o viceversa
#Creado por @neriphy
print("Si desea convertir Celsius a Fahrenheit introduzca 1 ")
print("Si desea convertir Fahrenheit a Celsius introduzca 2 ")
convertir_a = int(input())
if convertir_a == 1:
grados = int(input("Introduzca los grados Celsius "))
resultado = (grados * 1.5) + 32
print(grados,"grados Celsius, serian",resultado,"grados Fahrenheit")
if convertir_a == 2:
grados = int(input("Introduzca los grados Fahrenheit "))
resultado = (grados - 32) / 9/5
print(grados,"grados Fahrenheit, serian",resultado,"grados Celsius")
|
d29f423a95a6fd4ff10ae88f1a5353edfb1d6111 | carrikm/Minesweeper-Python | /minesweeper.py | 1,296 | 4.15625 | 4 | #**************************************************************************************************
# Created by Carrik McNerlin
# May 5, 2021
#
# This is the driver application for playing Minesweeper on an MxM grid with N mines.
# Each game uses 2 boards, one to show the player and one that holds the mines and proximity count.
# When the player chooses a space, swap the character with the one at that square on the mine board.
#**************************************************************************************************
from game import * #game imports boardFunctions.py
# default to yes for initial playthrough
keep_playing = 'y'
while (keep_playing[0].lower() == 'y'):
board_size = int(input("How many rows and columns would you like the board to be?\n"))
num_mines = board_size**2 + 1
# can't have more mines than spaces
while (num_mines < 1 or num_mines > board_size**2):
num_mines = int(input("How many mines would you like there to be?\n"))
if num_mines < 1:
print("Cannot play a game with no mines.")
elif num_mines > board_size**2:
print("Cannot have more mines than board tiles.")
play(board_size,num_mines)
keep_playing = str(input("Would you like to play again?\n"))
#end while
|
b1b0d0fabd6849f1f5f4e59caed496ce5043237b | sudoberlin/python-DSA | /stack_queue.py/circular_queue.py | 1,470 | 3.65625 | 4 | # 34, 45, 67, 78, 89, 12, 23, 31
# 0, 1, 2, 3, 4, 5, 6, 7
# R F
# (self.rear + 1) % self.size == self.front
# 2%8 == 2
class CircularQueue:
def __init__(self, size):
self.size = size
self.queue = [None for i in range (size)]
self.front = self.rear = -1
def enqueue(self, data):
if ((self.rear +1) % self.size == self.front):
print("queue is full")
return
elif (self.front == -1):
self.front = 0
self.rear = 0
self.queue[self.rear] = data
else:
self.rear = (self.rear + 1) % self.size
self.queue[self.rear] = data
def dequeue(self):
if (self.front == -1):
print("queue is already empty")
return
elif(self.front ==self.rear):
popval = self.queue[self.front]
self.front = -1
self.rear = -1
return popval
else:
popval = self.queue[self.front]
self.front = (self.front + 1) % self.size
return popval
cq = CircularQueue(10)
cq.enqueue(14)
cq.enqueue(22)
cq.enqueue(13)
cq.enqueue(-6)
print("Deleted value = ", cq.dequeue())
print("Deleted value = ", cq.dequeue())
print("Deleted value = ", cq.dequeue())
cq.enqueue(9)
cq.enqueue(20)
cq.enqueue(5)
print(cq)
print("Deleted value = ", cq.dequeue())
print("Deleted value = ", cq.dequeue())
print("Deleted value = ", cq.dequeue()) |
3ca5cd4aa56ea6fe70a5efd8aac95bc1334efc0f | AhmedAymann/Support-Vector-Regression-SVR- | /Support Vector Resgression.py | 1,483 | 3.5 | 4 | #importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# importing data
dataset = pd.read_csv('C:/Users/My Pc/Desktop/machine learning tests/regression/Polynomial Regression/Position_Salaries.csv')
x = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2:3].values
""" # splitting data into trainingset and testset
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split( dp, indp, test_size= 0.2, random_state= 0)"""
# Feature scalling
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
sc_y = StandardScaler()
x = sc_x.fit_transform(x)
y = sc_y.fit_transform(y)
# Fitting the Regression to the dataset
from sklearn.svm import SVR
regresor = SVR(kernel = 'rbf')
regresor.fit(x, y)
# predicitng a new result with polynomial regresion
y_pred = sc_y.inverse_transform(regresor.predict(sc_x.transform(np.array([[6.5]]).reshape(1, 1))))
# visualising SVR regression
plt.scatter(x, y, c = 'b')
plt.plot(x, regresor.predict(x), c = 'r')
plt.title('salary vs possiotion (SVR)')
plt.xlabel('position')
plt.ylabel('salary')
plt.show()
# visualising svr regression
x_grid = np.arange(min(x), max(x), 0.1)
x_grid = x_grid.reshape((len(x_grid), 1))
plt.scatter(x, y, c = 'g')
plt.plot(x_grid, regresor.predict(x_grid), c = 'r')
plt.title('salary vs possiotion (SVR)')
plt.xlabel('position')
plt.ylabel('salary')
plt.show()
|
51d5a531c3f7f10d6d89312df54f46e2fbb09d4f | javiermontenegro/Python_Sorting.Algorithms | /HeapSort.py | 3,081 | 4.09375 | 4 | #********************************************************************
# Filename: HeapSort.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the heap sort algorithm.
#*********************************************************************
def max_heap_sort(arr):
""" Heap Sort that uses a max heap to sort an array in ascending order
Complexity: O(n log(n))
"""
for i in range(len(arr) - 1, 0, -1):
max_heapify(arr, i)
temp = arr[0]
arr[0] = arr[i]
arr[i] = temp
def max_heapify(arr, end):
""" Max heapify helper for max_heap_sort
"""
last_parent = int((end - 1) / 2)
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
while current_parent <= last_parent:
# Find greatest child of current_parent
child = 2 * current_parent + 1
if child + 1 <= end and arr[child] < arr[child + 1]:
child = child + 1
# Swap if child is greater than parent
if arr[child] > arr[current_parent]:
temp = arr[current_parent]
arr[current_parent] = arr[child]
arr[child] = temp
current_parent = child
# If no swap occured, no need to keep iterating
else:
break
def min_heap_sort(arr):
""" Heap Sort that uses a min heap to sort an array in ascending order
Complexity: O(n log(n))
"""
for i in range(0, len(arr) - 1):
min_heapify(arr, i)
def min_heapify(arr, start):
""" Min heapify helper for min_heap_sort
"""
# Offset last_parent by the start (last_parent calculated as if start index was 0)
# All array accesses need to be offet by start
end = len(arr) - 1
last_parent = int((end - start - 1) / 2)
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
while current_parent <= last_parent:
# Find lesser child of current_parent
child = 2 * current_parent + 1
if child + 1 <= end - start and arr[child + start] > arr[child + 1 + start]:
child = child + 1
# Swap if child is less than parent
if arr[child + start] < arr[current_parent + start]:
temp = arr[current_parent + start]
arr[current_parent + start] = arr[child + start]
arr[child + start] = temp
current_parent = child
# If no swap occured, no need to keep iterating
else:
break
if __name__ == '__main__':
collection = [1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64]
print("List numbers: %s\n" % repr(collection))
max_heap_sort(collection)
print("Ordered list: %s" % collection)
|
1a3e284728c84cb5bfaa83f12886ba491800f1c4 | markedward82/pythonbootcamp | /ex18.py | 881 | 4.5 | 4 | #ex18 Names, Variables, Code, Function
#Function do three things:
#1. They name pieces of code the way variables name and numbers.
#2. They take arguement the way your script take argv
#3. using #1 and #2 they let you make your own "mini script" or "tiny command"
#you can create a function by using the word def in python
#This one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
#Ok, that *args is actually pointless, we can just do this.
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# this one only take one arguement
def print_one(arg1):
print(f"arg1:{arg1}")
#this one takes no arguement
def print_none():
print("I got nothing")
#execute all the functions
print_two("zed", "shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
|
0bb3417bf39a7ce125632a8f353098db7a775ec1 | mohitkhatri611/python-Revision-and-cp | /python programs and projects/python tricks to reduce time/output formats.py | 788 | 3.734375 | 4 | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
print("{:.6f}".format(sum(student_marks.get(query_name))/len(scores))) # this will print upto 6 digit after decimal.
#output: 56.000000
#other way:
#print("%.2f" % (sum(marks) / len(marks)))
Numbers = [1, 2, 3, 4, 6, 4, 3, 6, 8, 5, 8]
for i in enumerate(Numbers):
print("Index of {} is {}".format(i[1],i[0]))
pm = ['modi', 'biden', 'jacinda', 'scott', 'boris']
country = ['india', 'us', 'nz', 'aus', 'uk']
for pm ,country in zip(pm,country):
print("Prime Minister: %s Country is: %s" %(pm,country)) |
503386f1465c84feef8a9f36ce552d8a5e1e3c0b | Artarin/Python-Trashbox | /fucking_fibonacci.py | 383 | 3.71875 | 4 | #решение авторов:
#n = int(input())
#if n == 0:
# print(0)
#else:
# a, b = 0, 1
# for i in range(2, n + 1):
# a, b = b, a + b
# print(b)
num = int(input())
fMinusTwo = 0
fMinusOne = 1
for i in range (2,num+1):
f = fMinusOne+fMinusTwo
fMinusTwo = fMinusOne
fMinusOne = f
if num == 0:
f = 0
if num == 1:
f = 1
print (f)
|
2979c45d731aabb793df9540d68d5d698284a2c3 | terra-namibia/python-training | /circle1.py | 493 | 3.53125 | 4 | # coding: UTF-8
# 三角比を使って円を描画
import matplotlib.pyplot as plt
import numpy as np
# 角度
th = np.arange(0, 360, 1)
# 円周上の点の座標x,y (r * cos, r * sin)
r = 3 # 円の半径
x = r * np.cos(np.radians(th)) + 1 # +1:円の中心
y = r * np.sin(np.radians(th)) + 2 # +2:円の中心
# graph
plt.axis('equal') # x/yのメモリ単位を揃える
plt.plot(x,y, color='blue')
plt.grid(color = '0.8') # 背景のグリッド線描画
plt.show() # 画面表示
|
e098f70098de100d7272047a76cb625c524fcad6 | JMSEhsan/Python_Exercises | /Asgmt4/assignmnet4_Ehsan.py | 2,362 | 4.09375 | 4 | print("\n","\bEhsan *** Feb. 04, 2021 *** Team IV *** Assignment Day 4 \n")
#1
print("Exe.1- Division remainder of 7 over 5 = ", 7 % 5)
#2
if 7 >= 5:
print("Exe.2- Checked, 7 is greater than or equal to 5")
else:
print("Exe.2- Checked, 7 is NOT greater than or equal to 5")
#3
print("Exe.3- Binary Shift \"4\" by \"2\" = ", 4<<2, " decimal (base 10)") # 10000 in binary (base 2)
#4
myList = []
addList = ["apple", "banana", "cherry", "apple", "cherry"]
myList.extend(addList)
print("Exe.4- a) myList: ", myList)
ci = myList.index("cherry")
ai = myList.index("apple")
print("\t\bb) \"",myList[ci],"\"", ",", "\"",myList[ai],"\"")
#5
print("Exe.5- Lenth of myLsit: ", len(myList))
#6
print("Exe.6- Last two items on myList: ", myList[-2],",", myList[-1] )
#7
for x in myList:
if x == "apple":
ai = myList.index("apple")
myList[ai:ai+1] = ["grapes", "papaya"]
print("Exe.7- Changing the apple with grapes and papays: ", myList)
#8
myList.append("grapes") #2nd method: #myList.insert(len(myList), "grapes")
print("Exe.8- Appending grapes at the end: ", myList)
#9
if "papaya" in myList: #2nd method of removing "papaya": for y in myList:
print("Exe.9- a) Checked, papaya is on myList") #if y == "papaya":
mynewList = [y for y in myList if y != "papaya"] #myList.remove("papaya")
print("\t\bb) papaya removed: ", mynewList)
else:
print("Exe.9- Checked, papaya is NOT on myList")
#10
mynewList2 = [M.upper() for M in mynewList]
print("Exe.10- myList in uppercase: ", mynewList2)
#11
mynewList2.sort(reverse = True)
print("Exe.11- Sorting the list descending: ", mynewList2)
print("\n*** End ***\n") |
015e0afe60927a025a01646c23ed73a789f49dca | kylin-zhuo/data-structure-algorithms | /leetcode/python/trees/572.py | 2,189 | 3.96875 | 4 | """
572. Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def same_tree(s, t):
if not s and not t: return True
if not s and t or s and not t : return False
return s.val == t.val and same_tree(s.left, t.left) and same_tree(s.right, t.right)
if same_tree(s, t): return True
if not s and t or s and not t: return False
else:
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
# This recursive solution ranks only ~40%
# Try iterative one
class Solution_1(object):
def isSubtree(self, s, t):
# Preorder Traversal
pre_s, pre_t = [], []
self.preorder(pre_s, s)
self.preorder(pre_t, t)
# return '$'.join(pre_t) in '$'.join(pre_s)
return self.verify(pre_s, pre_t)
def verify(self, pre_s, pre_t):
if not pre_s and not pre_t: return True
for i in range(len(pre_s)):
if pre_s[i] == '#': continue
if pre_s[i:i+len(pre_t)] == pre_t:
return True
return False
def preorder(self, res, root):
if not root:
res.append('#')
return
res.append(str(root.val))
self.preorder(res, root.left)
self.preorder(res, root.right)
|
3a8e2ef64cf374e63430ec23ad677730906c5c06 | Yuziquan/LeetCode | /Problemset/super-egg-drop/super-egg-drop.py | 3,239 | 3.78125 | 4 |
# @Title: 鸡蛋掉落 (Super Egg Drop)
# @Author: KivenC
# @Date: 2019-03-02 19:23:14
# @Runtime: 56 ms
# @Memory: 13.3 MB
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
'''
基于动态规划:假设 f {n,m} 表示 n 层楼、m 个鸡蛋时找到最高楼层的最少尝试次数。当第一个鸡蛋从第 i 层扔下,如果碎了,还剩 m-1 个鸡蛋,为确定下面楼层中的安全楼层,还需要 f {i-1,m-1} 次,找到子问题;不碎的话,上面还有 n-i 层,还需要 f [n-i,m] 次,又一个子问题。 状态转移方程如下: f {n, m} = min (1 + max (f {n - 1, m - 1}, f {n - i, m}) ) 其中: i 为 (1, n), f {i, 1} = 1
基于数学方程的方法(对于K=2的情形):假设最少尝试次数为 x,那么,第一个鸡蛋必须要从第 x 层扔下,因为:如果碎了,前面还有 x - 1 层楼可以尝试,如果没碎,后面还有 x-1 次机会。如果没碎,第一个鸡蛋,第二次就可以从 x +(x - 1)层进行尝试,为什么是加上 x - 1,因为,当此时,第一个鸡蛋碎了,第二个鸡蛋还有可以从 x+1 到 x + (x - 1) - 1 层进行尝试,有 x - 2 次。如果还没碎,那第一个鸡蛋,第三次从 x + (x - 1) + (x - 2) 层尝试。碎或者没碎,都有 x - 3 次尝试机会,依次类推。那么,x 次的最少尝试,可以确定的最高的楼层是多少呢? x + (x - 1) + (x - 2) + … + 1 = x (x+1) / 2 那反过来问,当最高楼层是 100 层,最少需要多少次呢?x (x+1)/2 >= 100, 得到 x>=14,最少要尝试 14 次。
'''
'''
res = [[0 for _ in range(N+1)] for _ in range(K+1)]
for n in range(N+1):
res[1][n] = n
for k in range(2, K+1):
for n in range(1, N+1):
min_res = float('inf')
for i in range(1, n+1):
min_res = min(min_res, 1 + max(res[k-1][i-1], res[k][n-i]))
res[k][n] = min_res
return res[K][N]
'''
moves = 0
dp = [0 for _ in range(K+1)]
while dp[K] < N:
# 逆序从K---1,dp[i] = dp[i]+dp[i-1] + 1 相当于上次移动后的结果,dp[]函数要理解成抽象出来的一个黑箱子函数,跟上一次移动时鸡蛋的结果有关系
for i in range(K, 0, -1):
dp[i] += dp[i-1] + 1
# 以上计算式,是从以下转移方程简化而来
# dp[moves][k] = 1 + dp[moves-1][k-1] + dp[moves-1][k]
# 假设 dp[moves-1][k-1] = n0, dp[moves-1][k] = n1
# 首先检测,从第 n0+1 楼丢下鸡蛋会不会破。
# 如果鸡蛋破了,F 一定是在 [1:n0] 楼中,
# 利用剩下的 moves-1 次机会和 k-1 个鸡蛋,可以把 F 找出来。
# 如果鸡蛋没破,假如 F 在 [n0+2:n0+n1+1] 楼中
# 利用剩下的 moves-1 次机会和 k 个鸡蛋把,也可以把 F 找出来。
# 所以,当有 moves 个放置机会和 k 个鸡蛋的时候
#/ F 在 [1, n0+n1+1] 中的任何一楼,都能够被检测出来。
moves += 1
return moves
|
f7ee27121704f23cc14f5b8d8a38ed14ae5d7e6b | CharlesRajendran/go-viral | /backend/ImproveContent/FindPostEmotionSO.py | 2,319 | 3.5 | 4 | import nltk
import fileinput
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
def FindEmotionsSO(file_name):
stop_words = set(stopwords.words('english'))
angerSO = 0
antSO = 0
disgustSO = 0
fearSO = 0
joySO = 0
sadnessSO = 0
surpriseSO = 0
trustSO = 0
words = word_tokenize(file_name)
filtered_words = []
#stopwords removal
for w in words:
if w not in stop_words:
filtered_words.append(w)
#count anger
for line in fileinput.input("angerSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
angerSO = angerSO + int(chunks[1])
#count anticipation
for line in fileinput.input("anticipationSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
antSO = antSO + int(chunks[1])
#count disgust
for line in fileinput.input("disgustSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
disgustSO = disgustSO + int(chunks[1])
#count fear
for line in fileinput.input("fearSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
fearSO = fearSO + int(chunks[1])
#count joy
for line in fileinput.input("joySO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
joySO = joySO + int(chunks[1])
#count sadness
for line in fileinput.input("sadnessSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
sadnessSO = sadnessSO + int(chunks[1])
#count surprise
for line in fileinput.input("surpriseSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
surpriseSO = surpriseSO + int(chunks[1])
#count trust
for line in fileinput.input("trustSO.txt"):
chunks = line.split()
if chunks[0] in filtered_words:
trustSO = trustSO + int(chunks[1])
so = {'angerSO' : angerSO, 'antSO' : antSO, 'disgustSO' : disgustSO, 'fearSO' : fearSO, 'joySO' : joySO, 'sadnessSO' : sadnessSO, 'surpriseSO' : surpriseSO, 'trustSO': trustSO}
return so
#print (FindEmotionsPer(open("23.txt","r").read()))
|
d9096f4318bbf7144eb98d9e5e0103ce27ee812b | cdagnino/LearningModels | /src/models/finite_transitions_fs.py | 6,663 | 3.53125 | 4 | """
See Aguirregabiria & Jeon (2018), around equation (2)
$V_{b_t}(I_t)$ is the value of the firm at period $t$ given current information and beliefs.
The value of the firm is given by
$$V_{b_t}(I_t) = max_{a_t \in A} \{ \pi(a_t, x_t) + \beta
\int V_{b_{t+1}}(x_{t+1}, I_t) b_t(x_{t+1}| a_t, I_t )\; d x_{t+1}\} $$
Probably better notation would be to write $V_{b_{t+1}}(I_{t+1}(x_{t+1}, I_t))$
the firm has a prior belief $b_0(x_1 | a_0, x_0)$ that is exogenous.
This prior is a mixuter over a collection of L transition probabilities:
$$P = \{p_l (x_{t+1} | a_t, x_t) \}_{l=1}^L$$
so that
$$b_0(x_1 | a_0, x_0) = \sum_{l=1}^L \lambda_l^{(0)} p_l (x_1| a_0, x_0)$$
The firm observes the new state $x_t$ and uses this information to update its beliefs by using Bayes rule. The Bayesian updating is given by
$$\lambda_l^{(t)} = \frac{ p_l (x_t| a_{t-1}, x_{t-1}) \lambda_l^{(t-1)} }{ \sum_{l'=1}^L p_{l'} (x_t| a_{t-1}, x_{t-1}) \lambda_{l'}^{(t-1)}} $$
In words, $p_l (x_t| a_{t-1}, x_{t-1})$ is the probability that the $l$
transition probability gave to $x_t$ actually happening. If the probability of $x_t$ (the state that actually occured) is high under $l$, then that $l$ transition probability will get a higher weight in the beliefs of next period.
"""
import src.constants as const
import numpy as np
from typing import Callable
from scipy.interpolate import LinearNDInterpolator
from numba.decorators import njit
#TODO: vectorize over action (price). Hadamard + dot. Check black notebook
@njit()
def belief(new_state, transition_fs, lambda_weights, action: float, old_state) -> float:
"""
state: point in state space
transition_fs: list of transition probabilities
"""
return np.dot(transition_fs(new_state, action, old_state), lambda_weights)
@njit()
def update_lambdas(new_state: float, transition_fs: Callable, old_lambdas: np.ndarray,
action: float, old_state) -> np.ndarray:
"""
Update the beliefs for new lambdas given a new state.
new_state: in the demand model, correspondes to log(q)
Transition_fs are fixed and exogenous. k by 1
Output:
"""
denominator = (old_lambdas * transition_fs(new_state, action, old_state)).sum()
return transition_fs(new_state, action, old_state)*old_lambdas / denominator
#@jit('float64(float64, float64, float64)', nopython=True, nogil=True)
@njit()
def jittednormpdf(x, loc, scale):
return np.exp(-((x - loc)/scale)**2/2.0)/(np.sqrt(2.0*np.pi)) / scale
#TODO Pass betas_transition, σ_ɛ and α in a nicer way
betas_transition = const.betas_transition
σ_ɛ = const.σ_ɛ #0.5
α = const.α #1.0
#@jit('float64[:](float64, float64, float64)')
@njit()
def dmd_transition_fs(new_state, action: float, old_state) -> np.ndarray:
"""
Returns the probability of observing a given log demand
Action is the price. level, NOT log
"""
return jittednormpdf(new_state, loc=α + betas_transition * np.log(action), scale=σ_ɛ)
@njit()
def exp_b_from_lambdas(lambdas, betas_transition=const.betas_transition):
"""
Get E[β] from the lambdas
"""
return np.dot(lambdas, betas_transition)
def rescale_demand(log_dmd, beta_l, price):
"""
Rescales demand to use Gauss-Hermite collocation points
price: level price, NOT log
"""
mu = const.α + beta_l*np.log(price)
return const.sqrt2*const.σ_ɛ * log_dmd + mu
def eOfV(wGuess: Callable, p_array, lambdas: np.ndarray) -> np.ndarray:
"""
Integrates wGuess * belief_f for each value of p. Integration over demand
Sum of points on demand and weights, multiplied by V and the belief function
p_array: level prices, NOT log
"""
def new_lambdas(new_dmd, price):
return update_lambdas(new_dmd, transition_fs=dmd_transition_fs,
old_lambdas=lambdas, action=price, old_state=2.5)
integration_over_p = np.empty(p_array.shape[0])
#@jit('float64(float64[:])', nopython=True, nogil=True)
#def jittedwguess(lambdas):
# return wGuess(lambdas)
#TODO: vectorize over p
for i, price in enumerate(p_array):
sum_over_each_lambda = 0.
for l, beta_l in enumerate(const.betas_transition):
for k, hermite_point in enumerate(const.hermite_xs):
rescaled_demand = rescale_demand(hermite_point, beta_l, price)
new_lambdas_value = new_lambdas(rescaled_demand, price)
# wGuess takes all lambdas except last (because of the simplex)
v_value = wGuess(new_lambdas_value[:-1])
sum_over_each_lambda += v_value * const.hermite_ws[k] * lambdas[l]
integration_over_p[i] = sum_over_each_lambda
return np.pi ** (-0.5) * integration_over_p
def interpolate_wguess(simplex_points,
value_function_points: np.ndarray) -> Callable:
"""
:param simplex_points: defined on D dims. Interpolation happens on D-1 dims
:param value_function_points:
:return:
"""
dims = simplex_points.shape[1]
return LinearNDInterpolator(simplex_points[:, 0:(dims - 1)], value_function_points)
def bellman_operator(wGuess, price_grid, lambda_simplex, period_return_f: Callable):
"""
The approximate Bellman operator, which computes and returns the
updated value function Tw on the grid points.
:param wGuess: Matrix on lambdas or function on lambdas
:param price_grid:
:param lambda_simplex:
:param period_return_f: Period return function. E.g., current period profit
:return: interpolated_tw, policy
"""
policy = np.empty(lambda_simplex.shape[0])
Tw = np.empty(lambda_simplex.shape[0])
# 1. go over grid of state space
# 2. Write objective (present return + delta*eOfV)
# 3. Find optimal p on that objective
# 4. write optimal p and value function on that point in the grid
for iII, (λ1, λ2, λ3) in enumerate(lambda_simplex):
if iII%10==0:
print("doing {0} of {1}".format(iII, len(lambda_simplex)))
lambda_weights = np.array([λ1, λ2, λ3])
R_ : np.ndarray = period_return_f(price_grid, lambdas=lambda_weights)
eOfV_p : np.ndarray = eOfV(wGuess, price_grid, lambdas=lambda_weights)
assert isinstance(R_, np.ndarray)
assert isinstance(eOfV_p, np.ndarray)
objective_vals = R_ + const.δ * eOfV_p
p_argmax = np.argmax(objective_vals)
pStar = price_grid[p_argmax]
policy[iII] = pStar
Tw[iII] = objective_vals[p_argmax]
interpolated_tw = interpolate_wguess(lambda_simplex, Tw)
return interpolated_tw, policy
|
ac6da67bb7824e2bf0a7c86cbf761fa9b0aa78e0 | DeanDro/monopoly_game | /cards_classes/cards.py | 774 | 3.96875 | 4 | """Super class for all cards in the game"""
import pygame
class Cards:
"""Name, owner and saleable will be available across all cards"""
def __init__(self, name, saleable, board_loc, owner=None):
self.name = name
self.board_loc = board_loc
self.saleable = saleable
self.owner = owner
# Method to assign owner to a card if it is purchased
def assign_owner(self, new_owner):
self.owner = new_owner
# Check who is the property owner
def check_ownership(self):
return self.owner
def return_name(self):
"""In order for this method to return the name value for all children classes, each child class must
have a global variable named self.name
"""
return self.name
|
146a1ded2a35ba5557d674d7215239426e2c6602 | btoll/howto-algorithm | /python/array/best_time_to_buy_and_sell_stock.py | 400 | 3.71875 | 4 | def best_time(prices):
left, right = 0, 1
max_profit = 0
while right < len(prices):
# Is this profitable?
if prices[right] > prices[left]:
max_profit = max(max_profit, prices[right] - prices[left])
else:
left = right
right += 1
return max_profit
prices = [7, 1, 5, 3, 6, 4]
#prices = [7, 6, 4, 3, 1]
print(best_time(prices))
|
67aa821716774b31e77be1bc544bb43fd16a83da | TigiGln/Algo | /subparts/BWT.py | 2,578 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 15:58:34 2021
@author: Thierry Galliano
"""
from sys import argv
###############################################################################
def cryptage(sequence : str):
"""
Function to encrypt the sequence of interest
"""
#addition of special character allowing the encryption of the sequence
sequence += "$"
list_pattern = []
list_pattern2 = []
#creation of the list of different patterns with shift of the special character
for position in range(len(sequence), 0, -1):
list_pattern.append(sequence[position:] + sequence[0:position])
list_pattern2 = list_pattern[0:len(list_pattern)]
list_pattern2.sort()
bwt = ""
#Retrieve the encrypted sequence from the last column of the matrix
for pattern in list_pattern2:
bwt += pattern[-1]
return(list_pattern, list_pattern2, bwt)
##############################################################################
def decryptage(bwt:str):
"""
Function to decrypt the sequence of interest
"""
#creation of the bwt character list and the list with the transformation steps
bwt_list = list(bwt)
bwt_list_step = []
#the copy method creates a duplicate of the list and not a path to the memory location
bwt_list_step. append(bwt_list.copy())
bwt_list.sort()
bwt_list_step.append(bwt_list.copy())
#add bwt in the first column in each loop
for turn in range(1, len(bwt), 1):
for add_bwt in range(0, len(bwt), 1):
bwt_list[add_bwt] = bwt[add_bwt] + bwt_list[add_bwt]
bwt_list_step.append(bwt_list.copy())
#sorting of each line in lexicographical order
if turn != (len(bwt)-1):
bwt_list.sort()
bwt_list_step.append(bwt_list.copy())
#Recovery of the original decrypted sequence by searching for the special character
seq_decryption = ""
for elt in bwt_list:
if elt[-1] == "$":
seq_decryption = elt[0:len(elt)-1]
return seq_decryption, bwt_list, bwt_list_step
##############################################################################
if __name__ == "__main__":
if len(argv) == 2:
print("Encryption using the BWT method: ")
liste_pattern, liste_pattern2, bwt = cryptage(argv[1].upper())
print(bwt, "\n")
print("Decryption using the BWT method: ")
seq, liste, liste2 = decryptage(bwt)
print(seq)
else:
print("Please enter a sequence or respect the number of options")
|
f2b290d79e727801d8b5741a911ae31a3c4f8628 | eronekogin/leetcode | /2022/minimum_time_to_collect_all_apples_in_a_tree.py | 1,210 | 3.671875 | 4 | """
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/
"""
from collections import defaultdict
class Solution:
def minTime(
self,
n: int,
edges: list[list[int]],
hasApple: list[bool]
) -> int:
def walk(currNode: int) -> int:
if currNode in visited:
return 0
visited.add(currNode)
steps = 0
# Collecting apples in the sub tree.
for nextNode in graph[currNode]:
steps += walk(nextNode)
# Then back to its parent node.
if steps > 0:
return steps + 2
# No apple in the subtree, but having apple at the current node.
if hasApple[currNode]:
return 2
# No apple at the current node.
return 0
visited = set()
# Build graph.
graph = defaultdict(list)
for src, dest in edges:
graph[src].append(dest)
graph[dest].append(src)
# As the node zero does not have a parent, so we need to subtract 2
# from it to get the final total steps.
return max(walk(0) - 2, 0)
|
54913e8fa5f44b2b2bb9eaefc8b6db3e41323c06 | Aasthaengg/IBMdataset | /Python_codes/p02273/s580566466.py | 794 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import math
class Point_Class:
def __init__(self, x, y):
self.x = x
self.y = y
def printPoint(self):
print "%f %f" %(self.x, self.y)
def koch(n, p1, p2):
if n == 0:
return
sin60 = math.sin(math.radians(60))
cos60 = math.cos(math.radians(60))
s = Point_Class((2*p1.x+p2.x)/3, (2*p1.y+p2.y)/3)
t = Point_Class((p1.x+2*p2.x)/3, (p1.y+2*p2.y)/3)
u = Point_Class((t.x-s.x)*cos60-(t.y-s.y)*sin60+s.x, (t.x-s.x)*sin60+(t.y-s.y)*cos60+s.y)
koch(n-1, p1, s)
s.printPoint()
koch(n-1, s, u)
u.printPoint()
koch(n-1, u, t)
t.printPoint()
koch(n-1, t, p2)
n = int(raw_input())
p1 = Point_Class(0.0, 0.0)
p2 = Point_Class(100.0, 0.0)
p1.printPoint()
koch(n, p1, p2)
p2.printPoint() |
545f0296e290d5e95add6ea24486ae93ef44f771 | Davin-Rousseau/ICS3U-Unit4-04-Python | /break_statement_program.py | 1,090 | 4.125 | 4 | #!/usr/bin/env python3
# Created by: Davin Rousseau
# Created on October 2019
# This program asks user to pick a number from 0-9
# and tells them if they got it right or wrong
# and asks them to keep playing until they get it right
import random
random = random.randint(1, 9)
def main():
# This function makes the user guess a number from 0-9
loop_counter = 0
# input
number = input("Guess my number (0-9): ")
print("")
# process
for loop_counter in range(5):
try:
integer = int(number)
if integer == random:
# output
print("")
print("Correct!")
break
else:
print("")
print("Incorrect")
if loop_counter == 4:
break
else:
number = input("try again: ")
except ValueError:
print("Invalid input.")
print("")
print("Correct number is:{} ".format(random))
print("thanks for playing!")
if __name__ == "__main__":
main()
|
1738621fb97fe2c32ec48cbe8fc83d57bf31fe65 | ngocyen3006/learn-python | /practicepython.org/cowsBulls.py | 1,170 | 3.9375 | 4 | # http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html
import random
def cowBull(number, guess):
if len(number) > len(guess):
length = len(guess)
else:
length = len(number)
cow = length
bull = 0
for i in range(length):
if number[i] == guess[i]:
cow -= 1
bull += 1
return (cow, bull)
if __name__ == "__main__":
# random 4 digit number
number = str(random.randint(1000, 9999))
print(number)
count = 0 # count guess times
while True:
# user guess a number
print("Give me your guess!")
guess = input()
count += 1
if guess.lower() == "exit":
break
if len(guess) > len(number):
print("Your guess number is too large, try again.")
continue
result = cowBull(number, guess)
if result[1] == len(number):
print("You win the game with {} bulls after {} guess times.".format(result[1], count))
break
print("You have {} cows, and {} bulls.".format(result[0], result[1]))
print("Your guess isn't quite right, try again.")
|
74db2cb716b6061ba7af77c4ef33bb2dc6029e52 | igor-correia/URI-python | /Categoria iniciante/1035.py | 322 | 3.609375 | 4 | i = 0
numeros = input().split()
A = int(numeros[0])
B = int(numeros[1])
C = int(numeros[2])
D = int(numeros[3])
if B > C and D > A:
if (C + D) > (A + B):
if C >= 0 and D >= 0:
if (A % 2) == 0:
i = 1
if i == 1:
print('Valores aceitos')
else:
print('Valores nao aceitos')
|
3325f82cda3f225e1d81f7dbe047aca995e48ea5 | qmnguyenw/python_py4e | /geeksforgeeks/python/basic/6_13.py | 3,644 | 3.5625 | 4 | Gun Detection using Python-OpenCV
**Prerequisites:** Python OpenCV
Gun Detection using Object Detection is a helpful tool to have in your
repository. It forms the backbone of many fantastic industrial applications.
OpenCV(Open Source Computer Vision Library) is a highly optimized library with
focus on Real-Time Applications.
**Approach:**
1) **Creation of Haarcascade file of Guns:** Refer to Creation of own
haarcascade
From here, you will learn about how to create your own Haarcascade file. With
your single positive image, you can use the opencv_createsamples command to
actually create a bunch of positive examples, using your negative images. Your
positive image will be superimposed on these negatives, and it will be angled
and all sorts of things. It actually can work pretty well, especially if you
are really just looking for one specific object. If you are looking to
identify all guns, however, you will want to have thousands of unique images
of guns, rather than using the opencv_createsamples to generate samples for
you. We’ll keep it simple and just use one positive image, and then create a
bunch of samples with our negatives.
**Note:** For The Gun haar cascade created – click here.
**2) Detection of Guns using OpenCV**
__
__
__
__
__
__
__
import numpy as np
import cv2
import imutils
import datetime
gun_cascade = cv2.CascadeClassifier('cascade.xml')
camera = cv2.VideoCapture(0)
firstFrame = None
gun_exist = False
while True:
ret, frame = camera.read()
frame = imutils.resize(frame, width = 500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gun = gun_cascade.detectMultiScale(gray,
1.3, 5,
minSize = (100, 100))
if len(gun) > 0:
gun_exist = True
for (x, y, w, h) in gun:
frame = cv2.rectangle(frame,
(x, y),
(x + w, y + h),
(255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = frame[y:y + h, x:x + w]
if firstFrame is None:
firstFrame = gray
continue
# print(datetime.date(2019))
# draw the text and timestamp on the frame
cv2.putText(frame, datetime.datetime.now().strftime("% A % d % B % Y %
I:% M:% S % p"),
(10, frame.shape[0] - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.35, (0, 0, 255), 1)
cv2.imshow("Security Feed", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
if gun_exist:
print("guns detected")
else:
print("guns NOT detected")
camera.release()
cv2.destroyAllWindows()
---
__
__
**Output:**

OpenCV comes with a trainer as well as a detector. If you want to train your
own classifier for any object like car, planes, etc. you can use OpenCV to
create one.
Here we deal with the detection of Gun. First we need to load the required XML
classifiers. Then load our input image (or video) in grayscale mode. Now we
find the guns in the image. If guns are found, it returns the positions of
detected guns as Rect(x, y, w, h). Once we get these locations, we can
create a ROI(Region of Interest) for the gun.
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
affbc929ba6de612e1499cd9221ea7bac53ddd03 | KevinKnott/Coding-Review | /Month 01/Week 04/Day 03/a.py | 3,372 | 3.671875 | 4 | # Decode Ways: https://leetcode.com/problems/decode-ways/
# A message containing letters from A-Z can be encoded into numbers using the following mapping:
# 'A' -> "1"
# 'B' -> "2"
# ...
# 'Z' -> "26"
# To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
# "AAJF" with the grouping (1 1 10 6)
# "KJF" with the grouping (11 10 6)
# Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
# Given a string s containing only digits, return the number of ways to decode it.
# The answer is guaranteed to fit in a 32-bit integer.
class Solution:
def numDecodings(self, s: str) -> int:
self.memo = {}
def dfs(index=0):
if index in self.memo:
return self.memo[index]
if index == len(s):
return 1
if s[index] == '0':
return 0
if index == len(s) - 1:
return 1
# Go one
count = dfs(index+1)
# Go two
if int(s[index:index+2]) <= 26:
count += dfs(index+2)
# cache
self.memo[index] = count
return count
return dfs()
# The above works and cuts out a lot of the problems that we have however this still runs in o(N) and o(N)
# Can we improve on this solution? I think so this is almost like the fibonaci sequence where we can keep track of the last
# two answers and create the new one thus moving up and using only o(1) space
def numDecodingsImproved(self, s):
if s[0] == '0':
return 0
# If the first number isn't 0 then we have a valid case
# where two back is 1 but we skip over it by starting range at 1
oneBack = 1
twoBack = 1
for i in range(1, len(s)):
# Get a temp variable for combining the two results
current = 0
# make sure we don't have 0 because that makes going back two 0
# Also oneBack should be 1 if it isnt 0 as 0 is the only invalid digit
if s[i] == '0':
current = oneBack
twoDigit = int(s[i-1: i+1])
# Make sure that our new two digit is between 10-26 (we don't want 35)
if twoDigit >= 10 and twoDigit <= 26:
current += twoBack
# update the twoback and oneback to new values
twoBack = oneBack
oneBack = current
return oneBack
# So the above should work but it does so because it is like the fib sequence we only need two vals to create thrid 1 1 = 1 2
# so you keep the value that you need and discard outside of the range like a window
# Score Card
# Did I need hints? N
# Did you finish within 30 min? Y 25
# Was the solution optimal? I was able to create the optimal solution although I kind of skipped over the bottom up and tabulation that helps with
# creating the optimal solution as I have seen it before with the fib sequence
# Were there any bugs? I accidently pointed the second algo to current (because it is correct) but really I need to return oneBack because
# python can possibly clean up that val after the loop
# 5 5 5 3 = 4.5
|
d72f3166d67b6687d091ecf3a97e05f12a1b756f | priyapriyam/practices_questions | /swap.py | 291 | 3.984375 | 4 | def swap(list, a, b):
list[a], list[b] = list[b], list[a]
return list
list = ["priya","savita","priyanka","ravina"]
a, b = 0, 3
print(swap(list,a,b))
float_list=[8.9,9.1,5.9,9.0,1.9]
print (swap(float_list,a,b))
number_list=[4,6,7,8,6,5,5,4,8]
print(swap(number_list,a,b)) |
d83c4ec7b43a65900a496f4ac0a4c0289548f69e | Shalom91/Level_0_coding_challenges | /task_0_10.py | 443 | 4.125 | 4 | def common_letters(string_one, string_two):
"""
prints out common letters between
two strings
"""
common_letters_list = []
string_one, string_two = string_one.lower(), string_two.lower()
for i in string_one:
if i in string_two:
common_letters_list.append(i)
remove_duplicates = list(set(common_letters_list))
print(f"Common letters: {', '.join(letter for letter in remove_duplicates)}")
|
0b4679f1bbf7073bca4165252d7103f83a064f15 | dprelipcean/virus_propagator | /utils/binomial_expansion.py | 1,423 | 4.125 | 4 | import numpy as np
# Python3 program to print terms of binomial
# series and also calculate sum of series.
# function to calculate factorial
# of a number
def factorial(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
# Function to print the series
def series(A, X, n):
factors = list()
# calculating the value of n!
nFact = factorial(n)
# loop to display the series
for i in range(0, n + 1):
# For calculating the
# value of nCr
niFact = factorial(n - i)
iFact = factorial(i)
# calculating the value of
# A to the power k and X to
# the power k
aPow = pow(A, n - i)
xPow = pow(X, i)
# display the series
factor =int((nFact * aPow * xPow) / (niFact * iFact))
factors.append(factor)
return factors
def find_incremental_probability(total_probability):
A = 1
X = -1
n = 27
factors = series(A, X, n)
factors.reverse()
factors.append(total_probability)
roots = np.roots(factors)
for value in roots:
if value.imag == 0:
probability = abs(value.real)
if 0 < probability < 1:
incremental_probability = probability
return_value = min(incremental_probability, total_probability)
return return_value/10
if __name__ == '__main__':
find_incremental_probability(total_probability=0.1)
|
af25fc26c786cf845632f278cc314e76b905bbc1 | Arthur31Viana/PythonExercicios | /ex060.py | 359 | 4.03125 | 4 | #Faça um programa que leia um número qualquer e mostre o seu fatorial. Ex: 5! = 5 x 4 x 3 x 2 x 1 = 120
n = int(input('''Digite um número para
calcular seu Fatorial: '''))
c = n
f = 1
print(f'Calculando {n}! = ', end='')
while c > 0:
print(f'{c}', end='')
print(f' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print(f'{f}')
|
21c23ae18500bfa28f5bbdad6e74262c8e53b17f | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/06_RemoveKey.py | 396 | 4.1875 | 4 | """Program to remove a key from a dictionary"""
dict1 = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
key = 3 # dict.pop(key) removes item with key from dictionary & returns value for key
print(f'Item with {key} and value {dict1.pop(key)} removed and now dictionary is {dict1}')
# alternative way
'''
del dict1[key] # removes item with key from dictionary
''' |
4b4fff38b31af83396b44b5e8fc213466ffda1f0 | emmagrealy/BOB | /isogram.py | 501 | 4.5625 | 5 | def is_isogram(word):
"""Determine if word is an isogram"""
word = list(filter(str.isalpha, word.lower()))
return len(set(word)) == len(word)
#the filter() method filters the given iterable with the help of a
#function that tests each element in the iterable to be true or not.
#Determine if a word or phrase is an isogram. An isogram (also known as a "nonpattern word")
#is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times. |
b05dd9b7b2bd335a00350bb2994ccc74f98cb822 | thaus03/Exercicios-Python | /Aula17/AulaPrática.py | 1,142 | 4.1875 | 4 |
# Listas
lanche = ['Hambúrguer', 'Suco', 'Pizza', 'Pudim']
# Adiciona um elemento no final da lista
print(f'Lista inicial: {lanche}')
lanche.append('Cookie')
print(f'Lista após o append: {lanche}')
# Adicionar item na posição N
lanche.insert(0, 'Cachorro-quente')
print(f'Lista após o insert: {lanche}')
## Apagar elementos
#
#
# Apagam pelo índice
del lanche[3]
lanche.pop(3)
# Apaga pelo nome do elemento
lanche.remove('Cachorro-quente')
print(f'Lista após os deletes: {lanche}')
# Apaga o último elemento da lista
lanche.pop()
print(f'Lista após os deletes: {lanche}')
# Criar listas através de ranges
valores = list(range(4, 11))
print(valores)
valores2 = [8, 2, 5, 4, 9, 3, 0]
valores2.sort()
print(valores2)
valores2.sort(reverse=True)
print(valores2)
print(len(valores2))
valores3 = list()
valores3.append(5)
valores3.append(9)
valores3.append(4)
for c, v in enumerate(valores3):
print(f'Na posição {c} encontrei o valor {v}!')
print('Cheguei ao final da lista')
# Uma lista receber uma cópia dos dados da outra
a = [2, 3, 4, 7]
b = a[:]
b[2] = 8
print(f'Lista A: {a}')
print(f'Lista B: {b}')
|
c1f8a50cbbb3e2124eb61b9be92b1f3076b8c659 | vamshivarsa/tikinter_project | /billtable.py | 1,438 | 3.53125 | 4 | from tkinter import *
import psycopg2
def submit():
conn=psycopg2.connect(dbname="vamshi",user="postgres",password="davs",host="localhost",port="5432")
cur = conn.cursor()
name1 = namebox.get()
status1=statusbox.get()
amount1=amountbox.get()
paid_on1=paidbox.get()
query='''insert into bill(name,status,amount,paid_on) values(%s,%s,%s,%s); '''
cur.execute(query,(name1,status1,amount1,paid_on1))
print("data inserted successfully in bill table")
conn.commit()
conn.close()
root = Tk()
root.title("Bill Table")
root.geometry("560x360+120+120")
#adding canvas
canvas=Canvas(root,width=400,height=400)
canvas.pack()
frame = Frame(root)
frame.place(relx=0.3, rely=0.3,relwidth=0.8,relheight=0.8)
#adding column name lables
name = Label(frame,text="Name : ")
name.grid(row=0,column=2)
status = Label(frame,text="status : ")
status.grid(row=1,column=2)
amount = Label(frame,text="amount : ")
amount.grid(row=2,column=2)
paid = Label(frame,text="paid_on : ")
paid.grid(row=3,column=2)
# addiing entry boxes for respective columns
namebox = Entry(frame)
namebox.grid(row=0,column=3)
statusbox = Entry(frame)
statusbox.grid(row=1,column=3)
amountbox = Entry(frame)
amountbox.grid(row=2,column=3)
paidbox = Entry(frame)
paidbox.grid(row=3,column=3)
#adding buttons
insertbutton = Button(frame,text="insert",bd=6,command=submit)
insertbutton.grid(row=4,column=3)
root.mainloop() |
ffc9412aa11275dc8c22c4457cbbbb8d7c3d6fb6 | JD-Williams/Nucamp | /1-Fundamentals/assignments/wk05/solution1/guessing_game.py | 8,159 | 4.03125 | 4 | import random
import time
from textwrap import fill
class OutOfBoundsError(Exception): # <- Bonus Task 1
pass
#=========================
# TASK 1
#=========================
def guess_random_number(tries, start, stop):
rnd_num = random.randint(start, stop)
guesses = [] # <- Bonus Task 3
while tries:
print(f"Number of tries left: {tries}")
try:
guess = int(input(f"Guess a number between {start} and {stop}: "))
if not start <= guess <= stop:
raise OutOfBoundsError
except ValueError:
print("This is not a number. Try again.\n")
except OutOfBoundsError: # <- Bonus Task 1
print("Your guess is out of range.")
else:
if guess in guesses: # <- Bonus Task 3
print("You already guessed this number.")
continue
elif guess == rnd_num:
print("You guessed the correct number!")
return True
else:
print(f"Guess {'higher' if guess < rnd_num else 'lower'}!")
guesses.append(guess) # <- Bonus Task 3
tries -= 1
if not tries:
print(f"Tough luck! The correct number was {rnd_num}.")
return False
#=========================
# TASK 2
#=========================
def guess_random_num_linear(tries, start, stop):
rnd_num = random.randint(start, stop)
print(f"The number for the program to guess is {rnd_num}")
for guess in range(start, stop+1):
print(f"Number of tries left: {tries}")
tries -= 1
print(f"The program is guessing... {guess}")
if guess == rnd_num:
print("The program has guessed the correct number!\n")
return True
if tries == 0:
print("The program failed to guess the correct number.\n")
return False
#=========================
# TASK 3
#=========================
def guess_random_num_binary(tries, start, stop):
rnd_num = random.randint(start, stop)
print(f"Random number to find: {rnd_num}")
potentials = list(range(start, stop+1))
lo = 0
hi = len(potentials) - 1
while lo <= hi:
pivot = (lo + hi) // 2
pivot_value = potentials[pivot]
if pivot_value == rnd_num:
print(f"Found it! {rnd_num}\n")
return True
else:
if not tries:
break
if pivot_value > rnd_num:
print("Guessing lower!")
hi = pivot - 1
else:
print("Guessing higher!")
lo = pivot + 1
tries -= 1
print("Your program failed to find the number.\n")
return False
# Bonus Task 2
def show_guess_methods(dict_obj):
print("random number guess methods".upper())
for k,v in dict_obj.items():
print(f"{k} - {v['label']}")
def is_option_valid(choice, list_obj):
if not choice in list_obj:
print("You selected an invalid option. Try again.\n")
return choice in list_obj
def get_parameter(name:str, *args):
lower_bound = args[0] if args else None
while True:
try:
value = int(input(f"Enter the {name}: "))
except ValueError:
print("This is not a number.")
else:
if lower_bound != None and lower_bound >= value:
print(f"The upper bound must be greater than the lower bound ({lower_bound}).")
continue
elif not 0 <= value:
print("This is not a positive integer.")
continue
else:
return value
def select_guess_method():
options = {
'1': dict(label="User Input", action=guess_random_number),
'2': dict(label="Linear Search", action=guess_random_num_linear),
'3': dict(label="Binary Search", action=guess_random_num_binary),
}
tries = get_parameter("number of tries")
start = get_parameter("lower bound of the guess interval")
stop = get_parameter("upper bound of the guess interval", start)
print()
show_guess_methods(options)
while True:
option = input(fill("Select the corresponding number of the desired guess method for the options listed: "))
if is_option_valid(option, options.keys()):
break
print(f"\nYou chose '{options[option]['label']}' as your guess method.\n")
options[option]['action'](tries, start, stop)
print()
# Bonus Task 4
class Player:
"""
A class to represent a player
...
Attributes
----------
winnings : int
The value of a player's total winnings
after a bet is placed and executed
Class Variables
---------------
TEXT_WIDTH : int
Represents the maximum character length
of all messages output to the player
"""
TEXT_WIDTH = 50
def __init__(self, winnings:int=10):
self.winnings = winnings
def get_bet(self):
try:
wager = int(input(f"Enter a whole dollar amount to wager up to ${self.winnings if self.winnings < 10 else 10}: "))
except ValueError:
print("This is not an integer.")
else:
if not 0 < wager <= min(self.winnings, 10):
print(f"You cannot bet $0 or less, nor more than ${min(self.winnings, 10)}.")
return None
return wager
def get_outcome(self):
choices = ['n', 'y']
choice = input(fill("Do you think the computer will guess the correct number? (y/n): ", width=self.TEXT_WIDTH)).lower()
if choice[0] not in ['n', 'y']:
print("Invalid selection. Please choose 'y' or 'n'.")
return None
return choices.index(choice[0])
def gamble(self, func=guess_random_num_linear):
rounds = 0
while 0 < self.winnings < 50:
rounds += 1
print(f"round {str(rounds).zfill(2)}".upper())
print(fill("The computer will guess a random number using a 'Linear Search' algorithm.", width=self.TEXT_WIDTH))
while True:
prediction = self.get_outcome()
if prediction: break
while True:
bet = self.get_bet()
if bet: break
tries = random.randint(5, 5)
start = random.choice(range(1,101))
stop = start + (2*tries)
is_computer_successful = func(tries, start, stop)
if prediction == is_computer_successful:
self.winnings += bet*2
else:
self.winnings -= bet
print(f"Total Winnings: ${self.winnings}\n\n")
if self.winnings >= 50:
print(f"Congratulations! You played {rounds} rounds and earned a total of ${self.winnings}.")
else:
print(f"Tough luck. You played {rounds} {'rounds' if rounds > 1 else 'round'}... and you have nothing to show for it.")
""" Driver Code for Task 1 """
def driver_code1():
guess_random_number(5, 0, 10)
""" Driver Code for Task 2 """
def driver_code2():
guess_random_num_linear(5, 0, 10)
""" Driver Code for Task 3 """
def driver_code3():
guess_random_num_binary(5, 0, 100)
""" Driver Code for Bonus Task 2 """
def bonus2():
select_guess_method()
""" Driver Code for Bonus Task 4 """
def bonus4():
player1 = Player()
player1.gamble()
""" Driver Code for All Tasks and Bonuses """
def run_tests():
driver_code = [
dict(label="Task 1", action=driver_code1),
dict(label="Task 2", action=driver_code2),
dict(label="Task 3", action=driver_code3),
dict(label="Bonus Task 2", action=bonus2),
dict(label="Bonus Task 4", action=bonus4),
]
for code in driver_code:
border_length = 50
header_txt = f"Driver Code for {code['label']}".center(border_length)
print(f"{'='*border_length}")
print(f"{header_txt}".upper().center(border_length))
print("\nStarting...\n")
code['action']()
print("\n... Finished\n\n")
time.sleep(3)
if __name__ == '__main__':
run_tests()
|
636f5f1bab8e8d54780533e05b73a9487f48c394 | samsoon984/learn | /goldenpong.py | 612 | 3.765625 | 4 | from datetime import date
def soloXmas(plusYear=int(input("입력: "))):
변수 = 1
xmasDate, goldenSum, pongdangSum = date(2021, 12, 25), 0, 0
for i in range(0, plusYear):
xmasDate = date(2021+i, 12, 25)
if xmasDate.weekday() in [0, 4]:
goldenSum += 1
print(xmasDate, "황금 연휴")
elif xmasDate.weekday() in [1, 3]:
pongdangSum += 1
print(xmasDate, "퐁당")
else:
print(xmasDate)
print(f"총 황금연휴: {goldenSum}, 총 징검다리: {pongdangSum}")
if __name__ == "__main__":
soloXmas() |
09568c7fd077b97ab381c873ea5eeca7bbd165d6 | edu-athensoft/stem1401python_student | /py210628e_python1b/day11_210805/for_13.py | 801 | 4.375 | 4 | """
multiplication table 1
Python Program to Display the multiplication Table
Required:
Python for Loop
Python Input, Output and Import
input from keyboard: 10
Sample Result:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
input from keyboard: 8
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
input from keyboard: N
12 x 1 = 12
12 x 2 = 12
....
12 x N = 12*N
"""
# input
# num = input("Enter a number (num > 0):")
# num = int(num)
num = int(input("Enter a number (num > 0):"))
# print(type(num), num)
# print out table
# range(1, STOP)
A = 10
STOP = num + 1
for i in range(1,STOP):
# print(i)
result = A * 1
print("{} x {} = {}".format(A, i, result))
|
e67dc60949560690d5ee332a7b10b65caedbd4eb | StopDragon/CSE1017 | /Assignment/숙제 #5-1.py | 453 | 3.546875 | 4 | # -*- coding: utf-8 -*-
def searchWidestGap(list):
temp = 0
position = 0
if list == []:
return (0,-1)
for a in range(len(list)-2):
front = abs(list[a] - list[a+1])
back = abs(list[a+1] - list[a+2])
if front < back and temp < back:
temp = back
position = a + 1
elif front > back and temp < front:
temp = front
position = a
return (temp,position)
|
b4d1e68655352b3b5011dbdb7797870d1fe175c7 | zhued/discrete_structures | /Program2/Program2 (UbuntuPanda's conflicted copy 2014-02-26).py | 6,365 | 3.5625 | 4 | # Programming Assignment 2
# Edward Zhu
import itertools
import time
#import the graph
with open ('input.txt', 'r') as data:
datagraph = [];
for lines in data:
numbers = lines.split()
#~ numbers = [int (i) for i in numbers]
numbers = map(int, numbers)
datagraph.append(numbers)
#~ testdata = ([0, 3, 1],
#~ [3, 0, 2],
#~ [1, 2, 0])
testdata = ([0, 3, 7, 6, 8],
[3, 0, 7, 4, 5],
[7, 7, 0, 3, 9],
[6, 4, 3, 0, 4],
[8, 5, 9, 4, 0])
def getcost(path, graph):
cost = 0
prevnode = path[0]
for node in path[1:]:
if graph[prevnode][node] == 0:
break
cost += graph[prevnode][node]
prevnode = node
return cost
# edge class
class Edge:
def __init__(self, first, second, weight):
self.first = first
self.second = second
self.weight = weight
self.taken = False
self.discarded = False
def take(self):
self.taken = True
def untake(self):
self.taken = False
def discard(self):
self.discarded = True
def undiscard(self):
self.discarded = False
def getother(self, node):
if node == self.second:
return self.first
else:
return self.second
def __repr__(self):
return ("%s -- %d -- %s") % (self.first.name, self.weight, self.second.name)
class Node:
def __init__(self, name):
self.name = name
self.edges = []
def addedge(self, edge):
self.edges.append(edge)
def taken_edges(self):
return filter(lambda x: x.taken, self.edges)
def findnext(self, edge):
edges = filter(lambda x: x != edge, self.taken_edges())
if len(edges) == 0:
return None
else:
return edges[0]
def __str__(self):
return self.name
class Graph:
def __init__(self, matrix):
self.nodes = []
self.edges = []
for i, row in enumerate(matrix):
self.nodes.append(Node(i))
for node, edges in enumerate(matrix):
for to, weight in enumerate(edges):
if to > node and weight != 0:
e = Edge(self.nodes[node], self.nodes[to], weight)
self.nodes[node].addedge(e)
self.nodes[to].addedge(e)
self.edges.append(e)
def clear(self):
for edge in self.edges:
edge.untake()
edge.undiscard()
def valid(self, edge):
edge.take()
for node in self.nodes:
if len(node.taken_edges()) >= 3:
edge.untake()
return False
start = edge.first
next_edge = start.findnext(edge)
if next_edge is None:
edge.untake()
return True
node = start
while next_edge is not None:
node = next_edge.getother(node)
if node == start:
edge.untake()
return False
next_edge = node.findnext(next_edge)
edge.untake()
return True
def getnextedge(self):
edges = filter(lambda x: not x.discarded and not x.taken, self.edges)
if edges == []:
return None
nextedge = min(edges, key = lambda x: x.weight)
while not self.valid(nextedge):
nextedge.discard()
edges = filter(lambda x: not x.discarded and not x.taken, self.edges)
if edges == []:
return None
nextedge = min(edges, key = lambda x: x.weight)
nextedge.take()
return nextedge
def cheapestlink(self):
edges = []
edge = self.getnextedge()
while edge is not None:
edges.append(edge)
edge = self.getnextedge()
endnodes = filter(lambda x: len(x.taken_edges()) == 1, self.nodes)
last_edge = filter(lambda x: (x.first in endnodes and x.second in endnodes), self.edges)
self.clear()
return edges + last_edge
#exhaustive search
def ES(graph):
nodes = []
mincost = 0
for i in range(0, len(graph)):
nodes.append(i)
test = list(itertools.permutations(nodes))
for x in range(0, len(test)):
current = test[x]
if mincost == 0 or mincost > getcost(current, graph):
mincost = getcost(test[x], graph)
minpath = current
return minpath
print
print('EXHAUSTIVE SEARCH:')
print('')
print('Shortest Path:')
print(ES(testdata))
print('Path Cost:')
print(getcost(ES(testdata), testdata))
print('Average Runtime(seconds):')
total = 0
for x in range(0,10):
t1 = time.time()
ES(testdata)
elapsed = time.time() - t1
total += elapsed
avg = total/10
print avg
#nearest neighbor
def NN(graph, start):
path = [start]
node = start
while len(path) < len(graph):
row = graph[node]
isvalid = filter(lambda x: x[0] not in path and x[0] != node and x[1] != 0, enumerate(row))
if (isvalid == 0 ):
break
nextnode = min(isvalid, key = lambda x: x[1])[0]
path.append(nextnode)
path.append(start)
return path
print
print('NEAREST NEIGHBOR:')
print('Shortest Path:')
print(NN(datagraph,0))
print('Path Cost:')
print(getcost(NN(datagraph,0), datagraph))
print('Average Runtime(seconds):')
total = 0
for x in range(0,10):
t1 = time.time()
NN(datagraph,0)
elapsed = time.time() - t1
total += elapsed
avg = total/10
print avg
#repeated nearest neighbor
def RNN(graph):
rnnlist = []
mincost = 0
for i in range(0, len(graph)):
current = NN(datagraph, i)
if mincost == 0 or mincost > getcost(current, graph):
mincost = getcost(current, graph)
minpath = current
return minpath
print
print('REPEATED NEAREST NEIGHBOR:')
print('Shortest Path:')
print(RNN(datagraph))
print('Path Cost:')
print(getcost(RNN(datagraph), datagraph))
print('Average Runtime(seconds):')
total = 0
for x in range(0,10):
t1 = time.time()
RNN(datagraph)
elapsed = time.time() - t1
total += elapsed
avg = total/10
print avg
#cheapest link
structured = Graph(datagraph)
d = structured.cheapestlink()
print
print('CHEAPEST LINK:')
print('Shortest Path:')
for x in d:
print "(%s, %s)" % (x.first.name, x.second.name)
print('Path Cost:')
print sum(map(lambda x: x.weight, d))
print('Average Runtime(seconds):')
total = 0
for x in range(0,10):
t1 = time.time()
structured.cheapestlink()
elapsed = time.time() - t1
total += elapsed
avg = total/10
print avg
print
|
ecb7d3fdfc0c734a800f5725e657bb71083075f8 | Ashikunnabi/python_programming | /basic/_28_exceptions.py | 116 | 3.65625 | 4 | a = 0
b = 5
try:
print(b / a)
except ZeroDivisionError as e:
print("Number can't be divided by zero.", e)
|
e824e9b87fc9eef5c5826f4b8e32e8f8aede69bb | yingthu/MySandbox | /1_tree/LC105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py | 915 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
# analysis: first node in preorder -> root
# locate root idx in inorder
# inorder[:idx] belongs to left sub-tree
# inorder[idx+1:] belongs to right sub-tree
if not preorder:
return None
rootVal = preorder.pop(0)
root = TreeNode(rootVal)
idx = inorder.index(rootVal)
root.left = self.buildTree(preorder[:idx], inorder[:idx])
root.right = self.buildTree(preorder[idx:], inorder[idx+1:])
return root
# Time: O(n), Space: O(n)
|
ab41b9ca619044afa0d2f3e8c0765d6724aef930 | rafaelperazzo/programacao-web | /moodledata/vpl_data/6/usersdata/79/2387/submittedfiles/investimento.py | 699 | 3.921875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
#COMECE SEU CODIGO AQUI
#Entrada
A = input('Digite seu saldo em 2016: ')
#Processamento
B = A*0.05 + A
C = B*0.05 + B
D = C*0.05 + C
E = D*0.05 + D
F = E*0.05 + E
G = F*0.05 + F
H = G*0.05 + G
I = H*0.05 + H
J = I*0.05 + I
K = J*0.05 + J
#Saída
print('Seu saldo em 2017: ') +str(B)
print('Seu saldo em 2018: ') +str(C)
print('Seu saldo em 2019: ') +str(D)
print('Seu saldo em 2020: ') +str(E)
print('Seu saldo em 2021: ') +str(F)
print('Seu saldo em 2022: ') +str(G)
print('Seu saldo em 2023: ') +str(H)
print('Seu saldo em 2024: ') +str(I)
print('Seu saldo em 2025: ') +str(J)
print('Seu saldo em 2026: ') +str(K)
|
0d3d20bd5d89c642f4886d427fb75c558adbbb66 | SophiaTanOfficial/Day01 | /greet.py | 562 | 4.15625 | 4 | # name = "Sophia"
# name1 = "John"
# print("Good morning " + name + "!")
# print("Good morning %s" %name)
# print("Your name has " + str(len(name)) + " letters in it.") #str converts it to string
# age = 18
# print("Hello! My name is " + name + " and I am " + str(age) + " years old.")
# print("Let's see, what have we here? So your name is " + name + ".")
name = input("What is your name?")
namespecial = "Beyonce"
if name.casefold() == namespecial.casefold()
print("Greetings, Queen.")
else:
print("Greetings, " + name + "! Welcome to the program!") |
942b475b1608a6c7f152d1ad24f59ac7af8ecabc | carnad37/python_edu | /190117/Test02.py | 130 | 3.671875 | 4 | sumNum = 0
num = int(input("정수를 입력해주세요: "))
for i in range(1,(num+1),1):
sumNum = sumNum + i
print(sumNum) |
17b51b46a8e755a4bda346eca3168108f87e8759 | jdanray/leetcode | /equationsPossible.py | 653 | 3.703125 | 4 | # https://leetcode.com/problems/satisfiability-of-equality-equations/
class Solution(object):
def reach(self, start, dest, graph):
seen = {start}
stack = [start]
while stack:
u = stack.pop()
if u == dest:
return True
for v in graph[u]:
if v not in seen:
seen.add(v)
stack.append(v)
return False
def equationsPossible(self, equations):
equals = collections.defaultdict(set)
unequals = set()
for eq in equations:
x = eq[0]
y = eq[3]
if eq[1] == "!":
unequals.add((x, y))
else:
equals[x].add(y)
equals[y].add(x)
return not any(self.reach(x, y, equals) for (x, y) in unequals)
|
cee01be878648e10b1d7289abf073a5fd08e84af | yuyurun/nlp100-2020 | /src/ch01/ans05.py | 472 | 3.640625 | 4 | def create_ngram(text, n=2, mode='str'):
"""
n-gramを作る
Args:
text(str) : 対象となる文
n(int) : n-gramのn
mode(str) : strかword
"""
if mode == 'str':
l = [s for s in text]
else:
l = [s for s in text.split(' ')]
return [''.join(l[i:i+n]) for i in range(len(l) - n + 1)]
if __name__ == '__main__':
a = 'I am an NLPer'
print(create_ngram(a))
print(create_ngram(a, mode='word'))
|
8c9411679e625809a92b5e22b01f82504348a8da | JeniaJitsev/HIDA_COVID_Alpha_X_hackathon | /code_container/evaluation.py | 4,780 | 3.671875 | 4 | """
Simple evaluation code that can be used
to evaluate a submission using cross validation.
We need a common codebase for evaluating different
methods. Since the data is small, we can afford
to use cross validation to get an estimate on
the performance with an uncertainty estimate.
each submission is a class following scikit-learn API.
It has a `fit` and `predict` method.
`fit` is used for training phase, `predict` for testing phase.
the same model is evaluated several times using cross validation.
"""
import os
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.model_selection import RepeatedKFold, ShuffleSplit
from metrics import imputation_error_score, COLS
# cross validation scheme
N_SPLITS = 2
N_REPEATS = 1
RANDOM_STATE = 10101
MISSING_IMAGES_RATE = 31/210
# Abstract submission class
class Submission:
def __init__(self, train_path, test_path):
self.train_path = train_path
self.test_path = test_path
def fit(self, df_train):
pass
def predict(df_test):
"""
return a dataframe (nb_examples, nb_features) with identical shape as df_test.
task1. for each row, for each col in `COLS`, we predict the value of col given the other `COLS`.
In the end we get a complete imputed dataframe. Please make sure all values are imputed
whether they are Nans or not. That is, we need to predict all the nb_examples x nb_features
because it is needed for evaluation.
task2. replace the col `prognosis` values by either SEVERE or MILD
"""
raise NotImplementedError()
class DummySubmission(Submission):
"""
simple dummy submission for an example
"""
def predict(self, df_test):
# predict SEVERE for everything
df_test["Prognosis"] = "SEVERE"
# replace missing data with 0
df_test = df_test.fillna(0)
# replace the remaining cols with 0
df_test[COLS] = 0
return df_test
def evaluate(submission_cls, input_path="."):
print(f"Evaluating '{submission_cls.__name__}'...")
train_path = os.path.join(input_path, 'trainSet')
test_path = os.path.join(input_path, 'testSet')
df_train = pd.read_csv(os.path.join(train_path, 'trainSet.txt'))
df_test = pd.read_csv(os.path.join(test_path, 'testSet.txt'))
random_state = RANDOM_STATE
rng = np.random.RandomState(random_state)
# rkf = RepeatedKFold(n_splits=N_SPLITS, n_repeats=N_REPEATS, random_state=random_state)
rkf = ShuffleSplit(n_splits=2, random_state=random_state, train_size=0.85)
metrics = []
for train_index, valid_index in rkf.split(df_train):
train = df_train.iloc[train_index]
valid = df_train.iloc[valid_index]
submission = submission_cls(train_path=train_path, test_path=train_path)
submission.fit(train)
valid_ = valid.copy()
# hide labels
valid_["Prognosis"] = np.nan
# artifically make some images missing (like the actual test set)
# missing_images = (rng.uniform(size=len(valid_)) <= MISSING_IMAGES_RATE)
# valid_.loc[missing_images, "ImageFile"] = np.nan
# prediction
pred_valid = submission.predict(valid_)
#ensure no missing data is left
# assert np.all(~pd.isna(pred_valid))
pred_prognosis = pred_valid["Prognosis"]
true_prognosis = valid["Prognosis"]
metrics.append({
"prognosis_accuracy": (pred_prognosis==true_prognosis).mean(),
# compute imputation error only on non-nan values (we don't know the groundtruth values
# for the ones which are alreay Nan)
"imputation_error": imputation_error_score(valid_[COLS], pred_valid[COLS], ~(pd.isna(valid[COLS])).values ) ,
})
submission = submission_cls(train_path=train_path, test_path=test_path)
submission.fit(df_train)
pred_test = submission.predict(df_test)
# make sure the non-nan values in `df_test` are
# identical to the ones in `pred_test`
pred_test = pred_test.mask(~pd.isna(df_test), df_test)
#ensure no missing data is left
# assert np.all(~pd.isna(pred_test))
return metrics, pred_test
def display_metrics(metrics):
names = metrics[0].keys()
for name in names:
vals = np.array([m[name] for m in metrics])
mean = vals.mean()
std = vals.std()
print(f"{name}: {mean} ± {std}")
def full_evaluation(submission_cls):
base_path = str(Path(__file__).resolve().parents[1])
metrics, pred_test = evaluate(submission_cls, input_path=base_path + '/data/')
display_metrics(metrics)
pred_test.to_csv("test_submission.csv", index=False)
if __name__ == "__main__":
full_evaluation(DummySubmission)
|
833a33a4a59bbf8e010b475790a6890c03f6ea7f | thebigshaikh/PythonPractice | /oddEven.py | 197 | 4.0625 | 4 | inputn=int(input("Hey will you enter a number for me? \n"))
if(inputn%2==0):
print("the number is even")
if(inputn == 4):
print("The number is 4!")
else:
print("Number is odd") |
395ccacec3f322902281b0d95a330a627c4fa98c | IlyaTroshchynskyi/python_education_troshchynskyi | /data_structures/hash_table.py | 3,226 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Implements of simple HashTable.
"""
class Node:
"""
Implement simple Node with key, value, next_node
"""
def __init__(self, key, value, next_node=None):
self.key = key
self.value = value
self.next = next_node
def __repr__(self):
return f'Node {self.key}:{self.value}'
def __str__(self):
return f'Node {self.key}:{self.value}'
class LinkedList:
"""
Implementation of simple LinkedList.
"""
def __init__(self):
self.head = None
self.size = 0
def __repr__(self):
return f'Node {self.head.key}:{self.head.value}'
def __str__(self):
return f'Node {self.head.key}:{self.head.value}'
class HashTable:
"""
Implementation of simple HashTable.
"""
def __init__(self, size):
self.linked_list = LinkedList()
self.size = size
def insert(self, new_node):
"""
Add item with key to hash table.
"""
if new_node.key == self.lookup(new_node.key):
raise KeyError("Hash table contains such key. Please choose other one")
if self.linked_list.head is None:
self.linked_list.head = new_node
self.linked_list.head.key = self.hash_func(new_node.key)
else:
last_node = self.linked_list.head
while last_node.next is not None:
last_node = last_node.next
last_node.next = new_node
last_node.next.key = self.hash_func(new_node.key)
def hash_func(self, key):
"""
Count hash.
"""
hashed_key = 0
for char in key:
hashed_key += ord(char)
return hashed_key % self.size
def lookup(self, key):
"""
Get value by key.
"""
current_head = self.linked_list.head
hash_key = self.hash_func(key)
while current_head:
if current_head.key == hash_key:
return current_head.value
current_head = current_head.next
def delete(self, key):
"""
Remove value by key
"""
hash_key = self.hash_func(key)
current_head = self.linked_list.head
previous_head = None
if current_head.key == hash_key:
self.linked_list.head = current_head.next
else:
while current_head.next:
previous_head = current_head
current_head = current_head.next
if current_head.key == hash_key:
previous_head.next = current_head.next
def display(self):
"""
Display the chain of elements in LinkedList.
"""
temp_node = self.linked_list.head
while temp_node is not None:
print(temp_node.value, ":", temp_node.key, end='->')
temp_node = temp_node.next
if __name__ == '__main__':
hash_table = HashTable(30)
hash_table.insert(Node('first', 1))
hash_table.insert(Node('second', 2))
hash_table.insert(Node('third', 3))
hash_table.display()
print()
print(hash_table.lookup('second'))
print()
hash_table.delete('second')
hash_table.display()
|
e4440886371cb76036b4c803a1c89ea341d97781 | mreishus/aoc | /2015/python2015/tests/test_day08.py | 1,442 | 3.5 | 4 | #!/usr/bin/env python3
"""
Test Day08.
"""
import unittest
from aoc.day08 import len_code, len_expand
class TestDay08(unittest.TestCase):
"""Test Day08."""
def test_len_code(self):
"""Test len_code"""
str1 = '""'
self.assertEqual(len(str1), 2)
self.assertEqual(len_code(str1), 0)
str2 = '"abc"'
self.assertEqual(len(str2), 5)
self.assertEqual(len_code(str2), 3)
str3 = '"aaa\\"aaa"'
self.assertEqual(len(str3), 10)
self.assertEqual(len_code(str3), 7)
str3 = '"aaa\\"a\\"aa"'
self.assertEqual(len(str3), 12)
self.assertEqual(len_code(str3), 8)
str4 = '"\\x27"'
self.assertEqual(len(str4), 6)
self.assertEqual(len_code(str4), 1)
str5 = '"\\x27jj\\x27"'
self.assertEqual(len(str5), 12)
self.assertEqual(len_code(str5), 4)
def test_len_expand(self):
"""Test len_expand"""
str1 = '""'
self.assertEqual(len(str1), 2)
self.assertEqual(len_expand(str1), 6)
str2 = '"abc"'
self.assertEqual(len(str2), 5)
self.assertEqual(len_expand(str2), 9)
str3 = '"aaa\\"aaa"'
self.assertEqual(len(str3), 10)
self.assertEqual(len_expand(str3), 16)
str4 = '"\\x27"'
self.assertEqual(len(str4), 6)
self.assertEqual(len_expand(str4), 11)
if __name__ == "__main__":
unittest.main()
|
0fc4770edd83af02d18a97e2dc81794427101119 | communitylab/data | /_build/jupyter_execute/Chapters/06/viz quantitative.py | 5,143 | 4.53125 | 5 | # Visualizing Quantitative Data
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
We generally use different types of charts to visualize quantitative (numerical) data and qualitative (ordinal or nominal) data.
For quantitative data, we most often use histograms, box plots, and scatter plots.
We can use the [seaborn plotting library](http://seaborn.pydata.org/) to create these plots in Python. We will use a dataset containing information about passengers aboard the Titanic.
# Import seaborn and apply its plotting styles
import numpy as np
import pandas as pd
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
sns.set()
# Load the dataset and drop N/A values to make plot function calls simpler
titanic = sns.load_dataset('titanic').dropna().reset_index(drop=True)
print(titanic.shape)
titanic.head()
## Histograms
<hr>
We can see that the dataset contains one row for every passenger. Each row includes the age of the passenger and the amount the passenger paid for a ticket. Let's visualize the ages using a histogram. We can use seaborn's `distplot` function:
# Adding a semi-colon at the end tells Jupyter not to output the
# usual <matplotlib.axes._subplots.AxesSubplot> line
sns.distplot(titanic['age']);
By default, seaborn's `distplot` function will output a smoothed curve that roughly fits the distribution. We can also add a rugplot which marks each individual point on the x-axis:
sns.distplot(titanic['age'], rug=True);
We can also plot the distribution itself. Adjusting the number of bins shows that there were a number of children on board.
sns.distplot(titanic['age'], kde=False, bins=30);
## Box plots
<hr>
Box plots are a convenient way to see where most of the data lie. Typically, we use the 25th and 75th percentiles of the data as the start and endpoints of the box and draw a line within the box for the 50th percentile (the median). We draw two "whiskers" that extend to show the the remaining data except outliers, which are marked as individual points outside the whiskers.
sns.boxplot(x='fare', data=titanic);
We typically use the Inter-Quartile Range (IQR) to determine which points are considered outliers for the box plot. The IQR is the difference between the 75th percentile of the data and the 25th percentile.
lower, upper = np.percentile(titanic['fare'], [25, 75])
iqr = upper - lower
iqr
Values greater than 1.5 $\times$ IQR above the 75th percentile and less than 1.5 $\times$ IQR below the 25th percentile are considered outliers and we can see them marked indivdiually on the boxplot above:
upper_cutoff = upper + 1.5 * iqr
lower_cutoff = lower - 1.5 * iqr
upper_cutoff, lower_cutoff
Although histograms show the entire distribution at once, box plots are often easier to understand when we split the data by different categories. For example, we can make one box plot for each passenger type:
sns.boxplot(x='fare', y='who', data=titanic);
The separate box plots are much easier to understand than the overlaid histogram below which plots the same data:
sns.distplot(titanic.loc[titanic['who'] == 'woman', 'fare'])
sns.distplot(titanic.loc[titanic['who'] == 'man', 'fare'])
sns.distplot(titanic.loc[titanic['who'] == 'child', 'fare']);
## Brief Aside on Using Seaborn
<hr>
You may have noticed that the `boxplot` call to make separate box plots for the `who` column was simpler than the equivalent code to make an overlaid histogram. Although `sns.distplot` takes in an array or Series of data, most other seaborn functions allow you to pass in a DataFrame and specify which column to plot on the x and y axes. For example:
```python
# Plots the `fare` column of the `titanic` DF on the x-axis
sns.boxplot(x='fare', data=titanic);
```
When the column is categorical (the `'who'` column contained `'woman'`, `'man'`, and `'child'`), seaborn will automatically split the data by category before plotting. This means we don't have to filter out each category ourselves like we did for `sns.distplot`.
# fare (numerical) on the x-axis,
# who (nominal) on the y-axis
sns.boxplot(x='fare', y='who', data=titanic);
## Scatter Plots
<hr>
Scatter plots are used to compare two quantitative variables. We can compare the `age` and `fare` columns of our Titanic dataset using a scatter plot.
sns.lmplot(x='age', y='fare', data=titanic);
By default seaborn will also fit a regression line to our scatterplot and bootstrap the scatterplot to create a 95% confidence interval around the regression line shown as the light blue shading around the line above. In this case, the regression line doesn't seem to fit the scatter plot very well so we can turn off the regression.
sns.lmplot(x='age', y='fare', data=ti, fit_reg=False);
We can color the points using a categorical variable. Let's use the `who` column once more:
sns.lmplot(x='age', y='fare', hue='who', data=ti, fit_reg=False);
From this plot we can see that all passengers below the age of 18 or so were marked as `child`. There doesn't seem to be a noticable split between male and female passenger fares, although the two most expensive tickets were purchased by males. |
18f510c84ca54dcdf7de16943d2af62f25c8c487 | zhaihongle/zhaihongleck1 | /00源哥代码.py/09day/4-while嵌套.py | 148 | 3.859375 | 4 | i = 1
while i <= 4:#排数
#print("%d排"%i)
j = 1
while j <=5:#没排多少人
print("*",end = "")#* * * * *
j+=1
print("")#换行
i+=1
|
07dd3ae68dfe021f626d71b1c1090cfe4ea5ca6a | ganlanshu/datastructure | /search2sort/binarySearch.py | 1,927 | 3.90625 | 4 | #coding=utf-8
def binarySearch(alist,item):
"""
二分查找,alist必须是有序的,自己想的
"""
low = 0
high = len(alist)-1
while low < high:
mid = (low+high)/2
if item == alist[mid]:
return mid
elif item > alist[mid]:
low = mid + 1
else:
high = mid #改为high = mid-1更好,运算次数更少了
if low == high:
return 'not found'
def binarySearch2(alist,item):
"""
参考教程的
"""
first = 0
last = len(alist) - 1
found = False
while not found and first < last :
midpoint = (first + last)/2
if alist[midpoint] == item:
found = True
elif item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
def binarySearch3(alist,item):
"""
implement in recursive way
"""
low = 0
high = len(alist)-1
mid = (low+high)/2
if item == alist[mid]:
return mid #找到就返回索引
elif low == high:
return 'not found' #找不到就返回not found
elif item > alist[mid]:
return binarySearch3(alist[mid+1:],item)
else:
return binarySearch3(alist[:mid],item)
def binarySearch4(alist,item):
"""
implement in recursive way,
"""
mid = (len(alist)-1)/2
if item < alist[0]: #若不加这句,如果要查找的元素比alist[0]还小,会报IndexError
return False
elif item == alist[mid]:
return True
elif len(alist) == 1:
return False
elif item > alist[mid]:
return binarySearch4(alist[mid+1:],item)
return binarySearch4(alist[:mid],item)
if __name__ == '__main__':
#print binarySearch([1,5,76,98,100],75)
#print binarySearch2([1,5,76,98,100],75)
#print binarySearch3([1,5,76,98,100],102)
print binarySearch4([1,5,76,98,100],0)
|
615f99d1a121f99a92629e6d5b2bb71b5f54172e | kwhua/nihao- | /第一阶段/基础/day02/字符串方法.py | 1,958 | 3.578125 | 4 | '''
字符串方法(字符串是不可变类型)
查找字符串的索引
index:从左向右,只能查到第一个元素的索引
rindex:从右向左查到的第一个元素的索引
s ='hello world'
s1=s.index('o')
s2 =s.rindex('o')
print(s1)
print(s2)
s = 'hello world'
x = len(s)
s1 = [i for i, x in enumerate(s) if x == 'l']
print(s1)
# 如果直接用X.index(1),只能得到0这一个索引,而我们需要所有索引.
X = [1, 2, 3, 4, 5, 1, 2, 3, 1, 3, 4]
l = len(X)
# zip_list = zip(*(range(l),X))
# id1 = [z[0] for i,z in enumerate(zip_list) if z[1]==1]
# 或者更简单的
id1 = [i for i, x in enumerate(X) if x == 1]
print(id1)
字符串的切分 split 使用maxsplit限制切割的次数,限制次数多余时,全部切分不会报错
split:根据指定的内容进行切分,返回一个列表,指定的元素不保留
s ='hello world'
s1= s.split('l',maxsplit=1)
print(s1)
字符串的替换 replace __count= 代表着替换的次数
replace:可以将指定的字符串替换成新字符串
s ='hello world'
s1 =s.replace('o','嗯',__count=1)
print(s1)
strip:去掉字符串两边指定的元素,默认去掉空格
s ='*hello world*'
s1=s.strip("*")
print(s1)
count:返回指定元素的个数
s ='hello world'
s1=s.count("l")
print(s1)
format:格式化字符串
'''
s =f'hello world{123}'
print(s)
s1 = "姓名:%s 性别:%s 年龄:%d 身高:%0.2fm"%("匡文华","男",25,1.70)
print(s1)
for x in range(1,11):
s='http://pic.netbian.com/4kdongman/'
s1='http://pic.netbian.com/4kdongman/{}'
if x==1:
print('http://pic.netbian.com/4kdongman/')
else:
print('http://pic.netbian.com/4kdongman/index_{}.html'.format(x))
|
c16e847c3b653ed4f09663a7daffacf8101e3093 | brandonmorren/python | /C6 functions/oefFunctions/oefening 2.py | 280 | 3.96875 | 4 | def exchange(current_dollar_rate, Euro):
return current_dollar_rate * Euro
Current_dollar_rate2 = float(input("Current dollar rate (€ -> $): "))
Euro2 = float(input("Your amount in Euro: "))
print("€ " + str(Euro2) + " = $ " + str(exchange(Current_dollar_rate2, Euro2))) |
56a91419e20cd9e85770c8b2a2fc559afd881056 | marcelogarro/challenges | /FromTheInternet/Rotate an Array.py | 481 | 4.09375 | 4 | import unittest
"""
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
"""
n = 7
k = 3
arr = [1, 2, 3, 4, 5, 6, 7]
def rotate(k, original_array):
return original_array[k + 1:] + original_array[:k + 1]
class TestList(unittest.TestCase):
def test_right(self):
self.assertEqual(rotate(k, arr), [5, 6, 7, 1, 2, 3, 4])
if __name__ == '__main__':
unittest.main()
|
d8c5d381172bf4e6d28caad7d992403f201fe7ea | fbessez/Schoolwork | /COMP211 - Data Structures/Merge Sort and Loop Invariants/hw3a.py | 3,158 | 4.15625 | 4 |
def merge(xs, k, size):
m = k + size
n = k + 2*size
i = k
j = m
res = [] # type: List[int]
while i < m and j < n:
if xs[i] <= xs[j]: # key comparison: 1
list.append(res, xs[i]) # how many times through loop?
i = i + 1 # I think it goes through
else: # 1/2 len(xs) times
list.append(res, xs[j])
j = j + 1
if i == m: # key comparison: 2
list.extend(res, xs[j:n]) # happens just once each call
else:
list.extend(res, xs[i:m])
xs[k:n] = res
return None
def merge_sort(xs):
if len(xs) <= 1: # key comparison: 1
return None
size = 1
while size < len(xs):
i = 0
while i < len(xs):
merge(xs, i, size) # 1 + ([1/2 len(xs)] + 1) * 1/2 size
i = i + 2*size # or 1 + [len(xs) + 1] * [1/2 size]
size = 2*size
return None
# worst case scenario is the array is size n and n[0] > n[1] > n[2]...n[n-1]
# merge sort has set-up cost of 1 key comparison
# then it just calls merge
#
# cost of loop = (cost of one iteration) x (number of iterations)
#cost of merge sort is 1 + cost of inner loop = merge
# merge is 1 + cost of merge_loop
# merge_ loop is 1/2 len(xs) = 1/2 size
so 1 + (len(xs) /2) * 1/2 size
def radix_sort(xs):
# print("radix_sort(%r)" % xs)
if xs == []: #key comparison: 1
return None
# k is the number of digits in each numeral.
k = len(xs[0])
# print("\tk = %d" % k)
# i is the digit upon which we are sorting.
i = 0
while i < k:
# print("\ti = %d" % i)
# pfx is the prefix of the subsequence we will sort into bins.
pfx = xs[0][:i]
# xs[j] is the first element of xs with prefix pfx.
j = 0
while j < len(xs):
bin0 = [] # type: List[List[int]]
bin1 = [] # type: List[List[int]]
jj = j
# Scan through elements of xs with prefix pfx, sorting into bin0
# and bin1. When done, xs[j:jj] will have been sorted into the
# bins. Note that we are guaranteed that upon finishing this
# loop, jj > j.
while jj < len(xs) and xs[jj][:i] == pfx:
if xs[jj][i] == 0: #key comparison: 1
bin0.append(xs[jj]) # cost : 1
else: #key comparison: 2??
bin1.append(xs[jj]) # cost: 1
jj += 1
# Replace xs[j:jj] with bin0+bin1.
xs[j:jj] = bin0 + bin1 # assignment
# If we haven't made it through xs yet, update the prefix.
if jj < len(xs): # key comparison: 3
pfx = xs[jj][:i]
# Since jj > j, this is guaranteed to increase j.
j = jj
i = i + 1
return None
|
da71812230abdf9dd6f4467c2a25898c08f10e0c | rajinish01/Python_algorithms | /str_format.py | 156 | 3.8125 | 4 | age = 20
name = 'Sannith'
string = '''{0} was {1} years old when he wrote this book, why is {0} playing with the python.'''.format(name,age)
print (string)
|
b1aae22cccb22168fd4b2ccda2a0d47fc9c77c89 | Shimizu-sp/5CS_AI | /03-SemanticNetwork/s13527.py | 1,216 | 3.96875 | 4 | # -*- coding: utf-8 -*-
import sys
def main():
is_a = {"鳥":'生物', "オーム":'鳥'} #is-a関係の辞書
has_a = {"生物":'呼吸',"鳥":'翼',"オーム":'モノマネ'} #has-a関係の辞書
print("何を聴きますか?オームの特技が聴きたかったら1を入力してください。オームは呼吸するか聴きたかったら2を入力してください")
input_question = input('>> ')
#オームの特技について
if(input_question == "1"):
print("オームの特技は"+has_a["オーム"]+"です")
#オームは呼吸するのか調べる
elif(input_question == "2"):
tansaku='オーム'
#オームのis-a関係を調べる
for i in is_a.items():
if(i[0]==tansaku):
tansaku = i[1]
print(i[0]+"と"+i[1]+"はis-a関係にあります")
break
#鳥のis-a関係をしらべる
for i in is_a.items():
if(i[0]==tansaku):
tansaku = i[1]
print(i[0]+"と"+i[1]+"はis-a関係にあります")
break
#生物のhas-a関係を調べる
for i in has_a.items():
if(i[0]==tansaku and i[1]=='呼吸'):
print("YES")
break
else:
print("1もしくは2を入力してください")
sys.exit()
if __name__ == "__main__":
main() |
c448034da979c65ddf33deb74d8af45afe73c864 | variostudio/launchsim | /simulator/spacecalc.py | 4,088 | 3.5 | 4 | from simulator.combinedRocket import CombinedRocket
from simulator.rocket import Rocket
class SpaceCalculator:
N = 10
circles = 0
r_min = 9999.0
r_max = 0.0
min_dist = 0.0
land_dist = 0.0
max_dist = 0.0
landing_speed = 0.0
config = ''
def __init__(self, min_dist, max_dist, landing_speed, cfg):
self.max_dist = max_dist
self.min_dist = min_dist
self.land_dist = 2*min_dist
self.landing_speed = landing_speed
self.config = cfg
def newPosition(self, system):
for cnt in range(self.N):
for i in system:
# if object is a Rocket - execute flight program
if isinstance(i, Rocket):
i.flightProgram()
for j in system:
if i != j:
dist = i.dist(j)
dist -= (i.getSize() + j.getSize())
#print("Dist: ", dist)
if not self.isLanded(i, j, dist):
i.calcAccelTo(j)
#if isinstance(i, Rocket) and isinstance(j, Rocket):
#print(abs(i.vy - j.vy), abs(i.vx - j.vx), i.name, j.name)
self.r_min = min(self.r_min, dist)
else:
#If both of them are rockets, combine them
if isinstance(i, Rocket) and isinstance(j, Rocket):
self.combineObjects(i, j, system)
#If one of them is not a rocket it means landing
else:
self.landObjects(i, j)
#self.r_min = min(self.r_min, dist)
self.r_max = max(self.r_max, dist)
for i in system:
i.update()
#Put each object to screen
def drawSystem(self, system, screen, zoom, offset_x, offset_y, focused_object_id):
# If view focused on some object - put it to screen
if focused_object_id >= len(system):
focused_object_id = len(system)-1
if focused_object_id > -1:
dx = screen.get_width() / 2 - system[focused_object_id].x * zoom
dy = screen.get_height() / 2 - system[focused_object_id].y * zoom
# Not focused - put view to fixed position
else:
dx = (0 + screen.get_width()) * (1-zoom) / 2 + offset_x
dy = (0 + screen.get_height()) * (1-zoom) / 2 + offset_y
for i in system:
i.draw(screen, zoom, dx, dy)
def isLanded(self, object1, object2, dist):
res = True
if isinstance(object1, Rocket) and object1.engine_on:
res = False
if isinstance(object2, Rocket) and object2.engine_on:
res = False
if dist > self.land_dist:
res = False
if abs(object1.vx - object2.vx) > self.landing_speed:
res = False
#print("Vx1 - Vx2 is too big", abs(object1.vx - object2.vx))
if abs(object1.vy - object2.vy) > self.landing_speed:
res = False
#print("Vy1 - Vy2 is too big ", abs(object1.vy - object2.vy))
#if res:
#print("Landing of ", object1.name, " to ", object2.name, " is DONE!")
return res
#TODO: Add decombineObjects functios
def combineObjects(self, i, j, system):
if isinstance(i, Rocket) and isinstance(j, Rocket):
system.remove(i)
system.remove(j)
combine = CombinedRocket([i, j], self.config)
system.append(combine)
def landObjects(self, i, j):
vx = (i.vx*i.getMass() + j.vx*j.getMass())/(i.getMass() + j.getMass())
vy = (i.vy*i.getMass() + j.vy*j.getMass())/(i.getMass() + j.getMass())
i.vx = vx
i.vy = vy
j.vx = vx
j.vy = vy
def collisionDetected(self):
return self.r_min <= self.min_dist
def outOfSystemDetected(self):
return self.r_max >= self.max_dist
|
824dc9cf90f752143da1403c212ba86695196792 | el-18-works/solis-octo-luminaria | /study/alislam/analyse.py | 759 | 3.65625 | 4 | #!/usr/local/bin/python3
import re
#Check if the string starts with "The" and ends with "Spain":
#help(re)
m =1
LL =open("guerison.txt").readlines()
#for l in open("guerison.txt") :
CC =[]
NN =[]
for l in LL[2:] :
if l[0] == '#' : continue
x = re.search("^Sourate (.*) \(Chapitre (\d+)\)$", l)
if x :
s,n =x.groups()
#print(s)
n =int(n)
if m + 1 != n : print(m,n)#, exit()
m =n
#print(dir(x))
#print (NN)
NN.clear()
else :
#if 0 and re.search("(R|r)évélation", l) :
#k ="Lieu de révélation"
if re.search("^Les circonstances", l) :
k ="Les circonstances de la Révélation"
else :
k =l
if k not in CC :
print(k)
CC.append(k)
i =CC.index(k)
if i in NN :
print (k,l,m,i,NN,CC[i])
exit()
NN.append(i)
|
5ca367065cfdf4857e51970b2edf66e6d462ebde | blimon/cssi-labs | /python/labs/functions-cardio/reverseString.py | 147 | 4.25 | 4 | print("Welcome to Reverse String!")
word = raw_input("Give me a word: ")
def reverse_string(s1):
print(s1[-1:-len(s1)])
reverse_string(word)
|
6e87e9c9ffa87c6efe66eb57e31e5559e3f006dd | likewen623/Stylometric-Analyser-PY | /.gitignore/preprocessor_29330440.py | 1,185 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 21 19:18:43 2018
Name: Kewen Deng
Student ID: 29330440
Last modified date: May 24 2018
Description:
In this file, I have defined a class that will perform the basic preprocessing on each input text.
This class have one instance variable which is a list that holds the individual tokends of the entire text,
as a result of applying the tokenise() method defined in this class.
"""
class Preprocessor:
def __init__(self):
self.tokenlist = []
def __str__(self):
answer = 'The total number of tokens is: \n'
# Readbale format print
if any(self.tokenlist):
return answer + str(len(self.tokenlist))
else:
return 'There is no token. The total number is 0.'
def tokenise(self, input_sequence):
file_handle = open(input_sequence, 'r') # Open the exact book file.
for line in file_handle:
self.tokenlist.append(line) # Read in lines
file_handle.close() # Close the file
def get_tokenised_list(self):
if any(self.tokenlist):
return self.tokenlist
|
4761ed2260e2dc194b7309e570cc3cbda1accab9 | KilburnBuilding/Leetcode | /581.py | 860 | 3.671875 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left_index = -1
right_index = -1
total_number = 0
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
left_index = i -1
break
for i in range(len(nums) - 1, 0, -1):
if nums[i] <= nums[i - 1]:
right_index = i
break
print('left_index', left_index)
print('right_index', right_index)
if left_index != -1 and right_index != -1:
total_number = right_index - left_index + 1
return total_number
if __name__ == "__main__":
nums = [1,2,2,2, 3]
S = Solution()
print(S.findUnsortedSubarray(nums)) |
22d80ac6dde99a19215ce799c9d1c0da080f7f67 | lolotrgeek/TaskLearner | /environments/gym_desktop/gym_desktop/envs/events.py | 639 | 3.609375 | 4 | class KeyEvent():
"""
The KeyEvent consumes a key int
"""
def __init__(self, key=0):
self.key = key
class PointerEvent():
def __init__(self, x=0, y=0, buttonmask=0, wheel=0):
self.x = x
self.y = y
self.buttonmask = buttonmask
self.wheel = wheel
class SpecialEvent():
"""
The SpecialEvent consumes an action string
"""
# TODO: maybe better to encode as int for efficiency?
def __init__(self, action=''):
self.action = action
class WaitEvent():
"""
Waiting as an action
"""
def __init___(self, amount=0):
self.amount=amount |
1bdab61987badd46e1ea87e494cb25b453256ed4 | MollyQI3104/python_assignment | /english_braille.py | 11,566 | 3.703125 | 4 |
from text_to_braille import *
from char_to_braille import *
from to_unicode import *
from helpers import *
import filecmp
from Braille_translator.text_to_braille import file_to_braille, new_filename
ENG_CAPITAL = '..\n..\n.o'
ENG_NUM_END = '..\n.o\n.o'
# You may want to define more global variables here
####################################################
# Here are two helper functions to help you get started
def two_letter_contractions(text):
'''(str) -> str
Process English text so that the two-letter contractions are changed
to the appropriate French accented letter, so that when this is run
through the French Braille translator we get English Braille.
Provided to students. You should not edit it.
>>> two_letter_contractions('chat')
'âat'
>>> two_letter_contractions('shed')
'îë'
>>> two_letter_contractions('shied')
'îië'
>>> two_letter_contractions('showed the neighbourhood where')
'îœë ôe neiêbürhood ûïe'
>>> two_letter_contractions('SHED')
'ÎË'
>>> two_letter_contractions('ShOwEd tHE NEIGHBOURHOOD Where')
'ÎŒË tHE NEIÊBÜRHOOD Ûïe'
'''
combos = ['ch', 'gh', 'sh', 'th', 'wh', 'ed', 'er', 'ou', 'ow']
for i, c in enumerate(combos):
text = text.replace(c, LETTERS[-1][i])
for i, c in enumerate(combos):
text = text.replace(c.upper(), LETTERS[-1][i].upper())
for i, c in enumerate(combos):
text = text.replace(c.capitalize(), LETTERS[-1][i].upper())
return text
def whole_word_contractions(text):
'''(str) -> str
Process English text so that the full-word contractions are changed
to the appropriate French accented letter, so that when this is run
through the French Braille translator we get English Braille.
If the full-word contraction appears within a word,
contract it. (e.g. 'and' in 'sand')
Provided to students. You should not edit this function.
>>> whole_word_contractions('with')
'ù'
>>> whole_word_contractions('for the cat with the purr and the meow')
'é à cat ù à purr ç à meow'
>>> whole_word_contractions('With')
'Ù'
>>> whole_word_contractions('WITH')
'Ù'
>>> whole_word_contractions('wiTH')
'wiTH'
>>> whole_word_contractions('FOR thE Cat WITh THE purr And The meow')
'É thE Cat WITh À purr Ç À meow'
>>> whole_word_contractions('aforewith parenthetical sand')
'aéeù parenàtical sç'
>>> whole_word_contractions('wither')
'ùer'
'''
# putting 'with' first so wither becomes with-er not wi-the-r
words = ['with', 'and', 'for', 'the']
fr_equivs = ['ù', 'ç', 'é', 'à', ]
# lower case
for i, w in enumerate(words):
text = text.replace(w, fr_equivs[i])
for i, w in enumerate(words):
text = text.replace(w.upper(), fr_equivs[i].upper())
for i, w in enumerate(words):
text = text.replace(w.capitalize(), fr_equivs[i].upper())
return text
####################################################
# These two incomplete helper functions are to help you get started
def convert_contractions(text):
'''(str) -> str
Convert English text so that both whole-word contractions
and two-letter contractions are changed to the appropriate
French accented letter, so that when this is run
through the French Braille translator we get English Braille.
Refer to the docstrings for whole_word_contractions and
two_letter_contractions for more info.
>>> convert_contractions('with')
'ù'
>>> convert_contractions('for the cat with the purr and the meow')
'é à cat ù à purr ç à meœ'
>>> convert_contractions('chat')
'âat'
>>> convert_contractions('wither')
'ùï'
>>> convert_contractions('aforewith parenthetical sand')
'aéeù parenàtical sç'
>>> convert_contractions('Showed The Neighbourhood Where')
'Μë À Neiêbürhood Ûïe'
>>> convert_contractions('standardized')
'stçardizë'
'''
#
res = text.split(" ")
for word in res:
word_new = two_letter_contractions(whole_word_contractions(word))
text = text.replace(word, word_new)
return text
def convert_quotes(text):
'''(str) -> str
Convert the straight quotation mark into open/close quotations.
>>> convert_quotes('"Hello"')
'“Hello”'
>>> convert_quotes('"Hi" and "Hello"')
'“Hi” and “Hello”'
>>> convert_quotes('"')
'“'
>>> convert_quotes('"""')
'“”“'
>>> convert_quotes('" "o" "i" "')
'“ ”o“ ”i“ ”'
'''
#
res = ""
i = 0
for word in text:
if word == '"':
i += 1
if i % 2 == 0:
word = "”"
else:
word = "“"
res += word
return res
####################################################
# Put your own helper functions here!
def convert_parentheses(text):
'''(str) -> str
Convert open/close parentheses used in French Braille to parentheses used in English Braille.
>>> convert_parentheses('(')
'"'
>>> convert_parentheses('aa aaaaaa(a')
'aa aaaaaa"a'
>>> convert_parentheses('ss(saw(2(')
'ss"saw"2"'
'''
text = text.replace("(", '"')
text = text.replace(")", '"')
return text
def convert_q_mark(text):
'''(str) -> str
>>> convert_q_mark('www?')
'www('
'''
text = text.replace("?", '(')
return text
def convert_punctuation2(text):
'''(str) -> str
Convert parentheses, quotes and question mark in form of French Braille to English Braille.
>>> convert_punctuation2('www?')
'www('
>>> convert_punctuation2('w wwww?')
'w wwww('
>>> convert_punctuation2('3456 12 ?& ? hi')
'3456 12 (& ( hi'
'''
res = text.split(" ")
for punctuation in res:
punctuation_new = convert_q_mark(
(convert_parentheses(
convert_quotes(punctuation))))
text = text.replace(punctuation, punctuation_new)
return text
def convert_num(text):
'''
>>> convert_num('2')
'⠼⠃⠰'
'''
# res = ''
# text_without_NUMBER = text.replace(ostring_to_unicode(NUMBER), "")
# for i in range(len(text_without_NUMBER)):
# if is_digit(text_without_NUMBER[i]): # text_without_NUMBER is in form of unicode, cant be tested using is_digit
# if not is_digit(text_without_NUMBER[i+1]) and i < len(text_without_NUMBER)-1:
# res += ostring_to_unicode(ENG_NUM_END) + ostring_to_unicode('\n\n')
# if i == len(text_without_NUMBER)-1:
# res += ostring_to_unicode(ENG_NUM_END)
# if not is_digit(text_without_NUMBER[i-1]) and i >= 0:
# res # add in front of num
# return res
res = ""
for i in range(len(text)):
if is_digit(text[i]):
if i-1 >=0 and not is_digit(text[i-1]):
res += ostring_to_unicode(NUMBER)
elif i == 0:
res += ostring_to_unicode(NUMBER)
res += ostring_to_unicode(convert_digit(text[i]))
if i+1 < len(text) and not is_digit(text[i+1]):
res += ostring_to_unicode(ENG_NUM_END)
elif i == len(text)-1:
res += ostring_to_unicode(ENG_NUM_END)
else: res += text[i]
return res
####################################################
def english_text_to_braille(text2):
'''(str) -> str
Convert text to English Braille. Text could contain new lines.
This is a big problem, so think through how you will break it up
into smaller parts and helper functions.
Hints:
- you'll want to call text_to_braille
- you can alter the text that goes into text_to_braille
- you can alter the text that comes out of text_to_braille
- you shouldn't have to manually enter the Braille for 'and', 'ch', etc
You are expected to write helper functions for this, and provide
docstrings for them with comprehensive tests.
>>> english_text_to_braille('202') # numbers
'⠼⠃⠚⠃⠰'
>>> english_text_to_braille('2') # single digit
'⠼⠃⠰'
>>> english_text_to_braille('COMP') # all caps
'⠠⠠⠉⠕⠍⠏'
>>> english_text_to_braille('COMP 202') # combining number + all caps
'⠠⠠⠉⠕⠍⠏ ⠼⠃⠚⠃⠰'
>>> english_text_to_braille('and')
'⠯'
>>> english_text_to_braille('and And AND aNd')
'⠯ ⠠⠯ ⠠⠯ ⠁⠠⠝⠙'
>>> english_text_to_braille('chat that the with')
'⠡⠁⠞ ⠹⠁⠞ ⠷ ⠾'
>>> english_text_to_braille('hi?')
'⠓⠊⠦'
>>> english_text_to_braille('(hi)')
'⠶⠓⠊⠶'
>>> english_text_to_braille('"hi"')
'⠦⠓⠊⠴'
>>> english_text_to_braille('COMP 202 AND COMP 250')
'⠠⠠⠉⠕⠍⠏ ⠼⠃⠚⠃⠰ ⠠⠯ ⠠⠠⠉⠕⠍⠏ ⠼⠃⠑⠚⠰'
>>> english_text_to_braille('For shapes with colour?')
'⠠⠿ ⠩⠁⠏⠑⠎ ⠾ ⠉⠕⠇⠳⠗⠦'
>>> english_text_to_braille('(Parenthetical)\\n\\n"Quotation"')
'⠶⠠⠏⠁⠗⠑⠝⠷⠞⠊⠉⠁⠇⠶\\n\\n⠦⠠⠟⠥⠕⠞⠁⠞⠊⠕⠝⠴'
>>> english_text_to_braille('standardized')
'⠎⠞⠯⠁⠗⠙⠊⠵⠫'
>>> english_text_to_braille('understand')
'⠥⠝⠙⠻⠎⠞⠯'
'''
# You may want to put code after this comment. You can also delete this comment.
# Here's a line we're giving you to get started: change text so the
# contractions become the French accented letter that they correspond to
paragraphs = text2.split('\n')
total = ''
for i, text in enumerate(paragraphs):
text = convert_contractions(text)
text = convert_punctuation2(text)
text = convert_num(text)
# You may want to put code after this comment. You can also delete this comment.
# Run the text through the French Braille translator
text = text_to_braille(text)
# You may want to put code after this comment. You can also delete this comment.
# Replace the French capital with the English capital
text = text.replace(ostring_to_unicode(CAPITAL), ostring_to_unicode('..\n..\n.o'))
text = text.replace('“', ostring_to_unicode('..\no.\noo'))
text = text.replace('”', ostring_to_unicode('..\n.o\noo'))
# You may want to put code after this comment. You can also delete this comment.
total += text
if i < len(paragraphs) - 1: # keep paragraphs separate but no extra \ns
total += '\n'
return total
def english_file_to_braille(fname):
'''(str) -> NoneType
Given English text in a file with name fname in folder tests/,
convert it into English Braille in Unicode.
Save the result to fname + "_eng_braille".
Provided to students. You shouldn't edit this function.
>>> english_file_to_braille('test4.txt')
>>> file_diff('tests/test4_eng_braille.txt', 'tests/expected4.txt')
True
>>> english_file_to_braille('test5.txt')
>>> file_diff('tests/test5_eng_braille.txt', 'tests/expected5.txt')
True
>>> english_file_to_braille('test6.txt')
>>> file_diff('tests/test6_eng_braille.txt', 'tests/expected6.txt')
True
'''
file_to_braille(fname, english_text_to_braille, "eng_braille")
if __name__ == '__main__':
doctest.testmod() # you may want to comment/uncomment along the way
# and add tests down here
|
94137423adf3eb129eb0b7282797fc591a78ec75 | raianyrufino/Advanced-Algorithms | /Lista 1 - Ad hoc/A - Ehab and another construction problem.py | 71 | 3.640625 | 4 | x = int(raw_input())
if x==1:
print("-1")
else:
print x-x%2, 2
|
9b9e56586ee307c41de3fa892b8384fcbf456770 | Justice0320/python_work | /ch4/4-10_to_4-12.py | 1,055 | 4.25 | 4 | # 4-10 Slices
my_foods = ['pizza', 'falafel', 'carrot cake', 'burger', 'chips', 'curry', 'chili']
my_foods.append('cannoli')
print("My favourite foods are:")
print(my_foods)
print("\nThe first three items in the list are:")
print(my_foods[:3])
print("\nThe items from the middle of the list are:")
print(my_foods[2:5])
print("\nThe last three items in the list are:")
print(my_foods[-3:])
# 4-11 My Pizzas, You Pizzas
pizzas = ['pepperoni', 'cheese', 'mexican']
friend_pizzas = pizzas[:]
friend_pizzas.append('ham and pineapple')
for pizza in pizzas:
print('My favourite flavour of pizzas are, ' + pizza + '!\n')
for fpizza in friend_pizzas:
print("My friend's favourite flavours of pizza are, " + fpizza + '!\n')
# 4-12 More Loops
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favourite foods are:")
for my_food in my_foods:
print(my_food)
print("\nMy friend's favourite foods are:")
for ffood in friend_foods:
print(ffood)
|
9acdf5e4f59e7f0285be86c145a409b48ae2d592 | SR2k/leetcode | /first-round/475.供暖器.py | 2,293 | 3.765625 | 4 | #
# @lc app=leetcode.cn id=475 lang=python3
#
# [475] 供暖器
#
# https://leetcode-cn.com/problems/heaters/description/
#
# algorithms
# Medium (33.01%)
# Likes: 212
# Dislikes: 0
# Total Accepted: 20K
# Total Submissions: 60.5K
# Testcase Example: '[1,2,3]\n[2]'
#
# 冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
#
# 在加热器的加热半径范围内的每个房屋都可以获得供暖。
#
# 现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。
#
# 说明:所有供暖器都遵循你的半径标准,加热的半径也一样。
#
#
#
# 示例 1:
#
#
# 输入: houses = [1,2,3], heaters = [2]
# 输出: 1
# 解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。
#
#
# 示例 2:
#
#
# 输入: houses = [1,2,3,4], heaters = [1,4]
# 输出: 1
# 解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。
#
#
# 示例 3:
#
#
# 输入:houses = [1,5], heaters = [2]
# 输出:3
#
#
#
#
# 提示:
#
#
# 1
# 1
#
#
#
# @lc code=start
class Solution:
def findRadius(self, houses: list[int], heaters: list[int]) -> int:
houses.sort()
heaters.sort()
left, right = 0, 0
result = 0
for house in houses:
while left + 1 < len(heaters) and heaters[left + 1] <= house:
left += 1
while right + 1 < len(heaters) and heaters[right] < house:
right += 1
result = max(result, min(abs(heaters[left] - house), abs(heaters[right] - house)))
return result
# @lc code=end
s = Solution()
print(s.findRadius(houses = [1,2,3], heaters = [2]))
print(s.findRadius(houses = [1,2,3,4], heaters = [1,4]))
print(s.findRadius(houses = [1,5], heaters = [2]))
print(s.findRadius([1,2,3], [1,2,3]))
print(s.findRadius([1,2,3,4],[1,4]))
print(s.findRadius([282475249,622650073,984943658,144108930,470211272,101027544,457850878,458777923],[823564440,115438165,784484492,74243042,114807987,137522503,441282327,16531729,823378840,143542612])) # 161834419
|
c73d6cea0fc85fe3f099591374e35668833a8f1a | sashaobucina/interview_prep | /python/easy/missing_number.py | 1,657 | 3.984375 | 4 | from typing import List
def missing_number(nums: List[int]) -> int:
"""
# 268: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
NOTE: This is my original solution.
Time complexity: O(n)
Space complexity: O(1)
"""
N = len(nums)
for i in range(N):
while nums[i] != i and nums[i] != N:
num = nums[i]
nums[i], nums[num] = nums[num], nums[i]
for i in range(N):
if nums[i] == N:
return i
return N
def missing_number_XOR(nums: List[int]) -> int:
"""
We can harness the fact that XOR is its own inverse to find the missing element in linear time.
missing = 4 ∧ (0∧0) ∧ (1∧1) ∧ (2∧3) ∧ (3∧4)
= (4∧4) ∧ (0∧0) ∧ (1∧1) ∧ (3∧3) ∧ 2
= 0 ∧ 0 ∧ 0 ∧ 0 ∧ 2
= 2
Time complexity: O(n)
Space complexity: O(1)
"""
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing
def missing_number_gauss(nums: List[int]) -> int:
"""
Gauss' formula
Time complexity: O(n)
Space complexity: O(1)
"""
expected_sum = (len(nums) * (len(nums) + 1)) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
if __name__ == "__main__":
nums = [3, 0, 1]
assert missing_number(nums) == missing_number_XOR(
nums) == missing_number_gauss(nums) == 2
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
assert missing_number(nums) == missing_number_XOR(
nums) == missing_number_gauss(nums) == 8
print("Passed all tests!")
|
cb7bb8917ce01c1e13950044a9b16a0304a97b53 | aviadlevy/Intro2cs-huji-2014 | /ex2/ex2_square.py | 1,321 | 4.21875 | 4 | #!/usr/bin/env python3
def square_printing(n):
squareLen="#"*(2*n+1) #define the first and last line
#set counters
counter=1
counter2=0
eaZugy=1 #counter for the space between the "*"
#define the second and the one before last line (only one *)
line1="#"+" "*(n-counter)+"*"+" "*(n-counter)+"#"
print(squareLen) #print the first line (all #)
while counter<=int(n*2-1):
#print second and one before last
if counter==1 or counter==(2*n-1):
print(line1)
counter+=1
counter2+=1
#print first half of meuyan
elif counter<=n:
print("#"+" "*(n-counter)+"*"+" "*(eaZugy)+"*"+" "*(n-counter)+"#")
counter+=1
counter2+=1
eaZugy+=2
#print second half of meuyan
else:
counter+=1
counter2-=1
eaZugy-=2
print("#"+" "*(n-counter2)+"*"+" "*(eaZugy-2)+"*"+" "*(n-counter2)+"#")
print(squareLen) #print last line (all #)
#Here to help you test your code.
if __name__=="__main__": #If we are the main script, and not imported
from sys import argv
try:
n = int(argv[1])
except:
n = int(input("Please enter a positive integer: "))
square_printing(n)
|
fdfaf5f87a887c8d983bd663d8b91cea516b325e | JoaoPedroPiotroski/Game | /game 0.2.0.py | 9,622 | 3.78125 | 4 | import random
print("---- Você começa sua aventura ----")
print(" Escolha seu personagem ")
print("Você pode escolher entre : ")
print("1 - O GUERREIRO que empunha espada e escudo, um personagem bastante equilibrado")
print("2 - O MAGO que empunha seu cajado, dando grande quantidade de dano")
print("3 - O TANQUE que empunha um grande escudo, dando grande capacidade de defesa")
charclass=input("> ")
if charclass == "1":
print("Ótimo! Você escolheu o guerreiro!")
print("Você começa com uma quantidade igual de defesa e ataque")
ataque=10
defesa=10
elif charclass == "2":
print("Ótimo! Você escolheu o mago!")
print("Você começa com uma grande quantidade de ataque, mas pouca defesa")
ataque=15
defesa=5
elif charclass == "3":
print("Ótimo! Você escolheu o tanque!")
print("Você começa com uma maior quantidade de defesa, mas menor ataque")
ataque=8
defesa=12
firsttime=1
monsterhp=1
playermaxhp=25
playerhp=25
playerlevel=1
playerwantstocontinue=""
if firsttime==1:
xp=0
print("Agora é hora de começar sua aventura de verdade!")
while len(str(playerwantstocontinue))==0:
if playerlevel == 1:
if firsttime==1:
monsterhp=(random.randint(10,20))
monsterattack=(random.randint(5,10))
monsterdefense=(random.randint(5,10))
elif firsttime!=0:
monsterhp=(random.randint(10,30))
monsterattack=(random.randint(5,15))
monsterdefense=(random.randint(5,15))
elif playerlevel == 2:
monsterhp=(random.randint(20,40))
monsterattack=(random.randint(15,25))
monsterdefense=(random.randint(15,25))
elif playerlevel == 3:
monsterhp=(random.randint(30,50))
monsterattack=(random.randint(25,35))
monsterdefense=(random.randint(25,35))
elif playerlevel == 4:
monsterhp=(random.randint(40, 60))
monsterattack=(random.randint(35, 45))
monsterdefense=(random.randint(45, 55))
elif playerlevel == 5:
monsterhp=(random.randint(50,70))
monsterattack=(random.randint(55,65))
monsterdefense=(random.randint(55,65))
elif playerlevel == 6:
monsterhp=(random.randint(60,80))
monsterattack=(random.randint(65,75))
monsterdefense=(random.randint(65,75))
elif playerlevel == 7:
monsterhp=(random.randint(70,90))
monsterattack=(random.randint(75,85))
monsterdefense=(random.randint(75,85))
elif playerlevel == 8:
monsterhp=(random.randint(80,100))
monsterattack=(random.randint(85,95))
monsterdefense=(random.randint(85,95))
elif playerlevel == 9:
monsterhp=(random.randint(90,110))
monsterattack=(random.randint(95,105))
monsterdefense=(random.randint(95,105))
elif playerlevel == 10:
monsterhp=(random.randint(100,120))
monsterattack=(random.randint(105,115))
monsterdefense=(random.randint(105,115))
maxmonsterhp=monsterhp
if monsterhp <15:
species1=["slime","rato"]
elif 15 <= monsterhp <25:
species1=["goblin","mão rastejante","morcego"]
elif 25<= monsterhp <45:
species1=["esqueleto","fantasma fracote","mago wannabe","morcego gigante","homem lama"]
elif 45 <= monsterhp < 55:
species1=["gato marinho","pato-coelho","beholder cego","lich apodrecido"]
elif 55 <= monsterhp <65:
species1=[]
species=(random.choice(species1))
print("Você encontra um %s!"%species)
while monsterhp > 0:
print("Hp do monstro: %d / %d Seu hp: %d / %d Seu nivel: %d "%(monsterhp, maxmonsterhp, playerhp, playermaxhp, playerlevel))
print("Seu ataque: %d Sua defesa: %d Seu xp: %d"%(ataque, defesa, xp))
if firsttime==1:
print("Você ataca ou defende?")
firsttime=2
print("1 - Atacar 2 - Defender")
decisao=int(input("> "))
if decisao==1:
mdecision=random.randint(1,100)
if mdecision > 70 and monsterhp > 0:
print("O %s defende!"%species)
damagetoplayer=(monsterattack)/((random.randint(1,2)))
damagetomonster=(ataque*(random.randint(1,2)))-(monsterdefense*(random.randint(1,2)))
if damagetomonster > 0 :
monsterhp-=damagetomonster
if damagetoplayer > 0:
playerhp-=damagetoplayer
elif mdecision <=70 and monsterhp > 0:
print("O %s ataca!"%species)
damagetoplayer=monsterattack-defesa/(random.randint(1,2))
damagetomonster=ataque-monsterdefense/(random.randint(1,2))
if damagetomonster > 0 :
monsterhp-=damagetomonster
if damagetoplayer > 0:
playerhp-=damagetoplayer
elif decisao==2:
mdecision=random.randint(1,100)
if mdecision > 70 and monsterhp > 0:
print("O %s ataca!"%species)
damagetoplayer=monsterattack-defesa*(random.randint(1,2))
damagetomonster=ataque-monsterdefense/(random.randint(1,2))
if damagetomonster > 0 :
monsterhp-=damagetomonster
if damagetoplayer > 0:
playerhp-=damagetoplayer
elif mdecision <=70 and monsterhp > 0:
print("O %s defende!"%species)
damagetoplayer=monsterattack/(random.randint(1,2))-defesa*(random.randint(1,2))
damagetomonster=ataque/(random.randint(1,2))-(monsterdefense)*(random.randint(1,2))
if damagetomonster > 0 :
monsterhp-=damagetomonster
if damagetoplayer > 0:
playerhp-=damagetoplayer
print("Você deu %d de dano no %s e você tomou %d de dano"%(damagetomonster, species, damagetoplayer))
if playerhp < 0:
break
if monsterhp <= 0:
print("O %s morreu!"%species)
break
if monsterhp < 0:
xp = xp+((monsterattack+monsterdefense)/2)
print("Você ganhou %dXp"%xp)
if xp >= 10*playerlevel:
print("Você aumentou 1 nivel!")
playerlevel += 1
playermaxhp += 10
ataque += 10
defesa += 10
playerhp=playermaxhp
xp=0
print("Continuar - Nada Parar - Digite qualquer coisa")
playerwantstocontinue=input("> ")
if playerhp <= 0:
print("You died")
playerwantstocontinue=14414
playerhp+=playermaxhp/2
if playerhp > playermaxhp:
playerhp=playermaxhp
Exit=input("-Pressione qualquer tecla para sair-")
|
040f2c65b6ffc8d7e1d94f2fca1608f73b0f2bd5 | Jeklah/ProjectEuler100 | /27/quadratic_primes.py | 719 | 3.765625 | 4 | # project euler problem 27
# Author: Jeklah
import itertools
import math
def is_prime(n):
if n <= 1:
return False
return all(n % i != 0 for i in range(2, int(math.sqrt(n)) + 1))
def quadratic_primes(a, b):
n = 0
while True:
if is_prime(n ** 2 + a * n + b):
n += 1
else:
return n
def main():
max_primes = 0
max_a = 0
max_b = 0
for a_num, b_num in itertools.product(range(-999, 1000), range(-999, 1000)):
primes = quadratic_primes(a_num, b_num)
if primes > max_primes:
max_primes = primes
max_a = a_num
max_b = b_num
print(max_a * max_b)
if __name__ == '__main__':
main()
|
119cddb1144b75213fa1b8e93cb85c0c7f5bd003 | rfenzo/PrograAvanzada | /Curso/Ayudantias/AY05 - Funcional/AC/solucion_en_ayudantia.py | 1,600 | 3.53125 | 4 | from datetime import date
from functools import reduce
def leer_archivo(path):
with open(path) as archivo:
splitted = list(map(lambda l: tuple(l.split(";")),
archivo))
tuplas = map(lambda t: t[0:5] + tuple(map(int, t[5:11])),
splitted)
return list(tuplas)
def se_llama_como(tuplas, nombre):
return list(filter(lambda t: any(map(lambda x, y: x.lower() == y.lower(), t, nombre)),
tuplas))
def chilenos_zurdos(tuplas):
return list(filter(lambda t: t[3:5] == ("Chile", "izquierdo"),
tuplas))
def edades(tuplas):
anho = date.today().year # 2017
return list(map(lambda t: t[0:2] + (anho - t[7],),
tuplas))
def sub_17(tuplas):
return list(filter(lambda t: t[2] <= 17,
edades(tuplas)))
def goleador(tuplas):
return reduce(lambda x, y: x if x[8] > y[8] else y,
tuplas)
#return reduce(lambda x, y: max(x, y, key=lambda t: t[8]), tuplas)
def mayor_riesgo_obesidad(tuplas):
imc = lambda t: ((t[3] / (t[2]/100)**2),)
chilenos = filter(lambda t: t[3] == "Chile", tuplas)
aux = map(lambda t: t[0:2] + t[9:11], chilenos)
tuplas_con_imc = map(lambda t: t + imc(t), aux)
return reduce(lambda x, y: x if x[4] > y[4] else y,
tuplas_con_imc)
if __name__ == "__main__":
arch = leer_archivo("jugadores_sin_tildes.txt")
#print(mayor_riesgo_obesidad(leer_archivo("jugadores_sin_tildes.txt")))
print(se_llama_como(arch, ("Luis Felipe", "Suazo", "Perez")))
|
e68cf7c5c99d97df4dc021ba20c7a0fd01ae791b | UF-CompLing/Word-Normalization | /FromLecture.py | 1,010 | 4.21875 | 4 | import re
TextName = 'King-James-Bible'
## ~~~~~~~~~~~~~~~~~~~~
## START OF FUNCTIONS
print('opening file\n')
input_file = open('Original-Texts/' + TextName + '.txt', 'r')
# the second parameter of both of these open functions is
# the permission. 'r' means read-only.
#
# The 'Original-Texts/' part is so that it looks
# in the 'Original-Texts' folder
print('going through every line in file. hold on a sec...')
# store every word in here
for line in input_file:
# regex expressions
regexed = re.compile(r'\W+', re.UNICODE).split(line)
# this function takes out characters that are not
# letter or numbers
#
# BUT... it makes a list. let's join that list back together!
# build word to print back to file
toOutput = ''
for word in regexed:
# there are lots of blank spaces that get
# caught up in our program
if word is '':
continue
toOutput += word.lower() + ' '
# print word to our screen
print(toOutput + '\n')
|
27fccff6186e761d375c0a588b6b4d4ac3acd4f3 | sarahghanei/Euler-Project-Programming | /Problem3.py | 606 | 4 | 4 | # # Euler project Problem 3
# def is_prime(n):
# res = True
# for i in range(2, int(n ** 0.5) + 1):
# if n % i == 0:
# res = False
# return res
#
#
# def max_prime_factor(n):
# max_prime = 0
# while n % 2 == 0:
# max_prime = 2
# n /= 2
# for i in range(3, int(n ** 0.5) + 1, 2):
# while n % i == 0:
# max_prime = i
# n = n / i
# n = int(n)
# return max_prime
#
#
# num = input("Enter your number : ")
# num = int(num)
# print("The maximum prime factor of %i is %i" % (num, max_prime_factor(num)))
|
d6a5b613995b62924c65591bad59ddd57981679d | AndersonRoberto25/Python-Studies | /Lista/Trabalhando com listas/lista2.py | 1,426 | 4.59375 | 5 | #Criando listas numéricas
#A função range() de Python facilita gerar uma série de números.
for value in range(1,6):
print(value)
#A função range() faz Python começar a contar no primeiro valor que você lhe fornecer e parar quando atingir o segundo valor especificado. Como ele para nesse segundo valor, a saída não conterá o valor final.
#Se quiser criar uma lista de números, você pode converter os resultados de range() diretamente em uma lista usando a função list().
numbers = list(range(1,6))
print(numbers)
#Também podemos usar a função range() para dizer a Python que ignore alguns números em um dado intervalo. Por exemplo, eis o modo de listar os números pares entre 1 e 10:
even_numbers = list(range(2,11,2))#O valor 2 é somado repetidamente até o valor final, que é 11, ser alcançado ou ultrapassado
print(even_numbers)
#Os dez primeiros quadrados perfeitos em uma lista
squares = []
for value in range(1,11):
#square = value**2
squares.append(value**2)
print(squares)
#List comprehensions
squares = [value**2 for value in range(1,11)]
print(squares)
#Estatística simples com lista de números - Algumas funções Python são específicas para listas de números
digits = [1,2,3,4,5,6,7,8,9,0]
print('\nValores da lista:')
print(digits)
print('Valor mínimo: ' + str(min(digits)) + '\nValor máximo: ' + str(max(digits)) + '\nSoma dos números: ' + str(sum(digits)))
|
fc2cb8401a15c002d9a218d5d71d5c6616da8325 | Poppy22/coding-practice | /Leetcode/hashmap-hashset/distribute-candies.py | 1,509 | 3.859375 | 4 | ### Set - faster, shorter
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
freq = set()
for candy in candies:
freq.add(candy)
return min(len(freq), len(candies) // 2)
### Dictionary - time limit exceeded, but explains the idea
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
freq = {}
for candy in candies:
if candy in freq.keys():
freq[candy] += 1
else:
freq[candy] = 1
sister = 0
types = 0
brother = 0
for c in freq.keys():
if freq[c] > 1:
sister += 1
brother += freq[c] - 1
else:
sister += 1
# sister only has one candy from each type and has all unique candies
if sister <= brother:
# the have the same number or candies or
# the brother has more and when he gives candies to his sister
# it will be duplicates, so this is the maximum number of types
return sister
# some candies have to go to the brother in order to balance the number
# sister has only one candy from each type, so the balance is half of the total candies
return len(candies) // 2
|
e46460143f9b6075e9967e737e9e7be81d616d9c | anthonyescobar/SampleWork | /WordIndexer 12:05:2016/index.py | 1,964 | 3.78125 | 4 | # Do not import anything other than syand re!
import sys
import re
# this function removes punctuation from a string.
# you should use this before adding a word to the index,
# so that "asdf." and "asdf" and "asdf," are considered to be
# the same word.
def remove_punctuation(s):
return re.sub(r'[^\w\s]', '', s)
assert(remove_punctuation('asdf.') == 'asdf')
assert(remove_punctuation('asdf,') == 'asdf')
assert(remove_punctuation("?;'.!") == '')
# index is a global dictionary. The keys should be words, and the
# values should be tuples of (filename, line number, position in line).
index = {}
def build_index():
global index
args = sys.argv[1:]
args.sort()
for file in args:
ln = 0
with open(file,'r') as f:
for line in f:
ln += 1
pos = 0
for word in line.split():
tup = (file,ln,pos)
pos += len(word) +1
if remove_punctuation(word.lower().strip()) in index:
index[remove_punctuation(word.lower().strip())].append(tup)
else:
index[remove_punctuation(word.lower().strip())] = [tup]
return index
build_index()
# commands
def words(args):
arr = [x for x in index.keys() if x.startswith(args[0].lower())]
arr.sort()
for s in arr:
print(s)
def occurrences(args):
arr = index.get(args)
i = 0
for s in arr:
print(" ("+str(i)+") File " + str(arr[i][0]) + ", Line " + str(arr[i][1]) + ", Character " + str(arr[i][2]))
i += 1
arr = []
def output(args):
arr = list(index.keys())
arr.sort()
for s in arr:
print(s)
occurrences(s)
cmds = {
'words' : words,
'occurrences' : occurrences,
'output' : output,
}
def interact():
# print the prompt line
print('> ', end='', flush=True)
for ln in sys.stdin:
ln = ln.strip().split(' ')
if ln[0] == 'quit':
return
else:
cmds[ln[0]](ln[1:])
# print the next prompt line
print('> ', end='', flush=True)
interact()
|
08b65597821f33139a38d607394dd4e9bba1d2b0 | LizethAcosta/Tareas | /WSQ06.py | 384 | 3.796875 | 4 |
# Thais Lizeth Santos Acosta
# A01630056
# WSQ06
from random import randint
print("Guess what number I'm thinking between 1 and 100!")
a = int(input("Number: "))
x = randint(1,100)
while (a != x):
if (a>x):
print ("I'm sorry but is to high.")
else:
print ("I'm sorry but is to low.")
a = int(input(("Try again:")))
print("You got it!")
|
1a3d5f79de1e9cc3506856fb5687cb1a0f5bca7b | VVivid/python-programs | /Strings/4.py | 321 | 3.96875 | 4 | """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."""
def change_char(str1):
first = str1[0]
str1 = str1.replace(str1[0], '$')
str1 = first + str1[1:]
return str1
print(change_char('restart'))
|
d2f2f411684aad65686a12f22299aeedeed23c88 | AlanVek/Proyectos-Viejos-Python | /18.py | 1,510 | 4 | 4 | from math import pi
opcion=""
while opcion!="3":
print ("Las opciones son: ")
print ("1) Calcular perímetro.")
print ("2) Calcular área.")
print ("3) Salir.")
opcion=input("Ingrese la opción deseada: ")
if opcion=="1":
print ("Las opciones son: ")
print ("1) Triángulo.")
print ("2) Cuadrado. ")
print ("3) Círculo")
print ("4) Regresar. ")
opcion1=input("Ingrese la opción deseada: ")
if opcion1=="1":
a=int(input("Ingrese lado del triángulo: "))
b=int(input("Ingrese lado del triángulo: "))
c=int(input("Ingrese lado del triángulo: "))
print ("El perímetro es: ",a+b+c)
if opcion1=="2":
a=int(input("Ingrese lado del cuadrado: "))
print ("El perímetro es: ",4*a)
if opcion1=="3":
a=float(input("Ingrese radio del círculo: "))
print ("El perímetro es: ",2*pi*a)
if opcion=="2":
print ("Las opciones son: ")
print ("1) Triángulo.")
print ("2) Cuadrado. ")
print ("3) Círculo")
print ("4) Regresar. ")
opcion1=input("Ingrese la opción deseada: ")
if opcion1=="1":
a=int(input("Ingrese altura del triángulo: "))
b=int(input("Ingrese base del triángulo: "))
print ("El área es: ",a*b/2)
if opcion1=="2":
a=int(input("Ingrese lado del cuadrado: "))
print ("El área es: ",a**2)
if opcion1=="3":
a=float(input("Ingrese radio del círculo: "))
print ("El área es: ",pi*(a**2))
print ("Gracias por usar el programa.")
|
8b72d51599dd35a97724b9fe3aa694a6d3b87a9d | Biddy79/eclipse_python | /Getters_and_setters/main/__init__.py | 1,170 | 4.125 | 4 | from player import Player
Adam = Player("Adam")
#printing out all attributes of Player class
print(Adam.name)
print(Adam.lives)
print(Adam._level)
print(Adam._score)
#printing out lives attribute using _get_lives method
print(Adam._get_lives())
#setting number of lives using _set lives attribute
Adam._set_lives(300)
print(Adam.lives)
#Using the lives property() method in Player class which encapsulates instance attributes
#of _get_lives and _set_lives Take note this is not the same attribute as underscore _lives !!!
Adam.lives -= 10
#Agine printing out the lives attribute
print(Adam.lives)
#trying to set lives to negative number using _set_lives method. this will give a priinted warrning
#This is implemented in Player class inside of _set_lives method
Adam._set_lives(-5)
#printin Adam object. Method __str__ is implemented in Player class
print(Adam)
print("-" * 30)
#using the level the property method in player class to pass 2 as arg into _set_level method
Adam.level = 2
print(Adam._score)
Adam.level += 5
print(Adam)
Adam.level = 3
print(Adam)
#accsessing score property in player class to change the score
Adam.score = 500
print(Adam)
|
07ff50d1460c98a3684f4204e9c4f7910256a018 | OguzHaksever/UdemyPython3.9 | /trhuty_values.py | 379 | 4.21875 | 4 | if 0:
print("True")
else:
print("False")
name = input("Please enter your name: ")
if name:
print("Hello, " + name) # isim girilmezse name(False) olur,
# Çünkü boş string, if False ise
# else komutu çalışır
else:
print("Are you the man with no name")
|
185d8d41aaea2872197d1c15724fb44a4480ab23 | avviswas/Python-CA2020 | /python-week2/Task1.py | 1,830 | 4.375 | 4 | # 1. Create three variables in a single line and assign values to them in such a manner that each one ofthem belongs to a different data type.
a, b, c = 2, 2.03, 'string'
# 2.Create a variable of type complex and swap it with another variable of type integer.
a = complex(1,2)
b = 2
a = b
print(type(a))
# 3.Swap two numbers using a third variable and do the same task without using any third variable.
#with third variable
a,b = 1,2
c = a
a = b
b = c
print(a,b)
#without third variable
a,b = 1,2
a,b = b,c
print(a,b)
# 4.Write a program that takes input from the user and prints it using both Python 2.x and Python 3.xVersion.
# Python 2.x
a = raw_input('Input a value: ')
#Python 3.x
a = input('input a value: ')
# 5.Write a program to complete the task given below:Ask users to enter any 2 numbers in between 1-10 ,
# add the two numbers and keep the sum inanother variable called z. Add 30 to z and store the output in variable result
# and print result as thefinal output.
a = int(input('enter a value between 1 and 10: '))
b = int(input('enter another value between 1 and 10: '))
z = a+b
result = 30 + z
print('Final Result: ', result)
# 6.Write a program to check the data type of the entered values.
a = eval(input('enter any value : '))
print("The data type of the input value is ",type(a))
# 7.Create Variables using formats such as Upper CamelCase, Lower CamelCase, SnakeCase and UPPERCASE.
CamelCase = 1
CAMELCASE = 2
Camel_Case = 3
camelcase = 4
CAMELCASE = 5
# string = CamelCase
# string.lower()
# string.upper()
# string.capitalize()
# 8.If one data type value is assigned to ‘a’ variable and then a different
# data type value is assigned to ‘a’ again. Will it change the value? If Yes then Why?
#Answer:Yes, in python the latest declaration is considered as the value of the variable
|
9039e403892985b441a497682489411f75822dad | tribadboy/algorithm-homework | /week1/N叉树的层序遍历.py | 650 | 3.71875 | 4 | # -*-coding:utf-8 -*-
from typing import List
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root is None:
return []
result = []
stack = [root]
while len(stack) != 0:
new_stack = []
val_list = []
for node in stack:
val_list.append(node.val)
new_stack += node.children
stack = new_stack
result.append(val_list)
return result |
646e69769250eb55d8a9b4a2c8976d269cb25cd0 | Siddharth-22-1994/Python_Sams_lap | /Python1/Duplicate elements in list.py | 109 | 3.765625 | 4 | l1 = [2, 3, 4, 5, 2, 3]
l1.sort()
for i in range(len(l1) - 1):
if l1[i] == l1[i+1]:
print(l1[i])
|
f16e95151b101a27ebd5da1c289ff867e53fa000 | taoranzhishang/Python_codes_for_learning | /study_code/Day_09/04list更新方法.py | 413 | 3.8125 | 4 | mylist = [1, 2, 3, 4, 5, 6]
print(mylist)
for i in range(len(mylist)): # 修改列表必须用索引
if mylist[i] == 2:
mylist[i] = -2
print(mylist[i])
print(mylist)
'''
for data in mylist:#data相当于副本,改变副本不影响list元素值,修改失败,用于读取不修改
if data==2:
data=-2
print(data)#data可以改变,但元素不变
print(mylist)
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.