blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ca208c8bc7a37c214ddb26959219ab3413fe327d | TarekSw/SMTP-GMAIL | /smtp_network.py | 5,301 | 3.609375 | 4 | #First thing to do:
# - Got to the google account settings and turn On Less Secure Apps feature.
# in order to be able to send email from an outside application using the Gmail SMTP server.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from tkinter import messagebox
import tkinter as thinker
import smtplib
#used for checking the regular expression comparisoon
import re
#regular expression to check if the gmail entered is valid or not.
reg = '^[a-z0-9](\.?[a-z0-9]){5,}@g(oogle)?mail\.com$'
# the main function through where the email is sent and the SMTP connection is established
def mail(recipient_address, subject, body):
try:
sender_address = '' #sender email
sender_password = '' #sender email password
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = sender_password
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
text = message.as_string()
#Open a connection with the Gmail SMTP server on the port 587
SMTPserver = smtplib.SMTP('smtp.gmail.com', 587)
#Put the SMTP server connection into a TLS mode
#StartTLS is a protocol command used to inform the email server that the email client
#wants to upgrade from an insecure connection to a secure one using TLS or SSL
SMTPserver.starttls()
#LogIn into the server using the email and the password
#credentials of your own google account
SMTPserver.login(sender_address, sender_password)
#this is where you send the email, by passing those parameters
#sender email which he have to enable the less secure app access
#of his google account on this following link: https://myaccount.google.com/u/3/lesssecureapps
SMTPserver.sendmail(sender_address, recipient_address, text)
#Quit/End the connection with the server
SMTPserver.quit()
#if email was sent successfully it will show a dialog box saying that
# Your Email Was Sent Successfully
messagebox.showinfo("Successfull", 'Your Email is Sent Successfully to '+recipient_address)
#if any error happened for whatever reason it will show a dialog ox
# saying that an error occurred and also print the error message by using (str(e))
except Exception as e:
messagebox.showerror("Error!",'Error : ' + str(e))
#this function is used foe the sake is when the user clicks on the GUI send the email button it run
#the following code which as shown below takes an event as a parameter. where the event in this case
#is button clicked. after the button clicked it checks if the recipient gmail match the regular
#expression defined ^[a-z0-9](\.?[a-z0-9]){5,}@g(oogle)?mail\.com$ and if the regular expression matches
# the email entered it call the mail function defined previously and passes the required parameters.
def send_on_click(event):
if re.search(reg, str.lower(recipient_text.get())):
mail(str.lower(recipient_text.get()), subject_text.get(), body_text.get("1.0", "end"))
else:
#if any error occurred while doing the previous process it prints an error.
messagebox.showerror("Error!!", "Please make sure all your input are in the proper format!")
pass
#this function takes as an event parameters. where if the user enters the recipient address
# it enables the button. you can notice that when you open the UI the send this email button is disabled
#but after entering the recipient email the send this email button will be enabled through this function.
def text_get(event):
if(re.search(reg, str.lower(recipient_text.get()))):
send_button['state'] = 'normal'
send_button.bind('<Button-1>', send_on_click)
else:
send_button['state'] = 'disabled'
send_button.unbind('<Button-1>')
pass
#The Graphical User Interface (GUI)
if __name__ == "__main__":
window = thinker.Tk()
window.title("Networking Project")
firstFrame = thinker.Frame()
SecondFrame = thinker.Frame()
ThirdFrame = thinker.Frame()
recipient = thinker.Label(master=firstFrame, text="Recipient:")
recipient.pack(side=thinker.LEFT, fill=thinker.BOTH)
recipient_text = thinker.Entry(master=firstFrame)
recipient_text.pack()
recipient_text.bind('<KeyRelease>', text_get)
firstFrame.pack(padx=30, pady=30)
subject = thinker.Label(master=SecondFrame, text="Subject: ")
subject.pack(side=thinker.LEFT, fill=thinker.BOTH)
subject_text = thinker.Entry(master=SecondFrame)
subject_text.pack()
SecondFrame.pack(padx=10, pady=10)
body = thinker.Label(master=ThirdFrame, text="Body:",)
body.pack(side=thinker.LEFT, fill=thinker.BOTH)
body_text = thinker.Text(master=ThirdFrame)
body_text.pack()
ThirdFrame.pack(padx=10, pady=10)
send_button = thinker.Button(window, text="Send This Email..", font="bold")
send_button.pack(pady=5)
send_button.bind('<Button-1>', send_on_click)
if recipient_text.get() == "":
send_button['state'] = "disabled"
send_button.unbind("<Button-1>")
window.mainloop()
#End of UI code |
75f6d0e33ef63f984f464c15e50ac5cff6cf3204 | green-fox-academy/wenjing-liu | /week-03/day-01/bank-account/usa_dollar.py | 354 | 3.765625 | 4 | from currency import Currency
class USADollar(Currency):
def __init__(self, value):
super(USADollar, self).__init__(value, 'USD', 'Federal Reserve System')
'''
### USADollar
**`USADollar` is a `Currency`**
- It must accept a value.
- The code must be "USD" by default.
- The central bank name must be "Federal Reserve System" by default.
''' |
dae698c381c1d6a3a024f1b92c2fc79aad990b96 | holmes1313/Leetcode | /702_Search_in_a_Sorted_Array_of_Unknown_Size.py | 2,302 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 12:46:12 2019
@author: z.chen7
"""
# 702. Search in a Sorted Array of Unknown Size
"""
Given an integer array sorted in ascending order, write a function to search target in nums.
If target exists, then return its index, otherwise return -1.
However, the array size is unknown to you. You may only access the array using an
ArrayReader interface, where ArrayReader.get(k) returns the element of the array at index k (0-indexed).
You may assume all integers in the array are less than 10000,
and if you access the array out of bounds, ArrayReader.get will return 2147483647.
Example 1:
Input: array = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: array = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Note:
You may assume that all elements in the array are unique.
The value of each element in the array will be in the range [-9999, 9999].
"""
"""
The problem is that binary search requires us knowing the length of the list,
so that we can compare it to the target to the midpoint.
It's better to back off exponentially. Try 1, then 2, then 4, then 8 and so on.
This ensures that if the list has length n, we'll find the length in at most
O(log n) time.
Once we find the length, we just perform a (mostly) normal binary search
"""
class Solution(object):
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
index = 1
# in the processs, if the element is bigger than target
# we'll jump over to the binary search part early
while reader.get(index) < 10000 and reader.get(index) < target:
index *= 2
# we only need to check between index // 2 and index
# because the previous iteration ensured reader.get(index // 2) < target
low = index // 2
high = index
while low <= high:
mid = (low + high) // 2
middle = reader.get(mid)
if middle == target:
return mid
elif target < middle:
high = mid - 1
else:
low = mid + 1
return -1
|
2b8835db02a4d12bf2f1634cee1b314e8ff862e9 | MaxwellClemens/AdventOfCode2017 | /12/day12.py | 2,928 | 3.5 | 4 | import math
def calculateChangeToVelocities(currentPositions, allPositions, currentIndex):
changeToVelocities = [0,0,0]
for index, position in enumerate(allPositions):
if index == currentIndex:
continue
for k in range(3):
if currentPositions[k] < position[k]:
changeToVelocities[k] += 1
if currentPositions[k] > position[k]:
changeToVelocities[k] -= 1
return changeToVelocities
lines = open("input.txt", "r").readlines()#.split(",")
positions = []
velocities = []
previousStates=[{},{},{}]
for index, line in enumerate(lines):
values = line.replace("\n","").split(",")
position = (int(values[0]), int(values[1]), int(values[2]))
positions.append(position)
velocities.append((0,0,0))
# previousStates[index][(position,(0,0,0))] = True
steps = 0
while True:
lenx = len(previousStates[0])
leny = len(previousStates[1])
lenz = len(previousStates[2])
for i in range(3):
previousStates[i][((positions[0][i],positions[1][i],positions[2][i]),(velocities[0][i],velocities[1][i],velocities[2][i]))] = True
if lenx == len(previousStates[0]) and leny == len(previousStates[1]) and lenz == len(previousStates[2]):
break
newPositions = []
newVelocities = []
for j in range(len(positions)):
changeToVelocities = calculateChangeToVelocities(positions[j], positions, j)
newVelocity = (velocities[j][0] + changeToVelocities[0], velocities[j][1] + changeToVelocities[1], velocities[j][2] + changeToVelocities[2])
newPosition = (positions[j][0] + newVelocity[0], positions[j][1] + newVelocity[1], positions[j][2] + newVelocity[2])
newPositions.append(newPosition)
newVelocities.append(newVelocity)
steps += 1
# if steps % 1000000 == 0:
# print(steps)
# isRepeted = [False, False, False, False]
# for j in range(len(newPositions)):
# if (newPositions[j],newVelocities[j]) in previousStates[j]:
# isRepeted[j] = True
# previousStates[j][(newPositions[j],newVelocities[j])] = True
# if(isRepeted[0] and isRepeted[1] and isRepeted[2] and isRepeted[3]):
# break
positions = newPositions
velocities = newVelocities
print(steps)
print(len(previousStates[0]))
print(len(previousStates[1]))
print(len(previousStates[2]))
# potentialEnergies = []
# kineticEnergies = []
# for position in positions:
# energy = 0
# for value in position:
# energy += abs(value)
# potentialEnergies.append(energy)
# for velocity in velocities:
# energy = 0
# for value in velocity:
# energy += abs(value)
# kineticEnergies.append(energy)
# totalEnergy = 0
# for i in range(len(potentialEnergies)):
# totalEnergy += potentialEnergies[i] * kineticEnergies[i]
# print(potentialEnergies)
# print(kineticEnergies)
# print(totalEnergy) |
d9442feba85d179b29b482bd6e804ac30afb4c6d | manasbundele/computer-vision-projects | /modified-mnist/resnet_mnist.py | 5,003 | 4 | 4 | '''
By: Manas Bundele
Project Constraints:
The goal is to train a CNN to recognize images of digits from the MNIST dataset. This dataset consists of
gray level images of size 28x28. There is a standard partitioning of the dataset into training and testing.
The training has 60,000 examples and the testing has 10,000 examples. Standard CNN models achieves over
99% accuracy on this dataset.
In this project you are asked to solve a similar problem of creating a classifier for the MNIST data. However,
the training data in our case has only 6,000 images, and each image is shrunk to size 7x7. Specifically,
your program must include the following:
1. Your program must set the random seeds of python and tensorflow to 1 to make sure that your results
are reproducible.
2. The first layer in the network must be a 4 ⇥ 4 maxpooling layer. This e↵ectively shrinks the images
from 28x28 to 7x7.
3. Your program will be tested by training on a fraction of 0.1 of the standard training set. The testing
data will be the entire standard testing set.
4. The training and testing in you program should not take more than 6 minutes.
Results:
The designed network was able to achieve over 90% accuracy in under 4 and 1/2 minutes.
based on code from https://www.tensorflow.org/tutorials
'''
import tensorflow as tf
import numpy as np
import cv2
# set the random seeds to make sure your results are reproducible
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(1)
# specify path to training data and testing data
folderbig = "big"
foldersmall = "small"
train_x_location = foldersmall + "/" + "x_train.csv"
train_y_location = foldersmall + "/" + "y_train.csv"
test_x_location = folderbig + "/" + "x_test.csv"
test_y_location = folderbig + "/" + "y_test.csv"
print("Reading training data")
x_train_2d = np.loadtxt(train_x_location, dtype="uint8", delimiter=",")
x_train_3d = x_train_2d.reshape(-1,28,28,1)
x_train = x_train_3d
y_train = np.loadtxt(train_y_location, dtype="uint8", delimiter=",")
print("Pre processing x of training data")
x_train = x_train / 255.0
# erosion: preprocessing to improve the visibility to the model
for image_index in range(x_train.shape[0]):
kernel = np.ones((2,2),np.uint8)
res = cv2.erode(x_train[image_index,:,:,:],kernel,iterations = 1)
res = res.reshape(-1,28,28,1)
x_train[image_index,:,:,:] = res
# Residual network
inputs = tf.keras.Input(shape=(28,28,1))
intermediate_output = tf.keras.layers.MaxPool2D(4, 4, padding='same')(inputs)
intermediate_output = tf.keras.layers.Conv2D(128, (2,2), padding='same')(intermediate_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
intermediate_output = tf.keras.layers.Conv2D(256, (2,2), padding='same')(intermediate_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
block_1_output = intermediate_output
intermediate_output = tf.keras.layers.Conv2D(128, 2, padding='same')(block_1_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
intermediate_output = tf.keras.layers.Conv2D(256, 2, padding='same')(intermediate_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
block_2_output = tf.keras.layers.add([intermediate_output, block_1_output])
intermediate_output = tf.keras.layers.Conv2D(256, 2, padding='same')(block_2_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
intermediate_output = tf.keras.layers.Flatten()(intermediate_output)
intermediate_output = tf.keras.layers.Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(intermediate_output)
intermediate_output = tf.keras.layers.Dropout(0.1)(intermediate_output)
outputs = tf.keras.layers.Dense(10, activation='softmax')(intermediate_output)
model = tf.keras.Model(inputs, outputs)
model.summary()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print("train")
model.fit(x_train, y_train, epochs=10)
print("Reading testing data")
x_test_2d = np.loadtxt(test_x_location, dtype="uint8", delimiter=",")
x_test_3d = x_test_2d.reshape(-1,28,28,1)
x_test = x_test_3d
y_test = np.loadtxt(test_y_location, dtype="uint8", delimiter=",")
print("Pre processing testing data")
x_test = x_test / 255.0
# erosion
for image_index in range(x_test.shape[0]):
kernel = np.ones((2,2),np.uint8)
res = cv2.erode(x_test[image_index,:,:,:],kernel,iterations = 1)
res = res.reshape(-1,28,28,1)
x_test[image_index,:,:,:] = res
print("evaluate")
model.evaluate(x_test, y_test)
|
c40573d0eaaed88658b7e7c0ebe72df1a361448b | garret1evg/cousera_DB | /week3/problem4.py | 876 | 3.703125 | 4 | import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: document identifier
# value: document contents
key = record[0]
friend = record[1]
#emit main relationship
mr.emit_intermediate(key, record);
#emit friend relationship to check non-sym
mr.emit_intermediate(friend, record);
def reducer(key, list_of_values):
# key: word
# value: book
for v in list_of_values:
nonRel=[v[1],v[0]]
if nonRel not in list_of_values:
if v[0] == key:
mr.emit((v[0],v[1]))
else:
mr.emit((v[1],v[0]))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
14e348d7ea30d522b9646e29dc194b9cea8da561 | BIOSBrothers/IS-105_2016_Gruppe1 | /ICA05/Search5 copy.py | 497 | 3.609375 | 4 | from timeit import Timer
def fillList(l, n):
l.append(range(1, n + 1))
l = []
fillList(l, 100)
def search_fast(l):
for item in l:
if item == 10:
return True
return False
def search_slow(l):
return_value = False
for item in l:
if item == 10:
return_value = True
return return_value
t = Timer(lambda: 10 in l)
print(t.timeit())
t = Timer(lambda: search_fast(l))
print t.timeit()
t = Timer(lambda: search_slow(l))
print t.timeit() |
6db846e0b92683c11ad70b82d6ec926f37844fb0 | Bhawna4tech/Smart-Audio-Book-Reader | /rpi_shutdown.py | 415 | 3.765625 | 4 | #!/usr/bin/python
# Import the modules to send commands to the system and access GPIO pins
import RPi.GPIO as gpio
import os
#Set pin numbering to board numbering
gpio.setmode(gpio.BOARD)
#Set up pin 15 as an input
gpio.setup(13, gpio.IN) ###GPIO PIN FOR SHUT DOWN
# Set up an interrupt to look for pressed button
gpio.wait_for_edge(13, gpio.FALLING)
def shut_down():
# Shutdown
os.system('shutdown now -h')
|
dc573ba68e7849479839dc2d255f827500bc09bc | kodyamani/ChatBox | /ChatBox.py | 954 | 3.9375 | 4 | def intro():
print("Hey! I'm Penelope")
def process_input(solution):
greeting = ["hi", "hello", "what's up", "hello", "wessup", "wassup", "hey"]
goodbye = ["bye", "see ya", "kick rocks", "goodbye"]
if is_valid_input(solution, greeting):
say_greeting()
elif is_valid_input(solution, goodbye):
say_goodbye()
else:
say_default()
def say_greeting():
print("Hey There!")
def say_goodbye():
print("Goodbye!")
def say_default():
print("Greet me some other way :(.")
def is_valid_input(user_input, valid_responses):
for item in valid_responses:
if user_input == item:
return True
return False
def main():
intro()
while True:
answer = input("(Say something)")
answer = answer.lower()
process_input(answer)
def outro():
print("Goodbye!")
if __name__ == "__main__":
main()
|
026f40e779d1da1faabc471f22cc52cb33b3d84b | mduanaa/IoT | /Linux/echo_server.py | 1,067 | 3.53125 | 4 | import socket
import sys
# local_host = '127.0.0.1'
port = 49999
# create TCP/IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to the port
server_address = ('localhost', port)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# call listen() to push into server mode and accept () for incoming connection
# listen for incoming connections
sock.listen(1)
while True:
# wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
# recv data
try:
print('connection from', client_address)
while True:
data = connection.recv(1024)
print('received {!r}'.format(data))
if data:
print('sending data back to the client')
connection.sendall(data)
else:
print('no more data from', client_address)
break
finally:
# clean up the connection
print(sys.stderr, 'closing socket')
connection.close()
|
2a82df7420aada6ffbc3e3979026470ebd989c3b | StaticNoiseLog/python | /calculus_basic/derivative_and_integral.py | 622 | 3.84375 | 4 | def f(x):
return x**2
def derivative(x):
h = 1./1000.
rise = f(x+h) - f(x)
run = h
slope = rise / run
return slope
def integral(startingx, endingx, numberOfRectangles):
width = (float(endingx) - float(startingx)) / numberOfRectangles
runningSum = 0
for i in range(numberOfRectangles):
# each rectangle is 'width' after previous one
height = f(startingx + i*width)
area = height * width
runningSum += area
return runningSum
print(derivative(1))
print(derivative(2))
print(derivative(3))
print(integral(0, 1, 10000))
|
38c96eb9aa0327766b82b18b0a9cee213a4e5554 | rfabio8770/tkintersimple | /main.py | 920 | 3.859375 | 4 | from tkinter import Tk, Label, Entry, Button
ventana = Tk()
ventana.title("Ejemplo de Place")
ventana.geometry("400x200")
def fnsuma():
num1 = txt1.get()
num2 = txt2.get()
num3 = float(num1) + float(num2)
txt3.delete(0,'end')
txt3.insert(0, num3)
lbl1 = Label(ventana, text="Primer número:",bg="yellow")
lbl1.place(x=10,y=10,width=100,height=30)
txt1 = Entry(ventana, bg="pink")
txt1.place(x=120, y=10, width=100, height=30)
lbl2 = Label(ventana, text="Segundo número:",bg="yellow")
lbl2.place(x=10,y=50,width=100,height=30)
txt2 = Entry(ventana, bg="pink")
txt2.place(x=120, y=50, width=100, height=30)
btn = Button(ventana, text="Sumar",command=fnsuma)
btn.place(x=230, y=50,width=80, height=20)
lbl3 = Label(ventana, text="Resultado:",bg="yellow")
lbl3.place(x=10,y=120,width=100,height=30)
txt3 = Entry(ventana, bg="pink")
txt3.place(x=120, y=120, width=100, height=30)
ventana.mainloop() |
cabc1f11a7d69bdd776e1a1d6c5b4db78bff24ed | mahimasunny/home_security | /project/motion_detector.py | 1,564 | 3.5 | 4 | # This file implements the motion detector functionality
import RPi.GPIO as gpio
import io
import picamera
import cv2
import time
import numpy
import face_recognition_impl
from IPython.display import display
from PIL import Image, ImageDraw
import datetime
led=17
# pin 18 is connected to the PIR sensor OUT pin
pir=18
HIGH=1
LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(led, gpio.OUT) # initialize GPIO Pin as outputs
gpio.setup(pir, gpio.IN) # initialize GPIO Pin as input
data=""
# This function is used to capture the image when the PIR sensor detects motion
# Inpout arguments: None
# Output arguments: None
def capture_image():
data= time.strftime("%d_%b_%Y|%H:%M:%S")
print('Camera taking picture')
camera = picamera.PiCamera()
camera.start_preview()
time.sleep(5)
camera.capture('./output/motion_detected.jpg')
camera.stop_preview()
print('Picture saved')
if not face_recognition_impl.check_if_known_face('./output/motion_detected.jpg'):
print("Intruder detected")
b = datetime.datetime.now()
print('Total time taken is ', b-a)
gpio.output(led , 0)
i=0
while 1:
if gpio.input(pir)==1:
# motion detected
# pin 18 is high
# starting timer
a = datetime.datetime.now()
gpio.output(led, HIGH)
print('Motion detected')
capture_image()
while(gpio.input(pir)==1):
time.sleep(1)
else:
# motion not detected
gpio.output(led, LOW)
time.sleep(0.01)
|
cef6065e9ae5e7e0d5cd0014d0bf947ad6cbe7ab | Mon8Cats/Python100Days | /Study/object_oriented/class_test.py | 2,603 | 4.0625 | 4 |
class BookShelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"Bookself with {len(self.books)} books."
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Book {self.name}"
book = Book("Harry Potter")
book2 = Book("Python 101")
shelf = BookShelf(*[book, book2]) # or BookShelf(book, book2)
print(shelf)
'''
class Device:
def __init__(self, name, connected_by):
self.name = name
self.connected_by = connected_by
self.connected = True
def __str__(self):
return f"Device {self.name!r} ({self.connected_by})"
def disconnected(self):
self.connected = False
print("disconnnected")
class Printer(Device):
def __init__(self, name, connected_by, capacity):
super().__init__(name, connected_by)
self.capacity = capacity
self.remaining_pages = capacity
def __str__(self):
return f"{super().__str__()} ({self.remaining_pages} pages remaining)"
def print(self, pages):
if not self.connected:
print("your printer is not connected!")
return
print(f"Printing {pages} pages")
self.remaining_pages -= pages
#printer = Device("Printer", "USB")
printer = Printer("Printer", "USB", 500)
printer.print(20)
print(printer)
printer.disconnected()
printer.print(100)
class ClassTest:
def instance_method(self):
print(f'called instance_method of {self}')
@classmethod
def class_method(cls):
print(f"called class_method of {cls}")
@staticmethod
def static_method():
print("called static_method")
myobj = ClassTest()
ClassTest.instance_method(myobj)
myobj.instance_method()
ClassTest.class_method()
ClassTest.static_method()
class Book:
TYPES = ('hardcover', 'paperback') # class properties
def __init__(self, name, book_type, weight):
self.name = name
self.book_type = book_type
self.weight = weight
def __repr__(self):
return f"<Book {self.name}, {self.book_type}, weighing {self.weight}g>"
@classmethod # use as a factory method
def hardcover(cls, name, page_weight):
return cls(name, cls.TYPES[0], page_weight + 100)
@classmethod # use as a factory method
def paperback(cls, name, page_weight):
return cls(name, cls.TYPES[1], page_weight)
print(Book.TYPES)
book = Book("Harry Potter", "hardcover", 1500)
print(book)
book2 = Book.hardcover("Harry Potter", 1500)
print(book2)
book3 = Book.paperback("Harry Potter", 1500)
print(book3)
'''
|
c7901abc836b8bdf8a257df906a6d1b47096fe23 | jessie-JNing/Algorithms_Python | /Recursion_DP/Fibonacci_robotXY.py | 1,293 | 4.46875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Imagine a robot sitting on the upper left corner of a X by Y grid.
The robot can only move in two directions: right and down.
How many possible path are thre for the robot to go
from (0,0) to (X, Y)?
FOLLOW UP:
Imagine certain spots are "off limits", such that the robot can not
step on them. Desgin an algorithm to find a path for the robot from
from the top left to bottom right.
@author: Jessie
@email: jessie.JNing@gmail.com
"""
import random
def isFree(x, y):
#return True if random.randint(0, 1)==1 else False
return True
def robot_move(x, y):
if x > y:
return robot_move(y, x)
else:
numerator = 1
denominator = 1
for i in range(x):
numerator *= (x + y -i)
denominator *= (x - i)
return numerator/denominator
# find out the path in maze with stuck
def find_path(x, y, path):
path.append((x, y))
if x==0 and y == 0:
return True
success = False
if x >0 and isFree(x-1, y):
success = find_path(x-1, y, path)
if not success and y>0 and isFree(x, y-1):
success = find_path(x, y-1, path)
if success:
path.append((x, y))
return success
if __name__=="__main__":
print "robot_move(2, 2)", find_path(10, 4, []) |
c63b6402e84f5761cdf7654e7f8d0bf641e3dc8d | MuideenAM/MyPythonWorks | /tryme4.py | 359 | 3.78125 | 4 | def new_line():
print('.')
def three_lines():
new_line()
new_line()
new_line()
def nine_lines():
three_lines()
three_lines()
three_lines()
def clear_screen():
print('Calling clear_screen()')
i = 1
while(i <= 2):
nine_lines()
three_lines()
i += 1
new_line()
print('Printing nine lines')
nine_lines()
clear_screen()
|
51a5bce89e79e41ed0ffde5c6af8e2e05602e83b | daniel-reich/ubiquitous-fiesta | /KQe5w8AdSLbweW8ck_20.py | 387 | 3.578125 | 4 |
def char_at_pos(r, s):
if type(r)==list:
if s=='even':
return [r[i] for i,j in enumerate(r) if i%2!=0]
else:
return [r[i] for i in range(len(r)) if i%2==0]
else:
if s=='even':
return ''.join([r[i] for i,j in enumerate(r) if i%2!=0])
else:
return ''.join([r[i] for i in range(len(r)) if i%2==0])
|
89c15deca8a59ab75b308974f3fc63b96e8b96cf | betuppumo/sxpt | /python/5-1/2.py | 516 | 4.15625 | 4 | class People:
# 请在下面填入声明两个变量名分别为name和country的字符串变量的代码
#********** Begin *********#
#********** End **********#
def introduce(self,name,country):
self.name = name
self.country = country
print("%s来自%s" %(name,country))
name = input()
country = input()
# 请在下面填入对类People进行实例化的代码,对象为p
#********** Begin *********#
p=People()
#********** End **********#
p.introduce(name,country)
|
61393f769fbc92271fc4d0a56ec55d86c388cf2d | pythonthings/lettersmith_py | /lettersmith/lens.py | 3,377 | 3.765625 | 4 | """
A minimal implementation of Haskel-style lenses
Inspired by Elm's Focus library and Racket's Lenses library.
Lenses let you create getters and setters for complex data structures.
The combination of a getter and setter is called a lens.
Lenses can be composed to provide a way to do deep reads and deep writes
to complex data structures.
"""
from collections import namedtuple
from functools import reduce
Lens = namedtuple("Lens", ("get", "put"))
Lens.__doc__ = """
Container type for Lenses.
A lens is any structure with `get` and `put` functions that
follow the lens signature.
"""
def _lens_compose2(big_lens, small_lens):
"""
Compose 2 lenses. This allows you to create a lens that can
do a deep get/set.
"""
def get(big):
"""
Lens `get` method (composed)
"""
return small_lens.get(big_lens.get(big))
def put(big, small):
"""
Lens `update` method (composed)
"""
return big_lens.put(
big,
small_lens.put(big_lens.get(big), small)
)
return Lens(get, put)
def lens_compose(big_lens, *smaller_lenses):
"""
Compose many lenses
"""
return reduce(_lens_compose2, smaller_lenses, big_lens)
def get(lens, big):
"""
Get a value from `big` using `lens`.
"""
return lens.get(big)
def put(lens, big, small):
"""
Set a value in `big`.
"""
return lens.put(big, small)
def over(lens, func, big):
"""
Map value(s) in `big` using a `mapping` function.
"""
return put(lens, big, func(get(lens, big)))
def over_with(lens, func):
"""
Given a lens and a function, returns a single-argument function
that will map over value in `big` using `func`, and returning
a new instance of `big`.
"""
def over_bound(big):
"""
Map value(s) in `big` using a bound mapping function.
"""
return over(lens, func, big)
return over_bound
def update(lens, up, big, msg):
"""
Update `big` through an update function, `up` which takes the
current small, and a `msg`, and returns a new small.
"""
return put(lens, big, up(get(lens, big), msg))
def key(k, default=None):
"""
Lens to get and set a key on a dictionary, with default value.
Because it allows for a default, it technically violates the
lens laws. However, in practice, it's too darn useful not to have.
"""
def get(big):
"""
Get key from dict
"""
return big.get(k, default)
def put(big, small):
"""
Put value in key from dict, returning new dict.
"""
# Check that we're actually making a change before creating
# a new dict.
if big.get(k, default) == small:
return big
else:
return {**big, k: small}
return Lens(get, put)
def _pick(d, keys):
return {k: d[k] for k in keys}
def keys(*keys):
"""
Lens to get and set multiple keys on a dictionary. Note that
no default values are allowed.
"""
def get(big):
"""
Get key from dict
"""
return _pick(big, keys)
def put(big, small):
"""
Put value in key from dict, returning new dict.
"""
patch = _pick(small, keys)
return {**big, **patch}
return Lens(get, put) |
be1e531d83c260837aefd67c3e7bc848dded41bb | ShourjaMukherjee/Dummy | /11thcodes/Remedials/10) Aaquib Pattern (1).py | 730 | 4.0625 | 4 | def pattern(n): #Defining a function to
#display the required pattern
for i in range(1,2*n,2):
for j in range(2*(n-1),i,-2): #range for spaces
print " ",
for k in range(1,i+1): #range for stars
print "*",
print
for a in range(2*n-2,-1,-2):
for b in range(2*(n-1),a-1,-2): #range for spaces
print " ",
for c in range(2,a+1): #range for stars
print "*",
print
z=int(raw_input("Enter the no. of terms "))
pattern(z)
|
3d59a6b2ca83bff422c742c023e691acce9fc3fb | manuelamercado/structures-algorithms-nanodegree-projects | /P1/task2.py | 2,565 | 3.5625 | 4 | """
Finding Files
For this problem, the goal is to write code for finding all files under a directory (and all directories beneath it) that end with ".c"
Here is an example of a test directory listing, which can be downloaded here:
./testdir
./testdir/subdir1
./testdir/subdir1/a.c
./testdir/subdir1/a.h
./testdir/subdir2
./testdir/subdir2/.gitkeep
./testdir/subdir3
./testdir/subdir3/subsubdir1
./testdir/subdir3/subsubdir1/b.c
./testdir/subdir3/subsubdir1/b.h
./testdir/subdir4
./testdir/subdir4/.gitkeep
./testdir/subdir5
./testdir/subdir5/a.c
./testdir/subdir5/a.h
./testdir/t1.c
./testdir/t1.h
Python's os module will be useful—in particular, you may want to use the following resources:
os.path.isdir(path) https://docs.python.org/3.7/library/os.path.html#os.path.isdir
os.path.isfile(path) https://docs.python.org/3.7/library/os.path.html#os.path.isfile
os.listdir(directory) https://docs.python.org/3.7/library/os.html#os.listdir
os.path.join(...) https://docs.python.org/3.7/library/os.path.html#os.path.join
Note: os.walk() is a handy Python method which can achieve this task very easily. However, for this problem you are not allowed to use os.walk().
Here is some code for the function to get you started:
"""
from genericpath import isfile
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
result = []
for file in os.listdir(path):
current_path = os.path.join(path, file)
if os.path.isfile(current_path) and current_path.endswith(suffix):
result.append(current_path)
elif os.path.isdir(current_path):
result.extend(find_files(suffix, current_path))
return result
result = find_files('.c', './testdir')
print('.c files ---->')
for file in result:
print(file)
# './testdir/subdir3/subsubdir1/b.c', './testdir/t1.c', './testdir/subdir5/a.c', './testdir/subdir1/a.c'
result = find_files('.h', './testdir')
print('.h files ---->')
for file in result:
print(file)
# './testdir/subdir3/subsubdir1/b.h', './testdir/subdir5/a.h', './testdir/t1.h', './testdir/subdir1/a.h'
result = find_files('.x', './testdir')
print('.x files ---->')
for file in result:
print(file)
# []
|
5efbfe09cbc9b17e9b92a8ca4af6b216d063794f | jessicahuang513/data_structures | /binarytree.py | 908 | 3.921875 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def add(self, val):
newNode = Node(val)
if(self.root == None):
self.root = newNode
else:
self._add(self.root, newNode)
def _add(self, root, node):
if(root.val > node.val):
if(root.left == None):
root.left = node
else:
self._add(root.left, node)
if(root.val <= node.val):
if(root.right == None):
root.right = node
else:
self._add(root.right, node)
def printTree(self):
if(tree.root != None):
self._printTree(self.root, 0)
def _printTree(self, root, count):
if(root != None):
self._printTree(root.left, count + 1)
print(" " * count + str(root.val))
self._printTree(root.right, count + 2)
tree = BinaryTree()
tree.add(3)
tree.add(2)
tree.add(9)
tree.add(-14)
tree.add(15)
tree.printTree() |
d51c6790c2bc701d0e0fd207099f2eacb8beb3a2 | coolsnake/JupyterNotebook | /new_algs/Sequence+algorithms/Selection+algorithm/A-FnReliefF.py | 605 | 4.3125 | 4 | #https://medium.com/@yashdagli98/feature-selection-using-relief-algorithms-with-python-example-3c2006e18f83
from ReliefF import ReliefF
import numpy as np
from sklearn import datasets
import pandas as pd
#example of multi class problem
iris = datasets.load_iris()
X = iris.data
Y = iris.target
fs = ReliefF(n_neighbors=20, n_features_to_keep=2)
X_train = fs.fit_transform(X, Y)
print("(No. of tuples, No. of Columns before ReliefF) : "+str(iris.data.shape))
print("(No. of tuples, No. of Columns after ReliefF) : "+str(X_train.shape))
print("\nDataFrame\n")
print(pd.DataFrame.from_records(X_train)) |
b244234b58d9af3cfb511d93d799cdaa54a3a4ce | PO6OTAHK/Pixel-Warships | /projectile/projectile.py | 577 | 3.65625 | 4 | import pygame
class Projectile(pygame.sprite.Sprite):
"""Класс описывающий снаряд, принимает скорость, урон, тип, координаты, размер, картинка, группы(групп неограниченное кол-во)"""
def __init__(self, speed, damage, typke, position, size, img, *groups):
super().__init__(*groups)
self.speed = speed
self.damage = damage
self.typke = typke
self.position = position
self.size = size
self.img = img
help(Projectile) |
3111767aa96403246f4a01e739684fefcde8b4cd | star428/python_learn_X2 | /function/define.py | 237 | 3.546875 | 4 | import math
def drop():
print("i am drop")
def my_sin(number):
if not isinstance(number, (int, float)):
raise ValueError("it's not number")
else:
return math.sin(number)
print(my_sin(45))
print(math.pi)
|
1a263ffb40e61b54e800069a9a41fd055be8adca | nilizadeh/twitter-glass-ceiling | /code/gender_by_name.py | 3,730 | 4.0625 | 4 | import os
import io
import sys
class gender():
def __init__(self, indir, outdir):
self.dir = indir
self.outdir = outdir
self.names_female = {}
self.names_male = {}
def get_names_counts(self):
'''
The names for each year are listed in a file.
Read all the files and combine the info from all the years.
names_female and names_male includes the names and
their counts as Female or Male in the Census data.
A name can be listed in both dictionaries.
'''
files = os.listdir(self.dir)
for file in files:
f = open(self.dir + "/" + file, "rw+")
print "file: ", f.name
lines = f.readlines()
for line in lines:
words = line.split(",")
firstname = words[0].strip().lower()
male_female = words[1].strip()
count = int(words[2].strip())
#print (firstname + ", " + male_female + ", " + str(count))
#count = 0
if male_female == "F":
if firstname in self.names_female.keys():
#print (firstname + ", " + str(count))
count += self.names_female[firstname]
self.names_female[firstname] = count
#print (firstname + ", " + str(count))
else:
if firstname in self.names_male.keys():
#print (firstname + ", " + str(count))
count += self.names_male[firstname]
self.names_male[firstname] = count
#print (firstname + ", " + str(count))
f.close()
def get_gender(self):
'''
After running get_names_counts() and getting the counts for each name,
we label a name as female or male based on their appearance in
names_female and names_male dictionaries.
Creates three files as an output:
ambiguous-names.txt, female-1900-2013.txt and male-1900-2013.txt.
'''
print("Female Names: " + str(len(names_female.keys())))
print("Male Names: " + str(len(names_male.keys())))
overlap = open(self.outdir + "/ambiguous-names.txt", "wb")
female = open(self.outdir + "/female-1900-2013.txt", "wb")
for name in names_female:
percentage = 1
if name in names_male.keys():
female_count = names_female[name]
male_count = names_male[name]
percentage = female_count/float(female_count + male_count)
#print(percentage)
overlap.write(name +", " + "%.2f" %percentage +"\n")
if percentage >= 0.95:
female.write(name + "\n")
female.close()
male = open(self.outdir + "/male-1900-2013.txt", "wb")
for name in names_male:
percentage = 1
if name in names_female.keys():
female_count = names_female[name]
male_count = names_male[name]
percentage = male_count/float(female_count + male_count)
overlap.write(name + ": " + "%.2f" %percentage +"\n")
if percentage >= 0.95:
male.write(name+ "\n")
male.close()
overlap.close()
def get_quantified_gender(self):
'''
Computes a probablity for a name to be Male.
If it is equal to 1, it means the name has been used for males.
If it is equal to 0, it means the name has been used for females.
'''
for name in self.names_female:
print name,
outfile = open(self.outdir + "/quantified_gender_1900_2013.txt", "wb")
names = list(set(self.names_female.keys()) | set(self.names_male.keys()))
#names.add(self.names_female.keys())
#names.add(self.names_male.keys())
for name in names:
percentage = 0
female_count = 0
male_count = 0
if name in self.names_female.keys():
female_count = self.names_female[name]
if name in self.names_male.keys():
male_count = self.names_male[name]
percentage = male_count/float(female_count + male_count)
outfile.write(name + ": " + "%.2f" %percentage +"\n")
outfile.close()
if __name__ == "__main__":
obj = gender(sys.argv[1], sys.argv[2])
obj.get_names_counts()
obj.get_gener()
obj.get_quantified_gender()
|
6e959809bfe55899f1e93cfa63fbd8e405fce7f0 | dhackner/Fun-Puzzles | /AllPossiblePaths.py | 1,972 | 3.578125 | 4 | #!/usr/bin/env python
"""Number of nonintersecting paths in an n X n grid from (0, 0) to (n, n)
1x1 = 1
2x2 = 2
3x3 = 12
4x4 = 184
5x5 = 8512
This pattern is OEIS A007764 - number of nonintersecting (or self-avoiding) rook paths joining opposite corners of an n X n grid
(according to OEIS):
6x6 = 1262816
7x7 = 575780564
"""
from copy import deepcopy
__author__ = "Dan Hackner"
__maintainer__ = "Dan Hackner"
__email__ = "dan.hackner@gmail.com"
__status__ = "Production"
gridSize = 4
debug = False#True
# DRH | Note to self: This line is equivalent to nesting the list comprehensions,
# but [['x'] * gridSize] * gridSize DOESN'T work because the outer array
# doesn't make deep copies of the inner array =-/.
grid = [(['x'] * gridSize) for x in range(gridSize)]
def num_paths(ingrid, x=0, y=0, step_counter=1):
"""Number of total nonintersecting paths from (0,0) to (n,n)."""
ingrid[x][y] = step_counter
if debug:
print_grid(ingrid)
if x == y == (gridSize-1):
if debug:
print_grid(ingrid, True)
return 1
else:
total_paths_cell = 0 # Number of combined paths from surrounding cells
for (x2, y2) in get_steps(ingrid, x, y):
total_paths_cell += num_paths(deepcopy(ingrid), x2, y2, step_counter + 1)
return total_paths_cell
def get_steps(g, x, y):
"""Yield all steps from this position that haven't already been used."""
if x-1 >= 0 and g[x-1][y] == 'x':
yield (x-1, y)
if x+1 < len(g) and g[x+1][y] == 'x':
yield (x+1, y)
if y-1 >= 0 and g[x][y-1] == 'x':
yield (x, y-1)
if y+1 < len(g[x]) and g[x][y+1] == 'x':
yield (x, y+1)
def print_grid(g, success=False):
if success:
print '---SUCCESS---'
for y in range(0, len(g[0])):
for x in range(0, len(g)):
print '%s ' % g[x][y],
print ""
if success:
print '---SUCCESS---'
print ""
print '=== Total number of paths: %s' % num_paths(grid)
|
e7b05d6b3399d423d199cb20fdc74880d291e1ed | Totoro2205/python-rush-tasks | /level-1/task-1/task-1-44-1.py | 459 | 4.0625 | 4 | #!/usr/bin/env python3
#coding: utf-8
"""
Решение без проверок на ошибки ввода
"""
print('Расчет площади и периметра прямоугольника')
a = float(input('Введите первое число:'))
b = float(input('Введите второе число:'))
print("Площадь прямоугольника: ", a * b)
print("Периметр прямоугольника: ", 2 * a + 2 * b)
|
ae4751999f65ec7fc7341d428c016c6595b78ef1 | hestad/advent-of-code | /2018/day8/day8_tree.py | 1,754 | 3.5625 | 4 | from dataclasses import dataclass
from typing import List
@dataclass
class Node:
children: List[any]
metadata: List[int]
def metadata_sum(self) -> int:
return sum(self.metadata)
def has_no_children(self) -> bool:
return len(self.children) == 0
def children_count(self):
return len(self.children)
def read_input() -> List[int]:
with open('day8.txt') as f:
return list(map(int, f.readlines()[0].split(' ')))
def read_tree(input: List[int]) -> (Node, int):
metadata = input[1]
start_index = 2
end_index = len(input) - metadata
children = []
for i in range(input[0]):
result = read_tree(input[start_index:end_index])
children.append(result[0])
start_index += result[1]
return Node(children, input[start_index:start_index + metadata]), start_index + metadata
def tree_metadata_sum(node: Node) -> int:
total_sum = 0
for child in node.children:
total_sum += tree_metadata_sum(child)
return total_sum + node.metadata_sum()
def part1() -> int:
root = read_tree(read_input())[0]
return tree_metadata_sum(root)
def tree_value(node: Node) -> int:
total_sum = 0
childrenValues = []
for child in node.children:
childrenValues.append(tree_value(child))
if node.has_no_children():
total_sum += node.metadata_sum()
else:
for x in node.metadata:
if x > node.children_count() or x < 1:
continue
total_sum += childrenValues[x - 1]
return total_sum
def part2() -> int:
root = read_tree(read_input())[0]
return tree_value(root)
print(f"2018, day 8, part1: {part1()}") # 48155
print(f"2018, day 8, part2: {part2()}") # 40292
|
87fc10616dbec83ebee2fba200cdde45118b98e8 | ffionRichards/university_DataMining | /Question2.py | 878 | 3.59375 | 4 | from random import choice
from numpy import array, dot, random
from pylab import plot, ylim
#Creating a step function
stepfunction = lambda x: 0 if x < 0 else 1
#inputting training data
training_data = [ (array([-0.1,0.0]), 0),
(array([0.0,9.0]), 0),
(array([10.0,0.0]), 1),
(array([10.0,8.0]), 1),
]
#Altered weight due to incorrect output of second array
w = random.rand(2) - ([0.0,9.0])
#Error values
errors = []
#Variable controlling learning rate
eta = 0.2
#Number of iterations
n = 100
#Calculating the Dot Product to act like a function
for i in xrange(n):
x, expected = choice(training_data)
result = dot(w, x)
error = expected - stepfunction(result)
errors.append(error)
w += eta * x
#Printing results
for x, _ in training_data:
result = dot(x, w)
print("{}: {} -> {}".format(x[:2], result, stepfunction(result)))
|
2c552fcc2b2dfbd12efbacc0d159cf20dc0ee52a | sinadadashi21/Wave-1 | /making-change.py | 575 | 4.03125 | 4 | cost = int(input("Enter the number of cents: "))
toonies = cost // 200
after_toonies = cost % 200
loonies = after_toonies // 100
after_loonies = after_toonies % 100
quarters = after_loonies // 25
after_quarters = after_loonies % 25
dimes = after_quarters // 10
after_dimes = after_quarters % 10
nickels = after_dimes // 5
after_nickels = after_dimes % 5
pennies = after_nickels // 1
print("Your change is")
print("Toonies:", toonies)
print("Loonies:", loonies)
print("Quarters:", quarters)
print("Dimes:", dimes)
print("Nickels:", nickels)
print("Pennies:", pennies)
|
f044e58403cb79e4d7a13e597f2bffa81ec1e7a1 | flfelipelopes/Python-Curso-em-Video | /ex025.py | 164 | 3.96875 | 4 | #Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome.
nome = str(input('Digite o seu nome: ')).strip()
print('SILVA' in nome.upper())
|
eeee7b3c9aea694aadfffbacc942968bc2de5ded | pkenway/pearls | /3/datastructures.py | 1,328 | 3.609375 | 4 |
letter_definitions = {
'A' : [
'1*4- ,2-A,4- ',
'1*3- ,4-A,3- ',
'1*2- ,2-A,2- ,2-A,2- ',
'1*1- ,8-A-1- ',
'2*2-A,6- ,2-A'],
'I' : [
'3*6-I',
'3*2- ,2-I,2- ',
'3*6-I'],
}
def banner(letter):
if letter not in letter_definitions:
return None
definition = letter_definitions[letter]
rows = []
for block in definition:
print(block)
block_count = int(block[0])
chars = block[2:]
for row in range(0,block_count):
row_text = ''
for charset in chars.split(','):
print(charset)
set_parts = charset.split('-')
row_text += set_parts[1] * int(set_parts[0])
rows.append(row_text)
for row in rows:
print(row)
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def date_diff(date1, date2):
# just dealing with month/day here
return abs(get_day_of_year(date1) - get_day_of_year(date2))
def get_day_of_year(date):
date_parts = date.split('/')
month, day = int(date_parts[0]), int(date_parts[1])
year_day = 0
for i in range(0, month - 1):
year_day += days_per_month[i]
return year_day + day
if __name__ == '__main__':
print(date_diff('3/15','2/1')) |
1c579296c85e672599ebf8b8407fb2f7aaa10dd5 | jsh/fluent_python | /ch1/vector.py | 1,119 | 4.28125 | 4 | #!/usr/bin/env python
"""Demo infix operators, bool, abs, repr."""
from math import hypot
class Vector:
"""Vectors."""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return "Vector(%r, %r)" % (self.x, self.y)
def __bool__(self):
return bool(self.x or self.y)
def __abs__(self):
return hypot(self.x, self.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def magnitude(self):
"""Length of the vector.
:returns: length
:rtype: float
"""
return abs(self)
def main():
"""Everything interesting."""
v_00 = Vector(0, 0)
v_23 = Vector(2, 3)
v_45 = Vector(4, 5)
print(v_23)
print("[2, 3] is ", bool(v_23))
print("[0, 0] is ", bool(v_00))
print("[2, 3] + [4, 5] = ", v_23 + v_45)
print("[2, 3] * 10 = ", v_23 * 10)
print("magnitude of Vector(3,4) is ", Vector(3, 4).magnitude())
if __name__ == "__main__":
main()
|
c9770a1675f2c9fda09114327870bd122897c88f | mcnallyd/HackerRank | /solutions/array_left_rotation.py | 1,010 | 3.984375 | 4 | #https://www.hackerrank.com/challenges/ctci-array-left-rotation
def array_left_rotation(a, n, k):
"""
Rotate elements in an array of integers
n = number of i tegers in a
k = number of left rotations to perform
a = array of integers
"""
if (not a) or (k == 0) or (k%n == 0):
return a
k = k%n
a = a[k:] + a[:k]
return a
import unittest
class TestSolution(unittest.TestCase):
def test_array_left_rotation_empty_array(self):
expected = []
actual = array_left_rotation([], 0, 20)
self.assertEqual(expected, actual)
def test_array_left_rotation_k_less_than_n(self):
expected = [3,4,1,2]
actual = array_left_rotation([1,2,3,4], 4, 2)
self.assertEqual(expected, actual)
def test_array_left_rotation_k_greater_than_n(self):
expected = [1,2,3,4]
actual = array_left_rotation([1,2,3,4], 4, 12)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
ab75761833615b9fb934bb041abaa8bd5a3225d0 | chanyoonzhu/leetcode-python | /290-Word_Pattern.py | 666 | 3.53125 | 4 | """
- hashmap
- hashmap + hashset
- O(n), O(1)
"""
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(words) != len(pattern):
return False
mapping = {} # mapping: word -> char
assigned = set() # assigned char
for p, w in zip(list(pattern), words):
if w not in mapping:
if p in assigned: # easy to miss: bidirectional check
return False
mapping[w] = p
assigned.add(p)
else:
if mapping[w] != p:
return False
return True |
12369ededa7c946d6e9d85402ec1a05dfaf10707 | MingYanWoo/Leetcode | /146. LRU缓存机制.py | 2,847 | 3.796875 | 4 | # 146. LRU缓存机制
# 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
# 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
# 写入数据 put(key, value) - 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
# 进阶:
# 你是否可以在 O(1) 时间复杂度内完成这两种操作?
# 示例:
# LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
# cache.put(1, 1);
# cache.put(2, 2);
# cache.get(1); // 返回 1
# cache.put(3, 3); // 该操作会使得密钥 2 作废
# cache.get(2); // 返回 -1 (未找到)
# cache.put(4, 4); // 该操作会使得密钥 1 作废
# cache.get(1); // 返回 -1 (未找到)
# cache.get(3); // 返回 3
# cache.get(4); // 返回 4
class ListNode:
def __init__(self, x, key):
self.val = x
self.key = key
self.next = None
self.pre = None
class LRUCache:
def __init__(self, capacity: int):
self.head = ListNode(0, 'head')
self.tail = ListNode(0, 'tail')
self.head.next = self.tail
self.head.pre = None
self.tail.next = None
self.tail.pre = self.head
self.hash_map = {}
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self.hash_map:
return -1
self.move_to_head(self.hash_map[key])
return self.hash_map[key].val
def put(self, key: int, value: int) -> None:
if self.get(key) != -1:
self.hash_map[key].val = value
else:
if len(self.hash_map) >= self.capacity:
delete_node = self.tail.pre
delete_node.pre.next = self.tail
self.tail.pre = delete_node.pre
self.hash_map.pop(delete_node.key)
delete_node = None
node = ListNode(value, key)
self.head.next.pre = node
node.next = self.head.next
self.head.next = node
node.pre = self.head
self.hash_map[key] = node
def move_to_head(self, node):
pre = node.pre
next = node.next
pre.next = next
next.pre = pre
# move to head
self.head.next.pre = node
node.next = self.head.next
self.head.next = node
node.pre = self.head
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) |
d7f17ae6d03a2b5f5fa31c77c9cf44ee3f7ff953 | Oleksiy-Yurchenko/Habit-Tracker | /analytics.py | 1,059 | 3.703125 | 4 | """Module analytics contains functions tracked(), same_period(), longest_streak()."""
def tracked(habits_list, tracked_status=True):
"""Function takes a list with habits as an argument and returned the list of habits with the tracked status set to
True by default. If the flag tracked_status is set to false function will return a list of habits with the tracked
status set to False."""
return [habit for habit in habits_list if habit.tracked == tracked_status]
def same_period(habits_list, period):
"""Function takes a list with habits and period as arguments and returned the list of habits with the period.
Argument period is of type int. In current version it can be 1 - Daily or 7 - Weekly."""
return [habit for habit in habits_list if habit.period == period]
def longest_streak(habits_list):
"""Function takes a list with habits an returns a list containing a habit with the longest streak."""
streaks_list = sorted(habits_list, key=lambda habit: habit.longest_streak, reverse=True)
return streaks_list[:1]
|
e1abefe002d912289e320df2c53fdd887e57b211 | akash-ranjan8/PYTHON_CODES | /assert.py | 81 | 3.65625 | 4 | x=int(input("enter a number greater than 5"))
assert x>5,"invalid!!!!"
print(x) |
2f0d73be05e146da50a82edb69958efcb1421ca6 | md3sIam/vk_test | /Cluster.py | 977 | 3.765625 | 4 | class Cluster:
def __init__(self, x=None, clusters=None, diff=None):
if x is not None:
# creation a cluster by one point
self.height = 0
self.center = x
self.subclusters = []
self.left_point = x # to easily compute distances
self.right_point = x # to easily compute distances
return
else:
# creation a cluster by uniting 2 or more cluster
# where clusters is list of clusters in ascending order (left to right) to unite
# diff is a space between them
# both parameters are necessary
self.height = diff / 2
self.center = 0
for cluster in clusters:
self.center += cluster.center
self.center /= len(clusters)
self.subclusters = clusters
self.left_point = clusters[0].left_point
self.right_point = clusters[-1].right_point
|
bd9ea0976448b57b8f2cfe016435e8d065e77554 | chicory-gyj/JustDoDo | /pre_test/if.py | 133 | 3.84375 | 4 | #!/usr/bin/python
name=raw_input('enter your name:')
if name.endswith('chicory'): print 'hello,chicory'
else: print 'hello,strager'
|
d755f615039b736ac5b9098d1ee7f232891cd04a | cweiyu/a | /1.py | 526 | 3.703125 | 4 |
# coding: utf-8
# In[16]:
def reverse(word):
answer = ''
for i in word:
answer = i + answer
return(answer)
a= reverse("junyiacademy")
print(a)
# In[19]:
def reverse_2(word):
word = word + " "
alist = list()
answer_2 = ''
for i in word:
if i != ' ':
answer_2 = answer_2 + i
if i == ' ':
alist.append(answer_2)
answer_2 = ''
for d in alist:
print(reverse(d), end = ' ')
reverse_2("flipped class room is important")
|
c22b3209660298f22a28b4af6a9d96a207a0de50 | Wangbojia/CarPricePrediction | /temp01.py | 157 | 3.5 | 4 | class C:
def f1(self,a,b):
return a+b
class D:
def f1(self):
cc = C()
b=cc.f1(1,2)
return b
dd = D()
print(dd.f1()) |
2f87f80e9d2dc7a45d60b6d5b143fb0e53d409a2 | ishita-kumar/Applied-Algorithms-Code | /weighted scheduling.py | 2,587 | 3.8125 | 4 | import sys
from operator import itemgetter
# AIM : You are given a set of jobs. Each job i has a start time si and a finish time fi. It also has a weight wi.
# Two jobs are compatible if their start-finish intervals don't overlap. The goal is to find the maximum weight
# subset of mutually compatible jobs (a subset with the maximum sum of weights).
# Run your program on the two inputs provided. You have to output only the maximum weight, not the
# actual subset. Each input file contains multiple lines, where each line contains three numbers describing a
# job: si; fi;wi. Each of these numbers is an integer between 1 and 200.
# Returns a list of list
# input test file is a list with
# start time (s(i)), finish time (f(i))
# and weight (w(i)).
# job = [job[s(1),f(1),w(1)],job[s(2),f(2),w(2)],
# .....job[s(n),f(n),w(n)]]
def load_inputtxt(filename):
job = []
with open(filename, "r") as file:
for line in file:
line = line.split()
if line:
line = [int(i) for i in line]
job.append(line)
return job
# Binary search will return most optimal job
# that has start time less than the previous
# jobs finish time
def binarySearch(job, start):
lo = 0
hi = start - 1
while lo <= hi:
mid = (lo + hi) // 2
if job[mid][1] <= job[start][0]:
if job[mid + 1][1] <= job[start][0]:
lo = mid + 1
else:
return mid
else:
hi = mid - 1
# If optimal job not found
return -1
# Return_max will return the most optimal job
# from around its neighbours
def return_max(job):
# Itemgetter imported from operations that returns
# the sorted jobs array according to the least finish time
job= sorted(job, key=itemgetter(1))
# Array weight_table[i] will store the weights of the ith job
n = len(job)
weight_table = [0 for _ in range(n)]
# adding job with the least finish time into
# the weight_table array
weight_table[0] = job[0][2];
for i in range(1, n):
# If current job is included
with_prof = job[i][2]
l = binarySearch(job, i)
# If optimal job is not found
if (l != -1):
with_prof += weight_table[l];
# Find max weight from when a job is included and not included.
weight_table[i] = max(with_prof, weight_table[i - 1])
return weight_table[n-1]
if __name__ == "__main__":
job=load_inputtxt(sys.argv[1])
print(return_max(job))
|
12ca7e83286e59ee6eaced776cb2c6d154b2d4c3 | jhyang12345/algorithm-problems | /google_prep/dfs_stack.py | 475 | 3.90625 | 4 | def dfs(graph, cur):
visited = {}
stack = []
stack.append(cur)
while stack:
s = stack.pop()
if s not in visited:
print(s)
visited[s] = True
for node in graph[s]:
if node not in visited:
stack.append(node)
# https://www.geeksforgeeks.org/iterative-depth-first-traversal/
graph = {
1: [2, 3],
2: [4, 1],
3: [5, 6, 1],
4: [2],
5: [3],
6: [3],
}
dfs(graph, 1)
|
559dad97bc638486b651b431b391176568a23071 | zhanghua7099/LeetCode | /88.py | 941 | 4.375 | 4 | '''
题目:合并两个有序数组
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
'''
'''
示例:
输入: nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
'''
def merge(nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
if nums1[m-1] > nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m = m - 1
else:
nums1[m+n-1] = nums2[n-1]
n = n - 1
return nums1
print(merge([1,2,3,0,0,0],3,[2,5,6],3))
|
4ce6fd37558c24355ce9257ad917614c25e7dfd4 | sasadangelo/pythonbyexamples | /examples/for/for.py | 1,545 | 4.625 | 5 | letters=['a','b','c','d']
# For loops through the list, element by element, and print it.
# end =" " --> print without new line
for s in letters:
print(s, end =" ")
# Print a new line
print()
# The enumerate function return two value:
# - the index of the element
# - the element
for i, s in enumerate(letters):
print(i, s)
# range is a generator function that return the list
# [0, 1, 2, 3, 4]
# in this example, the for loops through it
for i in range(5):
print(i, end =" ")
# Print a new line
print()
# The function range can start from any number. For example,
# range(5, 10)=[5, 6, 7, 8, 9]
for i in range(5,10):
print(i, end =" ")
# Print a new line
print()
# The function range, by default, increment by 1 but you
# can skip by any number. For example:
# range(0,10,2)=[0,2,4,6,8]
for i in range(0,10,2):
print(i, end =" ")
# Print a new line
print()
# You can use continue in for loop like in C.
# It run the next for loop.
for i in range(5):
if (i%2==0):
print(f"{i} is an even number.")
else:
continue
# You can use else with for loop. It
# will be executed at the end of the loop.
for i in range(5):
print(i, end =" ")
else:
print("end loop")
# This example prints the numbers: 0, 1, 2, 3, 4.
# When i==5 it breaks and the else clause is not run.
# A rule of the for loop is that if break is executed
# the else clause is not run.
# It run the next for loop.
for i in range(10):
if (i==5):
break
else:
print(i, end =" ")
else:
print("end loop")
|
5bcbe6fb19d30be80e07b8357ab1a3246766fcea | jamilemerlin/exercicios_python | /CursoemVideo/e078.py | 626 | 3.953125 | 4 | valorlista = []
for contador in range(0, 5):
valorlista.append(int(input(f'Digite um número para a posição {contador}: ')))
print(f'Os números digitados são: {valorlista}')
ordenada = valorlista[:]
ordenada.sort()
menor = ordenada[0]
maior = ordenada[-1]
print(f'O menor número foi {menor} e está na posição ', end='')
for indice, valor in enumerate(valorlista):
if valor == menor:
print(f'{indice}...', end='')
print()
print(f'O maior número foi {maior} e está na posição ', end='')
for indice, valor in enumerate(valorlista):
if valor == maior:
print(f'{indice}...', end='')
print()
|
3a27480d99a0596fad958332ad990efd60377024 | youthcodeman/self-learning-python | /org.hzg.pyLearn/运算符/comparisonOperator.py | 193 | 3.84375 | 4 | #_*_ coding:utf-8 _*_
#比较运算符
num_a = 8
num_b = 56
print(num_a == num_b)
print(num_a != num_b)
print(num_a > num_b)
print(num_a >= num_b)
print(num_a < num_b)
print(num_a <= num_b)
|
2d9f892c82d30052ca7a2d3e5c9a982047afb937 | syn7hgg/ejercicios-python | /15_6/4.py | 1,645 | 3.703125 | 4 | class Student:
def __init__(self, name, rut, marks):
self.name = name
self.rut = rut
self.marks = marks
def get_name(self):
return self.name
def get_rut(self):
return self.rut
def get_marks(self):
return self.marks
def get_avg(self):
marks = self.marks
marks = [float(x) for x in marks]
avg = round(marks[0] * .2 + marks[1] * .2 + marks[2] * .05 + marks[3] * .2 + marks[4] * .25 + marks[5] * .1, 1)
return avg
def parse_data(filename):
students = []
file = open(filename+'.txt', 'r')
data = file.readlines()
for x in data:
parsed = x.split(';')
students.append(Student(
parsed[0],
parsed[1],
[
parsed[2],
parsed[3],
parsed[4],
parsed[5],
parsed[6],
parsed[7]
]
))
return students
def generate_lines(data):
lines = []
for x in data:
line = x.get_name()+','+x.get_rut()+','+str(x.get_avg())
lines.append(line)
return lines
def save_data(data, filename):
file = open(filename+'.txt', 'w')
for x in data:
file.write(x+'\n')
return print("Archivo TXT generado correctamente.")
def save_csv(data, filename):
file = open(filename+'.csv', 'w')
file.write("RUT,NOMBRE,NP\n")
for x in data:
file.write(x+'\n')
return print("Archivo CSV generado correctamente.")
students = parse_data('estudiantes')
lines = generate_lines(students)
save_data(lines, 'NP')
save_csv(lines, 'NP_csv')
|
bc2650f4d9de243d59170e315f3fd644e8df9537 | Doublespe11/MiniProjects | /Basic MiniProjects/calculator.py | 288 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 23:50:27 2019
@author: Michał
"""
while True:
evaluation = input()
if evaluation.startswith("q"):
break
if "^" in evaluation:
evaluation=evaluation.replace("^","**")
print(eval(evaluation)) |
45507e47d9145dc653194fa746234a9277857819 | Rory-git-hub/New_Repos | /DSSK2 - Assignment A..py | 1,670 | 3.515625 | 4 | def bs_func(data,func,size):
n = len(data)
bs_reps = np.empty(size)
for i in range(size):
bs_reps[i] = func(np.random.choice(data, size=n))
return bs_reps
#-- This is the bootstrap resampling function, which takes three arguments.
#-- By iterating over an empty numpy array we can store each sample which has a function, func, applied to it.
if __name__ == '__main__': #-- The main guard allows us to use the bs_func again without any baggage
import pandas as pd
import numpy as np
df = pd.read_csv("gandhi_et_al_bouts.csv",skiprows = 4) #--import csv using pandas
numpy_array = np.array(df) #--converting to a numpy array allows easy use of simple indexing
bout_length_wt = [value[1] for value in numpy_array if value[0] == 'wt'] #-- getting a list of the bout lengths of wild type fish
bout_length_mut = [value[1] for value in numpy_array if value[0] == 'mut']
mean_wt = np.mean(bout_length_wt) #-- Taking the mean before we resample
mean_mut = np.mean(bout_length_mut)
bs_reps_mut = bs_func(bout_length_mut,np.mean,10000) #--using the bs_func function to draw bootstrap replicates
bs_reps_wt = bs_func(bout_length_wt,np.mean,10000)
conf_int_wt = np.percentile(bs_reps_wt,[2.5,97.5]) #--create confidence intervals
conf_int_mut = np.percentile(bs_reps_mut,[2.5,97.5])
print('The confidence intervals are ',conf_int_wt,' and ',conf_int_mut,' for wild and mutant type respectively')
print('The means of the initial data: wt = ',mean_wt,', mut = ',mean_mut)
print('The means of the resampled data: wt = ',bs_reps_wt,', mut = ',bs_reps_mut)
|
727ed203e2c04978bf2adc046086c20074fb3703 | kevinmandich/Bengal | /skyscrapers.py | 641 | 3.53125 | 4 | ## skyscrapers.py
## Challenge # 120
import os
import sys
with open(os.getcwd()+'\\skyscrapers_example.txt', 'r') as lines:
#with open(sys.argv[1], 'r') as lines:
testCases = lines.read().splitlines()
for bld in testCases:
sky = {}
sky[0] = 0
for nums in bld.split(';'):
nums = nums.strip('(').strip(')')
low = int(nums.split(',')[0])
height = int(nums.split(',')[1])
high = int(nums.split(',')[2])
for x in range(low, high+1):
try:
if height > sky[x]:
sky[x] = height
except:
sky[x] = height
|
c177d09e782edabec8c2e3b1e082542d13038c95 | daveinnyc/various | /python-practice/debugger.py | 305 | 3.59375 | 4 | # Some code to use with pdb
# Use with: python3 -m pdb debugger.py
def adder(number):
plus_one = number + 1
return plus_one
def loops(number):
var_sum = 0
for i in range(number):
var_sum += adder(i)
return var_sum
if __name__ == "__main__":
print(f"Result: {loops(4)}")
|
6935e2dc8972447435618e95aa2c27aeb4478f50 | ShinjiKatoA16/azuma-python2 | /for4-06-var1.py | 382 | 3.75 | 4 | # python2 P37 for4-06 variation, change outer loop to while, it is easier to understand to use 2-d for loop
number = int(input('input number => '))
# row = (number+4)//5
while number > 0:
out_s = ''
for col in range(1,6):
if number > 0: # need to process more?
out_s += str(col)
number -= 1
else:
break
print(out_s) |
6d4386e94a65dedd65ba711e6a716bddcdadbd49 | mk777/haar_trees | /coint_stat.py | 1,365 | 3.5 | 4 | from __future__ import with_statement
from math import sqrt
import sys
def read_data(filename):
"""reads the file of results printed by haar_coint"""
result={}
with open(filename,'r') as file:
for l in file:
(n,s,vec)=l.partition('[');
if s:
result.setdefault(int(n),[]).append(
[float(num) for num in vec.split(' ')[:-1]])
return result
def result_avg(res_data):
"""averages the results for each key"""
return dict((k,map(lambda x: sum(x)/float(len(x)),zip(*v))) for k,v in
res_data.iteritems())
def result_std_div(res_data,res_avg):
"""returns std diviation for each component for each key"""
aux = dict((k,zip(res_avg[k],zip(*v))) for k,v in res_data.iteritems())
return dict((k,map(lambda (a,lst) :
sqrt(sum(map(lambda x: (x-a)*(x-a),lst))/(len(lst)-1.0)),v))
for k,v in aux.iteritems())
def print_stats(avg,stdev):
"""pretty prints the stats"""
for k in avg.keys():
print str(k)+": avg\t["+ " ".join(map(lambda x: "%.4f" % x,avg[k]))+"]"
print " stdev\t[" +" ".join(map(lambda x: "%.4f" % x,stdev[k]))+"]"
if __name__ == "__main__":
filename=sys.argv[1]
d=read_data(filename)
avg=result_avg(d)
stdev=result_std_div(d,avg)
print_stats(avg,stdev)
|
ba1fb9c86a1298ac19a065a7f3981bd91b268d74 | simonchuth/mutation_frequency | /src/plot_gene.py | 5,174 | 3.75 | 4 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mutation_frequency(site_list, gene_size, density=True, gene_name='', mutation_type=''):
"""To plot the mutation frequency of a gene
Args:
site_list (list of int): list containing sites of mutation
gene_size (int): the size of the gene of interest
density (bool, optional): Plot as density for cumulative frequency graph. Defaults to True.
gene_name (string, optional): Name of the gene. Defaults to ''.
mutation_type (string, optional): Type of mutation. Defaults to ''.
"""
values, base = np.histogram(site_list, bins=gene_size, density=density)
cumulative = np.cumsum(values)
plt.plot(base[:-1], cumulative, c='blue')
x_ticks = np.arange(0, gene_size, 100)
plt.xticks(x_ticks)
plt.xlim([0,gene_size])
plt.title(f'{gene_name} {mutation_type} Mutation Frequency')
plt.xlabel('Amino Acid Position')
plt.ylabel('Cumulative frequency')
def plot_cancer_type_freq(cancer, gene_name='', mutation_type=''):
"""Plot the mutation frequency by cancer type
Please download the stock image from the following URL before
using this class.
https://www.freepik.com/free-vector/human-anatomy-model-with-different-systems_4805791.htm
Args:
cancer (pandas series): perform a value_counts on the pandas df on cancer type
gene_name (string, optional): Name of the gene. Defaults to ''.
mutation_type (string, optional): Type of mutation. Defaults to ''.
"""
plt.figure(figsize=(15,10))
cancer.plot.bar()
plt.title(f'{gene_name} {mutation_type} Mutation Frequency')
plt.xlabel('Types of Cancer')
plt.ylabel('Frequency of mutation')
plt.tight_layout()
class Plot_site:
"""To plot the sites of cancer and frequency of
incidence (mutation/amplification..etc)
"""
def __init__(self):
self.site_dict = {'Brain': [1150, 300],
'Breast': [3800, 2300],
'Liver': [1000, 2700],
'Cervix': [3400, 4250],
'Lung': [800, 2000],
'Uterus': [3400, 4000]}
def get_site_dict(self):
"""Get the site_dict from class
Returns:
site_dict: dictionary of site name, and the coordinate
"""
return self.site_dict
def update_site_dict(self,site_dict):
"""Update the site_dict
Args:
site_dict (dict): dictionary with keys as site name, and
value and coordinates
"""
self.site_dict = site_dict
def map_site(self, df):
"""Map the site in df to coordinates in picture
Args:
df (pandas df): df of at least two columns
-site: primary site of cancer
-frequency: frequency of incidence
(mutation/amplification..etc)
Returns:
df (pandas df): df with an additional column 'coordinate'
"""
if 'site' not in df.columns:
print("Error! There is no column 'site'. Please ensure the \
dataframe contains 'site' and 'frequency'")
df['coordinate'] = df['site'].map(self.site_dict)
return df
def plot_site(self, df, img_path, size=2000, cmap=plt.cm.PiYG, figsize=(15,10)):
"""Plot a scatter plot on top of the stock image
Args:
df (pandas df): df of at least three columns
-site: primary site of cancer
-frequency: frequency of incidence
(mutation/amplification..etc)
-coordinate: coordinate of site on stock image
img_path (string): datapath to the stock image
*Please download the stock image from
https://www.freepik.com/free-vector/human-anatomy-model-with-different-systems_4805791.htm
size (int, optional): size of the scatterplot points. Defaults to 2000.
cmap (plt.cm maps, optional): plt.cm colour map. Defaults to plt.cm.PiYG.
figsize (tuple, optional): size of figure. Defaults to (15,10).
"""
if 'coordinate' not in df.columns:
df = self.map_site(df)
c_scale = 1/df.frequency.max()
img = plt.imread(img_path)
plt.figure(figsize=figsize)
plt.imshow(img)
for index, row in df.iterrows():
plt.scatter(row['coordinate'][0], row['coordinate'][1], c=cmap(np.array(row['frequency']*c_scale).reshape(1,)), s=row['frequency']*size)
plt.text(row['coordinate'][0]+200, row['coordinate'][1]+50, row['site'], fontsize=15, backgroundcolor='black', color='white')
plt.text(row['coordinate'][0]-100, row['coordinate'][1]+50,f'{round(row.frequency*100)}%', fontweight=800)
plt.tick_params(
bottom=False,
left=False,
labelleft=False,
labelbottom=False)
|
baca28082ccd70b164f0875f09026c9ef783928c | wileyj/public-python | /z-list_unique.py | 652 | 3.5 | 4 | class Solution(object):
def uniq(self, nums):
newlist = []
print "newlist: %s" % (newlist)
print "list_len: %i" % (len(nums))
for i in xrange(0,len(nums)):
print "i: %i" % (nums[i])
numcount = 0
for j in xrange(0,len(nums)):
if nums[i] == nums[j]:
numcount = numcount+1
if numcount > 1:
newlist.append(nums[i])
print "newlist: %s" % (newlist)
return newlist
list = [1, 2, 3, 1, 3]
print Solution().uniq(list)
# random val from list
import random
print random.sample(list, 1)[0]
|
ea4b3acae47e2d9efc754c60c6e2ed182b64f81c | rafasapiens/learning | /sqlite_3.py | 252 | 3.578125 | 4 | import sqlite3
connection = sqlite3.connect("Database.db")
c = connection.cursor()
#SQL
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS dados (id INTEGER, unix REAL, keyrd TEXT, datestamp TEXT, value REAL)")
create_table()
|
e84628c2f44e65ddde433bd12b1e9c974f3586bb | gistable/gistable | /all-gists/72a0da8d9b42bed28e61/snippet.py | 1,477 | 3.546875 | 4 | # Tweetに含まれる単語のポジネガによる感情度の付与
# 形態要素化できた単語のうち、ポジに分類されるものを1、ネガに分類されるものを-1
# 形態要素化できた単語数で割ることで平均値を取り指標化
pn_data = [data for data in posi_nega_dict.find({},{'word':1,'value':1})]
def get_emotion_value(word):
ret_val = None
for d in pn_data:
if d['word'] == word:
ret_val = d['value']
break
return ret_val
def isexist_and_get_data(data, key):
return data[key] if key in data else None
data = [d for d in tweetdata.find({'emo_val':{ "$exists": True }},{'noun':1,'adjective':1,'verb':1,'adverb':1})]
tweet_list = []
counter=0
for d in data:
counter += 1
if counter % 1000 == 0:
print counter
print datetime.datetime.today()
score = 0
word_count = 0
for k in ['noun','adjective','verb','adverb']:
if type(isexist_and_get_data(d,k))==list:
for i in d[k]:
v = get_emotion_value(i)
if v is not None:
score += v
word_count += 1
else:
v = get_emotion_value(isexist_and_get_data(d,k))
if v is not None:
score += v
word_count += 1
d['score'] = score/float(word_count) if word_count != 0 else 0
tweetdata.update({'_id' : d['_id']},{'$set': {'emo_val':d['score']}},True)
|
478f4869577d6943b350334689c9ce81f921d57c | lodado/PS | /BOJ/10815BOJ치킨배달.py | 485 | 3.890625 | 4 | def scan():
return map(int, input().split())
def binary_search(arr, val):
left = 0
right = len(arr)-1
while(left<=right):
mid = (right + left)//2
# print(left, mid, right)
now = arr[mid]
if(now<val):
left = mid + 1
elif(now==val):
return 1
else:
right = mid - 1
#print()
return 0
N = scan()
baseArr = sorted([i for i in scan()])
M = scan()
findArr = [i for i in scan()]
for i in findArr:
a = binary_search(baseArr, i)
print(a, end=' ')
|
e932ad1fde72263373aaef038a9d64299bbe00c1 | GabrielG-prog/EduPython | /exoPy.py | 185 | 3.78125 | 4 |
somme=0
nbarticle= int(input("saisir un nombre"))
for n in range(nbarticle):
nb=int (input("saisir nb article"))
somme=somme+nb
print("somme totale",somme)
|
0fed791153c3a399ee55d19b2c3f50804feddcc2 | sadiashormin/python_problems | /Designer DoorMat.py | 178 | 3.515625 | 4 | n, m = raw_input().split()
pattern = [('.|.'*(2*i + 1)).center(int(m), '-') for i in range(int(n)//2)]
print('\n'.join(pattern + ['WELCOME'.center(int(m), '-')] + pattern[::-1])) |
ab1bc02e972ccab35388c23e7615da5198030392 | erzelenki/PythonLearning | /except key.py | 228 | 3.90625 | 4 | # how to abuse the dictionary
# and how to deal with it
dict = { 'a' : 'b', 'b' : 'c', 'c' : 'd' }
ch = 'a'
try:
while True:
ch = dict[ch]
print(ch)
except KeyError:
print('No such key:', ch)
|
2cba051c06a405d45f6d84d4fe1ac6ced7da47bd | edarigo/python-project | /test_AverageRange.py | 2,088 | 3.78125 | 4 | import unittest
from AverageRange import AverageRange
class TestAverageRange(unittest.TestCase):
'''Unit test to test the AverageRange Class'''
def setUp(self):
'''Set up data to be used in test'''
# First matrix to test
self.test_matrix = [[0,6.3,141,51,62,58.03],[0,6.6,130,54,15.82,45.49],
[0,4.9,86,36,59,43.24],[5,7.7,140,64,175,136.73]]
# Second matrix to test
self.test_matrix2 = [[6,8.8,149,68,321,257.7],[3,7.9,110,72,17,40.83],
[1,6.4,107,31,30,13],[28,7.5,134,88,200,699.97]]
# Call AverageRange class to pass through test matrices
self.list1 = AverageRange(self.test_matrix)
self.list2 = AverageRange(self.test_matrix2)
def test_MovieAverage(self):
'''Test that the function will return the average of each matrix column'''
# Expected result 1
self.list1_result = [1.25,6.37,124.25,51.25,77.95,70.87]
# Expected result 2
self.list2_result = [9.5,7.65,125,64.75,142,252.88]
# Pass through the test matrices and compare to expected result
self.assertListEqual(self.list1.getMovieAverage(),self.list1_result)
self.assertListEqual(self.list2.getMovieAverage(),self.list2_result)
def test_RangeMinMax(self):
'''Test that the function will return the range (min-max) of each matrix
column'''
# Expected result 1
self.list1_result = [[0,5],[4.9,7.7],[86,141],[36,64],[15.82,175],
[43.24,136.73]]
# Expected result 2
self.list2_result = [[1,28],[6.4,8.8],[107,149],[31,88],[17,321],
[13,699.97]]
# Pass through the test matrices and compare to expected result
self.assertListEqual(self.list1.getRangeMinMax(),self.list1_result)
self.assertListEqual(self.list2.getRangeMinMax(),self.list2_result)
if __name__ == "__main__":
unittest.main() |
3fb50d89c90310a16cb8c5c8c1836b39152f2813 | murali-kotakonda/PythonProgs | /PythonBasics1/10decotor/closures/Ex6.py | 534 | 4.03125 | 4 | #Functions are objects:
#Python functions are first class objects.
#In the example below, we are assigning function to a variable.
#This assignment doesnt call the function.
#It takes the function object referenced by shout and creates a second name pointing to it, yell.
#Python program to illustrate functions can be treated as objects
num= 1
#closures
def myFun(str):
num =1;
def myfun2():
global num
num= num+1
print(str ,num)
return myfun2;
fObj = myFun("hello")
fObj()
fObj()
|
b502b9ceeb45c3c3be36762c9e1043ebed48072f | seonukim/Study | /keras/keras29_lstm.py | 1,308 | 3.625 | 4 | from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 1. 데이터 구성
x = array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])
y = array([4, 5, 6, 7])
y2 = array([[4, 5, 6, 7]]) # res : (1, 4)
y3 = array([[4], [5], [6], [7]]) # res : (4, 1)
print("x.shape : ", x.shape) # res : (4, 3)
print("y.shape : ", y.shape) # res : (4, )
# x = x.reshape(4, 3, 1)
x = x.reshape(x.shape[0], x.shape[1], 1)
# 4 3 1
print(x.shape)
'''reshape 후 검산을 해야함 -> 모두 곱해서 reshape 전후가 같은 값이 나오면 문제 없음'''
# 2. 모델 구성
model = Sequential()
# model.add(LSTM(10, activation = 'relu', input_shape = (3, 1))) # column의 갯수와 몇개씩 자를 것인지
model.add(LSTM(10, activation = 'relu', input_dim = 1, input_length = 3))
model.add(Dense(5))
model.add(Dense(6))
model.add(Dense(7))
model.add(Dense(8))
model.add(Dense(9))
model.add(Dense(10))
model.add(Dense(8))
model.add(Dense(1))
model.summary()
# 3. 실행
model.compile(loss = 'mse', optimizer = 'adam', metrics = ['mse'])
model.fit(x, y, epochs = 100, batch_size = 1)
x_input = array([5, 6, 7])
x_input = x_input.reshape(1, 3, 1)
print(x_input)
y_hat = model.predict(x_input)
print(y_hat)
|
0cfbcfa4108259dbf0d6e6b3054e426e81d673a4 | abhishek98as/30-Day-Python-DSA-Challenge | /Tkinter/sleep method.py | 479 | 3.75 | 4 | #sleep() method is used to stop execution of a program temporarliy for a given amount of time .
# when this function is called PVM stops program execution for given amount of time module
import time
for i in range (20):
print(i)
if(i==10):
time.sleep(6)
|
9c0abe700693251b6b2ed59cfb769191bb535baf | Steinunntry/M | /25agust/27.08.Assign3.whileloops/2.First n even numbers.py | 174 | 3.90625 | 4 | n = int(input("Input an int: ")) # Do not change this line
# Fill in the missing code below
min = 1
while min <= n :
if min % 2 == 0:
print(min)
min = n-1 |
810c3c24525ff1eec35f277c027e7afb6f0d46a9 | ssinghaldev/interview_bit | /arrays/merge_intervals.py | 4,139 | 3.90625 | 4 | #https://www.interviewbit.com/problems/merge-intervals/
import bisect
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param new_interval, a Interval
# @return a list of Interval
def insert(self, intervals, new_interval):
merged_intervals = []
all_start = [i.start for i in intervals]
all_end = [i.end for i in intervals]
#Finding where the starting/ending value of given interval lie
start_interval_index = bisect.bisect_right(all_start, new_interval.start)
end_interval_index = bisect.bisect_left(all_end, new_interval.end)
#determine four cases where they are and they we will proceed
is_start_outside = False
is_end_outside = False
if start_interval_index == 0:
is_start_outside = True
else:
to_check_index = start_interval_index - 1
if new_interval.start > intervals[to_check_index].end:
is_start_outside = True
if end_interval_index == len(all_end):
is_end_outside = True
else:
to_check_index = end_interval_index
if new_interval.end < intervals[to_check_index].start:
is_end_outside = True
#All four conditions
if is_start_outside == False and is_end_outside == False:
#print "in condition 1"
merge_interval_start_index = start_interval_index - 1
merge_interval_end_index = end_interval_index
interval_obj = Interval(intervals[merge_interval_start_index].start, intervals[merge_interval_end_index].end)
#merging the intervals
for i in range(merge_interval_start_index):
merged_intervals.append(intervals[i])
merged_intervals.append(interval_obj)
for i in range((merge_interval_end_index + 1), len(intervals)):
merged_intervals.append(intervals[i])
#print merged_intervals
elif is_start_outside == False and is_end_outside == True:
#print "In condition 2"
merge_interval_start_index = start_interval_index - 1
merge_interval_end_index = end_interval_index
interval_obj = Interval(intervals[merge_interval_start_index].start, new_interval.end)
#merging intervals
for i in range(merge_interval_start_index):
merged_intervals.append(intervals[i])
merged_intervals.append(interval_obj)
for i in range(merge_interval_end_index, len(intervals)):
merged_intervals.append(intervals[i])
#print merged_intervals
elif is_start_outside == True and is_end_outside == False:
#print "in condition 3"
merge_interval_start_index = start_interval_index
merge_interval_end_index = end_interval_index
interval_obj = Interval(new_interval.start, intervals[merge_interval_end_index].end)
for i in range(merge_interval_start_index):
merged_intervals.append(intervals[i])
merged_intervals.append(interval_obj)
for i in range(merge_interval_end_index + 1, len(intervals)):
merged_intervals.append(intervals[i])
elif is_start_outside == True and is_end_outside == True:
merge_interval_start_index = start_interval_index
merge_interval_end_index = end_interval_index
interval_obj = new_interval
for i in range(merge_interval_start_index):
merged_intervals.append(intervals[i])
merged_intervals.append(interval_obj)
for i in range(merge_interval_end_index , len(intervals)):
merged_intervals.append(intervals[i])
#print merged_intervals
return merged_intervals
|
c6c4655ab3f04f0dd2e604c4a9b1d30bb2af4a31 | astral-sh/ruff | /crates/ruff/resources/test/fixtures/flake8_bugbear/B020.py | 820 | 3.640625 | 4 | """
Should emit:
B020 - on lines 8, 21, and 36
"""
items = [1, 2, 3]
for items in items:
print(items)
items = [1, 2, 3]
for item in items:
print(item)
values = {"secret": 123}
for key, value in values.items():
print(f"{key}, {value}")
for key, values in values.items():
print(f"{key}, {values}")
# Variables defined in a comprehension are local in scope
# to that comprehension and are therefore allowed.
for var in [var for var in range(10)]:
print(var)
for var in (var for var in range(10)):
print(var)
for k, v in {k: v for k, v in zip(range(10), range(10, 20))}.items():
print(k, v)
# However we still call out reassigning the iterable in the comprehension.
for vars in [i for i in vars]:
print(vars)
for var in sorted(range(10), key=lambda var: var.real):
print(var)
|
d3bef9b4c589605c442f92e71f7ccbed22df2b0a | hb162/Algo | /Algorithm/Ex_130420/Ex_Second_Largest_BST.py | 1,147 | 4.03125 | 4 | """
Given the root to a binary search tree,
find the second largest node in the tree.
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(root, data):
if not root:
return Node(data)
if data < root.data:
root.left = insert(root.left, data)
if data > root.data:
root.right = insert(root.right, data)
return root
def find_max(root):
while root.right is not None:
root = root.right
return root.data
def find_second_largest(root):
if root is None or (root.left is None and root.right is None):
return None
if root.left and not root.right:
return find_max(root.left)
if (root.right and
not root.right.left and
not root.right.right):
return root.value
return find_second_largest(root.right)
root = None
root = insert(root, 2)
root = insert(root, 1)
root = insert(root, 3)
root = insert(root, 6)
root = insert(root, 5)
# print(find_max(root))
print(find_second_largest(root))
"""
Độ phức tạp: O(h), h là chiều cao của cây.
"""
|
62c20c30feba55e9e0c28599227b9ffcaaea649a | rafaelperazzo/programacao-web | /moodledata/vpl_data/21/usersdata/120/8023/submittedfiles/exercicio24.py | 359 | 3.9375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#ENTRADA
n=int(input('digite o valor do primeiro numero :'))
m=int(input('digite o valor do segundo numero :'))
#PROCESSAMENTO
mdc=1
divisor=2
while (divisor <=n):
if n% divisor==0 and m%divisor==0:
mdc=divisor
divisor= divisor + 1
print('MDC(%d,%d)=%d'%(n,m,mdc))
|
3c8680cfc8a8ab86b858226b122dc663bb627eef | JosephTagirov/LW_2 | /7.4.py | 193 | 4.09375 | 4 | from random import *
x=int(input('The computer has guessed a number from 1 to 10. Try to guess it: '))
if x==randint(1, 10):
print('You are right')
else:
print('You are wrong')
|
e1990259e2c3b08aac68d19f8ea009b98db3cae6 | paulbright/ml_training | /Multiple Linear Regression/load_model.py | 984 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 10:09:02 2019
@author: a142400
"""
import pandas as pd
import pickle as pickle
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder = LabelEncoder()
X[:, 3] = labelencoder.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
# Avoiding the Dummy Variable Trap
#remove the first column 0
#that is take all rows of X and all columns starting from 1
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
loaded_model = pickle.load(open("model.sav", 'rb'))
y_pred = loaded_model.predict(X_test)
print(y_pred)
|
635c55da11807353977a93fe8906d9d10d23db46 | karthik-ballullaya/Kannada_OCR_TTS | /Code/KannadaTextToSpeech.py | 636 | 3.625 | 4 | from gtts import gTTS
import os
import sys
# The text that you want to convert to audio
_, input_file, output_file = sys.argv
print(f'Reading from text {input_file}')
with open(sys.argv[1], 'r', encoding='utf-8') as f:
mytext = f.read()
# Language in which you want to convert
language = 'kn'
# Passing the text and language to the engine,
# here we have marked slow=False. Which tells
# the module that the converted audio should
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
print(f'Saving mp3 file {output_file}')
# Saving the converted audio in a mp3 file named
myobj.save(sys.argv[2]) |
e8d3e93f2ff9563a830c30823830655ce70e26b5 | glimperg/Lectures-Lesroosters | /classes.py | 2,551 | 4.28125 | 4 | class Course:
"""
Creates a course object containing course data and
a list of students following the course.
The course data is in the following format:
[name, lectures, seminars, seminar capacity,
practicals, practical capacity]
"""
def __init__(self, data, students):
self.name = data[0]
self.lectures = int(data[1])
self.seminars = int(data[2])
self.s_cap = int(data[3])
self.practicals = int(data[4])
self.p_cap = int(data[5])
self.students = students
def get_group_count(self, _type):
"""Determine number of groups of type _type."""
student_count = len(self.students)
if _type == "seminar":
capacity = self.s_cap
else:
capacity = self.p_cap
if student_count % capacity > 0:
return student_count//capacity + 1
else:
return student_count//capacity
def get_activity_count(self):
"""Determine amount of activities of the course."""
return self.lectures + self.seminars + self.practicals
class Student:
"""
Creates a student object containing student info and a list
of courses which the student is following. The student data is
in the following format: [name, id, course1, course2, ...]
"""
def __init__(self, data):
self.name = data[1] + " " + data[0]
self.id = int(data[2])
courses = []
for str in data[3:]:
if str:
courses.append(str)
self.courses = courses
class Teaching:
"""
Creates a teaching object containing the type of teaching,
course data, a list of students following the teaching,
the hall and the timeslot.
"""
# declare static variables
#lecture_count, seminar_count, practical_count = 0, 0, 0
def __init__(self, _type, course, students, group="",
hall=None, timeslot=0):
self.course_name = course.name
self.type = _type
self.students = students
self.group = group
self.hall = hall
self.timeslot = timeslot
def __repr__(self):
group_str = ""
if self.group:
group_str = " - Group " + self.group
return self.course_name + " - " + self.type + group_str
class Teaching_Hall:
"""
Creates a teaching hall object containing hall data.
The data is in the following format: [name, capacity].
"""
def __init__(self, data):
self.name = data[0]
self.capacity = data[1]
|
b0e6712be398d1f62c99eccdfc21012bdd98c956 | WilbertHo/hackerrank | /challenges/algorithms/graph_theory/even_tree/py/eventree.py | 758 | 3.53125 | 4 | #!/usr/bin/env python
from collections import defaultdict
import fileinput
def build_graph(input):
graph = defaultdict(list)
for adj, node in input:
graph[node].append(adj)
return graph
def subtree_count(graph, v):
count = 1
queue = graph.setdefault(v, [])
for v in queue:
count += subtree_count(graph, v)
return count
def cut_count(graph, v):
count = 0
for i in range(v, 1, -1):
if subtree_count(graph, i) % 2 == 0:
count += 1
return count
def main():
input = [map(int, line.strip().split()) for line in fileinput.input()]
vertexes, edges = input[0]
graph = build_graph(input[1:])
print cut_count(graph, vertexes)
if __name__ == '__main__':
main()
|
d645cd08f03764e81430bae0d0254fd6aafb3ac8 | Huxhh/LeetCodePy | /1-50/014LongestCommonPrefixEasy.py | 1,235 | 3.671875 | 4 | # coding=utf-8
"""
思路
首先找到所有字符串中长度最短的一个,将它用enumerate表示,即字符下标与字符一一对应
遍历其他字符串,每个字符与enumera中的字符比较,出现不同时返回下标得到结果
时间复杂度 O(m*n) 空间复杂度O(n)
"""
def longestCommonPrefix(strs):
res = ""
if len(strs) == 0:
return res
flag = 1
i = 0
for s in strs:
if len(s) == 0:
return res
while flag:
if i >= len(strs[0]):
break
tmps = strs[0][i]
for s in strs:
if i >= len(s):
flag = 0
break
if s[i] != tmps:
flag = 0
i += 1
if flag:
res += tmps
else:
break
return res
def longestCommonPrefix2(strs):
if not strs:
return ""
minlen = min(strs, key=len)
for i, ss in enumerate(minlen):
for other in strs:
if other[i] != ss:
return minlen[:i]
return minlen
if __name__ == '__main__':
print(longestCommonPrefix2(["flower","flow","flight"]))
# strs = ["flower","flow","flight"]
# print(list(enumerate(strs))) |
cf70ec11705a585f5bedb522a074576bafcd5668 | meganesu/twitter-scraper | /tweet-parser.py | 190 | 3.71875 | 4 | import json
# Load the data from the JSON file into a dictionary named tweets
tweets = json.load(open('tweets.json'))
for t in tweets:
# Do things with the data here!
print(t["text"])
|
7c0b792fd02d1cd156f7c58b8b8b2cc286b802e9 | Z-Clark/algorithm007-class02 | /Week_01/G20200343040212/LeetCode_189_0212.py | 1,349 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020-03-12 22:53
# @Author : peniridis
# @Version : V0.1
# @File : leetcode_189.py
# @Desc :
# 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
#
# 示例 1:
#
# 输入: [1,2,3,4,5,6,7] 和 k = 3
# 输出: [5,6,7,1,2,3,4]
# 解释:
# 向右旋转 1 步: [7,1,2,3,4,5,6]
# 向右旋转 2 步: [6,7,1,2,3,4,5]
# 向右旋转 3 步: [5,6,7,1,2,3,4]
#
#
# 示例 2:
#
# 输入: [-1,-100,3,99] 和 k = 2
# 输出: [3,99,-1,-100]
# 解释:
# 向右旋转 1 步: [99,-1,-100,3]
# 向右旋转 2 步: [3,99,-1,-100]
#
# 说明:
#
#
# 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
# 要求使用空间复杂度为 O(1) 的 原地 算法。
#
# Related Topics 数组
from typing import List
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
第一个想到的解法,操作数组
:param nums: 数组
:param k: 移动K个位置
:return:
"""
k %= len(nums)
if k == 0:
return
for i in range(len(nums) - k):
nums.append(nums[0])
nums.pop(0)
# leetcode submit region end(Prohibit modification and deletion)
|
2b41e85b88993729de188045582c0cc9ffd5e58f | djefford/hacking | /Python/theboringstuff/tablePrinter.py | 682 | 3.765625 | 4 | #! python3
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
## Start functions
def maxLength(myList):
length = 0
for item in myList:
if len(item) > length:
length = len(item)
return length
def printTable(myTable, colWidths):
for i in range(len(myTable[1])):
for j in range(len(myTable[:])):
print(myTable[j][i].rjust(colWidths[j]), end=' ')
print()
## Start program
colWidths = []
for i in tableData:
length = maxLength(i)
colWidths.append(length)
printTable(tableData, colWidths) |
b28d9b3621aa76fc478302cd6bad6206183559da | kiu1202/hello-world | /helloworld2 | 792 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
age=20
if age>=18:
print('your age is',age)
print('adult')
age=3
if age>=18:
print('your age is',age)
print('adult')
else:
print('your age is',age)
print('teenager')
age=3
if age>=18:
print('adult')
elif age>=6:
print('teenager')
else:
print('kid')
age=20
if age>=6:
print('teenager')
elif age>=18:
print('adult')
else:
print('kid')
x=3
if x:
print('True')
birth=input('birth: ')
birth=int(birth)
if birth<2000:
print('before 2000')
else:
print('after 2000')
height=1.75
weight=80.5
bmi=weight/(height*height)
if bmi<18.5:
print('slim')
elif bmi<25:
print('normal')
elif bmi<28:
print('overweight')
elif bmi<32:
print('obesity')
else:
print('too fat')
print(bmi)
|
bed8b0b7d685d422f65f2d0da96302e57235d08d | Cohiba3310/BMI-Calculator | /bmi.py | 403 | 4 | 4 | h = input('請輸入身高(m): ')
w = input('請輸入體重(kg): ')
h = float(h)
w = float(w)
bmi = w / (h ** 2)
print('您的BMI為: ', bmi)
if bmi < 18.5:
print('體重過輕!')
elif 18.5 <= bmi < 24:
print('正常範圍')
elif 24 <= bmi < 27:
print('過重!')
elif 27 <= bmi < 30:
print('輕度肥胖!!')
elif 30 <= bmi < 35:
print('中度肥胖!!!')
elif bmi >= 35:
print('重度肥胖!!!!') |
f4eec1bd08483d69848b66631fbf3f893677b527 | CS7591/Python-Classes | /1. Python Basics/2. Basic Rules/3. Data Types and Conversions.py | 3,785 | 4.03125 | 4 | '''
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Setting the data type occurs naturally, during assignment to a variable
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple",
"banana",
"cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
'''
# ############################################################################
# # Definition of data type happens on assignment (dynamically typed language)
# # Use the type() function to check on the current data type
# x = 'text'
# print(type(x)) # <class 'str'>
#
# x = 0
# print(type(x)) # <class 'int'>
#
# x = 0.0
# print(type(x)) # <class 'float'>
#
# x = True
# print(type(x)) # <class 'bool'>
#
# x = {}
# print(type(x)) # <class 'dict'>
#
# x = []
# print(type(x)) # <class 'list'>
#
# x = ()
# print(type(x)) # <class 'tuple'>
#
# ##################################################################
# # Digging into data types
#
# # Numbers
# # int, long, float, complex
# x = 10
# y = 51667292876
# Z = 20.0
# w = 0.867j
#
# # Strings
# my_str = 'Hello World!'
#
# # Lists
# my_list = [1.2, 10, 'a string', [0, 1, 2, 3, 4], 0.234j]
#
# # Reference to a item of a list is made with the item index
# # Lists always start at index 0
#
# print(my_list[0]) # 1.2
# print(my_list[1]) # 10
# print(my_list[3]) # [0, 1, 2, 3, 4]
# print(my_list[3][4]) # 4
#
# # Tuples
# tpl = (1.2, 10, 'string', [0, 1, 2, 3, 4], 0.234j)
#
# # Dictionaries
# dct = {'Name': 'John', 'Age': 30, 'Nationality': 'Belgium'}
# ##################################################################
# # Conversions - Use any of the following conversion functions
# # Converts x to an integer. base specifies the base if x is a string
# int(x [,base])
print(int(3.7))
print(int('5'))
# # Converts x to a floating-point number
# float(x)
print(float(4))
print(float('5'))
# # Converts object x to a string representation.
# str(x)
print(str(5.0))
print(str(2))
# # Converts an integer to a character.
# chr(x)
for i in range(256):
print(chr(i), end=',')
# # Converts x to a long integer. base specifies the base if x is a string.
# long(x [,base] )
#
# # Creates a complex number.
# complex(real [,imag])
#
# # Converts object x to an expression string.
# repr(x)
#
# # Evaluates a string and returns an object.
# eval(str)
#
# # Converts s to a tuple.
# tuple(s)
#
# # Converts s to a list.
# list(s)
#
# # Converts s to a set.
# set(s)
#
# # Creates a dictionary. d must be a sequence of (key,value) tuples.
# dict(d)
#
# # Converts s to a frozen set.
# frozenset(s)
#
# # Converts an integer to a Unicode character.
# unichr(x)
#
# # Converts a single character to its integer value.
# ord(x)
#
# # Converts an integer to a hexadecimal string.
# hex(x)
#
# # Converts an integer to an octal string.
# oct(x)
|
c33571fe6158790d4e7f7006ea33132f05273f43 | hendricktyler5/Simple-Encryption-Decryption | /Encryption.py | 1,916 | 3.921875 | 4 | """
Encryption.py
Simple Encryption/Decryption Program
Written by Tyler Hendrick
"""
def main():
while True:
enOrDe = input("Enter 1 for Encrypting a message or 2 for Decrypting a message\n")
if (enOrDe == 1):
print "Welcome to the Encryption program"
str = raw_input("Enter your string to be encrypted: ")
key = raw_input("Enter your integer key: ")
encStr = encrypt(str, key)
print "Your encrypted message is: %s" %encStr
else:
print "Welcome to the Decryption program"
str = raw_input("Enter the string to be decrypted: ")
key = raw_input("Enter your integer key: ")
decStr = decrypt(str, key)
print "Your message is: %s" %decStr
again = raw_input("Do you wan to go again? y or n: ")
if again.lower() == 'n':
break
def encrypt(st, key):
alphaDict, numDict = createDict()
newStr = ""
for i in st:
if i.isalpha():
newNum = (int(alphaDict[i.lower()]) + int(key)) % 26
j = numDict[newNum]
newStr += j
elif i.isdigit():
newNum = (int(i) + int(key)) % 10
newStr += str(newNum)
else:
newStr += " "
return newStr
def decrypt(st, key):
alphaDict, numDict = createDict()
newStr = ""
for i in st:
if i.isalpha():
newNum = (int(alphaDict[i.lower()]) - int (key)) % 26
j = numDict[newNum]
newStr += j
elif i.isdigit():
newNum = (int(i) - int(key)) % 10
newStr += str(newNum)
else:
newStr += " "
return newStr
def createDict():
newdict = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z':25}
array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
return newdict, array
if __name__ == "__main__":
main() |
aff697eb15c1bc18f5b73da64c646d0839e5913c | thiago02/python-fundamentals | /HandsOn/Aula05/exec1.py | 852 | 3.6875 | 4 | # ----- CONEXAO COM O BANCO
import psycopg2
con = psycopg2.connect(
"host=%s dbname=%s user=%s password=%s" % (
'localhost' , 'projeto' , 'postgres' , '123456'
)
)
cur =con.cursor()
print con
# INSERIR UM POST
conteudo = raw_input("digite o conteudo: ")
titulo = raw_input ("digite o titulo: ")
cur = con.cursor()
cur.execute(" \
INSERT INTO posts (conteudo, titulo) \
VALUES ('%s' , '%s' )" %(conteudo, titulo) )
con.commit
print cur.rowcount
# RECEBE CONTEUDO E TITULO
cur.execute("SELECT * FROM posts")
for row in cur.fetchall():
print 'Conteudo: %s \n Titulo: %s' %(
row[1], row[2] )
#BUSCA UM POST
# RECEBE TRECHO DO TITULO
id = raw_input ("digite um trecho na busca: ")
cur.execute("SELECT * FROM posts WHERE id= %s " % id)
row = cur.fetchone()
print "ID %s , Titulo %s, Conteudo %s" % (
row[0], row[1], row[2]
)
|
67299319d1a963f1bf988a8b75a1d724885ccc4d | rheena/Python-basics | /Sequences and Collections.py | 3,779 | 4.5625 | 5 | #Sequence is a collection of elements. One object that contains multiples values but can be treated as one thing.
#List -Defined using square brackets []
mylist = [10, 20, 30, 'string', True, 8.97]
print(mylist)
#Most sequences are indexed. Index is a number that gives us information about the position of an element in our collection
print(mylist[3]) #This is to specify a certain index
print(mylist[:3]) #This means from the beginning upto index 2, excluding the third index
print(mylist[-2]) #use of the - is to indicate that you're counting the second element from right to left.
mylist[3] = 'Rheena' #This changes the value of the third index to a new value
print(mylist)
#Iterate over lists using for loops
for x in mylist:
print(x)
#Operations in lists
x = [1, 2, 3]
y = [4, 5, 6]
print(x + y) #This merges the lists
print(x * 4) #This repeats the list 4 times in a row
#Functions in lists - they give some information on lists
x = [1, 2, 3]
print(len(x)) #Tells the length of the list
print(max(x)) #Tells the biggest value of the list but only works when the values are of the same data type
print(min(x)) #Tells the smallest value of the list but only works when the values are of the same data type
#Methods in lists
#Append method - it append (adds) one more value at the end of the list
x = [1, 2, 3]
x.append('Rhee')
print(x)
#Insert method - it inserts (adds) one more value at a given part of the list
x = [1, 2, 3]
x.insert(2, 'Rhee')
print(x)
#Remove method - it removes a value from the list
x = [1, 2, 3, 'Rhee', 'KM']
x.remove('KM')
print(x)
#Pop function - allows you to removes a value from a specific index without knowing what the element is
x = [1, 2, 3, 'Rhee', 'KM']
x.pop(2)
print(x)
#Index method - You pass a value to it and if the value is in the list, the method returns the index of the value
x = [1, 2, 3, 'Rhee', 'KM']
print(x.index('Rhee'))
x.pop(x.index('Rhee')) #Pops (removes) the stated index
print(x)
#Sort method - basically sorts the list
x = [24, 55, 31, 52, 27]
x.sort() #The values of x change to the new sorted values
print(x)
print(sorted(x)) #sorted is a key word to print a sorted list but the values of x remains the same
'''Tuples - They are immutable.
Their value and/or structure cannot be changed. They are defined with parethesis
'''
y = (1, 2, 3)
y = list(y) #Doing this allows you to change the values (type casting) but it appears as a list
y[2] = 10
y = tuple(y) #This changes it back to a tuple with the new changed value in it
print(y)
'''Dictionary - They are composed of key value pairs and they are not indexed.
A key value pair consists of a unique key which is the replacement for the index and a value that belongs to that key.
The access of value of a dictionary is referred to by the key:
Dictionaries are defined by curly brackets
'''
person = {'Name': 'Rheena', 'Age': 24, 'Gender': 'Female'}
print(person)
print(person['Age']) #This is to acces a particular key
person['NewAge'] = 25 #This adds a new key to the dictionary
print(person)
#Dictionary methods
#item - This returns a list of all items
print(person.items())
#keys - This returns a list of all they keys
print(person.keys())
#values - This returns a list of all values
print(person.values())
#Membership operators - They check if an element is contained in the sequence
x = [1, 2, 3]
print(2 in x)
print(7 in x)
print(3 not in x)
print(8 not in x)
#Identity operator - check if the value is a type
x = 10
if type(x) is int:
print('x is int!')
else:
print('x is not int!')
y = 'Hello'
if type(y) is not int:
print('y is string!')
else:
print('y is not string!')
|
a3743e2ec4c51f61a10250808c684d70a9b81187 | jennyChing/leetCode | /399_calcEquation.py | 2,261 | 3.9375 | 4 | '''
399. Evaluate Division
Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
'''
import collections
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
# built graph with dict of dict and calculate the values
graph = collections.defaultdict(dict)
for e, v in zip(equations, values):
graph[e[0]][e[1]], graph[e[1]][e[0]] = v, 1.0 / v
graph[e[0]][e[0]], graph[e[1]][e[1]] = 1.0, 1.0
for k in graph: # the middle guy
for i in graph: # if i can reach j through k
for j in graph: # (i to j) = (i to k) * (k to j)
if k in graph[i] and j in graph[k]:
graph[i][j] = graph[i][k] * graph[k][j]
res = []
for q in queries: # lookup graph updated with kij algorithm
if q[1] not in graph[q[0]]:
res.append(-1)
else:
res.append(graph[q[0]][q[1]])
return res
if __name__ == "__main__":
equations = [ ["a", "b"], ["b", "c"] ]
values = [2.0, 3.0]
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]
res = Solution().calcEquation(equations, values, queries)
print(res)
|
b2dc38eec8889fab9c836ea77b804c9267c5b336 | max180643/Pre-Programming-61 | /Onsite/Week-2/Friday/Vending Machine.py | 718 | 3.84375 | 4 | """Vending Machine"""
def main():
"""Main Function"""
money = 0
item = 0
total = 0
while True:
input_ = input()
if input_ != "END":
if int(input_) >= 0:
money += int(input_)
elif int(input_) < 0:
item += 1
total += abs(int(input_))
if money - total < 0:
print("ERROR: Not enough money for this item.")
total -= abs(int(input_))
if item > 0:
item -= 1
else:
print("Items: %i" % (item))
print("Change: %i THB" % (money - total))
break
main()
|
f4f84ad70047863feadde8c43759f6cbac537388 | wuyaqiang/Algorithm_Learn | /剑指Offer/MyCode/No_12.py | 2,643 | 3.953125 | 4 | '''
剑指 Offer 第12题
leetcode 79. Word Search
leetcode 212. Word Search II
'''
def has_path(board, word):
'''
剑指Offer 12
leetcode 79. Word Search
'''
# 解法一 剑指Offer解法,使用 visited 矩阵:
# if not board or len(board) == 0 or not board[0] or len(board[0]) == 0:
# return False
#
# def judge(board, rows, cols, row, col, pos, word, visited):
# if pos == len(word):
# return True
#
# has_path = False
#
# if row >= 0 and row < rows and col >= 0 and \
# col < cols and board[row][col] == word[pos] and \
# visited[row][col] == False:
#
# pos += 1
# visited[row][col] = True
# has_path = judge(board, rows, cols, row - 1, col, pos, word, visited) or \
# judge(board, rows, cols, row, col - 1, pos, word, visited) or \
# judge(board, rows, cols, row + 1, col, pos, word, visited) or \
# judge(board, rows, cols, row, col + 1, pos, word, visited)
#
# if not has_path:
# pos -= 1
# visited[row][col] = False
#
# return has_path
#
# rows, cols = len(board), len(board[0])
# visited = [[False] * cols for _ in range(rows)]
#
# for row in range(rows):
# for col in range(cols):
# if judge(board, rows, cols, row, col, 0, word, visited):
# return True
#
# return False
# 解法二 不使用 visited 矩阵,更加简洁
if not board or len(board) == 0 or len(board[0]) == 0:
return False
def judge(board, rows, cols, row, col, word):
if len(word) == 0:
return True
if row < 0 or row >= rows or col < 0 or col >= cols or board[row][col] != word[0]:
return False
cur_char = board[row][col]
board[row][col] = "#" # 访问过的字符置为“#”,与 visited 矩阵起到相同作用,更加节省空间
res = judge(board, rows, cols, row - 1, col, word[1:]) or \
judge(board, rows, cols, row + 1, col, word[1:]) or \
judge(board, rows, cols, row, col - 1, word[1:]) or \
judge(board, rows, cols, row, col + 1, word[1:])
board[row][col] = cur_char
return res
rows, cols = len(board), len(board[0])
for row in range(rows):
for col in range(cols):
if judge(board, rows, cols, row, col, word):
return True
return False
def find_words(board, words):
'''
较难,暂略
'''
pass |
17fdb4c697f033ea8880b4577e8d64b28feb8d6c | Keerti-Gautam/PythonLearning | /Functions/FirstClass-Anonymous-HigherOrderFunc.py | 880 | 3.890625 | 4 | # Python has first class functions
def create_adder(x):
def adder(y): #
return x + y
return adder # create_adder returns x+y
add_10 = create_adder(10) # 10+y is put in add_10
add_10(3) # => 10+3 =13
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# There are built-in higher order functions
map(add_10, [1, 2, 3]) # => [11, 12, 13]
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
# You can construct set and dict comprehensions as well.
{x for x in 'abcddeef' if x in 'abc'} # Set => {'a', 'b', 'c'}
{x: x ** 2 for x in range(5)} # Dict => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
|
7ff8d7cd66cc1c28e9613e8ad74f80fc537e182d | abhaykoduru/sql | /cars_insert_update.py | 761 | 4.0625 | 4 | import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
data = (('Ford', 2013, 1000),
('Ford', 2014, 2000),
('Ford', 2015, 3000),
('Honda', 2014, 10000),
('Honda', 2015, 15000))
c.executemany("insert into inventory values(?,?,?)", data)
c.execute("select * from inventory")
rows = c.fetchall()
print "After INSERT"
print "------------"
for r in rows:
print r[0], r[1], r[2]
# update
c.execute("update inventory set Quantity=4000\
where Make='Ford' and Model=2014")
c.execute("update inventory set Quantity=8000\
where Make='Ford' and Model=2015")
c.execute("select * from inventory")
rows = c.fetchall()
print "After UPDATE"
print "------------"
for r in rows:
print r[0], r[1], r[2]
|
be9267b86feeef3c68232a5119a8306944d7e183 | Omkarj21/Data-Structures_Collections_Collectors | /Dict_Comprehension.py | 255 | 3.671875 | 4 | keys = ['a', 'b', 'c', 'd', 'e']
values = [1, 2, 3, 4, 5]
# 1st Way :
abc = {p:q**2 for p,q in zip(keys,values)}
print(abc)
# 2nd Way :
abc = {p:p**2 for p in values}
print(abc)
# 3rd Way :
abc = {x: x**3 for x in range(10) if x**3 % 4 == 0}
print(abc) |
fd8b1570b0333b8449145bec4de5ecaf6ade9a22 | pzengseu/leetcode | /SwapNodesinPairs.py | 825 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs2(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
h = ListNode(-1)
h.next = head
curr = h
a = ListNode(-1)
b = ListNode(-1)
while curr.next and curr.next.next:
a = curr.next
b = curr.next.next
a.next = b.next
b.next = a
curr.next = b
curr = a
return h.next
def swapPairs(self, head):
if not head: return None
if not head.next: return head
temp = head.next
head.next = self.swapPairs(temp.next)
temp.next = head
return temp
|
a39bed5482a0c9fc73f5b58eab44ce5f42811b37 | jrmak/FNNR-ABM | /FNNR_ABM/excel_import_2014.py | 8,237 | 3.546875 | 4 | # !/usr/bin/python
"""
This document imports household, individual, and land parcel data from the excel file.
It also converts the imported data into workable values.
"""
from openpyxl import *
import inspect
from excel_import import *
# Directory in which source file is located, exact name of source file + extension
currentpath2014 = str(inspect.getfile(inspect.currentframe()))[:-21] # 'removes excel_import_2014.py' at end
os.chdir(currentpath2014)
currentbook2014 = '2014_survey_validation_edited.xlsx'
# openpyxl commands
wbglobal2014 = load_workbook(currentbook2014)
sheet2014 = wbglobal2014.active
def assign_sheet_parameters_2014(hh_row, variable):
"""Given a household id and name of variable, returns cell range for given variable"""
"""Will create a new function when this list gets long enough"""
parameters = []
row = str(int(hh_row))
# print(row) # For example, row 3 in the Excel file corresponds to Household ID #1
# all lowercase!
if variable.lower() == '2014_hh_id':
parameters.append(str('B' + row))
parameters.append(str('B' + row))
elif variable.lower() == 'hh_id':
parameters.append(str('A' + row))
parameters.append(str('A' + row))
elif variable.lower() == 'name':
parameters.append(str('C' + row))
parameters.append(str('K' + row))
elif variable.lower() == 'age':
parameters.append(str('U' + row))
parameters.append(str('AC' + row))
elif variable.lower() == 'gender':
parameters.append(str('L' + row))
parameters.append(str('T' + row))
elif variable.lower() == 'education':
parameters.append(str('AD' + row))
parameters.append(str('AL' + row))
elif variable.lower() == 'marriage':
parameters.append(str('AM' + row))
parameters.append(str('AU' + row))
elif variable.lower() == 'workstatus':
parameters.append(str('AV' + row))
parameters.append(str('BD' + row))
elif variable.lower() == 'migration_network':
parameters.append(str('BG' + row))
parameters.append(str('BG' + row))
elif variable.lower() == 'non_gtgp_area':
parameters.append(str('BW' + row))
parameters.append(str('CA' + row))
elif variable.lower() == 'gtgp_area':
parameters.append(str('BR' + row))
parameters.append(str('BV' + row))
elif variable.lower() == 'non_gtgp_rice_mu':
parameters.append(str('BN' + row))
parameters.append(str('BN' + row))
elif variable.lower() == 'gtgp_rice_mu':
parameters.append(str('BP' + row))
parameters.append(str('BP' + row))
elif variable.lower() == 'non_gtgp_dry_mu':
parameters.append(str('BO' + row))
parameters.append(str('BO' + row))
elif variable.lower() == 'gtgp_dry_mu':
parameters.append(str('BQ' + row))
parameters.append(str('BQ' + row))
elif variable.lower() == 'non_gtgp_plant_type':
parameters.append(str('IB' + row))
parameters.append(str('IF' + row))
elif variable.lower() == 'pre_gtgp_plant_type':
parameters.append(str('CB' + row))
parameters.append(str('CF' + row))
elif variable.lower() == 'gtgp_travel_time':
parameters.append(str('CG' + row))
parameters.append(str('CK' + row))
elif variable.lower() == 'non_gtgp_travel_time':
parameters.append(str('IQ' + row))
parameters.append(str('IU' + row))
elif variable.lower() == 'pre_gtgp_output':
parameters.append(str('CL' + row))
parameters.append(str('CP' + row))
elif variable.lower() == 'non_gtgp_output':
parameters.append(str('CQ' + row))
parameters.append(str('CU' + row))
elif variable.lower() == 'pre_gtgp_land_type':
parameters.append(str('CV' + row))
parameters.append(str('CZ' + row))
elif variable.lower() == 'non_gtgp_land_type':
parameters.append(str('DA' + row))
parameters.append(str('DE' + row))
elif variable.lower() == ('initial_migrants'):
parameters.append(str('BH' + row))
parameters.append(str('BL' + row))
elif variable.lower() == ('mig_remittances'):
parameters.append(str('BM' + row))
parameters.append(str('BM' + row))
elif variable.lower() == ('income_local_off_farm'):
parameters.append(str('BE' + row))
parameters.append(str('BE' + row))
# add more later; added variable strings must be lowercase
else:
print('Sorry,', variable, 'is not a valid variable category.')
pass
return parameters
def get_hh_row_2014(hh_id):
"""Returns an Excel household row when given the ID"""
column_counter = 0
for CellObj in sheet2014['A']:
column_counter += 1
if CellObj.value == hh_id:
return column_counter
def initialize_labor_2014(hh_row):
num_labor = 0
# There are 94 total households, but ids range from 1-169.
# for clarity: hh_row refers to the Excel spreadsheet row, 3-96 (representing 94 households).
# hh_id refers to household ids as assigned in the Excel column, numbering from 1-169.
agelist = return_values_2014(hh_row, 'age') # find the ages of people in hh
if agelist is not None: # if there are people in the household,
for age in agelist: # for each person (can't use self.age because not a Household-level attribute),
# ages are strings by default, must convert to float
if 15 < float(age) < 59: # if the person is 15-65 years old,
num_labor += 1 # defines number of laborers as people aged 15 < x < 59
#except:
# num_labor = 0
else:
print(hh_row, 'except2014')
return num_labor
def initialize_migrants_2014(hh_row):
if_migrant = return_values_2014(hh_row, 'initial_migrants')
if if_migrant is not None and if_migrant[0] != -3:
num_mig = 1
else:
num_mig = 0
return num_mig
def assign_variable_per_hh_2014(x, y):
"""Adds value of a certain variable to that household's list"""
var = []
for Column in sheet2014[x:y]:
for CellObj in Column:
if x == y:
if CellObj.value not in ['-1', '-3', '-4', -1, -3, -4, None]:
# if the value is not null
var = str(CellObj.value)
elif x != y:
# in this case, var is a list, not a str, because it has multiple items
if CellObj.value not in ['-1', '-3', '-4', -1, -3, -4, None]:
var.append(CellObj.value)
# var = str(CellObj.value)
return var
def return_values_2014(hh_row, var):
"""Returns values given hh_id and variable (combines previous functions)"""
# Example: return_values(1,'gender')
hh_row_variable = assign_sheet_parameters_2014(hh_row, var)
variable_per_hh = assign_variable_per_hh_2014(hh_row_variable[0], hh_row_variable[1])
# print(variable_per_hh) # Example: ['1', '2', '1'] for genders in a household
if variable_per_hh != []:
return variable_per_hh
def initialize_labor_2014(hh_row):
num_labor = 0
agelist = return_values_2014(hh_row, 'age') # find the ages of people in hh
if agelist is not None: # if there are people in the household,
for age in agelist: # for each person (can't use self.age because not a Household-level attribute),
# ages are strings by default, must convert to float
if 15 < float(age) < 59: # if the person is 15-65 years old,
num_labor += 1 # defines number of laborers as people aged 15 < x < 59
#except:
# num_labor = 0
else:
print(hh_row, 'except')
return num_labor
def initialize_migrants_2014(hh_row):
if_migrant = return_values_2014(hh_row, 'initial_migrants')
if if_migrant is not None and if_migrant[0] != -3:
num_mig = 1
else:
num_mig = 0
return num_mig |
739ac022c29814d67a2803f938f47c723116e98b | fghjgfdfgh/statistics | /function.py | 3,234 | 3.75 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import metrics
from sklearn.metrics import r2_score
def number_of_occurence(numpy_array:np.array):
"""function that checks the number of times each value occurs in an array
Arguments:
numpy_array: One dimensional numpy array
"""
values_checked_list = [] # this list keeps track of values that have been checked so that no value is checked twice
new_array = np.array([ # this is a two dimensional array, the top row will be the value and the row below it will correspond to the
[], # the number of times that value occurs in the data set
[]
])
for i in numpy_array: # checks each value in array
if i not in values_checked_list: # if the value has not been checked
values_checked_list.append(i) # adds value to the list of checked values
count = 0 # initializes count variable
for value in numpy_array:
if value == i: # if the value matches the valuable we are checking for
count += 1 # increment the count variable
append_array = np.array([[i],[count]]) # two dimensional array with row one being the value checked and row two being the number of times the value occurs in the data set
new_array = np.append(new_array, values=append_array, axis=1) # append the above array to the main array
return new_array # return the two dimensional new array
test_array = np.array([1,2,3,4,5,6,7,5,3,3,4,6,32,2,4,6,3,43,56,6,7,8,4,3,5,6,7,8,9,54,6])
def get_function(numpy_array:np.array):
"""Returns optimal polynomial regression function
Issues - Can sometimes fuck up if your data is really shit but unless theres some really fucked up data you will be fine
If u wanna fix it stick in some simple error handling
"""
list_of_values = [] #stores nested lists that contain the order of the polynomial, the r^2 score(how good the line of best fit is and the eqution of the polynomial)
for i in range(10):
model = np.poly1d(np.polyfit(x=numpy_array[0], y=numpy_array[1], deg=i)) # create an equation of polynomial degree i
score = r2_score(numpy_array[1], model(numpy_array[0])) # check how well this eqution fits the data
list_of_values.append([i, score, model]) # append sublist to main list
df = pd.DataFrame(list_of_values, columns=['degree', 'score', 'model']) # create a pandas data frame from the main list
row = 0 # variable to increment in below loop
model_found = False
max = df['score'].max() # finds maximum r^2 score
for i in df['score']: # this loop checks for the polynomial that matches the highest r^2 score
if i == max: # it also ensures that if there are multiple equtions with the same r^2 score it will pick the eqaution with lower order
if not model_found: # this should give the pretttiest line of best fit
final_model = df.iloc[row]['model']
score = i
model_found=True
row += 1
if model_found:
return(final_model, score) # return the final model and its r^2 score
|
6b391388364666dd0bbaa2cf5ee1841dd62475a0 | PhilLint/Master | /Knowledge Representation/Satisfiability Solver/process_sudokus.py | 2,460 | 3.5 | 4 | import math as m
import os
# reads.txt sudoku collection to a list
def read_txt(path, name):
input_file = open(path + name)
sudoku_lines = input_file.readlines()
sudokus = list()
for sd in sudoku_lines:
sudokus.append(list((sd.strip('\n'))))
return sudokus
# processes one sudoku_list to dimac format list
def one_sudoku_to_dimac(sudoku):
colcounter = 1
rowcounter = 1
# one sudoku as one dimac
dimac = list()
for i in range(0, len(sudoku)):
if sudoku[i] != '.':
dimac.append(str(rowcounter) + str(colcounter) + str(sudoku[i]) + " 0")
colcounter += 1
if colcounter > m.sqrt(len(sudoku)):
if rowcounter < m.sqrt(len(sudoku)):
rowcounter += 1
colcounter = 1
return dimac
# loops the one_sudoku_to_dimac function over the entire sudoku_list in one .txt file
def sudokus_to_dimacs(sudokus):
dimacs = list()
for sd in sudokus:
dimacs.append(one_sudoku_to_dimac(sd))
return dimacs
# saves each sudoku from dimac_list in one .txt file
def save_sudokus_in_dimacs(dimacs, save_path, file_name):
for i in range(len(dimacs)):
sudoku_name = file_name[:-4] + "_" + str(i) + ".txt"
file = open(save_path + sudoku_name, 'w')
file.write("\n".join(map(lambda x: str(x), dimacs[i])) + "\n")
file.close()
# saves sudokus of a collection in single .txt files
def save_collection(path, save_path, name):
dimacs = sudokus_to_dimacs(read_txt(path, name))
save_sudokus_in_dimacs(dimacs, save_path, name)
save_path = ".\\data\\processed_sudokus\\"
path = ".\\data\\"
# all collections
filenames = ["damnhard.sdk.txt", "subig20.sdk.txt", "top91.sdk.txt", "top91.sdk.txt", "top95.sdk.txt", "top100.sdk.txt",
"top870.sdk.txt", "top2365.sdk.txt"]
# save all sudokus of all collections
for name in filenames:
save_collection(path, save_path, name)
all_sudokus = os.listdir("data\\processed_sudokus")
rule_path = ".\\data\\sudoku-rules.txt"
processed_path = ".\\data\\processed_sudokus\\"
# Add rules to sudoku DIMACS
for i in range(len(all_sudokus)):
sudoku_name = all_sudokus[i]
rule_list = open(rule_path).readlines()
sudoku_list = open(processed_path + sudoku_name).readlines()
merged_list = rule_list + sudoku_list
with open(processed_path + sudoku_name, 'w') as f:
for item in merged_list:
f.write("%s" % item)
|
b032d63ae3f1084ad83f30a138b98772c4c9dd4b | OnlyHyun/Python | /ones.py | 841 | 3.578125 | 4 | """
2나 5로 나눌 수 없는 0 이상 10,000 이하의 정수 n이 주어졌는데,
n의 배수 중에는 10진수로 표기했을 때 모든 자리 숫자가 1인 것이 있다.
그러한 n의 배수 중에서 가장 작은 것은 몇 자리 수일까?
바보냐?? 1 11 111 1111 11111 ... 이 나눠지는지 봐
병신같이 풀려면 일일이 배수 곱해서 하면 된다
"""
s = []
while True:
n = input("0~1000이하의 정수를 입력하시오: ")
if(n == ' '):
print("끝 수고!!")
break
elif(int(n)%2 == 0 or int(n)%5 == 0):
print("제대로 입력 안하냐")
break
else:
while True:
s.append('1')
s1 = "".join(s)
if(int(s1)%int(n) == 0):
print(len(s1))
break
|
2958d6dfca1fe10c6630870b979084d1c2e2459e | Hallyson34/uPython | /ultrapassandoz.py | 128 | 3.65625 | 4 | x = int(input())
y = int(input())
i=1
soma=x
while x>=y:
y=int(input())
while soma<=y:
soma=soma+(x+i)
i+=1
print(i) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.