text stringlengths 37 1.41M |
|---|
if __name__ == '__main__':
x = eval(input("x = "))
if x >= 20:
print(0)
elif x >= 10:
print(0.5 * x - 2)
elif x >= 5:
print(3 * x - 5)
elif x >= 0:
print(x)
else:
print(0)
|
class Node:
left = right = None
def __init__(self, data=None):
self.data = data
def insert(self, data):
'''Insert new data to this BST'''
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
el... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
print('ใใใGitHubใฎไบ็ชใใฎใใกใคใซ')
# In[2]:
n = int(input('n = '))
# In[3]:
for i in range(n):print(i)
# In[ ]:
|
#!/usr/bin/env python3
import sys
class Marble:
def __init__(self, value):
self.value = value
self.cw = None
self.ccw = None
def place(self, other):
'''Inserts a new marble in the circle according to the stupid elven
rules. Returns the new current marble.
'''
... |
#!/usr/bin/env python3
import sys
import itertools
def main():
fname = sys.argv[1]
with open(fname) as f:
numbers = (int(line.rstrip()) for line in f if line != '\n')
freq = 0
encountered = set()
for num in itertools.cycle(numbers):
freq += num
if freq i... |
#import turtle
fib_x=1
fib_next=1
n=input()
n=int(n)
if n<=2:
fib_n=1
else:
print(fib_x)
print(fib_next)
#turtle.circle(fib_x,180)
#turtle.circle(fib_x,180)
i=3
count=0
while i<=n:
i+=1
count+=1
fib_temp=fib_x+fib_next
fib_x=fib_next
fib_next=fib_temp
#turtle.circle(fib_next,180)
print(fib_next)
... |
str=input("please enter any sentence: ")
for i in str:
print(i)
|
def number_sum(numbers):
result=0
for number in numbers:
result+=number
average=result/len(numbers)
return average
avg=number_sum([1,2,30,4,5,9])
print(avg) |
print('Enter the name of cat 1:')
catName1=input()
print('Enter the name of cat 2:')
catName2=input()
print('Enter the name of cat 3:')
catName3=input()
print('Enter the name of cat 4:')
catName4=input()
print('Enter the name of cat 5:')
catName5=input()
print('Enter the name of cat 5:')
catName6=input()
print('The cat... |
import pygame
import os
import random
import math
# ๋ฒ๋ธ ํด๋์ค ์์ฑ
class Bubble(pygame.sprite.Sprite):
def __init__(self, image , color, position=(0,0) ,row_idx=-1, col_idx=-1):
super().__init__()
self.image = image
self.color = color
self.rect = image.get_rect(center=position)
... |
class Pilha(object):
def __init__(self):
self.dados = []
#self.est = []
#self.parent = -1
def empilha(self, elemento):
self.dados.append(elemento)
#self.est.append(num)
#self.parent = num
def desempilha(self,tam):
for i in range(0,tam):
self.dado... |
def proper_divisors_list(n):
divisors = [[] for _ in range(n)]
for i in range(1, n):
k = i * 2
while k < n:
divisors[k].append(i)
k += i
return divisors
def find_amicable_total(divisors):
n = len(divisors)
sum_divisor = [sum(divisors[i]) for i in range(n)]
... |
def factorials_list(n):
if n == 0:
return [1]
else:
factorials = [1]
for i in range(1, n):
factorials.append(factorials[-1]*i)
return factorials
def lex_permutations(n):
"""
Find the nth permutation of the basic 10 digits in lexicographic order
"""
fator... |
""""
MongoDB database model for Lesson 7
"""
import os
from datetime import datetime
from pymongo import MongoClient
program_start = datetime.now()
class MongoDBConnection(object):
""" MongoDB Connection for content manager """
def __init__(self, host='127.0.0.1', port=27017):
""" Use the ip address... |
# Student: Bradnon Nguyen
# Class: Advance Python 220 - Jan2019
# Lesson04 - Refactor - basic_operations.py.
"""
Importing customer_db_model.py this file has the following function:
- add_customer.
-search_customer.
-delete_customer.
-update_customer_credit.
-list_active_customers.
"""
import logging
import datetime
... |
# Furniture class
# pylint: disable=too-few-public-methods
# pylint: disable=too-many-arguments
"""
Module to define furniture class
"""
from inventory_management.inventory_class import Inventory
class Furniture(Inventory):
"""
This class inherets from Inventory class and adds furniture attributes
to a di... |
# Student: Bradnon Nguyen
# Class: Advance Python 220 - Jan2019
# Lesson03 - customer_db_model.py
"""
This will create a customer model and database that can be used at HP Norton with the
following data:
Customer ID. Name. Lastname. Home address.
Phone number. Email address.
Status (active or inactive customer). Cr... |
""" Unit tests for assignment01 """
from unittest import TestCase
# from unittest.mock import MagicMock
from inventory_management.inventory_class import Inventory
from inventory_management.furniture_class import Furniture
from inventory_management.electric_appliances_class import ElectricAppliances
from inventory_mana... |
def counter(start=0):
count = start
def increment():
nonlocal count
count += 1
return count
return increment
def make_multipler(n):
def multiply(x):
return x * n
return multiply
mycounter = counter()
print('1st mycounter():', mycounter())
print('2nd mycounter():',... |
# Create Database
# pylint: disable=unused-wildcard-import
# pylint: disable=wildcard-import
"""
Module to create a database and define the Customer model
"""
from peewee import *
TABLE_NAME = 'customers'
DATABASE = SqliteDatabase(TABLE_NAME + '.db')
def main():
""" This fucntions initiates the database connect... |
"""
Module:calculator with basic methods.
"""
from .exceptions import InsufficientOperands
#class Calculator(object):
class Calculator:
"""
Class: Calculator
"""
def __init__(self, adder, subtracter, multiplier, divider):
self.adder = adder
self.subtracter = subtracter
self.mu... |
"""
Class object to handle inventory dictionary
"""
class Fullinventory:
""" Inventory Dictionary Utiltiy"""
def __init__(self):
self.full_inventory_dict = {}
def add_inventory(self, item_code, item_dict):
""" Add an item to the inventory dictionary """
self.full_inventory_dict[i... |
def most_common(filename):
fd = open(filename)
letters = "abcdefghijklmnopqrstuvwxyz"
dic = {}
for line in fd:
for letter in line:
if letter in letters:
if letter in dic:
dic[letter] += 1
else:
dic[letter] = 1
... |
#!/usr/bin/env python
#coding:utf -8
# l = [1,2,3,4,5,6,7,2,3,4]
# t = {"a":4, "b":2,"c":5,"e":3,"d":2}
# n = sorted(t.items(),key=lambda x:x[1],reverse=True)#1ไปฃ่กจvalue็ๅผ็ฑๅฐๅฐๅคง,reverseไปฃ่กจๅ่ฝฌ
# m = sorted(t.items(),key=lambda x:x[0])#0ไปฃ่กจkey็โaโๅฐโeโ
# print l[2:]
# print l[2:5]
# print l[2:5:2]
# print l[2:5:3]
# print n
# pr... |
import gc
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
temp=self.head
if self.head... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAft... |
#print("hello world")
---------------------------------------------------------------
#my_message = "Hello Aabhar"
#print(my_message)
---------------------------------------------------------------
#message = "hello Aabhar"
#print(message[0:5]) #print string from 0 to 4th index (but not 5th index)
#print(message... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Add Digits https://leetcode.com/problems/add-digits/
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
'''
#... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Two Sum: https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
'''
class Solution_first(object):
def twoSum(self,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
67. Add Binary https://leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
For example, a = "11" b = "1" Return "100".
'''
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
... |
"""
This script is meant to find duplicate files in a directory and subdirectories via md5 checksums
Any collisions found are listed.
Collisions are any two files with the same md5 hash value.
"""
from hashlib import md5
import os
rootDir="/home/user/Music/"
renamedCount = 0
fileDict = {}
collisions=0
ta... |
\Lists:
Complexity
Operation | Example | Class | Notes
--------------+--------------+---------------+-------------------------------
'Index' | l[i] | O(1) |
'Store' | l[i] = 0 | O(1) |
'Length' | len(l) | O(1) |
'App... |
def getFactors (n):
result = []
temp = []
getResult(n, 2, temp, result)
return result
def getResult(num, start, currentResult, finalResult):
import copy
if (num == 1):
if (len(currentResult) > 1):
# x= copy.deepcopy()
finalResult.append(currentResult[:]) #<------... |
class LinkedList:
def __init__(self, val= None, next = None):
self.val = val
self.next = next
def print_list(self):
node = self
r=''
while node:
r+= str(node.val)
node = node.next
if node: r += "-->"
print(r)
def remov... |
p = [0,1,2,3,4,5,6,7]
def findCelebrity(self, n):
x = 0
for i in xrange(n):
if knows(x, i):
x = i
if any(knows(x, i) for i in xrange(x)):
return -1
if any(not knows(i, x) for i in xrange(n)):
return -1
return x
'''
The first loop is to exclude n - 1 labels that ar... |
# dfs + stack
# def binaryTreePaths1(self, root):
# if not root:
# return []
# res, stack = [], [(root, "")]
# while stack:
# node, ls = stack.pop()
# if not node.left and not node.right:
# res.append(ls+str(node.val))
# if node.right:
# ... |
import collections
class simple_graph:
def __init__(self):
self.edges = {}
def neighbours(self, vertex):
return self.edges[vertex]
class Queue:
def __init__(self):
self.elements = collections.deque()
def empty(self):
return len(self.elements)==0
def put(self,... |
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
survey = ['jen','sarah','ellen','phil']
for person in favorite_languages:
if person in survey:
print('Thank you for accepting my survey, '+person.title()+'!')
else:
p... |
import numpy as np
import matplotlib.pyplot as plt
import random
from math import exp
from sys import exit
def main():
numberOfIteration = int(input("How many iteration do you want?"))
learningRate = float(input("What learning rate do you want?"))
#I shuffled the data
x = np.loadtxt('dataTrain.c... |
## Training using the Perceptron implementation in scikit-learn, as described
## in Python Machine Learning (pg 50), by Sebastian Raschka.
from moldata import *
## Data prep.
trainset1 = Molset(100, 'C', 20)
print(trainset1.X)
print(trainset1.y)
print([(len(trainset1.X), len(trainset1.X[0])), len(trainset1.y)])... |
# P3.40
# get cost input
cost = int(input("Please enter the cost of your groceries: $"))
if(10 <= cost <= 60):
coupon = 8
elif(60 < cost <= 150):
coupon = 10
elif(150 < cost <= 210):
coupon = 12
elif(210 < cost):
coupon = 14
else:
coupon = 0
if(coupon == 0):
print("You do not win a... |
# # Python File Write
# # To write to an existing file, you must add a parameter to the open() function:
# # 1. "a" - Append - will append to the end of the file
# # 2. "w" - Write - will overwrite any existing content (That means will delete the previous content and add new lines.
a = "Open the file Hello.txt an... |
'''Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.'''
x= 5
y = "Jhon"
print(x)
print(y)
'''Casting
If you want to specify the data type of a variable, this can be done with casting.'''
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
... |
a = 5
b = 10
a,b = b,a
'''temp = a
a = b
b = temp'''
print(a)
print(b)
'''a = int(input("Enter a value: "))
b = int(input("Enter a value: "))
temp = a
a = str(b) #10
b = str(temp) #5
print("A is: " + a)
print("B is: " + b)''' |
import sys
a = "Tuple is a collection which is odered but unchangeable.\nThat means there is no option to add or remove data directly from the array. But we can put duplicate values"
print(a)
tuple = (1, (2,3,4),5, 6,7)
print('tuple', sys.getsizeof(tuple)) #Memory requirement low
print(tuple)
'''del tuple #... |
from numpy import *
a= "2D array:"
print(a)
arr1 = array([
[1, 2, 3, 4, 9, 2],
[5, 6, 7, 8, 4, 1]
])
print("Array 1 is: ", arr1)
print("Datatype of Array1: ", arr1.dtype)
print("Dimension of Array1 :", arr1.ndim)
print("Shape of Array1 : ", arr1.shape)
b = "\n2D to 1D Array"
print(b)
arr2... |
from string import ascii_lowercase, ascii_uppercase
def rotate(text, offset):
new_lowercase = ascii_lowercase[offset:] + ascii_lowercase[:offset]
new_uppercase = ascii_uppercase[offset:] + ascii_uppercase[:offset]
translation = str.maketrans(ascii_lowercase + ascii_uppercase, new_lowercase + new_uppercase)
ret... |
def verify(isbn):
count = 0
total = 0
for ch in isbn:
if count <= 9 and ch.isdigit():
total += int(ch) * (10 - count)
count += 1
elif count == 9 and ch == 'X':
total += 10
count += 1
elif ch == '-':
pass
else:
... |
from random import choice
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if key == None:
self.key = ''.join(choice(ascii_lowercase) for _ in range(100))
elif key.isalpha() and key.islower():
self.key = key
else:
rai... |
#Gabriel Abraham
#notesonartificialintelligence
#printing out the value in a range, this time with a set increment
even_numbers = list(range(2,11,2))
print(even_numbers)
#A list will be created with value between 2 and 10. The third argument in range is the value of the increment to be followed.
#The program will go ... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 9
#Write a class admin that inherits from the user class.
from users import Users
from privileges import Privileges
class Admin(Users):
"""A simple admin class"""
def __init__(self, first_name, last_name, age):
"""Initialise attribute... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 6
#A list in a dictionary
#Store information about a pizza being ordered.
pizza = {
'crust' : 'thick',
'toppings' : ['mushroom', 'entra cheese'],
}
#Summarise the order.
print(f"You ordered a {pizza['crust']}-crust pizza with the f... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 7
#Write a loop which will ask users for their age, and then tell them the sode of their movie ticket.
prompt = "Welcome to the ticket machine. Enter your age: "
prompt += "\nType 'Quit' to end program\n"
age = ""
while age.lower() != 'q... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 9
class Restaurant:
def __init__(self, name, type):
restaurant_name = self.name
cusine_type = self.type
def open_restaurant():
"""Display a message"""
print(f"The restaurant {restaurant.name} is now open")
def describe_restaura... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 9
#Modify the class below.
class Users:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
#Add an attribute login_attempts
self.login_attempts = 0
def descri... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 5
#Turn the example from eariler into an if_elif_else chain
alien_color = 'purple'
if alien_color.lower() == "green":
print("You've just earned 5 points")
elif alien_color.lower() == 'yellow':
print("You've just earned 10 points")
else:... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 5
#Choose a color for an alien as was done in the eariler expamle, and then write an if-else chain.
alien_color = "yellow"
if alien_color.lower() == "green":
print("you've just earned 5 points")
else:
print("You've just earned 10 points... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 5
#Write an if statement that determines a person's stage at life. Set a value for the variable age, and then:
age = 46
if age < 2:
print("The person in question is a baby.")
elif age < 4:
print("the person is question is a toddler")
el... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 9
#The attributes will be information
#The classes will be behaviours
class Dog:
"""A simple attempt to model a god."""
def __init__(self, name,age):
"""Initialise name and age atrributes."""
self.name = name
self.age = age
def ... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 11
#Testing a function.
def get_formatted_name(first, last, middle = ""):
"""Generate a neatly formatted full name."""
if middle:
full_name = f"{first} {middle} {last}"
else:
full_name = f"{first} {last}"
return full_name.title()
... |
#Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 11
import unittest
from city_country import city_country
class CityTestCase(unittest.TestCase):
"""Test the city country function."""
def test_city_country(self):
"""Will the function work?"""
output = city_country('santiago', 'chil... |
# Assign a message to a variable, and print that message.
# Them change the value of the variable to a new message, and print the new message.
message = "This is the first message"
print(message)
message = "This is will be the new message with the latest variable"
print(message) |
#Gabriel Abraham
#notesonartificialintelligence
#Make a copy of the "pizza list", and then do the following:
minerals = ["Selenium", "Calcium","Magnesium"]
#Creating a copy of minerals list.
friend_minerals = minerals[:]
#Add a different pizza to the friend_mineral
friend_minerals.append("Cobalt")
#Prove that the li... |
#Gabriel Abraham
#notesinartificialintelligence
#Python Crash Course - Chapter 8
def make_album(artist_name, album_title, number_of_songs = ''):
"""Music Album Dictionary"""
music_album = {'Name' : artist_name, 'Album Name' : album_title}
if number_of_songs:
music_album['Number Of Songs'] = number_of_songs
re... |
#Gabriel Abraham
#notesofartificialintelligence
#Python Crash Course - Chapter 8
def show_messages(message_list):
"""Print elements from a list"""
for message in message_list:
print(message)
messages = ['Mental peace and Clarity', 'Abundance and Love', 'Radient energy and God form']
#I'll pass it a cpoy and not ... |
"""" Write a python program which accepts the radius of a circle from the user and compute the area (area of circle=pi*radius)"""
radius = int(input("Enter the radius"))
pi = 3.14
area = radius*pi
print("The area of the circle is", area) |
from __future__ import print_function
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
# define a function to convert a vector of time series into a 2D matr... |
def add_time(start, duration, day_of_week=''):
## Parse inputs
start_hour = int(start.split()[0].split(':')[0])
start_minute = int(start.split()[0].split(':')[1])
am_pm = start.split()[1]
duration_hour = int(duration.split(':')[0])
duration_minute = int(duration.split(':')[1])
## Days of t... |
class Stack:
num_of_stacks = 0
class Node:
def __init__(self,data):
self.data = data
self.next_node = None
def __init__(self):
self.top = None
self.stack_size = 0
Stack.num_of_stacks += 1
# isEmpty
def is_empty(self):
... |
import datetime
from src.handlers.code_handler import *
months = {
"jan": 1, "feb": 2, "mar": 3, "apr": 4,
"may": 5, "jun": 6, "jul": 7, "aug": 8,
"sep": 9, "oct": 10, "nov": 11, "dec": 12,
"january": 1, "february": 2, "march": 3,
"april": 4, "june": 6, "july": 5,
"august": 8, "september": 9, "... |
from sympy import (
Circle,
Point,
)
def get_location(list_of_positions_and_distance):
"""
This method receive a list with all postions and the distance to the emisor.
To to get the origin this method create three circles and get the intersection
point between this circles
>>> get_location... |
n=int(input())
flag=0
for i in range(2,n,-1):
if n%1==0:
flag=1
break
if flag==0:
print("prime")
else:
print("not")# your code goes here
|
s=input()
if s.isalpha():
print("Alphabest")
elif s.isnumeric():
print("Number")
else:
print("Special char")
|
def nth(n):
n = int(n)
if (n==1):
return str(n) + "st"
elif (n==2):
return str(n) + "nd"
elif (n==3):
return str(n) + "rd"
else:
return str(n) + "th" |
"""
Consider a singly linked list whose nodes are numbered starting at 0.
Define the even-odd merge of the list to be the list consisting of the even-numbered nodes followed by the odd-numbered nodes.
Write a program that computes the even-odd merge.
Example:
Input: L0 -> L1 -> L2 -> L3 -> L4
Output: L0 -> L2 -> L4 ... |
def max_unique_split(s: str) -> int:
# Container to track already used substrings
used_substrings = set()
current_substring = ''
for i, char in enumerate(s):
# Add the character to the current substring
current_substring += char
# If it's a new un... |
n=int(input("Enter the number of fibonacci numbers you want: - "))
a,b=0,1
print("\n{}\t{}".format(a,b),end=" ")
for i in range(n-2):
c=a+b
print("\t{}".format(c),end=" ")
a=b
b=c
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 24 11:34:34 2017
@author: dldien
"""
import numpy as np
X = np.matrix([[1, 1, 1, 1, 1], [0, 0.5, 1.2, 2.5, 3]]).T
y = np.matrix([1, 2.5, 3.5, 4, 5.5]).T
theta = np.matrix([0, 0.5]).T
alpha = 0.03
it = 10
for i in range(0, it):
h = X * theta;... |
import numpy as np
A = np.array([2,5,3,6,7,8])
B = np.array(range(1,200+1))
C = np.linspace(0, 1000, 1001)
C = C[C % 2 == 0]
A5 = A + 5
B3 = B * 3
A_sort = np.sort(A)
Dict = {'Name' : 'Duong Lu Dien', 'Age' : 21, 'Course' : 'Nguyen Ly May Hoc'}
Dict['Course'] = 'Tri Tue Nhan Tao'
def hello():
name = input('Ent... |
def strStr(haystack: str, needle: str) -> int:
if needle == '':
return 0
if needle in haystack:
print(haystack.index(needle))
else:
print(-1)
if __name__ == '__main__':
strStr("hello", "ll") |
def smallerNumbersThanCurrent(nums):
small = []
for i in range(len(nums)):
count = 0
for a in range(len(nums)):
if nums[i] > nums[a]:
count += 1
small.append(count)
print(small)
if __name__ == '__main__':
smallerNumbersThanCurrent([7, 7, 7, 7]) |
"""
This program analyzes bikeshare data for several cities and
interactively displays important summary statistics for each city.
Author Gregory Rowe
"""
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washi... |
# ------
# Robot.py class
# This runs the robot.
# Copyright 2015. Pioneers in Engineering.
# ------
import Motors
class Robot:
# Constructor for a generic robot program
def __init__(self):
self.motors = []
for addr in Motor.addrs:
motor = Motor(addr)
self.motors.a... |
#!/usr/bin/env python3
# HW05_ex09_01.py
# Write a program that reads words.txt and prints only the
# words with more than 20 characters (not counting whitespace).
##############################################################################
# Imports
# Body
def print_large_words():
try:
with open("words... |
import tkinter as tk
from tkinter import ttk
class HelloView(tk.Frame):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.name = tk.StringVar()
self.hello_string = tk.StringVar()
self.hello_string.set("Hello World")
name_label = t... |
import tkinter as tk
from tkinter import ttk
from tkinter.simpledialog import askstring
def ask_string_dialog(title="Enter a string input dialog", prompt="Please enter a value") -> str:
root = tk.Tk()
string = askstring(
parent=root,
title=title,
prompt=prompt
)
root.destroy()
... |
from enum import Enum
def is_station(station):
try:
names = set([member.name for member in Station])
if station.name in names:
return True
else:
return False
except AttributeError:
print("Station does not exist")
class DateFormat(Enum):
""" Enum fo... |
#!/usr/bin/env python3
# Calculator V2 - ACG Intro to Python Scripting Chapter 5
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
if num2 == 0:
pri... |
from collections import deque
g = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 4],
3: [2, 4],
4: [2, 3]
}
q = deque()
def bfs(g, node, q):
visited = [False for k in g.keys()]
inqueue = [False for k in g.keys()]
q.appendleft(node)
inqueue[node] = True
combs = [... |
'''
***Logistic Regression***
With Gradient Descent
Author :
Pranath Reddy
2016B5A30572H
'''
import math
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# A function to return the column at specified index
def getcol(data,c):
col = []
for i in range(len(data)):
... |
import threading
import time
class multithreading (threading.Thread):
def __init__(self, threadID, nome):
threading.Thread.__init__(self)
self.threadID = threadID
self.nome = nome
def run(self):
print ("Initializing " + self.name)
string = 'testetestetestetestetestet... |
class Person(object):
count=0
name1='vs'
def __init__(self,a,b,c):
self.name=a
self.sex=b
self.classroom=c
Person.count+=1
p1 = Person('Bob', 'boy',423)
p2 = Person('Boq', 'girl',403)
print(p1.classroom)
print(Person.count)
p1.name1='afa'
#Person.name1='afa'
print(p1.name1)... |
print("Welcome to the Temperature Conversion Program")
tmp = float(input("What is the given temperature in degree fahrenheit?"))
cs = ((tmp - 32) * 5) / 9
kv = ((tmp + 459.67) * 5) / 9
print("Degrees Fahrenheit:", tmp)
print("Degrees Celsius:", round(cs,4))
print("Degrees Kelvin:", round(kv, 4)) |
print("Welcome to the Multiplication/Exponent Table app")
name = input("Hello, what is your name:")
num = float(input("What number would you like to work with?"))
print("Multiplication table for %s", num)
for i in range(1,10):
mult = i*num
print("{} * {} = {}".format(i,num,round(mult,2)))
for i in range(1,10... |
# -*- coding: utf-8 -*-
#LeetCode - 392_Is_Subsequence.py
#192ms 74.79%
'''
Instruction: LeetCode 392 - Is Subsequence - [M]
Developer: lrushx
Process Time: Apr 13, 2017
'''
'''
Total Accepted: 28263
Total Submissions: 63778
Given a string s and a string t, check if s is subsequence of t.
You may assume that there... |
## 141_Linked_List_Cycle.py
## 82ms 50%
'''
Total Accepted:233.8K
Total Submissions:
Instruction: LeetCode 141 - Linked List Cycle [E]
Developer: lrushx
Process Time: Feb 23, 2018
'''
'''
Given a linked list, determine if it has a cycle in it.
'''
# Definition for singly-linked list.
# class ListNode(object):
# ... |
#!/bin/python3
'''
Instruction: HackerRank - The Full Counting Sort - [M]
Success Rate: 83.41%
Max Score: 40
Difficulty: Medium
Submitted 20512 times
Developer: lrushx
Process Time: Mar 29, 2018
https://www.hackerrank.com/challenges/countingsort4/problem
'''
import sys
from collections import defaultdict
def countin... |
# -*- coding:utf-8 -*-
'''
Challenge: duplicate
Total Acceptence: 27.35%
Developer: lrushx
Process Time: Apr 08, 2018
https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=3&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
'''
class Solution:
... |
## 815_Bus_Routes\[H\].py
## 512ms %
'''
Total Accepted: 1.7K
Total Submissions: 5.4K
Developer: lrushx
Process Time: Apr 11, 2018
https://leetcode.com/problems/bus-routes/description/
'''
'''
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [... |
## 796_Rotate_String.py
## 36ms 95.95%
'''
Total Accepted: 7.4K
Total Submissions: 11.4K
Instruction: LeetCode 796 - Rotate String [M]
Developer: lrushx
Process Time: Mar 18, 2018
'''
'''
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.