blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
5db2ce733c009c2807c8179ef38c2dae82c46036 | x223/cs11-student-work-Aileen-Lopez | /find_odds.py | 157 | 3.65625 | 4 | list = [3,4,7,13,54,32,653,256,1,41,65,83,92,31]
def find_odds(input):
for whatever in input:
if whatever % 2 == 1:
print "whatever"
|
e12e1a8823861cee15aee0f931bcc4f117d3e514 | KNootanKumar/prototype-for-Notifying-user-of-a-database-through-mail | /youtube_video_list.py | 778 | 3.8125 | 4 | import sqlite3
#print("hello")
conn =sqlite3.connect("Youtube_videos.db")
cur=conn.cursor()
#print("hiii babes")
cur.execute("CREATE TABLE IF NOT EXISTS youtube_videos(id INTEGER,tittle text , url text)")
#print("hello baby")
cur.execute("INSERT INTO youtube_videos VALUES(12,'Video_12','https://www.youtube.com/watch?v=Ae7yiE6Sx38')")
#cur.execute("INSERT INTO youtube_videos VALUES(2,'Video_2','https:////www.youtube.com//watch?v=0Zp0dvT3nCQ')")
#cur.execute("INSERT INTO youtube_videos VALUES(3,'Video_3','https://www.youtube.com/watch?v=sayK41hPXyM')")
#cur.execute("INSERT INTO youtube_videos VALUES(4,'Video_4','https://www.youtube.com/watch?v=KyOPKQZUaJA')")
cur.execute("SELECT *FROM youtube_videos")
conn.commit()
db=cur.fetchall()
print(db)
conn.commit()
conn.close()
|
016c7e2da4516be168d3f51b34888d12e0be1c5d | adrian-calugaru/fullonpython | /sets.py | 977 | 4.4375 | 4 | """
Details:
Whats your favorite song?
Think of all the attributes that you could use to describe that song. That is: all of it's details or "meta-data". These are attributes like "Artist", "Year Released", "Genre", "Duration", etc. Think of as many different characteristics as you can.
In your text editor, create an empty file and name it main.py
Now, within that file, list all of the attributes of the song, one after another, by creating variables for each attribute, and giving each variable a value. Here's an example:
Genre = "Jazz"
Give each variable its own line. Then, after you have listed the variables, print each one of them out.
For example:
Artist = "Dave Brubeck"
Genre = "Jazz"
DurationInSeconds = 328
print(Artist)
print(Genre)
print(DurationInSeconds)
Your actual assignment should be significantly longer than the example above. Think of as many characteristics of the song as you can. Try to use Strings, Integers and Decimals (floats)!
"""
|
40ec1ba7e942414a776398fba3730f76d3471fb7 | star83424/python-practice | /python-practice/sorting.py | 5,137 | 3.984375 | 4 | def swap(nums, i, j):
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
class SortUtils:
@staticmethod
def bubble_sort(nums):
print(f'start sorting {nums}')
for i in range(len(nums) - 1):
for j in range(len(nums) - 1):
if nums[j] > nums[j+1]:
swap(nums, j, j+1)
return nums
@staticmethod
def selection_sort(nums):
print(f'start sorting {nums}')
for i in range(len(nums)):
min_index = i
for j in range(i + 1, len(nums)):
if nums[j] < nums[min_index]:
min_index = j
swap(nums, i, min_index)
return nums
@staticmethod
def insertion_sort(nums):
print(f'start sorting {nums}')
ans = [nums[0]]
for i in range(1, len(nums)):
for j in range(len(ans)):
if nums[i] < ans[j]:
ans.insert(j, nums[i])
break
if j == len(ans)-1:
ans.append(nums[i])
return ans
@staticmethod
def quick_sort(nums):
print(f'start sorting {nums}')
left, right, pivot = 0, len(nums)-2, len(nums)-1
while True:
while left < pivot and nums[left] <= nums[pivot]:
left += 1
while right > left and nums[right] >= nums[pivot]:
right -= 1
# print(nums)
if left < right:
# print(f'swap {left}(val:{nums[left]}) with {right}(val:{nums[right]})')
swap(nums, left, right)
else:
swap(nums, pivot, left)
# print(f"swap pivot {pivot} at {left}: {nums}")
if left > 0:
nums[0: left] = SortUtils.quick_sort(nums[0: left])
if left < len(nums)-2:
nums[left+1:] = SortUtils.quick_sort(nums[left+1:])
return nums
return nums
@staticmethod
def merge_sort(nums):
print(f'start sorting {nums}')
length = len(nums)
if length < 2:
return nums
left = SortUtils.merge_sort(nums[0: int(length/2)])
right = SortUtils.merge_sort(nums[int(length/2):])
ans, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
ans.append(left[i])
i += 1
else:
ans.append(right[j])
j += 1
if i < len(left):
ans.extend(left[i:])
if j < len(right):
ans.extend(right[j:])
return ans
@classmethod
def heap_sort(cls, nums):
print(f'start sorting {nums}')
# build the heap : n^n
cls.__build_heap(nums)
print(f'__build_heap: {nums}')
# pop out the first one & heapify down to maintain the heap
for i in range(len(nums)-1, -1, -1):
cls.__pop(nums, i)
cls.__heapify(nums, 0, i)
return nums
@classmethod
def __build_heap(cls, nums):
# Heapify all none leaves nodes from bottom to top
for i in range(int(len(nums)/2), -1, -1):
cls.__heapify(nums, i, len(nums))
@staticmethod
def __heapify(nums, i, length):
max_index = i
left = i*2 + 1
if left < length and nums[left] > nums[max_index]:
# left child might be the max
max_index = left
right = (i+1) * 2
if right < length and nums[right] > nums[max_index]:
# right child is the max
max_index = right
# Need swap
if max_index != i:
nums[i], nums[max_index] = nums[max_index], nums[i]
# keep on heapify-ing down
SortUtils.__heapify(nums, max_index, length)
@staticmethod
def __pop(nums, i):
print(f'pop{nums[0]}')
# fake pop: swap the popped one with the last one
nums[i], nums[0] = nums[0], nums[i]
class Node:
def __init__(self, val, left=None, right=None):
self.left = left
self.right = right
self.val = val
"""
0
1 2
3 4 5 6
[3, 1, 5, 3, 4, 2, 1, 6, 7, 8, 4, 10, 12, 8, 9, 0, 11]
12
11 10
7 8 5 9
6 1 4 4 3 2 8 1
0 3
[0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12]
"""
class Sorting:
@staticmethod
def main(case):
# 2021/05/09
# print(SortUtils.bubble_sort(case1[:]))
# print("----")
# print(SortUtils.selection_sort(case1[:]))
# print("----")
# print(SortUtils.insertion_sort(case1[:]))
# print("----")
# print(SortUtils.quick_sort(case1[:]))
# print("----")
# print(SortUtils.merge_sort(case1[:]))
# ----------------------------------------------------------
# 2021/05/10
for i in range(20 - 1, -1, -1):
print(i)
print("----")
print(SortUtils.heap_sort(case[:]))
|
9987ab52003b44485eca176c04f343d30a0e937a | star83424/python-practice | /python-practice/binary_search_tree.py | 1,984 | 3.921875 | 4 | from sorting import SortUtils
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def print(self):
print(f'val: {self.val}, left: "{self.left}, right: {self.right}')
def build_binary_search_tree(nums):
root = None
for i in nums:
root = build_tree_node(root, i)
return root
def build_tree_node(root, i):
if root is None:
return Node(i)
if i >= root.val:
if root.right is None:
root.right = Node(i)
else:
root.right = build_tree_node(root.right, i)
else:
if root.left is None:
root.left = Node(i)
else:
root.left = build_tree_node(root.left, i)
return root
def traversal(root):
if root is None:
return
traversal(root.left)
root.print()
traversal(root.right)
#
# def self_then_children(root):
# if root is None:
# return
# root.print()
# self_then_children(root.left)
# self_then_children(root.right)
def binary_search_in_sorted_list(nums, target, i = None, j = None):
if i is None:
i = 0
if j is None:
j = len(nums)
if i == j:
print(f"Cannot find {target}!")
return
center = int((i+j) / 2)
if target == nums[center]:
print(f"{target} found!")
elif target > nums[center]:
binary_search_in_sorted_list(nums, target, center+1, j)
else:
binary_search_in_sorted_list(nums, target, i, center)
"""
0
1 2
3 4 5 6
left: i*2 +1
right (i+1)*2
"""
class BST:
@staticmethod
def main(case1):
root = build_binary_search_tree(case1)
traversal(root)
# Binary search
test = [8, 2, 4, 1, 3]
print(test)
SortUtils.heap_sort(test)
print(test)
binary_search_in_sorted_list(test, 5)
|
6dba0696232cf84d9d0f5625f8e58972f892d179 | Robo4al/robot | /step.py | 1,606 | 3.546875 | 4 | import time
from machine import Pin
'''
[StepMotor]
Por padrão, ao criar um objeto do tipo StepMotor os pinos utilizados do Roberval serão:
- PIN1 = 18
- PIN2 = 19
- PIN3 = 22
- PIN4 = 23
* Fases do motor:
a) phase IN4 = [0,0,0,1]
b) phase IN4 and IN3 = [0,0,1,1]
c) phase IN3 = [0,0,1,0]
d) phase IN3 and IN2 = [0,1,1,0]
e) phase IN2 = [0,1,0,0]
f) phase IN2 and IN1 = [1,1,0,0]
g) phase IN1 = [1,0,0,0]
h) phase IN1 and IN4 = [1,0,0,1]
* step()
- Movimento = direita | velocidade = 5ms | passos = 1
stepMotor.step(False)
- Movimento = direita | velocidade = 10ms | passos = 1
stepMotor.step(False, 10)
- Movimento = esquerda | velocidade = 10ms | passos = 100
stepMotor.step(True, 10, 100)
- Movimento = direita | velocidade = 5ms | passos = 100
stepMotor.step(False, stepCount=100)
- Movimento = esquerda | velocidade = 10ms | passos = 1
stepMotor.step(True, sleepMs=100)
'''
class StepMotor:
def __init__(self, PIN1=18, PIN2=19, PIN3=22, PIN4=23):
self.in1 = Pin(PIN1, Pin.OUT)
self.in2 = Pin(PIN2, Pin.OUT)
self.in3 = Pin(PIN3, Pin.OUT)
self.in4 = Pin(PIN4, Pin.OUT)
def step(self, left, sleepMs=5, stepCount=1):
values = [[0,0,0,1], [0,0,1,1], [0,0,1,0], [0,1,1,0], [0,1,0,0], [1,1,0,0], [1,0,0,0], [0,0,1,1]]
if left:
values.reverse()
for count in range(stepCount):
for value in values:
self.in1.value(value[0])
self.in2.value(value[1])
self.in3.value(value[2])
self.in4.value(value[3])
time.sleep_ms(sleepMs)
if __name__ == "__main__":
motor = StepMotor()
motor.step(False, stepCount=4096) |
6657511dc98487fd3160d8fbe9bfee4975f5cb6d | mkatzef/difference-checker | /DifferenceChecker.py | 7,078 | 3.8125 | 4 | """ Number base, and to/from ASCII converter GUI. Now supporting Fractions
Author: Marc Katzef
Date: 20/4/2016
"""
from tkinter import *
#from tkinter.ttk import *
class Maingui:
"""Builds the gui in a given window or frame"""
def __init__(self, window):
"""Places all of the GUI elements in the given window/frame, and
initializes the variables that are needed for this GUI to do anything"""
self.window = window
self.top_rely = 0
self.next_rely = 0.15
top_height = 40
self.w2 = StringVar()
self.w2.set('20')
self.h2 = StringVar()
self.h2.set('14')
self.top_bar = Frame(window)
self.top_bar.place(x=0, y=0, relwidth=1, height=top_height)
self.entry1_label = Label(self.top_bar, text='Text A', font=('Arial', 12), anchor='center')
self.entry1_label.place(relx=0.1, y=0, height=top_height, relwidth=0.3)
self.entries = Frame(window)
self.string1_entry = Text(self.entries)
self.string1_entry.place(relx=0, y=0, relwidth=0.5, relheight=1)
self.entry2_label = Label(self.top_bar, text='Text B', font=('Arial', 12), anchor='center')
self.entry2_label.place(relx=0.6, y=0, height=top_height, relwidth=0.3)
self.string2_entry = Text(self.entries)
self.string2_entry.place(relx=0.5, y=0, relwidth=0.5, relheight=1)
self.entries.place(relx=0, y=top_height, relwidth=1, relheight=1, height=-(top_height))
self.button1 = Button(self.top_bar, command=self.check, font=('Arial', 10, 'bold'))
self.button1.place(relx=0.5, y=top_height/2, relwidth=0.2, anchor='center')
self.displaying_results = False
self.change_button('light gray', 'Check')
def insert_result(self, result, summary, ratio, red_map=-1):
self.result = Text(self.entries)
self.result.place(relx=0, relwidth=1, relheight=1)#
self.button1['command'] = self.remove_results
self.result.delete('1.0', END)
self.result.tag_configure("red", background="#ffC0C0")
self.result.tag_configure("grey", background="#E0E0E0")
grey_white = 0
if red_map == -1:
self.result.insert(END, result)
else:
counter = 0
for line in result:
self.result.insert(END, line + '\n')
is_red = red_map[counter]
grey_white = 1 - grey_white
if is_red:
self.result.tag_add("red", '%d.0' % (counter + 1), 'end-1c')
elif grey_white:
self.result.tag_add("grey", '%d.0' % (counter + 1), 'end-1c')
counter += 1
self.entry1_label['text'] = ''
self.entry2_label['text'] = ''
#red_component = int((1-ratio) * 255)
#green_component = int((2 ** ratio - 1) * 255)
#colour = "#%02x%02x00" % (red_component, green_component)
if summary == 'Identical':
self.change_button("light green", "100%")
else:
self.change_button("#FFC0C0", "%.0f%%" % (100 * ratio))
self.displaying_results = True
def change_button(self, colour, text):
self.button1['background'] = colour
self.button1['text'] = text
def remove_results(self):
self.result.destroy()
self.change_button('light gray', 'Check')
self.button1['text'] = 'Check'
self.button1['command'] = self.check
self.entry1_label['text'] = 'Text A'
self.entry2_label['text'] = 'Text B'
self.displaying_results = False
def check(self, *args):
"""Collects the appropriate information from the user input, then
retrieves the appropriate output, and places it in the appropriate text
field, appropriately"""
file_a = input_string = self.string1_entry.get('1.0', 'end-1c')
file_b = input_string = self.string2_entry.get('1.0', 'end-1c')
list_a = [line.strip() for line in file_a.splitlines()]
list_b = [line.strip() for line in file_b.splitlines()]
size_a = len(list_a)
size_b = len(list_b)
oh_oh = 'Empty:'
problem = 0
if size_a == 0:
oh_oh += ' Text A'
problem += 1
if size_b == 0:
oh_oh += ' Text B'
problem += 1
if problem == 1:
self.insert_result(oh_oh, 'Problem', 0)
return
elif problem == 2: #Both empty
self.insert_result(oh_oh, 'Identical', 1)
return
result = []
identical = True
red_map = []
correct_counter = 0
space = max([len(line) for line in list_a])
common_template = '%d:\t%' + str(space) + 's |=| %''s'
difference_template = '%d:\t%' + str(space) + 's |X| %''s'
#common_template = '%s |= %d =| %s\n'
#difference_template = '%s |X %d X| %s\n'
for index in range(min(size_a, size_b)):
line_a = list_a.pop(0)
line_b = list_b.pop(0)
if line_a == line_b:
correct_counter += 1
result.append(common_template % (index+1, line_a, line_a))
#result += common_template % (line_a, index+1, line_a)
red_map.append(False)
else:
identical = False
new_part = difference_template % (index+1, line_a, line_b)
result.append(new_part)
red_map.append(True)
#result += difference_template % (line_a, index+1, line_b)
if len(list_a) > 0:
identical = False
for line in list_a:
index += 1
new_part = difference_template % (index+1, line, '')
result.append(new_part)
red_map.append(True)
#result += difference_template % (line, index+1, '')
elif len(list_b) > 0:
identical = False
for line in list_b:
index += 1
new_part = difference_template % (index+1, '', line)
result.append(new_part)
red_map.append(True)
#result += difference_template % ('', index+1, line)
correct_ratio = correct_counter / max(size_a, size_b)
if identical:
summary = 'Identical'
else:
summary = 'Different'
self.insert_result(result, summary, correct_ratio, red_map)
def main():
"""Sets everything in motion"""
window = Tk()
window.title('Difference Checker')
window.minsize(220, 200)
Maingui(window)
window.mainloop()
if __name__ == '__main__':
main()
|
f1dd49c9897bd996a589f1421a058fed769e444d | AnttiVainikka/ot-harjoitustyo | /game/src/UI/move.py | 1,056 | 3.546875 | 4 | # pylint: disable=no-member
import pygame
pygame.init()
from Classes.character import Character
def move(character):
"""Registers if the player presses or releases the arrow keys and configures the main character based on it."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
character.move_left()
if event.key == pygame.K_RIGHT:
character.move_right()
if event.key == pygame.K_UP:
character.move_up()
if event.key == pygame.K_DOWN:
character.move_down()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
character.stop_left()
if event.key == pygame.K_RIGHT:
character.stop_right()
if event.key == pygame.K_UP:
character.stop_up()
if event.key == pygame.K_DOWN:
character.stop_down()
|
95b5e8ce6cfb6939b7c7eb12614f655792453046 | kaen98/python_demo | /ChapterFive/5-3.py | 203 | 3.640625 | 4 | alien_color = ['green', 'yellow', 'red']
alien_one = 'green'
if alien_one in alien_color:
print('alien color is green, +5 points')
alien_two = 'white'
if alien_two in alien_color:
print('+5 points') |
1c3ab432c612e27d412d644ff7386660a18a209a | Evohmike/Password-Locker | /Display.py | 8,410 | 4.125 | 4 | #!/usr/bin/env python3.6
from creds import Credentials
from user import User
def create_account(username,password):
'''
This function creates new account
'''
new_user = User(username,password)
return new_user
def save_new_user(user):
'''
This function saves a user
'''
User.save_user(user)
def login_account(login):
return User.user_login(login)
def create_credentials(account,username,email,password):
'''
This creates new credentials
'''
new_credentials = Credentials(account,username,email,password)
return new_credentials
def save_user_credentials(credentials):
'''
This function saves credentials
'''
credentials.save_credentials()
def delete_credentials(credentials):
'''
This deletes credentials
'''
credentials.delete_credentials()
def find_credentials(name):
'''
this finds the credentials using account name and returns details
'''
return Credentials.find_by_account_name(name)
def copy_username(name):
return Credentials.copy_username(name)
def check_credentials_exist(name):
'''
This function to check if a credentials exists
'''
return Credentials.credentials_exist(name)
def display_credentials():
'''
Function that returns all the saved credentials
'''
return Credentials.display_credentials()
def generate_password(password_length):
return Credentials.generate_password(password_length)
def main():
print("HELLO! WELCOME TO PASSWORD LOCKER!!")
while True:
print('''
ca - create account
log - login
esc - Escape''')
short_code = input().lower()
if short_code == "ca":
print("Create Acount")
print("First, Create a username:")
print("_" * 20)
username = input()
password= input("Choose a password of your choice: ")
print("_" * 20)
save_new_user(create_account(username, password))
print(f"""Your user details - Username : {username} Password : {password}""")
print("")
print(f"Hello {username} Choose the options below")
print("")
while True:
print("Use these short codes: cc - create new credentials, dc - display credentials, fc - find a credentials, wq - exit credentials list")
short_code = input().lower()
if short_code == 'cc':
print("New credentials")
print("-"*40)
print('')
print("Account name ...")
a_name = input()
print('')
print("User name ...")
u_name = input()
print('')
print("Email address ...")
email = input()
print('')
print("Account password")
acc_password = input()
print('')
save_user_credentials(create_credentials(a_name, u_name, email, acc_password))
print('')
print(f"New credential account : {a_name}, User name : {u_name}")
print('')
elif short_code == 'dc':
if display_credentials():
print("This is a list of all the credentials")
print('')
for Credentials in display_credentials():
print(f"Account : {Credentials.account_name}, User name : {Credentials.user_name} E-mail address : {Credentials.email} Password : {Credentials.password}")
print('')
else:
print('')
print("I'm sorry, you seem not to have saved any credentials")
print('')
elif short_code == 'fc':
print("Enter the Account you want")
search_name = input()
if check_credentials_exist(search_name):
search_name = find_credentials(search_name)
print('')
print(f"{search_name.user_name} {search_name.email}")
print('-'*20)
print('')
print(f"Account ... {search_name.account_name}")
print(f"Password ... {search_name.password}")
print('')
else:
print('')
print("Credentials do not exist")
print('')
elif short_code == "wq":
print('')
print("Goodbye ...")
break
else:
print("Please input a valid code")
elif short_code == "log":
print("Log in")
print("Enter User Name")
uname = input()
print("Enter password")
password = input()
print("_" * 20)
print(f"Hello {uname} Kindly choose the options below")
print("")
while True:
print("Use these short codes: cc - create new credentials, dc - display credentials, wq - exit credentials list")
short_code = input().lower()
if short_code == 'cc':
print("New credentials")
print("-"*10)
print('')
print("Account name ...")
a_name = input()
print('')
print("User name ...")
u_name = input()
print(f"Hello {uname} Kindly choose the options below")
print("")
while True:
print("Use these short codes: cc - create new credentials, dc - display credentials, wq - exit credentials list")
short_code = input().lower()
if short_code == 'cc':
print("New credentials")
print("-"*10)
print('')
print("Account name ...")
a_name = input()
print('')
print("User name ...")
u_name = input()
print('')
print("Email address ...")
email = input()
print('')
print("Account password")
acc_password = input()
save_user_credentials(create_credentials(a_name, u_name, email, acc_password))
print('')
print(f"New credential account : {a_name}, User name : {u_name}")
print('')
elif short_code == 'dc':
if display_credentials():
print("This is a list of all the credentials")
print('')
for Credentials in display_credentials():
print(f"Account : {Credentials.account_name}, User name : {Credentials.user_name} E-mail address : {Credentials.email} Password : {Credentials.password}")
print('')
else:
print('')
print("I'm sorry, you seem not to have saved any credentials")
print('')
elif short_code == "wq":
print('')
print("Goodbye ...")
break
else:
print("Please input a valid code")
elif short_code == "esc":
print('')
print("Exiting")
break
else:
print("The short code does not seem to exist,please try again")
if __name__ == '__main__':
main() |
c0fcc2f027faf50b1e329d5f5e4ef07f6228eff3 | mercado-joshua/Tkinter__Program_Password-Generator | /main.py | 3,720 | 3.546875 | 4 | #===========================
# Imports
#===========================
import tkinter as tk
from tkinter import ttk, colorchooser as cc, Menu, Spinbox as sb, scrolledtext as st, messagebox as mb, filedialog as fd
import string
import random
class Password:
"""Creates Password."""
def __init__(self, adjectives, nouns):
self._adjectives = adjectives
self._nouns = nouns
self._adjective = random.choice(self._adjectives)
self._noun = random.choice(self._nouns)
self._number = random.randrange(0, 100)
self._special_char = random.choice(string.punctuation)
# ------------------------------------------
def generate(self):
password = f'{self._adjective}{self._noun}{str(self._number)}{self._special_char}'
return password
#===========================
# Main App
#===========================
class App(tk.Tk):
"""Main Application."""
#------------------------------------------
# Initializer
#------------------------------------------
def __init__(self):
super().__init__()
self._init_config()
self._init_vars()
self._init_widgets()
#-------------------------------------------
# Window Settings
#-------------------------------------------
def _init_config(self):
self.resizable(False, False)
self.title('Password Generator Version 1.0')
self.iconbitmap('python.ico')
self.style = ttk.Style(self)
self.style.theme_use('clam')
#------------------------------------------
# Instance Variables
#------------------------------------------
def _init_vars(self):
self._adjectives = [
'sleepy', 'slow', 'smelly', 'wet', 'fat',
'red', 'orange', 'yellow', 'green', 'blue',
'purple', 'fluffy', 'white', 'proud', 'brave'
]
self._nouns = [
'apple', 'dinosaur', 'ball', 'toaster', 'goat',
'dragon', 'hammer', 'duck', 'panda', 'cobra'
]
#-------------------------------------------
# Widgets / Components
#-------------------------------------------
def _init_widgets(self):
frame = self._create_frame(self,
side=tk.TOP, fill=tk.BOTH, expand=True)
fieldset = self._create_fieldset(frame, 'Create Password',
side=tk.TOP, fill=tk.BOTH, expand=True, padx=10, pady=10)
self.password = tk.StringVar()
self._create_entry(fieldset, '', self.password, 'Helvetica 20 bold',
fill=tk.X, padx=10, pady=10, ipady=10)
self._create_button(fieldset, 'Generate', self._create_password,
pady=(0, 10))
# INSTANCE ---------------------------------
def _create_frame(self, parent, **kwargs):
frame = ttk.Frame(parent)
frame.pack(**kwargs)
return frame
def _create_fieldset(self, parent, title, **kwargs):
fieldset = ttk.LabelFrame(parent, text=title)
fieldset.pack(**kwargs)
return fieldset
def _create_button(self, parent, title, method, **kwargs):
button = ttk.Button(parent, text=title, command=lambda: method())
button.pack(**kwargs)
return button
def _create_entry(self, parent, title, var_, font, **kwargs):
entry = ttk.Entry(parent, text=title, textvariable=var_, font=font)
entry.pack(**kwargs)
return entry
def _create_password(self):
password = Password(self._adjectives, self._nouns)
self.password.set(password.generate())
#===========================
# Start GUI
#===========================
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main() |
8e2115c1623bfb4c296b2c4ec8a88ce21dd41e93 | nalin2002/Cryptography-Encryptions | /upload_file_to_googledrive.py | 1,232 | 3.5 | 4 |
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os
def Upload_File_GD(filename):
gauth=GoogleAuth()
gauth.LocalWebserverAuth()
drive=GoogleDrive(gauth)
local_file_path=" " # The path of the file in the system
for file in os.listdir(local_file_path):
if (file==' '): #Mention the file name to be uploaded
f= drive.CreateFile({'title':file})
f.SetContentString(os.path.join(local_file_path,file))
f.Upload()
f=None
str= filename+' Successfully Uploaded to Google Drive'
print(str)
# gauth = GoogleAuth()
# gauth.LocalWebserverAuth()
# drive = GoogleDrive(gauth)
#
# #used for creating a new file and then upload into my drive
# file1=drive.CreateFile({'title':'Hello.pdf'})
# file1.SetContentString('Success')
# file1.Upload()
#
# #for sending a local file to google drive
# #path=r"C:\Users\aprab\PycharmProjects\Python_Projects"
# path=r"D:\downloads"
# for x in os.listdir(path):
# if(x=='download.txt'):
# f=drive.CreateFile({'title':x})
# f.SetContentString(os.path.join(path,x))
# f.Upload()
# f=None
|
4da4b5e0a87f9220caa5fb470cac464fe17975cb | aniketpatil03/Hangman-Game | /main.py | 1,650 | 4.125 | 4 | import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
Death|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
# Variable that is going to keep a track of lives
lives = 6
# Generating random word from list
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print("psst, the chosen random word", chosen_word)
# Generating as many blanks as the word
display = []
for _ in range(len(chosen_word)):
display += "_"
print(display)
game_over = False
while not game_over: # Condition for while loop to keep going
# Taking input guess from user
guess = input("Enter your guess: ").lower()
# Replacing the blank value with guessed letter
for position in range(len(chosen_word)):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(display)
if guess not in chosen_word:
lives = lives - 1
if lives == 0:
print("The end, you lose")
game_over = True
if "_" not in display:
game_over = True # Condition which is required to end while loop or goes infinite
print("Game Over, you won")
# prints stages as per lives left from ASCII Art and art is arranged acc to it
print(stages[lives])
|
6f308a43412f0cdeca2b3764cf5c2b84be15f98e | apostonaut/6.00.1x | /problem_sets/probset2/pay_off_fully.py | 732 | 3.71875 | 4 | def pay_off_fully(balance, annualInterestRate):
"""
Calculates the minimum monthly payment required in order to pay off the balance of a credit card
within one year
:param balance: Outstanding balance on credit card
:type balance: float
:param annualInterestRate: annual interest rate as a decimal
:type annualInterestRate: float
:param monthlyPaymentRate: minimum monthly payment rate as a decimal
:type monthlyPaymentRate: float
:return: monthly payment required to pay off balance within one year, as a multiple of $10
:rtype: int
>>> pay_off_fully(3329, 0.2)
310
"""
#variable assignment
currentBalance = balance
monthlyInterestRate = annualInterestRate/12
|
20694cf0fb96be02c7eb330b5eb4e020d1e162ec | zouzhuo939/python | /冒泡排序.py | 194 | 3.828125 | 4 | # array = [4,5,6,4,6,3,9]
# for i in range(len(array)):
# for j in range(i+1):
# if array[i]<array[j]:
# array[i],array[j]=array[j],array[j]
# print(array)
|
5ef84c9d17063edd0bc3f5351c291cf46b1cf2c0 | qinghao1/cmpe561 | /FST.py | 1,004 | 3.609375 | 4 | class State:
#Transition list is a list of tuples of (input, output, next_state)
def __init__(self, state_num):
self.state_num = state_num
#self.transition is a hashmap of input -> (output, next_state)
self.transition = {}
def add_transition(self, _input, _output, next_state):
self.transition[input] = (_output, next_state)
class FST:
def __init__(self):
self.states = {}
def add_arc(self, state1, state2, _input, _output):
if not state1 in self.states:
self.states[state1] = State(state1)
if not state2 in self.states:
self.states[state2] = State(state2)
self.states[state1].add_transition(_input, _output, state2)
def feed(self, string):
current_state = self.states[0] #Start state TODO
for char in string:
print(current_state.transition('c'))
output_tuple = current_state.transition[char]
print(output_tuple(0))
current_state = states[output_tuple[1]]
f = FST()
f.add_arc(0, 1, 'c', 'c')
f.add_arc(1, 2, 'a', 'u')
f.add_arc(2, 3, 't', 't')
f.feed("cat") |
4e292f2cd12f9adeb7df2ddc5bdd927b706beef1 | DStar1/word_guessing_game | /srcs/print_graphics.py | 3,497 | 3.59375 | 4 | import os
from termcolor import colored, cprint
class Graphics:
def __init__(self):
self.body_parts = [ colored("O", "magenta", attrs=["bold"]),
colored("|", "green", attrs=["bold"]),
colored("-", "red", attrs=["bold"]),
colored("-", "red", attrs=["bold"]),
colored("/", "blue", attrs=["bold"]),
colored("\\", "blue", attrs=["bold"])]
self.parts = [ colored("/", "cyan", attrs=["bold"]),
colored("___", "cyan", attrs=["bold"]),
colored("\\", "cyan", attrs=["bold"]),
colored("|", "cyan", attrs=["bold"])]
def draw_person(self, num_wrong_guesses):
for i in range(num_wrong_guesses):
print(self.body[i])
class Print(Graphics):
def __init__(self):
super().__init__()
self.help_message = "\nTo play enter the level 1-10, then a valid letter or '-' for the computer to make a guess for you.\
\nWhen prompted to play again, enter y/n to play again\nType -exit anywhere to exit\n"
self.bye_message = "\nEnding game, bye! Hope to see you again soon!\n"
self.letter_input = "Enter a letter or word to guess, enter '-' for computer to guess: "
self.play_again = "Would you like to play again? y/n: "
self.level_input = "\nEnter level int 1-10: "
self.secret = None
self.print_parts = None
# Clears the screen for UI
def clear_screen(self):
os.system('cls' if os.name == 'nt' else 'clear')
def update_print_variables(self, secret, level=None):
self.secret = secret
self.print_parts = [self.body_parts[idx] if idx < len(secret.wrong_guesses) else " " for idx in range(len(self.body_parts))]
if level:
self.level = level
def new_game_header(self):
cprint("NEW GAME OF HANGMAN\n", "blue")
def print_progress_info(self):
self.clear_screen()
self.new_game_header()
if not self.secret:
print(f" {self.parts[1]} ")
print(f" {self.parts[0]} {self.parts[2]}")
print(f" {self.parts[3]}")
print(f" {self.parts[3]}")
print(f" {self.parts[3]}")
print(f" {self.parts[1]}")
else:
print(f" {self.parts[1]} ")
print(f" {self.parts[0]} {self.parts[2]}", end="")
print(" Word length is:", len(self.secret.word))
print(f" {self.print_parts[0]} {self.parts[3]}", end='')
print(" Level is:", self.level)
print(f" {self.print_parts[2]}{self.print_parts[1]}{self.print_parts[3]} {self.parts[3]}", end='')
print(" Total guesses:", len(self.secret.guesses))
print(f" {self.print_parts[4]} {self.print_parts[5]} {self.parts[3]}", end='')
cprint(f" Wrong guesses: {', '.join(self.secret.wrong_guesses)}", "red")
print(f" {self.parts[3]}", end='')
print(" Remaining guesses:", 6 - len(self.secret.wrong_guesses))
print(f" {self.parts[1]}", end='')
print(" ", self.secret.word_to_show)
print()
def correct(self, correct, guesser):
self.print_progress_info()
if correct:
cprint(f"\'{guesser.input}\' is correct! :)", "green")
else:
cprint(f"\'{guesser.input}\' is not correct! :(", "red")
def invalid_input(self, start= False):
self.print_progress_info()
cprint("Invalid input, -help for usage", "red")
def win_loose(self, win):
self.print_progress_info()
if win:
cprint("\nYOU WIN!!!!!\n", "green")
else:
cprint("\nYou LOST after 6 wrong guesses :(\n", "red")
print(f"The word was {self.secret.word}\n")
def help(self):
self.print_progress_info()
print(self.help_message)
def exit(self):
self.print_progress_info()
print(self.bye_message)
|
149ad2636c553b6dd7717586d306a9a343260295 | FredericoTakayama/TicTacToe-Project | /projeto1.py | 5,668 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#tic tac toe - project1 study python
import os
SQUARE_SPACE_V=5
SQUARE_SPACE_H=9
TABLE_SPACE=29
def draw_x(pos_x,pos_y,table_matrix):
# matrix_x=[[0]*SQUARE_SPACE_H]*SQUARE_SPACE_V
# x=''
# for i in len(matrix_x):
# if i < (SQUARE_SPACE_H/2):
# x+='\\'
# elif i > (SQUARE_SPACE_H/2):
# x+='/'
# else:
# x+='X'
x=[]
x += [r' \ / ']
x += [r' \ / ']
x += [r' X ']
x += [r' / \ ']
x += [r' / \ ']
for i in range(0,SQUARE_SPACE_V):
for j in range(0,SQUARE_SPACE_H):
table_matrix[(pos_x*SQUARE_SPACE_V)+(1*pos_x)+i][(pos_y*SQUARE_SPACE_H)+(1*pos_y)+j]=x[i][j]
def draw_o(pos_x,pos_y,table_matrix):
o=[]
o += [r' --- ']
o += [r' / \ ']
o += [r'| |']
o += [r' \ / ']
o += [r' --- ']
for i in range(0,SQUARE_SPACE_V):
for j in range(0,SQUARE_SPACE_H):
table_matrix[(pos_x*SQUARE_SPACE_V)+(1*pos_x)+i][(pos_y*SQUARE_SPACE_H)+(1*pos_y)+j]=o[i][j]
def draw_vertical_lines(table_matrix):
for i in range(0,2):
for j in range(0,SQUARE_SPACE_V*3+2):
table_matrix[j][(SQUARE_SPACE_H)*(i+1)+(1*i)] = '|'
def draw_horizontal_lines(table_matrix):
for i in range(0,2):
for j in range(0,TABLE_SPACE):
table_matrix[((SQUARE_SPACE_V)*(i+1)+(1*i))][j] = '-'
def draw_number_positions(table_matrix):
count=1
for i in range(0,3): # row
for j in range(0,3): # column
table_matrix[SQUARE_SPACE_V*i+i][SQUARE_SPACE_H*j+j] = str(count)
count+=1
def draw_table(game_table):
# nao serve! ele copia como referencia e depois nao permite mexer um elemento sem mexer
# table_matrix = [['0']*TABLE_SPACE]*(SQUARE_SPACE_V*3+2)
table_matrix = [[' ' for j in range(0,TABLE_SPACE)] for i in range(0, SQUARE_SPACE_V*3+2)]
# print(len(table_matrix)) # rows
# print(len(table_matrix[0])) # columns
# matrix[5*3+2)][30]
draw_vertical_lines(table_matrix)
draw_horizontal_lines(table_matrix)
for i in range(0,3):
for j in range(0,3):
if game_table[i*3+j] == 1:
draw_x(i,j,table_matrix)
elif game_table[i*3+j] == 2:
draw_o(i,j,table_matrix)
# add number positions
draw_number_positions(table_matrix)
drew_table = ''
for row in table_matrix:
for column in row:
drew_table += column
drew_table += '\n'
return drew_table
def gretting_display():
print('_____________________________________')
print('___________ tic tac toe _____________')
print('_____________________________________')
print('')
game_table=[0]*9
# game_table=[[0]*3]*3
def check_position(position):
try:
return game_table[(int(position)-1)] == 0
except:
return False
def check_end_game(game_table):
'''check if there is a winner or its a tie'''
for i in range(0,3):
# check rows:
if(game_table[i] == game_table[i+1] == game_table[i+2] and game_table[i] != 0):
return game_table[i] # player wins
# check columns:
elif(game_table[i] == game_table[3+i] == game_table[6+i] and game_table[i] != 0):
return game_table[i] # player wins
if(game_table[0] == game_table[4] == game_table[8] and game_table[4] != 0) or\
(game_table[2] == game_table[4] == game_table[6] and game_table[4] != 0):
return game_table[4] # player wins
for i in range(0,9):
if(game_table[i] == 0):
return 0 # didn't finished
return -1 # tie
if __name__ == "__main__":
# pega o tamanho do terminal
# rows, columns = os.popen('stty size', 'r').read().split()
# print(rows,columns)
# FACTOR=0.7
# TABLE_SPACE = int(int(rows)*FACTOR*2.3)
# SQUARE_SPACE_V=int((int(rows)*FACTOR)/3.0)
# SQUARE_SPACE_H=int((int(rows)*FACTOR)/1.3)
player = 0
# print(game_table) # debug
gretting_display()
print(draw_table(game_table))
while(True):
text = 'Player %s, please choose a position:' % str(player+1)
position = input(text)
os.system('clear')
# printar o tabuleiro com lugares disponíveis
try:
if int(position) > 0 and int(position) <= 9 and check_position(position):
# valid position
game_table[int(position)-1] = player+1
#exchange between players
player = (player+1)%2
# print(game_table) # debug
gretting_display()
print(draw_table(game_table))
else:
gretting_display()
print(draw_table(game_table))
print('Invalid position. Please try again.')
except:
gretting_display()
print(draw_table(game_table))
print('Invalid position. Please try again.')
# check if game finished:
res = check_end_game(game_table)
if res == 0:
continue
else:
if res == -1:
print('Game end: Tie!')
else:
print('Game end: Player %s wins!' % res)
if input('Play again? (y/n): ') == 'y':
# reset games
game_table=[0]*9
gretting_display()
print(draw_table(game_table))
player=0
else:
break
|
b696c672826c50de8f03c45055ca4553031c7f02 | JNFernandes/Python-Scripts | /Tic Tac Toe/player_choice.py | 375 | 4 | 4 | def player_choice(board):
position = int(input('Choose a position from 1 to 9 (ONLY INTEGERS): '))
while position not in range(1,10) or not check_space(board,position):
print('Either you selected an already filled position or the number is out of range! Try again')
position = int(input('Choose a position from 1 to 9: '))
return position |
b5ab8666d6d080ea2022313f0e484f60fb94a229 | JNFernandes/Python-Scripts | /Morse_Code/main.py | 340 | 3.953125 | 4 | from decode_encode import encoding,decoding
from logo import logo
print(logo)
message = input("Type message to encode: ").upper()
decoding_msg = input("Do you want to decode? Type 'y' for yes or 'n' for no: ").lower()
if decoding_msg == 'n':
encoding(message)
else:
decoding(message,encoding(message))
|
0edcfa5c925d6cff46f7eb48f44a882de410d452 | lawellwilhelm-dev/money | /m02_03_charges_list_for_loop.py | 356 | 3.53125 | 4 | balance = 1000.0
name = 'Nelson Olumide'
account_no = '01123581231'
print('Name:', name, ' account:', account_no, ' original balance:', '$' + str(balance))
charges = [5.99, 12.45, 28.05]
for charge in charges:
balance = balance - charge
print('Name:', name, ' account:', account_no, ' charge:', charge, ' new balance ', '$' + str(balance))
|
4ce5c10eaf4a27ff54a1b12c87110659daf3f04a | aubreystevens/image_processing_pipeline | /text_files/Test.py | 1,033 | 4.15625 | 4 | #B.1
def complement(sequence):
"""This function returns the complement of a DNA sequence. The argument,
'sequence' represents a DNA sequence."""
for base in 'sequence':
if 'A' in 'sequence':
return 'T'
elif 'G' in 'sequence':
return 'C'
elif 'T' in 'sequence':
return 'A'
else:
return 'G'
#B.2
def list_complement(dna):
"""This function returns the complement of a DNA sequence."""
if 'A':
return 'T'
elif 'G':
return 'C'
elif 'T':
return 'A'
else:
return 'G'
#B.3
def product(numbers):
"""Returns sum of all numbers in the list."""
for x in numbers:
final += x
return final
#B.4
def factorial(x):
"""Returns factorial of number x."""
if x = 0 :
return 1
else:
return x = x * (x-1)
#B.5
|
7e00a5253bc7c9ffedf9bd34f27b158577150aa2 | fwang2/ML | /src/ex-layer-3.py | 1,732 | 3.578125 | 4 | import numpy as np
np.random.seed(1)
def relu(x):
''' this function sets all negative number to 0 '''
return (x > 0) * x
def relu2deriv(x):
''' Return 1 for x > 0; return 0 otherwise '''
return x > 0
alpha = 0.2
hidden_size = 4
streetlights = np.array([[1, 0, 1], [0, 1, 1], [0, 0, 1], [1, 1, 1]])
walk_vs_stop = np.array([[1, 1, 0, 0]]).T
# randomly initialize weight matrix: 0 to 1
weights_0_1 = 2 * np.random.random((3, hidden_size)) - 1
weights_1_2 = 2 * np.random.random((hidden_size, 1)) - 1
for it in range(60):
layer_2_error = 0
for i in range(len(streetlights)):
# go through each input
# do forward propergation, which is weighted sum
layer_0 = streetlights[i:i + 1]
# REFER TO Step #3
layer_1 = relu(np.dot(layer_0, weights_0_1))
layer_2 = np.dot(layer_1, weights_1_2)
# REFER TO Step #4
layer_2_error += np.sum((layer_2 - walk_vs_stop[i:i + 1])**2)
# REFER TO Step #5
layer_2_delta = (layer_2 - walk_vs_stop[i:i + 1])
# NEW, not covered in previous steps
# this line computes the delta at layer_1 given the delta at layer_2
# by taking the layer_2_delta and multiplying it by its connecting
# weights (weights_1_2)
layer_1_delta = layer_2_delta.dot(weights_1_2.T) * relu2deriv(layer_1)
# REFER TO Step #6, but calculated different, need some revisit
weight_delta_1_2 = layer_1.T.dot(layer_2_delta)
weight_delta_0_1 = layer_0.T.dot(layer_1_delta)
# update weights
weights_1_2 -= alpha * weight_delta_1_2
weights_0_1 -= alpha * weight_delta_0_1
#
if (it % 10 == 9):
print(f"Error: {layer_2_error}") |
fd35a5def2bc3ff4fa178c6d3033770b1b144b39 | fwang2/ML | /src/linear-regression2.py | 1,412 | 3.890625 | 4 | # linear regression gradient descent
# datasets/ex1data1.txt
#
# Best cost: 4.47697137598 after 10000 iterations
# Weights: [[-3.89578082] [1.19303364]]
#
from .gradient import *
# ex1data1.txt
# column 1: population of a city
# column 2: profit of a food truck in that city
data = np.loadtxt("../datasets/ex1data2.txt", delimiter=',')
n, m = data.shape
# add a column to X
X = data[:,:-1] # all columns except last
y = data[:, -1] # last columns
mu, sigma, X = feature_normalize(X)
y = y.reshape(n,1)
X = np.hstack((np.ones((n, 1)), X.reshape(n, m - 1)))
c, w = gradient_descent(X, y, num_iters=500)
print("Gradient Descent:")
print("Cost: {:,.2f}".format(c[-1]))
print("Weights: {}".format(w.T))
# Estimate the price of a 1650 sq-ft, 3 br house
temp = np.array([1.0, 1650.0, 3.0])
temp[1] = (temp[1] - mu[0])/sigma[0]
temp[2] = (temp[2] - mu[1])/sigma[1];
price = temp.reshape(1,3).dot(w)
print("Predicted price for 1650 sq ft, 3 bed rooms: {}".format(price))
X = data[:,:-1] # all columns except last
y = data[:, -1] # last columns
y = y.reshape(n,1)
X = np.hstack((np.ones((n, 1)), X.reshape(n, m - 1)))
w = normal_equation(X, y)
print("\nNormal equation:")
c = compute_cost(X, y, w)
print("Cost: {:,.2f}".format(c))
print("Weights: {}".format(w.T))
temp = np.array([1.0, 1650.0, 3.0])
price = temp.reshape(1,3).dot(w)
print("Predicted price for 1650 sq ft, 3 bed rooms: {}".format(price))
|
d7b7b93e17a9ff03b1741598b701ff612857999e | damianKokot/Python | /Lista1/Zad3.py | 202 | 3.65625 | 4 | def filterRepeat(table):
output = []
for item in table:
if item not in output:
output.append(item)
return output
table = [1,1,2,2,2,3,3,5,5,5,4,4,4,0]
print(filterRepeat(table)) |
df9de1ede3c960dc2b9f472c9fd07d41be3c5fe1 | Hemie143/Tic-Tac-Toe | /Problems/Vowels/task.py | 96 | 3.890625 | 4 | vowels = 'aeiou'
# create your list here
text = input()
print([c for c in text if c in vowels])
|
6925adb236ce9626b85d34055e66aa36bdc40fe7 | ValeWasTaken/Project_Euler | /Python_Solutions/Project_Euler_Problem_025.py | 293 | 3.734375 | 4 | def main():
x,y,z = 0,1,0
counter = 1
while len(str(z)) != 1000:
z = x + y
x = y
y = z
counter += 1
print("The " + str(counter) + "nd number in the Fibonacci sequence produces the first 1000 digit number.")
# Expected output: 4782
main()
|
60fc8f1ad6540bcfa3e2e0fe3e45ceebd39e542b | tvvoty/PythonLearning | /Recursive_sum.py | 1,007 | 3.8125 | 4 | arr1 = [2, 4, 6]
def rec_sum(arr):
total = 0
print(arr)
if len(arr) == 0:
print(total)
return 0
else:
total = arr1.pop(0) + rec_sum(arr1)
def fact(x):
if x == 1:
return 1
else:
return x * fact(x - 1)
def sum(numlist):
lists_sum = numlist[0] + numlist[1:]
def listsum(numlist):
if len(numlist) == 1:
return numlist[0]
else:
return numlist[0] + listsum(numlist[1:])
def listamount(numlist):
if numlist == []:
return 0
else:
return 1 + listamount(numlist[1:])
def listmax(numlist):
if len(numlist) == 1:
return numlist[0]
print(numlist[0])
elif numlist[0] >= numlist[1]:
x = numlist[0]
print(numlist[0])
return x > listmax(numlist[1:])
elif numlist[0] <= numlist[1]:
x = numlist[1]
print(numlist[1])
return x > listmax(numlist[1:])
else:
print("error")
print(listmax([1, 33, 4, 5, 8, 22]))
|
3c7592aba43830ae963bc5dec0549c5bf5e7bcb3 | tvvoty/PythonLearning | /Euler 6.py | 367 | 3.53125 | 4 | def sumofsq():
total1 = 0
for x in range(1, 101):
total1 = total1 + x**2
return total1
print(sumofsq())
def sqrofsum():
total2 = 0
for x in range(1, 101):
total2 = total2 + x
sqrsum1 = total2**2
return sqrsum1
print(sqrofsum())
def sumoftwo():
notsum = sqrofsum() - sumofsq()
return notsum
print(sumoftwo())
|
2e6aa5c1725bf0578901a0d7ca2106c429445056 | maneeshapaladugu/Learning-Python | /Basic Concepts/usr_def_function_example.py | 1,616 | 3.921875 | 4 | def hello():
print('Hello !')
print('Hello !!!')
print('Hello World !!!!!')
hello()
hello()
hello()
hello()
#******************************************
def hello(name):
print('Hello ' + name)
hello('Maneesha')
hello('Manoj')
#**********************************************
print('Maneesha has ' + str(len('Maneesha')) + ' letters in it')
print('Manoj has ' + str(len('Manoj')) + ' letters in it')
#*************************************************
def plusone(number):
return number + 1
newNumber = plusone(5)
print(newNumber)
#*************************************************
#print() return value is None
#spam = print()
#spam -> has nothing
#spam == None -> displays True
#************************************************
#print() function call automatically adds new line to the passed string
print('Hello')
print('World')
#Output:
#Hello
#World
#**************************************************
#The print function has keyword arguments end and sep
#Keywords arguments to functions are optional
#Keyword arguement end makes below print() function call without new line at the end of string Hello
print('Hello',end='')#empty end keyword argument
print('World')
#Output:
#HelloWorld
#When we pass multiple values to the print function, it automatically sepeartes them with a space
print('cat', 'dog', 'mouse')
#Output:
#cat dog mouse
#To set seperate char/string, we can pass the sep keyword argument with a value (seperator)
print('cat', 'dog', 'mouse', sep='ABC')
#Output:
#catABCdogABCmouseABC
|
f081583af062ff602cac5b23ecdc6e8e4e6f273a | maneeshapaladugu/Learning-Python | /Basic Concepts/Character_Count.py | 2,247 | 4.03125 | 4 | message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {} #This dictionary will store the character key and its count. Ex: r:5
for character in message: #here, lower case and upper case counts are seperate
count.setdefault(character, 0) #if character doesn't exists in count dictionary, sets the character count as 0 as an initialization
count[character] = count[character] + 1
print(count)
#output:
#{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
#-----------------------------------------------------------------------------------------------------
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {} #This dictionary will store the character key and its count. Ex: r:5
for character in message.upper(): #returns an upper case from the string
count.setdefault(character, 0) #if character doesn't exists in count dictionary, sets the character count as 0 as an initialization
count[character] = count[character] + 1
print(count)
#output: All the lower cases are converted to upper case
#{'I': 7, 'T': 6, ' ': 13, 'W': 2, 'A': 5, 'S': 3, 'B': 1, 'R': 5, 'G': 2, 'H': 3, 'C': 3, 'O': 2, 'L': 3, 'D': 3, 'Y': 1, 'N': 4, 'P': 1, ',': 1, 'E': 5, 'K': 2, '.': 1}
#----------------------------------------------------
#The pprint() function in pprint module for a pretty print
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {} #This dictionary will store the character key and its count. Ex: r:5
for character in message.upper(): #returns an upper case from the string
count.setdefault(character, 0) #if character doesn't exists in count dictionary, sets the character count as 0 as an initialization
count[character] = count[character] + 1
pprint.pprint(count)
#output:
{' ': 13,
',': 1,
'.': 1,
'A': 5,
'B': 1,
'C': 3,
'D': 3,
'E': 5,
'G': 2,
'H': 3,
'I': 7,
'K': 2,
'L': 3,
'N': 4,
'O': 2,
'P': 1,
'R': 5,
'S': 3,
'T': 6,
'W': 2,
'Y': 1}
|
8c30efc6efcc16854f6f87a28e7b5b747a267bd3 | maneeshapaladugu/Learning-Python | /Basic Concepts/Sample_Program.py | 1,212 | 4.09375 | 4 | #Sample program - This program says hello and prompts for name and age
#str(int(age)+1) #age evaluates to '25'
#str(int('25')+1) #int('25') evaluates to integer 25
#str(25+1)
#str(26) #str(26) evaluates to string '26'
#'26'
print('Hello! This is Robot')
print('What is your name?')
myname = input()
print('Good to meet you ' + myname)
print('Length of your name:')
print(len(myname))
print('What is your age?')
age = input()
print('Your age will be ' + str(int(age)+1) + ' in an year')
print('Glad to meet you')
#**********************************************************
print('1' + '1') #Output: 11
print("'1' + '1' is " + str('1'+'1')) #Output: 11
print(1+1) #Output: 2
print('1 + 1 is ' + str(1+1)) #Output :1 +1 is 2
#***********************************************************
age = 24
print('Your age will be ' + str(age+1) + ' in an year') #No error
age = input()
print('Your age will be ' + str(int(age)+1) + ' in an year')#Solution to below error
age = input()
print('Your age will be ' + str(age+1) + ' in an year') #Here age is a string and str(age+1) throws TypeError: can only concatenate str (not "int") to str.
|
33d73944bf28351346ac72cbee3f910bcf922911 | maneeshapaladugu/Learning-Python | /Practice/Armstrong_Number.py | 763 | 4.46875 | 4 | #Python program to check if a number is Armstrong or not
#If the given number is 153, and 1^3 + 5 ^ 3 + 3 ^ 3 == 153, then 153 is an Armstrong number
def countDigits(num):
result = 0
while num > 0:
result += 1
num //= 10
print(result)
return result
def isArmstrong(num):
digitCount = countDigits(num)
temp = num
result = 0
while temp:
result += pow(temp%10, digitCount)
temp //= 10
if result == num:
return 1
else:
return 0
num = int(input("Enter a number:\n")) #Receive the input as an integer
if isArmstrong(num):
print("%d is an Armstrong Number" %(num))
else:
print("%d is not an Armstrong number" %(num))
|
52291cd8dd0ec26b3b4d263a4578a7925821b4d4 | hscottharrison/udemy-python | /variables_methods.py | 282 | 3.90625 | 4 | a = 5
b = 10
my_variable = 56
string_variable = "hello"
# print(my_variable)
##
def my_print_method(par1, par2):
print(par1)
print(par2)
# my_print_method("hello", "world")
def my_multiply_method(one, two):
return one * two
result = my_multiply_method(5, 3)
print(result) |
35f2bffe77e3ff8a66fa6452cd94793899565879 | thoamsxu/Python | /2-22.py | 1,078 | 3.875 | 4 | def capitals(word):
return [
index for index in range(len(word))
if word[index] == word[index].upper()
]
print("====== CodEWaRs ======")
print(capitals("CodEWaRs"))
def digital_root(inputNumber):
print("====== digital root " + str(inputNumber) + " ======")
int_result = inputNumber
while (int_result >= 10):
str_num = str(int_result)
list_num = [int(str_num[index]) for index in range(len(str_num))]
int_result = sum(list_num)
print("=> " + " + ".join(map(str, list_num)))
print("=> %d" % int_result)
#递归
def digital_root1(inputNumber):
if inputNumber < 10:
print("=> ", inputNumber)
return inputNumber
else:
arr = list(str(inputNumber))
print(" + ".join(arr))
num_sum = sum(map(int, arr))
if (num_sum > 10):
print("=> ", num_sum, " ...")
digital_root1(num_sum)
number1 = 16
number2 = 942
number3 = 132189
number4 = 493193
digital_root1(number1)
digital_root1(number2)
digital_root1(number3)
digital_root1(number4) |
37bd1683785377afe49b17d3aec9700665e3d3db | MyoMinHtwe/Programming_2_practicals | /Practical 5/Extension_3.py | 1,804 | 4.1875 | 4 | def bill_estimator():
MENU = """11 - TARIFF_11 = 0.244618
31 - TARIFF_31 = 0.136928
41 - TARIFF_41 = 0.156885
51 - TARIFF_51 = 0.244567
61 - TARIFF_61 = 0.304050
"""
print(MENU)
tariff_cost = {11: 0.244618, 31: 0.136928, 41: 0.156885, 51: 0.244567, 61: 0.304050}
choice = int(input("Which tariff? 11 or 31 or 41 or 51 or 61: "))
if choice == 11:
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
bill = (tariff_cost[11] * daily_use * billing_days)
print("Estimated bill:$ {:.2f}".format(bill))
elif choice==31:
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
bill = (tariff_cost[31] * daily_use * billing_days)
print("Estimated bill:$ {:.2f}".format(bill))
elif choice==41:
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
bill = (tariff_cost[41] * daily_use * billing_days)
print("Estimated bill:$ {:.2f}".format(bill))
elif choice==51:
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
bill = (tariff_cost[51] * daily_use * billing_days)
print("Estimated bill:$ {:.2f}".format(bill))
elif choice==61:
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
bill = (tariff_cost[61] * daily_use * billing_days)
print("Estimated bill:$ {:.2f}".format(bill))
else:
while 1:
print("Invalid input")
bill_estimator()
break
bill_estimator()
|
6e27d14ec66db99139840586ca72f316717f100b | MyoMinHtwe/Programming_2_practicals | /Practical 3/gopher_population.py | 805 | 4.0625 | 4 | import random
STARTING_POPULATION = 1000
print("Welcome to the Gopher Population Simulator")
print("Starting population: {}".format(STARTING_POPULATION))
def birth_rate():
for i in range(1, 11):
born = int(random.uniform(0.1, 0.2)*STARTING_POPULATION)
return born
def death_rate():
for i in range(1, 11):
died = int(random.uniform(0.05, 0.25)*STARTING_POPULATION)
return died
def main():
population = STARTING_POPULATION
for i in range(1, 11):
print()
print("Year", i,"\n"+"*"*5)
born = birth_rate()
died = death_rate()
print("{} gophers were born. {} died.".format(born, died))
remain = born - died
population = population + remain
print("Population: {}".format(population))
main()
|
8071c3f0f77261cb68e0c36d09a814ba95fdb474 | MyoMinHtwe/Programming_2_practicals | /Practical 5/Extension_1.py | 248 | 4.3125 | 4 | name_to_dob = {}
for i in range(2):
key = input("Enter name: ")
value = input("Enter date of birth (dd/mm/yyyy): ")
name_to_dob[key] = value
for key, value in name_to_dob.items():
print("{} date of birth is {:10}".format(key,value)) |
cb0c2a4c02c8fee656a94fe659ac0c25115bd4bc | MyoMinHtwe/Programming_2_practicals | /Practical 3/temperatures.py | 1,045 | 4.125 | 4 | MENU = """C - Convert Celsius to Fahreneit
F - Convert Fahrenheit to Celsius
Q - Quit"""
print(MENU)
choice = input("Input your choice: ").lower()
def main(choice):
#choice = input("Input your choice: ").lower()
print(choice)
i = True
while i==True:
if choice == "c":
celsius = float(input("Celsius: "))
result = calc_celsius(celsius)
print("Result: {:.2f} Fahrenheit".format(result))
i = False
elif choice == "f":
fahrenheit = float(input("Fahrenheit: "))
result = calc_fahrenheit(fahrenheit)
print("Result: {:.2f} Celsius".format(result))
i = False
elif choice == "q":
i = False
else:
print("Invalid entry: ")
choice = input("Input your choice: ")
print("Thank you")
def calc_celsius(celsius):
result = celsius * 9.0 / 5 + 32
return result
def calc_fahrenheit(fahrenheit):
result = 5 / 9 * (fahrenheit - 32)
return result
main(choice)
|
a288abbab98175fb70e1c1a34c5c6f4eeeed438a | HarshKapadia2/python_sandbox | /python_sandbox_finished_(by_harsh_kapadia)/tuples_sets.py | 1,269 | 4.25 | 4 | # A Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
# create tuple
fruit_1 = ('mango', 'watermelon', 'strawberry', 'orange', 'dragon fruit')
# using constructor
fruit_2 = tuple(('mango', 'watermelon', 'strawberry', 'orange', 'dragon fruit'))
print(fruit_1, fruit_2)
fruit_3 = ('apple')
print(fruit_3, type(fruit_3)) # type str
fruit_4 = ('blueberry',) # single value needs trailing comma to be a tuple
print(fruit_4, type(fruit_4)) # type tuple
# get value
print(fruit_1[0])
# values cannot be changed in tuples
# fruit_1[0] = 'water apple' # error
# deleting a tuple
del fruit_2
# print(fruit_2) # o/p: error. 'fruit_2' not defined
# length of tuple
print(len(fruit_1))
# A Set is a collection which is unordered and unindexed. No duplicate members.
fruit_5 = {'mango', 'apple'}
# check if in set
print('mango' in fruit_5) # RT: bool
# add to set
fruit_5.add('watermelon')
print(fruit_5)
# add duplicte member
fruit_5.add('watermelon') # doesn't give err, but doesn't insert the duplicate val
print(fruit_5)
# remove from set
fruit_5.remove('watermelon')
print(fruit_5)
# clear the set (remove all elements)
fruit_5.clear()
print(fruit_5)
# delete set
del fruit_5
# print(fruit_5) # o/p: error. 'fruit_5' not defined |
828e176b7aae604d3f4d38a206d4f1cfa5d49197 | HarshKapadia2/python_sandbox | /python_sandbox_finished_(by_harsh_kapadia)/loops.py | 854 | 4.1875 | 4 | # A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
people = ['Selena', 'Lucas', 'Felix', 'Brad']
# for person in people:
# print(person)
# break
# for person in people:
# if person == 'Felix':
# break
# print(person)
# continue
# for person in people:
# if person == 'Felix':
# continue
# print(person)
# range
# for i in range(len(people)):
# print(i)
# print(people[i])
# for i in range(0, 5): # 0 is included, but 5 is not
# print(i)
# for i in range(6): # starts from 0, goes till 5
# print(i)
# While loops execute a set of statements as long as a condition is true.
count = 10
while count > 0:
print(count)
count -= 1 # count-- does not exist in python (ie, post/pre increment ops do not exist in python) |
5a7b007836701868c909dd8cdbef18402c546577 | Walter64/LyndaPythonApp | /02_bitwise.py | 1,018 | 4 | 4 | #!/usr/bin/env python3
x = 0x0a
y = 0x02
z = x & y
print('The & operator')
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
z = x | y
print('\nThe | operator')
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
x = 0x0a
y = 0x05
z = x | y
print('\nThe | operator')
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
x = 0x0a
y = 0x0f
z = x ^ y
print('\nThe ^ operator')
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
x = 0x0a
y = 0x01
z = x << y
print('\nThe << operator')
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
z = x >> y
print('\nThe >> operator')
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
|
e773e16406755eea6871525ad41dd6157d5ce7fd | ProfLeao/codes_site_pessoal | /shortcirc.py | 514 | 4 | 4 | # Códigos do artigo:
# Short Circuiting no Python 3: Fechando curtos-circuitos em seus códigos.
# Função para teste lógico de valores
def teste_tf(valor):
if valor:
print(f"{valor} é avaliado como verdadeiro.")
else:
print(f"{valor} é avaliado como falso.")
# Declaração de valores para teste
valores = [
None, [], (), {}, set(), "", range(0), [1,2], (3,4), set([5,6]), {'a','a'},
' ', 'a', 'A', 1, 2, 1.2, 3.2e3
]
# Teste dos valores
for i in valores:
teste_tf(i) |
3fa6c5c674507c52c1a781f66d7e82601a136052 | PARVATHY-S-PRAKASH/PROGRAMMING-LAB | /Write a python program display the given pyramid with the step number accepted from user using function/pattern.py | 172 | 3.828125 | 4 |
n = int(input("enter the number of rows :"))
x=1
for i in range(x,n+1):
for j in range(x, i+1):
print(i*j, end=' ')
print()
|
17b6d99d1d01d51382c55e816bf57636954d383b | sd1064/Hackathon | /Player/player.py | 1,437 | 3.65625 | 4 | # current position
# known locations
# print current board
# move
import time
from Constants.constants import constants
class player:
currentPosition = [0,0]
knownLocations = [] #[[ROW,COL,TYPE]]
board=[]
DECIDE_TIME = 3
def __init__(self,board,DECIDE_TIME):
self.board=board
self.currentPosition[1]=int(len(board.board)/2)
self.DECIDE_TIME = DECIDE_TIME
def printCurrentBoard(self):
fogOfWarBoard=[]
for i in range(0,len(self.board.board)):
row=[]
for i in range(0,len(self.board.board)):
row.append(constants.UNKNOWN)
fogOfWarBoard.append(row)
for i in range(0,len(self.knownLocations)):
fogOfWarBoard[self.knownLocations[i][0]][self.knownLocations[i][1]]=self.knownLocations[i][2]
fogOfWarBoard[self.currentPosition[0]][self.currentPosition[1]]=constants.PLAYER
print "\n"
for i in range(0,len(fogOfWarBoard)):
print fogOfWarBoard[i]
print "\n"
def scanForMine(self):
self.knownLocations = self.knownLocations + self.board.scanForMine(self.currentPosition[0],self.currentPosition[1])
def decideMove(self):
#Logic for deciding move based on situation
def check_valid_move(self,move):
#check move not out of bounds
#check move doesnt activate mines
def move(self,moveType):
#IMPLEMENT MOVE FORWARD,LEFT,RIGHT
|
b74747432f07f43859a2adee3aeac1e25ace22a4 | c10023596/280201044 | /lab08/1.py | 168 | 3.671875 | 4 | def list_sum(a):
summation = 0
for x in range(len(a)):
summation += a[x]
return summation
a_list = [12, -7, 5, -89.4, 3, 27, 56, 57.3]
print(list_sum(a_list)) |
42f41d07e0718446e00b78942534fa1e5b38e517 | c10023596/280201044 | /lab07/3.py | 377 | 4.03125 | 4 | employees = {}
pawns_i = input("Names of employees with , between them: ")
salaries_i = input("Their payments with , between them: ")
pawns = ["pawn1","pawn2","pawn3","pawn4","pawn5"]
salaries = [350, 470, 438, 217, 387]
for i in range(len(pawns)):
employees[salaries[i]]=pawns[i]
salaries.sort()
print(employees[salaries[-1]],employees[salaries[-2]],employees[salaries[-3]]) |
06445c460e1c8736aa073573f0fb715369c84296 | c10023596/280201044 | /lab10/2.py | 204 | 3.609375 | 4 | def hailstone(x, seq=[]):
seq.append(str(x))
if x == 1:
return ",".join(seq)
else:
if x % 2 == 1:
return hailstone(3*x + 1)
else:
return hailstone(x//2)
print(hailstone(5)) |
de02d42116a147070605067cce79a3dacd5c6971 | c10023596/280201044 | /lab07/2.py | 257 | 3.6875 | 4 | books = ["ULYSSES","ANIMAL FARM","BRAVE NEW WORLD","ENDER'S GAME"]
book_dict = {}
for i in range(len(books)):
book_name = books[i]
unq_letters = list(set(book_name))
value = len(book_name),len(unq_letters)
book_dict[book_name]=value
print(book_dict) |
0fbe418f86cb8c7b171f3cf66912b2477b6080da | aliev-m/Python | /stepik_python/3.1_1.py | 164 | 3.875 | 4 | x=float(input())
def f(x):
if x<=-2:
return (1-(x+2)**2)
elif -2<x<=2:
return (x/2)*-1
elif x>2:
return ((x-2)**2)+1
print(f(x))
|
b2c5eb0a36f0b37826391386cfde161e61c5eeef | avaska/PycharmProjects | /workpy/7모듈과패키지/1_1표준모듈종류.py | 8,304 | 3.71875 | 4 |
#표준 모듈 종류
# random모듈
# -> 랜덤값을 생성할떄 사용하는 모듈
#random모듈 불러오기
import random
print("#random 모듈")
#random모듈의 random()함수는 0.0 <= 랜덤값 < 1.0 랜덤값을 float를 리턴합니다
print(random.random())
#random모듈의 uniform(min,max) 함수는 지정한 범위 사이의 랜덤값을 float를 리턴합니다
print(random.uniform(10,20))
#random모듈의 randranage()함수는 지정한 범위 사이의 랜덤값을 int로 리턴합니다
#문법) randrange(max) : 0부터 max값 사이의 랜덤값을 int로 리턴합니다
print(random.randrange(10))
#문법) randrange(min,max) : min값부터 max값사이의 랜덤값을 int로 리턴합니다
print(random.randrange(10,20))
#random모듈의 choice(리스트)함수는 리스트 내부에 있는 요소를 랜덤하게 선택합니다
print( random.choice([1,2,3,4,5]) )
#random모듈의 shuffle(리스트)함수는 리스트의 요소들을 랜덤하게 섞어서 제공해줌
list = ["ice cream", "pancakes", "brownies", "cookies", "candy"]
random.shuffle(list)
print(list)
#random모듈의 sample(리스트, k=숫자) 함수는
#리스트의 요소 중에 k개를 랜덤으로 뽑아냅니다
print( random.sample([1,2,3,4,5], k=2))
#예제. 계산 문제를 맞히는 게임 -> random_1.py파일 생성
#예제. 타자 게임 -> typing.py파일 생성
#예제. 거북이 그래픽 모듈 사용하기 -> turtle_1.py 파일 생성 , turtle_2.py , turtle_3.py
#----------------------------------------------------------------------------
#sys 모듈
#-> 시스템과 관련된 정보를 가지고 있는 모듈
#모듈을 불러 옵니다
import sys
#컴퓨터 환경과 관련된 정보를 불러와 출력함
print(sys.getwindowsversion())
print("---")
print(sys.copyright)
print("---")
print(sys.version)
#프로그램을 강제로 종료 함
# sys.exit()
#---------------------------------------------------------------------
# os모듈
# -> 운영체제와 관련된 기능을 가진 모듈입니다
# 새로운 폴더를 만들거나 폴더 내부의 파일목록을 보는 일도 모두 os모듈을 활용해서 처리 합니다
#예제. 간단하게 os모듈의 몇가지 변수와 함수를 사용해 봅시다.
#모듈을 읽어 들입니다
import os
#기본 정보를 몇개 출력해 봅시다.
print("현재 운영체제 : ", os.name)
print("현재 폴더 : ", os.getcwd())
print("현재 폴더 내부의 요소들(목록):", os.listdir() )
#폴더를 만들고 제거합니다 [폴더가 비어있을때만 제거 가능]
#os.mkdir("hello") # hello폴더 생성
#os.rmdir("hello") # hello폴더 삭제
#파일을 생성하고 생성한 파일에 데이터를 씁니다.
# with open('original.txt','w') as file:
# file.write("hello")
#파일 이름을 변경 합니다
#os.rename('original.txt','new.txt')
#파일을 제거 합니다
#os.remove('new.txt')
#--------------------------------------------------------------------
# datetime 모듈
# -> 날짜, 시간과 관련된 모듈로, 날짜형식을 만들때 사용되는 코드들로 구성되어 있는 모듈
#예제 .datetime모듈을 사용해서 날짜를 출력하는 다양한 방법
#모듈을 읽어들입니다
import datetime
#현재 시각을 구하고 출력하기
print("현재 시각 출력하기")
#datetime모듈. datetime클래스의 now()함수를 호출하여 현재 날짜와 시간정보를 모두 얻는다
now = datetime.datetime.now()
print(now.year,"년")
print(now.month,"월")
print(now.day, "일")
print(now.hour, "시")
print(now.minute, "분")
print(now.second, "초")
print()
#시간 출력 방법
print("시간을 포맷에 맞춰 출력하기")
#현재 년도 월 일 시 분 초를 포맷에 맞춰서 출력하기
output_a = now.strftime("%Y.%m.%d %H:%M:%S")
print(output_a)
print("----------------------")
output_b = "{}년 {}월 {}일 {}시 {}분 {}초".format(now.year,
now.month,
now.day,
now.hour,
now.minute,
now.second)
print(output_b)
print("-----------------------------")
# 문자열 ,리스트 등 앞에 별 *를 붙이면 요소 하나하나가 매개변수로 지정된다
output_c = now.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월일시분초")
print(output_c)
#결론 : output_a처럼 strftime()함수를 사용하면 시간을 형식에 맞춰 출력할 수 있습니다.
# 다만, 한국어등의 문자는 매개변수에 넣을수 없습니다.
# 그래서 이를 보완하고자 output_b 와 output_c같은 형식을 사용함
#특정 시간 이후의 시간 구하기
print("datetime모듈의 timedelta함수로 시간 더하기")
#timedelta함수를 사용하면 특정한 시간의 이전 또는 이후를 구할수 있습니다
#다만 1년 후 , 2년 후 등의 몇 년 후를 구하는 기능은 없습니다
#그래서 1년후를 구할때는 replace()함수를 사용해 아예 날짜 값을 교체하는 것이 일반적입니다
# 현재날짜시간정보에 + 1주일, 1일, 1시간, 1분, 1초
after = now + datetime.timedelta(weeks=1, days=1, hours=1, minutes=1, seconds=1 )
print(after.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월일시분초"))
print()
#특정시간 요소 교체하기
print("now.replace()함수로 1년 더하기")
output = now.replace(year=(now.year + 1))
print(output.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월일시분초"))
print()
#-----------------------------------------------------------------------
# time모듈
# -> 시간과 관련된 기능을 다룰때는 time모듈을 사용합니다
# time모듈로 날짜와 관련된 처리를 할수 있지만, 그런처리는 datetime모듈을 사용하는 경우가 더 많습니다
# -> time모듈은 유닉스 타임(1970년 1월 1일 0시 0분 0초를 기준으로 계산한 시간단위)를 구할때
# 특정 시간 동안 코드 진행을 정지할때 많이 사용합니다
#예제 time모듈의 sleep()함수 사용해보기
#sleep(매개변수)함수는 특정 시간 동안 코드 진행을 저징할 때 사용하는 함수 입니다
#매개변수에는 정지하고 싶은 시간을 초 단위로 입력 합니다
import time
# print("지금 부터 5초 동안 정지 합니다")
# time.sleep(5)
# print("프로그램을 종료 합니다")
# start = time.time()
# print(start)
#---------------------------------------------------------------------
#urllib모듈
# -> 웹브라우저 주소창에 입력하는 인터넷 주소를 활용할때 사용하는 모듈입니다
#urllib모듈에 있는 request모듈을 읽어 들이자
from urllib import request
#request모듈 내부에 있는 urlopen()함수를 이용해서 구글의 메인 페이지의 코드 내용을 읽어 들입니다
#urlopen()함수는 URL주소의 페이지를 열어 주는 함수이다
#이렇게 입력하면 웹브라우저에 "https://google.com"을 입력해서 접속하는 것처럼
#파이썬프로그램이 "https://google.com"에 접속해 줍니다.
target = request.urlopen("https://google.com")
#이어서 read()함수를 호출하면 해당 웹 페이지에 있는 전체 소스 내용을 읽어서 가져옵니다
#urllib모듈의 request모듈의 urlopen()함수는 웹서버에 정보를 요청한 후, 돌려 받은 응답을 저장하여
#응답객체 HTTPResponse를 반환합니다.
#반환된 응답객체의 read()함수를 실행하여 웹 서버가 응답한 데이터를 바이트 배열로 읽어들입니다
#읽어들인 바이트 배열은 이진수로 이루어진 수열이어서 그대로는 사용하기 어렵다
#웹 서버가 응답한 내용이 텍스트 형식의 데이터라면, 바이트 배열의 decode('utf-8')메소드를 실행하여
#문자열로 변환할수 있다. 이때 utf-8 은 유니코드 부호화 형식의 한종류인데 decode()함수의 기본 인자이므로
#생략해도 된다.
output = target.read().decode("utf-8")
#읽어 드린 내용을 출력
print(output)
|
10a8176af5cbba01be295eb892b4b3d7ee1d4dca | avaska/PycharmProjects | /workpy/5예외처리/handle_with_codition.py | 1,801 | 3.859375 | 4 |
#주제 :조건문으로 예외 처리하기
# #숫자를 입력받습니다
# user_input_a = input("정수입력>")
#
# #입력받은 문자열을 숫자로 변환 합니다
# number_input_a = int(user_input_a)
#
# #출력합니다
# print("원의 반지름 : ", number_input_a)
# print("원의 둘레 : ", 2 * 3.14 * number_input_a)
# print("원의 넓이 : ", 3.14 * number_input_a * number_input_a)
#위 코드는 정수를 입력하지 않으면 문제가 발생합니다
#따라서 정수를 입력하지 않았을때 조건으로 구분해서 해당 상황일때 다른 처리를 하도록 설정해 봅시다.
#--------------------------------------------------------------------------------
#숫자를 입력 받습니다
user_input_a = input("정수 입력>")
#참고 : 문자열의 isdigit()함수는 변수에 저장되어 있는 값이 숫자로만 구성된 글자인지 판별하여
# 숫자로만 구성되어 있으면 True를 반환함
#사용자 입력이 숫자로만 구성되어 있을때 True를 반환 하여 if문 내부 실행
if user_input_a.isdigit():
#숫자로 변환합니다
number_input_a = int(user_input_a)
#출력합니다
print("원의 반지름 : ", number_input_a)
print("원의 둘레 : ", 2 * 3.14 * number_input_a)
print("원의 넓이 : ", 3.14 * number_input_a * number_input_a)
else:
print("정수를 입력하지 않았습니다")
print("출력성공 또는 실패!")
#위 예제 설명
#- 예외처리 후 정수로 변환할수 없는 문자열을 키보드로 입력 받았을 경우
# lsdigit()함수를 사용해 숫자로 구성되어 있지 않다는 것을 확인하고,
# else 구문 쪾으로 들어가서 '정수를 입력 하지 않았습니다' 라는 문자열을 출력합니다.
|
b7fa760a313c7edbaf44ef540037481f66b1b02c | avaska/PycharmProjects | /workpy/5예외처리/file_closed02.py | 573 | 3.734375 | 4 |
#try except 구문을 사용합니다
try:
#파일을 쓰기모드로 연다
file = open("info.txt","w")
#여러가지 처리를 수행합니다
예외.발생해라()
except Exception as e:
print(e)
finally:
# 파일을 닫습니다
file.close()
print("파일이 제대로 닫혔는지 확인하기")
print(file.closed)
#코드를 실행 해보면 closed속성의 반환값이 False이므로 파일이 닫히지 않았다는 것을 알수 있습니다
#따라서 반드시 finally구문을 사용하여 파일을 닫게 해야합니다.
|
bc1dd0bbe542a976033950c6d48544ecf405bd63 | avaska/PycharmProjects | /workpy/1파이썬둘러보기/파이썬 기초 문법 따라 해 보기.py | 315 | 3.96875 | 4 |
# 실행 단축키 ctrl + shift + F10
print(1+2)
print(3/2.4)
print(3 * 9)
a = 1
b = 2
print(a + b)
a = "Python"
print(a)
a = 3
if a > 1:
print("a is geater than 1")
for a in [1,2,3]:
print(a)
i = 0
while i<3:
i = i + 1
print(i)
def add(c,d):
return c + d
print(add(10,100))
|
1d65b3d06b41868caf13b3629ac6a87a7d72ed44 | laurensierra/CSC442-TeamSphinx | /xor.py | 831 | 3.90625 | 4 | ###########################
#Name: Lauren Gilbert
#Date: May 5, 2020
#Version: Python 2
#Notes:this program takes ciphertext and plaintext and changes it to the other using a key that is in the file
###########################
from sys import stdin, stdout
import sys
#read key from file that we open through the program
#key file is in same directory as program
key_file = open('key.bin', 'rb').read()
#input text file as byte array
text = sys.stdin.read()
byteArray = bytearray()
i=0
#xor with each value in key with value that goes in input array and store result in binary array
while(i < len(key_file)):
#xor one byte at a time
xor = ord(text[i]) ^ ord(key_file[i])
#bytearray from the key and text that have been compared
byteArray.append(xor)
i += 1
#send bytearray to stdout
sys.stdout.write(byteArray)
|
8ef59dc9e39a022a7af161e04abe987b72f271a5 | hjfrun/python-learning-course | /intermediate-python/13-decorators.py | 1,499 | 3.578125 | 4 | import functools
# def start_end_decorator(func):
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# print("-----Start-----")
# result = func(*args, **kwargs)
# print("-----End-----")
# return result
# return wrapper
# @start_end_decorator
# def print_name():
# print("Alex")
# print_name = start_end_decorator(print_name)
# print_name()
# @start_end_decorator
# def add5(x):
# return x + 5
# result = add5(10)
# print(result)
# print(help(add5))
# print(add5.__name__)
# def repeat(num_times):
# def decorator_repeat(func):
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# for _ in range(num_times):
# result = func(*args, **kwargs)
# return result
# return wrapper
# return decorator_repeat
# @repeat(num_times=3)
# def greet(name):
# print(f"Hello, {name}")
# greet("Tengjiao")
# @start_end_decorator
# def say_hello(name):
# greeting = f'Hello {name}'
# print(greeting)
# return greeting
# say_hello('htj')
class CountCalls:
def __init__(self, func):
self.func = func
self.num_calls = 0
def __call__(self, *args, **kwargs):
# print('Hi There')
self.num_calls += 1
print(f"This is executed {self.num_calls} times")
return self.func(*args, **kwargs)
# cc = CountCalls(None)
# cc()
@CountCalls
def say_hello():
print("Hello")
say_hello()
say_hello()
|
622589e96be15dc7e742ce2a1dc83ea91507b5dc | DeepanshuSarawagi/python | /ModulesAndFunctions/dateAndTime/datecalc.py | 354 | 4.25 | 4 | import time
print(time.gmtime(0)) # This will print the epoch time of this system which is usually January 1, 1970
print(time.localtime()) # This will print the local time
print(time.time()) # This will print the time in seconds since epoch time
time_here = time.localtime()
print(time_here)
for i in time_here:
print(i)
print(time_here[0])
|
20a78703d5dde6ad6994c5832e05206da4fa7e79 | DeepanshuSarawagi/python | /100DaysOfPython/Day20-21/SnakeGame/snake.py | 1,869 | 3.921875 | 4 | from turtle import Turtle
MOVE_DISTANCE = 20
ANGLE = 90
UP = 90
DOWN = 270
RIGHT = 0
LEFT = 180
class Snake:
def __init__(self):
self.all_snakes = []
self.initialise_snake_body()
self.head = self.all_snakes[0]
def create_snake_body(self):
for _ in range(3):
timmy = Turtle()
timmy.color("white")
timmy.shape("square")
timmy.penup()
self.all_snakes.append(timmy)
def snake_position(self):
for i in range(len(self.all_snakes)):
if i == 0:
continue
else:
previous_turtle = self.all_snakes[i - 1]
turtle = self.all_snakes[i]
turtle.setx(previous_turtle.position()[0] - 20)
def initialise_snake_body(self):
self.create_snake_body()
self.snake_position()
def extend_snake(self):
last_segment = self.all_snakes[-1]
position = last_segment.position()
timmy = Turtle()
timmy.color("white")
timmy.shape("square")
timmy.penup()
timmy.goto(position)
self.all_snakes.append(timmy)
def move(self):
for turtle_num in range(len(self.all_snakes) - 1, 0, -1):
new_x = self.all_snakes[turtle_num - 1].xcor()
new_y = self.all_snakes[turtle_num - 1].ycor()
self.all_snakes[turtle_num].goto(new_x, new_y)
self.head.forward(MOVE_DISTANCE)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
|
91bfc92d73cf257344dc1260e433bdbd9d6cb4d5 | DeepanshuSarawagi/python | /freeCodeCamp/ConditionalExecution/conditionalExecution.py | 309 | 4.1875 | 4 | # This is a python exercise on freeCodeCamp's python certification curriculum
x = 5
if x < 5:
print("X is less than 5")
for i in range(5):
print(i)
if i <= 2:
print("i is less than or equal to 2")
if i > 2:
print("i is now ", i)
print("Done with ", i)
print("All done!")
|
bb6210fa257ed3c753101ae8b2502fbb8e21825f | DeepanshuSarawagi/python | /ModulesAndFunctions/dateAndTime/tztest.py | 1,109 | 3.65625 | 4 | import pytz
import datetime
country = "Europe/Moscow"
tz_to_display = pytz.timezone(country)
local_time = datetime.datetime.now(tz=tz_to_display)
print(f"The time in country {country} is {local_time}")
print(f"The UTC time is {datetime.datetime.utcnow()}")
for x in pytz.all_timezones:
print(x) # This will print all the timezones which pytz.timezone() method will accept
for x in pytz.country_names:
print(x + ": " + pytz.country_names[x]) # This will print all the country codes and country names
print("=" * 50)
# for x in sorted(pytz.country_names):
# print(f"{x}: {pytz.country_names[x]}: {pytz.country_timezones.get(x)}")
for x in sorted(pytz.country_names):
print(f"{x}: {pytz.country_names[x]}", end=': ')
if x in pytz.country_timezones:
for zone in pytz.country_timezones[x]:
tz_to_display = pytz.timezone(zone)
local_time = datetime.datetime.now(tz=tz_to_display)
print("\n\t\t {}: {}".format(zone, local_time))
# print(f"{pytz.country_timezones[x]}")
else:
print("No time zones defined")
|
7384fbb693486ec0f00158292487d6a2086fc2ac | DeepanshuSarawagi/python | /Data Types/numericOperators.py | 485 | 4.34375 | 4 | # In this lesson we are going to learn about the numeric operators in the Python.
a = 12
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
# We will learn about the operator precedence in the following example.
print(a + b / 3 - 4 * 12) # This should evaluate to -35.0 as per the BODMAS rule. If you have got it 12, you are wrong.
print(a + (b/3) - (4 * 12))
print((((a + b) / 3) - 4) * 12) # This will evaluate to 12.0.
print(a / (b * a) / b)
|
a2f4d989d9519493126f343e1e613b0c0d1c313d | DeepanshuSarawagi/python | /ModulesAndFunctions/Functions/parabolaFunction.py | 832 | 3.890625 | 4 | import tkinter
def parabola(page, size):
for x in range(-size, size):
y = x*x / size
plot(page, x, y)
# draw axes in the canvas
def draw_axes(page):
page.update()
x_origin = page.winfo_width() / 2
y_origin = page.winfo_height() / 2
page.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
page.create_line(-x_origin, 0, x_origin, 0, fill='black')
page.create_line(0, y_origin, 0, -y_origin, fill='black')
print(locals())
def plot(page, x, y):
page.create_line(x, -y, x + 1, -y + 1, fill='blue')
mainWindow = tkinter.Tk()
mainWindow.title('Parabola')
mainWindow.geometry('640x480')
canvas = tkinter.Canvas(mainWindow, width=640, height=480)
canvas.grid(row=0, column=0)
draw_axes(canvas)
parabola(canvas, 100)
parabola(canvas, 200)
mainWindow.mainloop()
|
6d34356e7e6d161aa6e838b8ca588e3dce3b01f4 | DeepanshuSarawagi/python | /100DaysOfPython/Day2/DataTypes/typeConversion.py | 944 | 4.25 | 4 | # In this lesson we are going to convert the int data type to string data type
num_char = len(input("What is your name?\n"))
print("Your name has " + str(num_char) + " characters") # Type conversion happens here. Where we convert
# the type integer to string
# Or we can use the fStrings
print("Your name has {} characters".format(num_char))
print(70 + float("170.5"))
# Day 2 - Exercise 1 - Print the sum of digits of a number
two_digit_number = input("Type a two digit number of your choice: ")
print(int(two_digit_number[0]) + int(two_digit_number[1]))
# Better solution
sum_of_numbers = 0
for i in range(0, len(str(two_digit_number))):
sum_of_numbers += int(two_digit_number[i])
print(sum_of_numbers)
# Remembering the PEMDASLR rule (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction, Left to Right)
print(3 * 3 + 3 / 3 - 3)
print(3 * 3 / 3 + 3 - 3)
|
a9aaf4e426597e6a54aff443fdadefad6e4fb9d6 | DeepanshuSarawagi/python | /100DaysOfPython/Day1/main.py | 647 | 4.375 | 4 | print("Print something")
print("Hello World!")
print("Day 1 - Python Print Function")
print("print('what to print')")
print("Hello World!\nHello World again!\nHellooo World!!")
print()
# Day 1. Exercise 2 Uncomment below and debug the errors
# print(Day 1 - String Manipulation")
# print("String Concatenation is done with the "+" sign.")
# print('e.g. print("Hello " + "world")')
# print(("New lines can be created with a backslash and n.")
print("Day 1 - String Manipulation")
print("String Concatenation is done with the " + "+" + " sign.")
print('e.g. print("Hello " + "world")')
print("New lines can be created with a backslash and n.")
|
34c3bcf8c09826d88ff52370f8c9ae9735d2f966 | DeepanshuSarawagi/python | /100DaysOfPython/Day19/Turtle-GUI-2/main.py | 796 | 4.21875 | 4 | from turtle import Turtle, Screen
tim = Turtle()
screen = Screen()
def move_forward():
tim.forward(10)
screen.listen() # In order for our turtle to listen to the screen events, we need to call this screen method
screen.onkey(fun=move_forward, key="Up") # The Screen.onkey() method accepts two arguments, 1. Function and 2. Kwy.
# We need to ensure that when we pass a function as an argument, it is coded without parentheses. Passing the function
# with parentheses calls the function immediately, instead we want it listen to an event and call the function when an
# event occurs. Like for example, in our case, when a key is presses.
screen.exitonclick()
# Higher Order Functions. A higher Order Function is called when a function accepts another function as an
# input/argument
|
3784c046f7d92ea5da937cc8920d75c2d18ed891 | DeepanshuSarawagi/python | /100DaysOfPython/Day2/DataTypes/LivesInWeeks.py | 168 | 3.9375 | 4 | age = int(input("Enter your age: "))
print("You have {} days or {} weeks or {} months left to live.".
format((90 - age) * 365, (90 - age) * 52, (90 - age) * 12))
|
e9e42890ea221e41dd51181364f24590d1b0ce6e | DeepanshuSarawagi/python | /whileLoop/whileLoop.py | 423 | 4.125 | 4 | # In this lesson we are going to learn about while loops in Python.
# Simple while loop.
i = 0
while i < 10:
print(f"i is now {i}")
i += 1
available_exit =["east", "west", "south"]
chosen_exit = ""
while chosen_exit not in available_exit:
chosen_exit = input("Please enter a direction: ")
if chosen_exit == "quit":
print("Game over")
break
else:
print("Glad that you got out of here")
|
11bc279d354a5d57bcae0bd9d14b8ed52db97a4b | DeepanshuSarawagi/python | /100DaysOfPython/Day27/ArgsAndKwargs/kwargs_example.py | 1,160 | 4.6875 | 5 | """
In this lesson we are going to learn about unlimited keyword arguments and how it can be used in functions. The general
syntax is to define a function with just one parameter **kwargs.
We can then loop through the 'many' keyword arguments and perform necessary actions.
Syntax: def function(**kwargs):
some operation
"""
def calculate(**kwargs):
for key in kwargs:
print(f"{key}: {kwargs[key]}")
calculate(add=5, subtract=6, multiply=10, divide=2)
def calculate(n, **kwargs):
n += kwargs["add"]
print(n)
n -= kwargs["subtract"]
print(n)
n *= kwargs["multiply"]
print(n)
n /= kwargs["divide"]
print(n)
calculate(n=10, add=5, subtract=6, multiply=10, divide=2)
"""Similarly we can use **kwargs in the __init__ method while creating a class. Refer to below exmaple"""
class Car:
def __init__(self, **kwargs):
self.model = kwargs["model"]
self.make = kwargs["make"]
def print_car_details(self):
print("You created a car. Your car make is {} and model is {}.".format(self.make, self.model))
my_car = Car(make="BMW", model="GT")
my_car.print_car_details()
|
bf93f065e5b1fe4d533137140254a9fa671233c9 | DeepanshuSarawagi/python | /DSA/LinkedLists/linked_lists.py | 5,363 | 4.375 | 4 | """
We will be creating singly linked lists with one head, one node and one tail.
SLL - is abbreviated as Singly Linked List
"""
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
# Insertion in singly linked list
def insert_singly_linked_list(self, value, location):
new_node = Node(value=value)
if self.head is None:
self.head = new_node
self.tail = new_node # By doing this we are adding the first node in our SLL
else:
if location == 0: # If location is zero, we are inserting the element at beginning of SLL
new_node.next = self.head # We are doing this because head stores node1's physical location.
# Hence we are setting the new node's next reference to the first node's physical location
self.head = new_node # Here we are updating the head with new node's physical location
elif location == 1: # inserting element at the end of SLL
new_node.next = None # Here we are setting last node's next reference to null
self.tail.next = new_node # Here we are setting the next reference of last node to new node
self.tail = new_node
else:
temp_node = self.head
index = 0
while index < location - 1:
temp_node = temp_node.next
index += 1
next_node = temp_node.next # considering temp node is current node, current node's next value is next
# node
temp_node.next = new_node # Inserting new node in between current node and current's next node
new_node.next = next_node # and setting new node's next reference to next node
# Traverse through Single Linked List
def traverse_singly_linked_list(self):
if self.head is None:
print("The Singly Linked List is empty")
else:
node = self.head
while node is not None:
print(node.value)
node = node.next
# Search in Single Linked List
def search_singly_linked_list(self, value):
if self.head is None:
return "The Singly Linked List is empty"
else:
node = self.head
index = 0
while node is not None:
if node.value == value:
return "Found element at index {}".format(index)
node = node.next
index += 1
return "The value does not exist in the list"
# Deleting a node from singly linked list
def delete_node(self, location):
if self.head is None:
print("The list is empty")
else:
if location == 0: # Checking if we want to delete the node at beginning of SLL
if self.head == self.tail: # Checking if we have just one node in SLL
self.head = None
self.tail = None # Breaking the links of head/tail with that node
else:
self.head = self.head.next # We know that head has reference of first node's physical location.
# hence we are setting the head's reference with first node's next node i.e., second node
# this will delete the link between head and first node
elif location == 1: # checking if we want to delete the last node
if self.head == self.tail: # Checking if we have just one node in SLL
self.head = None
self.tail = None # Breaking the links of head/tail with that node
else:
node = self.head
while node is not None:
if node.next == self.tail: # we know that tail has reference to last node, hence traverse
# until we find the last node and then break the loop. Loop will terminate at last node's
# previous node
break
node = node.next
node.next = None # once last node is found, set its previous node's reference to Null
self.tail = node # and set the tail with reference of previous node
else:
temp_node = self.head
index = 0
while index < location - 1:
temp_node = temp_node.next # iterate until we find the node we want to delete. temp node is the
# one before the node which has to be deleted
index += 1
next_node = temp_node.next
temp_node.next = next_node.next # setting temp node's next reference with next node's next reference.
# hence this will break the link between current node and next node.
def delete_singly_linked_list(self):
if self.head is None:
print("The list is empty.")
else:
self.head = None
self.tail = None
|
1f369c908a949991be5f732c724851a51732ee1e | DeepanshuSarawagi/python | /100DaysOfPython/Day24/FilesDirectoriesPaths/scoreboard.py | 1,279 | 3.796875 | 4 | from turtle import Turtle
FILE_LOCATION = "/Users/deepanshusarawagi/Desktop/Learning/python/100DaysOfPython/Day24/FilesDirectoriesPaths"
class Scoreboard(Turtle):
def __init__(self):
super(Scoreboard, self).__init__()
self.score = 0
with open(f"{FILE_LOCATION}/highscore.txt", "r") as file:
data = file.read()
self.high_score = int(data)
self.hideturtle()
self.color("white")
self.penup()
self.setposition(-30, 280)
self.write(f"Score = {self.score} High Score = {self.high_score}", font=("Arial", 20, "normal"))
def update_score(self):
self.clear()
self.write(f"Score = {self.score} High Score = {self.high_score}", font=("Arial", 20, "normal"))
# def game_over(self):
# self.color("red")
# self.goto(0, 0)
# self.write("GAME OVER", align="center", font=("Arial", 12, "normal"))
def reset(self):
if self.score > self.high_score:
self.high_score = self.score
with open(f"{FILE_LOCATION}/highscore.txt", "w") as file:
file.write(f"{self.high_score}")
self.score = 0
self.update_score()
def increase_score(self):
self.score += 1
self.update_score()
|
2ddf4c14b370e909c54921dd801a077fab4dba8b | DeepanshuSarawagi/python | /100DaysOfPython/Day22/PongGameProject/paddle.py | 577 | 3.703125 | 4 | from turtle import Turtle
class Paddle(Turtle):
def __init__(self, x_cor, y_cor):
super(Paddle, self).__init__()
self.shape("square")
self.color("white")
self.shapesize(stretch_wid=5.0, stretch_len=1.0)
self.penup()
self.setposition(x_cor, y_cor)
def move_paddle_up(self):
new_y = self.ycor() + 20
if self.ycor() < 230:
self.goto(self.xcor(), new_y)
def move_paddle_down(self):
new_y = self.ycor() - 20
if self.ycor() > -230:
self.goto(self.xcor(), new_y)
|
ad0cf84f3a01da48c32aa7efae44cf3b964d44d1 | DeepanshuSarawagi/python | /100DaysOfPython/Day2/DataTypes/BMICalculator.py | 209 | 4.28125 | 4 | height = float(input("Enter your height in meters: "))
weight = float(input("Enter your weight in kilograms: "))
print("Your BMI is {}".format(round(weight / (height * height), 2)))
print(8 // 3)
print(8 / 3)
|
31a342ddff6fade8595b45f6127868b7525feca1 | DeepanshuSarawagi/python | /DSA/Arrays/TwoDimensionalArrays/main.py | 2,074 | 4.40625 | 4 | import numpy
# Creating two dimensional arrays
# We will be creating it using a simple for loop
two_d_array = []
for i in range(1, 11):
two_d_array.append([i * j for j in range(2, 6)])
print(two_d_array)
twoDArray = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print(twoDArray)
# Insertion in 2D array
new2DArray = numpy.insert(twoDArray, 1, [[21, 22, 23, 24]], axis=1) # The first int parameter is the position
# where we want to add. And axis=1 denotes we want to add new values as columns, if axis=0, add it as rows
# Important Note: While using numpy library to insert elements in a 2-D array is that we meed to match the
# row/column size while inserting new elements in array
print(new2DArray)
# We will now use the append function to insert a new row/column at the end of the array
new2D_Array = numpy.append(twoDArray, [[97], [98], [99], [100]], axis=1)
print(new2D_Array)
print(len(new2D_Array)) # This prints the no. of rows in an array
print(len(new2D_Array[0])) # This prints the no. of columns in an array
def access_elements(array, rowIndex: int, colIndex: int) -> None:
if rowIndex >= len(array) and colIndex >= len(array[0]):
print("You are trying to access an element which is not present in the array")
else:
print(array[rowIndex][colIndex])
access_elements(new2D_Array, 3, 5)
# Traversing through the 2-D array
def traverse_array(array):
for i in range(len(array)):
for j in range(len(array[0])):
print(array[i][j], end="\t")
print()
traverse_array(new2D_Array)
def search_element(element, array):
for i in range(len(array)):
for j in range(len(array[0])):
if array[i][j] == element:
return "{} found at row {} and column {}".format(element, i + 1, j + 1)
return "The element {} is not found in given array.".format(element)
print(search_element(15, new2D_Array))
# How to delete a row/column in 2-D array
new2D_Array = numpy.delete(twoDArray, 0, axis=0)
print(new2D_Array)
|
6669908da54e6f1491a5ad8b00abd23e70e35ed5 | DeepanshuSarawagi/python | /DecimalComparison/decimalComparison.py | 723 | 3.796875 | 4 | input1 = str(input("Enter a decimal number of your choice: "))
input2 = str(input("Enter a second decimal number of your choice: "))
# input1 = str(3.1567)
# input2 = str(3.156)
print(input1)
print(input2)
print(input1[0] == input2[0])
extractedDecimal = []
for char in input1:
if char == ".":
extractedDecimal = input1.split(".")
print(extractedDecimal)
extractedDecimal2 = []
for char in input2:
if char == ".":
extractedDecimal2 = input2.split(".")
print(extractedDecimal2)
print(extractedDecimal[1][0:3] == extractedDecimal2[1][0:3])
if extractedDecimal[1][0:3] == extractedDecimal2[1][0:3]:
print("first three decimals are same")
else:
print("First three decimals are not same")
|
393fd4a8a5281a36764de18a36fa5b30425f2fc3 | DeepanshuSarawagi/python | /100DaysOfPython/Day4/Lists/RockPapersScissors.py | 971 | 4.09375 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
rpsl = [rock, paper, scissors]
choice = int(input("Type what you choose? 0 for Rock, 1 for Paper and 2 for Scissors: "))
computer = random.choice(rpsl)
print("You chose: \n " + rpsl[choice])
print("Computer chose: \n" + computer)
if rpsl[choice] == computer:
print("It is a draw")
elif rpsl[choice] == rock:
if computer == scissors:
print("You win")
else:
print("You lose")
elif rpsl[choice] == paper:
if computer == rock:
print("You win")
else:
print("You lose")
elif rpsl[choice] == scissors:
if computer == paper:
print("You win")
else:
print("You lose")
|
4bde74d331959c0b3ca9002de605e7b39066c22d | DeepanshuSarawagi/python | /100DaysOfPython/Day3/IfElseAndConditionaloperators/BMICalculator.py | 575 | 4.375 | 4 | # BMI calculator 2.0
height = float(input("Please enter your height in meters: "))
weight = float(input("Please enter your weight in kgs: "))
bmi = float(round(weight / (height ** 2), 2))
if bmi < 18.5:
print("BMI = {:.2f}. You are underweight".format(bmi))
elif 18.5 <= bmi <= 25:
print("BMI = {:.2f}. You are normal weight.".format(bmi))
elif 25 < bmi <= 30:
print("BMI = {:.2f}. You are overweight.".format(bmi))
elif 30 < bmi <= 35:
print("BMI = {:.2f}. You are obese.".format(bmi))
else:
print("BMI = {:.2f}. You are clinically obese.".format(bmi))
|
c32944fc92021af6a9aab1d68844287921f5f7dd | DeepanshuSarawagi/python | /100DaysOfPython/Day21/InheritanceBasics/Animal.py | 563 | 4.375 | 4 | class Animal:
def __init__(self):
self.num_eyes = 2
def breathe(self):
print("Inhale, Exhale")
# Now we are going to create a class Fish which will inherit properties from the Animal class and also has it's own
# properties
class Fish(Animal):
def __init__(self):
super().__init__() # Initializing all the attributes in super class
self.num_eyes = 3 # Here we are changing the field num_eyes to 3
def swim(self):
print("I can swin in water")
def print_eyes(self):
print(self.num_eyes)
|
1a528576c8f93aaa42a02bc429263c30a970bf32 | Qian7L/100-python-examples | /practice.py | 33,274 | 3.546875 | 4 | # -*- coding: utf-8 -*-
#案例实战
#1.有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
for i in range(1,5):
for k in range(1,5):
for j in range(1,5):
if (i != j) and (i != k) and (j != k):
print(i,k,j)
#2.企业发放的奖金根据利润提成
i=int(input("输入利润"))
if i <= 10:
m=0.1*i
elif i <= 20:
m=10*0.1+(i-10)*0.075
elif i <= 40:
m=10*0.1+10*0.075*(i-20)*0.05
elif i <= 60:
m=10*0.1+10*0.075+20*0.05+(i-40)*0.03
elif i <= 100:
m=10*0.1+10*0.075+20*0.05+20*0.03+(i-60)*0.015
else:
m=10*0.1+10*0.075+20*0.05+20*0.03+40*0.015+(i-100)*0.01
print(m)
#3.输入某年某月某日,判断这一天是这一年的第几天?
i=input('请输入日期,例如20181029')
month_day=[31,28,31,30,31,30,31,31,30,31,30,31]
year=int(i[:4])
month=int(i[4:6])
day=int(i[6:8])
#d=sum(month_day[:month-1],day)
d=0
for i in range(month-1):
d=d+int(month_day[i])
if (year % 4 == 0 and year %100 != 0) or (year % 400 == 0):
if month>2:
d=d+1
print('是第{0}天'.format(d+day))
#4.输入三个整数x,y,z,请把这三个数由小到大输出
x=int(input('输入x'))
y=int(input('输入y'))
z=int(input('输入z'))
d=sort(x,y,z)
print(d[0],d[1],d[2])
#5.将一个列表的数据复制到另一个列表中
a1=[1,2,3]
a2=[4,5,6]
print(a1+a2)
#6.输出9*9乘法口诀表
for i in range(1,10):
for j in range(1,10):
print('{0}*{1}={2}'.format(i,j,i*j),end=' ')
print('\n')
#7.暂停一秒输出
import time
d = {"a":1,"b":2}
for i in d:
print i
time.sleep(1) #暂停一秒输出
#8.暂停一秒输出,并格式化当前时间
import time
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
time.sleep(1)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
#9.斐波那契数列
def fib(n):
if n == 1:
return [0]
if n == 2:
return [0,1]
fibs=[0,1]
for i in range(2,n):
fibs.append(fibs[i-2]+fibs[i-1])
return fibs
print(fib(10))
#10.古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
#f(n)=f(n-1)+f(n-2),恰好为斐波那契数列
f1=1
f2=1
for i in range(1,21):
print(f1,f2,end=' ')
if (i % 3) == 0:
print ('')
f1 = f1 + f2
f2 = f1 + f2
#11.一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
def equ(n):
import math
a = math.sqrt(n)
if int(a) == a:
return 1
for i in range(-100,10000):
if equ(i + 100) == 1 and equ(i + 268) == 1:
print(i)
#12.判断101-200之间有多少个素数,并输出所有素数
import math
k=0
m=[]
for i in range(101,201):
n=0
for j in range(2,int(math.sqrt(i)+1)):
if i % j == 0:
break
n=n+1
if n == int(math.sqrt(i))-1:
k=k+1
m.append(i)
print(m)
print(k)
#13.打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方
for i in range(100,1000):
a=i // 100
b=(i // 10) % 10
c=i % 10
if (a ** 3 + b ** 3 + c ** 3) == i:
print(i)
#14.将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5
def su(n):
import math
b=0
for i in range(2,int(math.sqrt(n))+1):
if n % i == 0:
b=b+1
break
if b == 0:
return 1
t=1
q=0
i=int(input("输入一个数"))
print('{}='.format(i),end='')
for h in range(1,10):
for j in range(2,int(i/t)):
if i % j == 0:
print('{}*'.format(j),end='')
t=j
i=i/t
break
if su(i) == 1:
print(int(i))
break
#15.利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示
a=int(input('请输入成绩'))
if a >= 90:
grade='A'
elif (a > 60) and (a < 90):
grade='B'
else:
grade='C'
print('{}分为{}'.format(a,grade))
#16.输出指定格式的日期
import datetime
if __name__ == '__main__':
# 输出今日日期,格式为 dd/mm/yyyy。更多选项可以查看 strftime() 方法
print(datetime.date.today().strftime('%d/%m/%Y'))
# 创建日期对象
miyazakiBirthDate = datetime.date(1941, 1, 5)
print(miyazakiBirthDate.strftime('%d/%m/%Y'))
# 日期算术运算
miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=1)
print(miyazakiBirthNextDay.strftime('%d/%m/%Y'))
# 日期替换
miyazakiFirstBirthday = miyazakiBirthDate.replace(year=miyazakiBirthDate.year + 1)
print(miyazakiFirstBirthday.strftime('%d/%m/%Y'))
#17.输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
import string
alpha=0
digit=0
space=0
others=0
a=input('请输入字符')
for i in range(0,len(a)):
m=a[i]
if m.isalpha():
alpha += 1
elif m.isdigit():
digit += 1
elif m.isspace():
space += 1
else:
others += 1
print(alpha,digit,space,others)
#18.求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制
a=int(input('请输入a'))
n=int(input('请输入n'))
m=[a]
b=a
for i in range(1,n):
b=10*b+a
m.append(b)
print(sum(m))
print(m)
#19.一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数
for i in range(2,1001):
m=0
for j in range(1,i):
if i % j == 0:
m = m+j
if m == i:
print(i)
#20.一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
h=100
l=0
for i in range(1,11):
l=l+h+h/2
h=h/2
l=l-h
print(h,l)
#21.猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少
x1=1
for i in range(9):
x1=(x1+1)*2
print(x1)
#22.两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单
for a in ['x','y','z']:
for b in ['x','y','z']:
for c in ['x','y','z']:
if (a != b) and (a != c) and (b != c) and (a != 'x') and (c != 'x') and (c != 'z'):
print(a,b,c)
#23.打印出如下图案(菱形)
for i in range(1,5):
print(' ' * (4-i),'*' * (2*i-1),' ' * (4-i))
for i in range(3,0,-1):
print(' ' * (4-i),'*' * (2*i-1),' ' * (4-i))
#24.有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和
def qiuhe(n):
a=1
b=2
s=0
for i in range(n):
s=s+b/a
a,b=b,a+b
print(s)
qiuhe(20)
#25.求1+2!+3!+...+20!的和
def qiuhe(n):
h=0
for i in range(1,n+1):
k=1
for j in range(1,i+1):
k=k*j
h=h+k
print(h)
qiuhe(20)
#26.利用递归方法求5!
def jiecheng(n):
s=0
if n == 1:
s = 1
else:
s = n * jiecheng(n-1)
return s #这里要用return,因为递归要用到这里的数值,用return返回int,而print不会,会报错
print(jiecheng(5))
#27.利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来
def digui(s,l):
if l==0:
return
print(s[l-1])
digui(s,l-1)
a=input('请输入字符')
l=len(a)
digui(a,l)
#28.有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
def age(n):
if n==1:
a=10
else:
a=age(n-1)+2
return a
print(age(5))
#29.给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字
s=int(input('输入数字'))
a=s//10000
b=s%10000//1000
c=s%1000//100
d=s%100//10
e=s%10
if a!=0:
print('5位数',e,d,c,b,a)
elif b!=0:
print('4位数',e,d,c,b)
elif c!=0:
print('3位数',e,d,c)
elif d!=0:
print('2位数',e,d)
else:
print('1位数',e)
#30.一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同
s=input('输入数字')
flag=1
for i in range(int(len(s)/2)):
if s[i]!=s[len(s)-i-1]:
flag=0
if flag==1:
print('是回文数')
else:
print('不是回文数')
#31.请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母
letter = input("please input:")
# while letter != 'Y':
if letter == 'S':
print('please input second letter:')
letter = input("please input:")
if letter == 'a':
print('Saturday')
elif letter == 'u':
print('Sunday')
else:
print('data error')
elif letter == 'F':
print('Friday')
elif letter == 'M':
print('Monday')
elif letter == 'T':
print('please input second letter')
letter = input("please input:")
if letter == 'u':
print('Tuesday')
elif letter == 'h':
print('Thursday')
else:
print('data error')
elif letter == 'W':
print('Wednesday')
else:
print('data error')
#32.按相反的顺序输出列表的值
a=['apple','banana','orange']
for i in a[::-1]:
print(i)
#33.按逗号分隔列表
L = [1,2,3,4,5]
s1 = ','.join(str(n) for n in L)
print s1
#34.练习函数调用
def use():
print('so is life')
def using():
for i in range(3):
use()
if __name__=='__main__':
using()
#35.文本颜色设置
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
print(bcolors.WARNING + "警告的颜色字体?" + bcolors.ENDC)
#36.求100之内的素数
def sushu(n):
k=0
for i in range(2,n):
if n % i==0:
k=k+1
if k==0:
print(n)
for i in range(2,101):
sushu(i)
#37.对10个数进行排序
import random
m=[]
for i in range(10):
m.append(random.randint(0,99))
for i in range(len(m)-1,0,-1):
for j in range(i):
if m[j]>m[j+1]:
m[j],m[j+1]=m[j+1],m[j]
print(m)
#38.求一个3*3矩阵主对角线元素之和
import numpy as np
a=np.random.randint(1,100,size=(3,3))
print(a)
b=0
for i in range(3):
b=b+a[i][i]
print(b)
#39.有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中
import numpy as np
c=np.random.randint(1,100,size=10)
a=list(c)
for i in range(len(a)):
for j in range(len(a)-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print(a)
b=int(input('请输入一个数'))
m=0
for i in range(len(a)-1):
if a[i]>b:
a.append(0)
m=i
break
for j in range(len(a)-2,m-1,-1):
a[j+1]=a[j]
a[m]=b
print(a)
#40.将一个数组逆序输出
import numpy as np
c=np.random.randint(1,100,size=10)
print(c)
#a=list(c)
for i in range(int(len(c)/2)):
c[i],c[len(c)-i-1]=c[len(c)-i-1],c[i]
print(c)
#41.模仿静态变量的用法
def varfunc():
var = 0
print ('var = %d' % var)
var += 1
if __name__ == '__main__':
for i in range(3):
varfunc()
# 类的属性
# 作为类的一个属性吧
class Static:
StaticVar = 5
def varfunc(self):
self.StaticVar += 1
print(self.StaticVar)
print (Static.StaticVar)
a = Static()
for i in range(3):
a.varfunc()
#42.学习使用auto定义变量的用法
num = 2
def autofunc():
num = 1
print 'internal block num = %d' % num
num += 1
for i in range(3):
print 'The num = %d' % num
num += 1
autofunc()
#43.模仿静态变量(static)另一案例
class Num:
nNum = 1
def inc(self):
self.nNum += 1
print ('nNum = %d' % self.nNum)
if __name__ == '__main__':
nNum = 2
inst = Num()
for i in range(3):
nNum += 1
print ('The num = %d' % nNum)
inst.inc()
#44.两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵
import numpy as np
a=np.random.randint(1,100,size=(3,3))
b=np.random.randint(1,100,size=(3,3))
c=np.random.randint(1,100,size=(3,3))
print(a,b)
for i in range(3):
for j in range(3):
c[i][j]=a[i][j]+b[i][j]
print(c)
#45.统计 1 到 100 之和
print(sum(range(1,101)))
#46.求输入数字的平方,如果平方运算后小于 50 则退出
q=1
while q==1:
a = int(input('请输入数字'))
print('输入数字的平方为{}'.format(a * a))
if a*a<50:
q=0
#47.两个变量值互换
def exchange(a, b):
print('第一个变量 = {}, 第二个变量 = {}'.format(a, b))
a, b = b, a
print('第一个变量 = {}, 第二个变量 = {}'.format(a, b))
if __name__ == '__main__':
x = 1
y = 8
exchange(x, y)
#48.数字比较
def compare(a,b):
if a>b:
print('{}>{}'.format(a,b))
elif a<b:
print('{}<{}'.format(a,b))
else:
print('{}={}'.format(a,b))
a=int(input('请输入a'))
b=int(input('请输入b'))
compare(a,b)
#49.使用lambda来创建匿名函数
maxin=lambda x,y:(x>y)*x+(x<=y)*y
minin=lambda x,y:(x>y)*y+(x<=y)*x
if __name__ =='__main__':
x=20
y=30
print(maxin(x,y))
print(minin(x,y))
#50.输出一个随机数
import random
print(random.random())
#random.uniform
#random.randint
#51.学习使用按位与 &
if __name__ == '__main__':
a = 7
b = a & 3
print('a & b = %d' % b)
b &= 7
print('a & b = %d' % b) #换算为二进制,同一位上都是1运算结果才为1
#52.学习使用按位或 |
if __name__ == '__main__':
a = 7
b = a | 3
print('a | b is %d' % b)
b |= 15
print ('a | b is %d' % b) #同一位上只要有一个为1结果就为1
#53.学习使用按位异或 ^
if __name__ == '__main__':
a = 7
b = a ^ 3
print('The a ^ 3 = %d' % b)
b ^= 7
print('The a ^ b = %d' % b) #同一位上两者结果不同则为1
#54.取一个整数a从右端开始的4〜7位 #二进制的
if __name__ == '__main__':
a = int(input('input a number:\n'))
b = a >> 4
c = ~(~0 << 4)
d = b & c
print ('%o\t%o' %(a,d))
#55.学习使用按位取反~
a=147
b=~a
print(b)
#56.画图,学用circle画圆形
#用tkinter画
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width=800, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
k = 1
j = 5
for i in range(0, 26):
canvas.create_oval(310 - k, 250 - k, 310 + k, 250 + k, width=1)
k += j
j += 0.3
mainloop()
#用turtle画
if __name__ == '__main__':
import turtle
turtle.title("画圆")
turtle.setup(800,600,0,0)
pen=turtle.Turtle()
pen.color("yellow")
pen.width(5)
pen.shape("turtle")
pen.speed(1)
pen.circle(100)
#用matplotlib画
import numpy as np
import matplotlib.pyplot as plt
x = y = np.arange(-11, 11, 0.1)
x, y = np.meshgrid(x,y)
#圆心为(0,0),半径为1-10
for i in range(1,11):
plt.contour(x, y, x**2 + y**2, [i**2])
#如果删除下句,得出的图形为椭圆
plt.axis('scaled')
plt.show()
#57.画图,学用line画直线。
if __name__ =='__main__':
from tkinter import *
canvas=Canvas(width=500,height=500,bg='yellow')
canvas.pack(expand=YES,fill=BOTH)
x0=250
x1=260
y0=300
y1=180
for i in range(20):
canvas.create_line(x0,y0,x1,y1)
x0-=5
x1+=5
y0-=5
y1+=5
mainloop()
#用turtle
import turtle
def drawline(n):
t=turtle.Pen()
t.color(0.3,0.8,0.6) #设置颜色,在0--1之间
t.begin_fill() #开始填充颜色
for i in range(n): #任意边形
t.forward(50)
t.left(360/n)
t.end_fill() #结束填充颜色
drawline(4)
#58.画图,学用rectangle画方形
if __name__ == '__main__':
from tkinter import *
canvas = Canvas( width=400, height=400, bg='yellow')
canvas.pack()
x0 = 100
y0 = 100
y1 = 300
x1 = 300
for i in range(19):
canvas.create_rectangle(x0, y0, x1, y1)
x0 -= 5
y0 -= 5
x1 += 5
y1 += 5
mainloop()
#59.画图,综合例子
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 150
y0 = 100
canvas.create_oval(x0 - 10, y0 - 10, x0 + 10, y0 + 10)
canvas.create_oval(x0 - 20, y0 - 20, x0 + 20, y0 + 20)
canvas.create_oval(x0 - 50, y0 - 50, x0 + 50, y0 + 50)
import math
B = 0.809
for i in range(16):
a = 2 * math.pi / 16 * i
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
canvas.create_oval(x0 - 60, y0 - 60, x0 + 60, y0 + 60)
for k in range(501):
for i in range(17):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 + math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
for j in range(51):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
mainloop()
#60.计算字符串长度
a=input('请输入字符串')
print(len(a))
#61.打印出杨辉三角形(要求打印出10行如下图)
a=[]
for i in range(10):
a.append([])
for j in range(i+1):
if j==0:
a[i].append(1)
elif j==i:
a[i].append(1)
else:
a[i].append(a[i-1][j-1]+a[i-1][j])
for i in range(10):
for j in range(i):
print(a[i][j],end=' ')
print('\n')
#62.查找字符串
a='sdgga0'
b='0'
print(a.find(b))
#63.画椭圆
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width=800, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
canvas.create_oval(380, 250 , 310 , 220 , width=1)
mainloop()
#64.利用ellipse 和 rectangle 画图
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width = 400,height = 600,bg = 'white')
left = 20
right = 50
top = 50
num = 15
for i in range(num):
canvas.create_oval(250 - right,250 - left,250 + right,250 + left)
canvas.create_oval(250 - 20,250 - top,250 + 20,250 + top)
canvas.create_rectangle(20 - 2 * i,20 - 2 * i,10 * (i + 2),10 * ( i + 2))
right += 5
left += 5
top += 10
canvas.pack()
mainloop()
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ell1 = Ellipse(xy = (0.0, 0.0), width = 4, height = 8, angle = 30.0, facecolor= 'yellow', alpha=0.3)
ax.add_patch(ell1)
x, y = 0, 0
ax.plot(x, y, 'ro')
plt.axis('scaled')
# ax.set_xlim(-4, 4)
# ax.set_ylim(-4, 4)
plt.axis('equal') #changes limits of x or y axis so that equal increments of x and y have the same length
plt.show()
#65.一个最优美的图案
import math
from tkinter import *
class PTS:
def __init__(self):
self.x = 0
self.y = 0
points = []
def LineToDemo():
screenx = 400
screeny = 400
canvas = Canvas(width = screenx,height = screeny,bg = 'white')
AspectRatio = 0.85
MAXPTS = 15
h = screeny
w = screenx
xcenter = w / 2
ycenter = h / 2
radius = (h - 30) / (AspectRatio * 2) - 20
step = 360 / MAXPTS
angle = 0.0
for i in range(MAXPTS):
rads = angle * math.pi / 180.0
p = PTS()
p.x = xcenter + int(math.cos(rads) * radius)
p.y = ycenter + int(math.sin(rads) * radius * AspectRatio)
angle += step
points.append(p)
canvas.create_oval(xcenter - radius,ycenter - radius,
xcenter + radius,ycenter + radius)
for i in range(MAXPTS):
for j in range(i,MAXPTS):
canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)
canvas.pack()
mainloop()
if __name__ == '__main__':
LineToDemo()
#66.输入3个数a,b,c,按大小顺序输出
import random
a=[]
for i in range(3):
a.append(random.randint(10,50))
print(sorted(a))
#67.输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组
import numpy as np
c=np.random.randint(1,100,size=10)
print(c)
#a=list(c)
minin=c[0]
maxin=c[0]
max=0
min=0
for i in range(len(c)):
if c[i]<minin:
minin=c[i]
min=i
if c[i]>maxin:
maxin=c[i]
max=i
c[max],c[0]=c[0],c[max]
c[min],c[len(c)-1]=c[len(c)-1],c[min]
print(c)
#68.有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
def sort_(n,m):
import numpy as np
c=np.random.randint(1,100,size=n)
d=np.random.randint(1,100,size=n)
print(c)
for i in range(m):
d[i]=c[n-m+i]
for i in range(n-m):
d[m+i]=c[i]
print(d)
sort_(15,5)
#69.有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位
def findit(n):
m=[]
for i in range(n):
m.append(i+1)
l=len(m)
q=0
while l>1:
w=l % 3
for i in range(len(m),0,-1):
if (i+q) % 3==0:
m.remove(m[i-1])
l=len(m)
q=q+w
print(m)
findit(34)
#70.写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度
if __name__=='__main__':
a=input('输入字符串')
print('{}的长度为{}'.format(a,len(a)))
#71.编写input()和output()函数输入,输出5个学生的数据记录
N = 3
student = []
for i in range(5):
student.append(['', '', []])
print(student)
def input_stu(stu):
for i in range(N):
stu[i][0] = input('input student num:\n')
stu[i][1] = input('input student name:\n')
for j in range(3):
stu[i][2].append(int(input('score:\n')))
def output_stu(stu):
for i in range(N):
print('%-6s%-10s' % (stu[i][0], stu[i][1]))
for j in range(3):
print('%-8d' % stu[i][2][j])
if __name__ == '__main__':
input_stu(student)
print(student)
output_stu(student)
#72.创建一个链表
if __name__ == '__main__':
ptr = []
for i in range(5):
num = int(input('please input a number:\n'))
ptr.append(num)
print(ptr)
#73.反向输出一个链表
if __name__ == '__main__':
ptr = []
for i in range(5):
num = int(input('please input a number:\n'))
ptr.append(num)
print(ptr)
for i in range(int(len(ptr)/2)):
ptr[i],ptr[len(ptr)-1-i]=ptr[len(ptr)-1-i],ptr[i]
print(ptr)
#74.列表排序及连接
if __name__ == '__main__':
a = [1, 3, 2]
b = [3, 4, 5]
a.sort()
print(a)
print(a + b)
a.extend(b)
print(a)
#75.放松一下,算一道简单的题目
if __name__ == '__main__':
for i in range(5):
n = 0
if i != 1: n += 1
if i == 3: n += 1
if i == 4: n += 1
if i != 4: n += 1
if n == 3:
print(64 + i)
#76.编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
def jishu(n):
m=0
for i in range(int((n+1)/2)):
m=m+1/(2*i+1)
return m
def oushu(n):
m=0
for i in range(int(n/2)):
m=m+1/(2*i+2)
return m
a=int(input('输入一个数'))
if a % 2 ==0:
print(oushu(a))
else:
print(jishu(a))
#77.循环输出列表
if __name__ == '__main__':
s = ["man","woman","girl","boy","sister"]
for i in range(len(s)):
print(s[i])
#78.找到年龄最大的人,并输出。请找出程序中有什么问题
if __name__ == '__main__':
person = {"li": 18, "wang": 50, "zhang": 20, "sun": 22}
m = 'li'
for key in person.keys():
if person[m] < person[key]:
m = key
print('%s,%d' % (m, person[m]))
#79.字符串排序
l = []
for i in range(3):
l.append(input("int something:"))
l.sort()
print(l)
#80.海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
num = int(input("输入猴子的数目:"))
def fn(n):
if n == num:
return (4 * x) # 最后剩的桃子的数目
else:
return (fn(n + 1) * 5 / 4 + 1)
x = 1
while 1:
count = 0
for i in range(1, num):
if fn(i) % 4 == 0:
count = count + 1
if count == num - 1:
print("海滩上原来最少有%d个桃子" % int(fn(0)))
break
else:
x = x + 1
#简洁版
if __name__ == '__main__':
i = 0
j = 1
x = 0
while (i < 5) :
x = 4 * j
for i in range(0,5) :
if(x%4 != 0) :
break
else :
i += 1
x = (x/4) * 5 +1
j += 1
print (x)
#81.809*??=800*??+9*?? 其中??代表的两位数, 809*??为四位数,8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*??后的结果
i=1
while 1:
if (809*i>1000) and (809*i<10000) and (8*i>10) and 8*i<100 and 9*i>100 and 9*i<1000:
print(i,809*i)
break
else:
i=i+1
#82.八进制转换为十进制
n=input('输入一个数')
m=0
for i in range(len(n)):
m=m+(8 ** (len(n)-i-1)*int(n[i]))
print(m)
#83.求0—7所能组成的奇数个数
m=4
s=4
for i in range(2,9):
if i==2:
m*=7
if i>2:
m*=8
s=s+m
print(s)
#84.连接字符串
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
#85.输入一个奇数,然后判断最少几个 9 除于该数的结果为整数。
a=int(input('输入一个数'))
if a % 2 ==0:
print('请输入一个奇数')
a = int(input('输入一个数'))
b=9
while 1:
c=b/a
if int(c)==c:
break
else:
b=b*10+9
print(b,c)
#86.两个字符串连接程序
a = "acegikm"
b = "bdfhjlnpq"
c = a + b
print(c)
#87.回答结果(结构体变量传递)
if __name__ == '__main__':
class student:
x = 0
c = 0
def f(stu):
stu.x = 20
stu.c = 'c'
a= student()
a.x = 3
a.c = 'a'
f(a)
print (a.x,a.c)
#88.读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*
for i in range(7):
a=int(input('输入一个数'))
if a >50 or a<1:
print('错误输入')
a = int(input('输入一个数'))
print('*'*a)
#89.某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换
a=input('请输入一个四位数的数')
m=[]
for i in range(4):
m.append((int(a[i])+5)%10)
m[0],m[3]=m[3],m[0]
m[1],m[2]=m[2],m[1]
print("".join('%s' %s for s in m))
#90.列表使用实例
testList = [10086, '中国移动', [1, 2, 4, 5]]
print(len(testList))
print(testList[1:])
testList.append('i\'m new here!')
print(len(testList))
print(testList[-1])
print(testList.pop(1))
print(len(testList))
print(testList)
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(matrix)
print(matrix[1])
col2 = [row[1] for row in matrix]
print(col2)
col2even = [row[1] for row in matrix if row[1] % 2 == 0]
print(col2even)
#91.时间函数举例1
if __name__ == '__main__':
import time
print (time.ctime(time.time()))
print (time.asctime(time.localtime(time.time())))
print (time.asctime(time.gmtime(time.time())))
#92.时间函数举例2
if __name__ == '__main__':
import time
start = time.time()
for i in range(3000):
print(i)
end = time.time()
print(end - start)
#93.时间函数举例3
if __name__ == '__main__':
import time
start = time.clock()
for i in range(10000):
print (i)
end = time.clock()
print ('different is %6.3f' % (end - start))
#94.时间函数举例4,一个猜数游戏,判断一个人反应快慢
if __name__ == '__main__':
import time
import random
play_it = input('do you want to play it.(\'y\' or \'n\')')
while play_it == 'y':
c = input('input a character:\n')
i = random.randint(0, 2 ** 32) % 100
print('please input number you guess:\n')
start = time.clock()
a = time.time()
guess = int(input('input your guess:\n'))
while guess != i:
if guess > i:
print('please input a little smaller')
guess = int(input('input your guess:\n'))
else:
print('please input a little bigger')
guess = int(input('input your guess:\n'))
end = time.clock()
b = time.time()
var = (end - start) / 18.2
print(var)
if var < 15:
print('you are very clever!')
elif var < 25:
print('you are normal!')
else:
print('you are stupid!')
print('Congradulations')
print('The number you guess is %d' % i)
play_it = input('do you want to play it.')
#95.字符串日期转换为易读的日期格式
from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print(dt)
#96.计算字符串中子串出现的次数
if __name__ == '__main__':
str1 = input('请输入一个字符串:\n')
str2 = input('请输入一个子字符串:\n')
ncount = str1.count(str2)
print(ncount)
#97.从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止
if __name__ == '__main__':
from sys import stdout
filename = input('输入文件名:\n')
fp = open(filename,"w")
ch = input('输入字符串:\n')
while ch != '#':
fp.write(ch)
stdout.write(ch)
ch = input('')
fp.close()
#98.键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存
if __name__ == '__main__':
fp = open('test.txt','w')
string = input('please input a string:\n')
string = string.upper()
fp.write(string)
fp = open('test.txt','r')
print (fp.read())
fp.close()
#99.有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中
if __name__ == '__main__':
import string
fp = open('test1.txt')
a = fp.read()
fp.close()
fp = open('test2.txt')
b = fp.read()
fp.close()
fp = open('test3.txt', 'w')
l = list(a + b)
l.sort()
s = ''
s = s.join(l)
fp.write(s)
fp.close()
#100.列表转换为字典
i = ['a', 'b']
l = [1, 2]
print(dict([i,l])) |
27cf83c0562510abb73ab837edea6d9d59eb1641 | MichaelNormandyGavin/Zillow-Apartments | /time_series/analysis.py | 3,874 | 3.640625 | 4 | from math import sqrt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import adfuller
def compute_correlation(x,y,r2=False,auto=False):
'''Take two array-like series to calculate the correlation
x: numpy.array or pandas.DataFrame: x value for correlation
y: numpy.array or pandas.DataFrame: y value for correlation
r2: Boolean (optional): return r-squared value instead of r'''
'''Need to remove the mean for autocorrelation?'''
df = pd.DataFrame({'x':x,'y':y})
if auto:
df['x'] = df['x'] - df['x'].mean()
df['y'] = df['y'] - df['y'].mean()
df.dropna(inplace=True)
n = len(df)
df['x2'] = np.square(df['x'])
df['y2'] = np.square(df['y'])
df['xy'] = df['x'] * df['y']
sum_x = df['x'].sum()
sum_y = df['y'].sum()
sum_xy = df['xy'].sum()
sum_x2 = df['x2'].sum()
sum_y2 = df['y2'].sum()
corr = (n*(sum_xy) - (sum_x*sum_y)) / (sqrt(((n*(sum_x2) - (sum_x**2)) *((n*(sum_y2) - (sum_y**2))))))
#corr_test = np.cov(df['x'].values,df['y'].values)[0,1]
return df, corr
def acf_compute(x,y):
if isinstance(x,pd.DataFrame) or isinstance(x,pd.Series):
x = x.dropna().values
if isinstance(y,pd.DataFrame) or isinstance(y,pd.Series):
y = y.dropna().values
nx = len(x)
ny = len(y)
x = x[nx-ny:]
top = np.mean(np.dot((x-np.mean(x)), (y-np.mean(y))))
bot = np.sum(np.square((x-np.mean(x))))
acf_r = top/bot
return acf_r
def autocorrelate(x,shift=1,conf_int=False,lags=None,df=False):
if isinstance(x,pd.DataFrame) or isinstance(x,pd.Series):
x = x.values
n = len(x)
if lags is None:
lags = n
else:
lags = lags
r_array = np.empty(lags)
conf_lower = np.empty(lags)
conf_upper = np.empty(lags)
for i in range(lags):
r_array[i] = acf_compute(x[i:],x[:len(x)-i])
conf_lower[i] = -1.96 / np.sqrt(len(x)-i)
conf_upper[i] = 1.96 / np.sqrt(len(x)-i)
if df:
r_array = pd.DataFrame(data=r_array)
if conf_int:
return r_array, conf_upper, conf_lower
return r_array
def plot_auto_corr(x,title=None,lags=None):
auto_corr, conf_upper, conf_lower = autocorrelate(x,conf_int=True,lags=lags)
plt.plot(auto_corr,linestyle='none',marker='o',color='red')
for i, x in enumerate(auto_corr):
plt.vlines(x=i,ymin=min(0,x),ymax=max(0,x))
plt.fill_between([i for i in range(len(auto_corr))],conf_lower,conf_upper,color='green',alpha=0.2)
if title is None:
title = 'Autocorrelation (Lags = {})'.format(len(auto_corr))
else:
title = title + ' (Lags = {})'.format(len(auto_corr))
plt.title(title,fontsize=16)
plt.show()
def test_stationarity(df, print_results=True, **kwargs):
'''Use stattools adfuller function with a more DataFrame-friendly format
df = pandas.DataFrame or pandas.Series: required, used for testing stationarity
**kwargs = dict, used to feed adfuller arguments'''
raw_results = adfuller(df,**kwargs)
df_rows = {fk: fv for fv, fk in zip(raw_results[:4],list(['Test Statistic','P-Value','Lags Used','Observations Taken']))}
df_rows.update({sk: sv for sk, sv in raw_results[4:-1][0].items()})
dickey_test_results = pd.DataFrame(index=df_rows.keys(),data=list(df_rows.values()),columns=['Metric'])
if print_results:
print('Results of the Augmented Dickey-Fuller Test: \n\n', dickey_test_results.head(10))
return dickey_test_results
|
686b72c072f4358136a7225bf2effd169a9d4988 | AYSE-DUMAN/python-algorithm-exercises | /edabit-problems/matrix_operations.py | 1,217 | 3.953125 | 4 | def add_matrix(a,b):
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
# iterate through rows
for i in range(len(a)):
# iterate through columns
for j in range(len(a[0])):
result[i][j] = a[i][j] + b[i][j]
for k in result:
print(k)
# second solution for matrix addition
def add_matrix2(a,b):
result = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
for r in result:
print(r)
# matrix multiplication
def mult_matrix(a,b):
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
# iterate through row of a
for r in range(len(a)):
# iterate through column of b
for j in range(len(b[0])):
# iterate through by rows of b
for k in range(len(b)):
result[i][j] += a[i][k] * b[k][j]
for r in result:
print(r)
# second solution for matrix multiplication
def mult_matrix2(a,b):
result = np.dot(a, b)
for r in result:
print(r)
if __name__ == "__main__":
x = [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
y = [[4,4,4,4],[5,5,5,5],[6,6,6,6]]
add_matrix(x, y)
print("---------")
add_matrix2(x,y)
|
b4562dd899df9bdb93992e1b50f6f82e0792908e | rdrabina/PlotterWithDataFromCsv | /Date.py | 2,473 | 3.953125 | 4 | class Date:
def __init__(self, hour, minute, day, month, year):
self.hour = hour
self.minute = minute
self.year = year
self.month = month
self.day = day
@property
def hour(self):
return self.__hour
@hour.setter
def hour(self, hour):
if not 0 <= hour < 24:
raise ValueError
else:
self.__hour = hour
@property
def minute(self):
return self.__minute
@property
def day(self):
return self.__day
@property
def month(self):
return self.__month
@property
def year(self):
return self.__year
@minute.setter
def minute(self,minute):
if not 0 <= minute < 60:
raise ValueError
else:
self.__minute = minute
@day.setter
def day(self,day):
month = self.month
year = self.year
global days
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
else:
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
days = 29
else:
days = 28
else:
days = 29
else:
days = 28
if not 0 < day <= days:
raise ValueError
else:
self.__day = day
@month.setter
def month(self,month):
if not 0 < month < 13:
raise ValueError
else:
self.__month = month
@year.setter
def year(self,year):
self.__year = year
def __eq__(self, other):
return self.day == other.day and self.month == other.month and self.year == other.year
def __str__(self):
if self.hour < 10:
hour_string = "0"+str(self.hour)
else:
hour_string = str(self.hour)
if self.minute < 10:
minute_string = "0"+str(self.minute)
else:
minute_string = str(self.minute)
if self.day < 10:
day_string = "0" + str(self.day)
else:
day_string = str(self.day)
if self.month < 10:
month_string = "0" + str(self.month)
else:
month_string = str(self.month)
return "Date: "+ hour_string +":"+minute_string+" "+day_string+"."+month_string+"."+str(self.year) |
f5c54aa33157cfbefd9c6b9e470a4cd21c978040 | navarrovitor/mackenzie-assignments | /Algoritmos/VALÉRIA/matrix.py | 559 | 3.921875 | 4 | answers = ["a", "b", "b", "a", "c", "d", "e", "e", "a", "b"]
def grade(tests):
grades = []
for i in range(3): # mudar o número 2 para o número de provas
singular_grade = 0
for j in range(10):
if tests[i][j] == answers[j]:
singular_grade += 1
grades.append(singular_grade)
return grades
provas = [
["a", "b", "c", "d", "e", "a", "b", "c", "d", "e"],
["a", "a", "b", "b", "c", "c", "d", "d", "e", "e"],
["a", "b", "b", "a", "c", "d", "e", "e", "a", "b"],
]
print(grade(provas)) |
8a94d372afb86307c1f92794bb101fc62a533436 | navarrovitor/mackenzie-assignments | /Algoritmos/JEAN/Aulas/ex2.py | 210 | 3.8125 | 4 | #ENTRADA
NUM1 = int(input("Insira o primeiro número: "))
NUM2 = int(input("Insira o segundo número: "))
#PROCESSAMENTO
#SAÍDA
print("Seus números em ordem inversa são: " + str(NUM2) + " e " + str(NUM1)) |
d04ec50bd077ee78cb1328b1fa2a8d8fc1ae33a1 | navarrovitor/mackenzie-assignments | /Algoritmos/JEAN/10março/main_2.py | 244 | 3.640625 | 4 | km = float(input("Qual a quantidade de quilômetros percorridos? "))
dias = int(input("Qual a quantidade de dias pelos quais o carro foi alugado? "))
preço = (0.15 * km) + (60 * dias)
print("O preço a pagar é igual a: " + str(preço)) |
656cb91c4a6d870a42caa36fd3f05bd473501b30 | navarrovitor/mackenzie-assignments | /Dados/03GASTON/20-09-BP-manual.py | 535 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
height = [1.52,1.57,1.57,1.63,1.67,1.68,1.68,1.69,1.7,1.7,1.7,1.73,1.74,1.75,1.75,1.75,1.75,1.78,1.78,1.78,1.78,1.82,1.86,1.87,1.9]
weight = [52,53,55,60,60,62,62,64,68,72,72,72,72,73,74,75,75,75,76,80,83,85,87,94,94]
plt.figure(figsize=(12,6))
plt.subplot(1,2,1)
plt.tight_layout(pad=2)
plt.title('Distribuição de alturas')
plt.boxplot(height)
plt.subplot(1,2,2)
plt.tight_layout(pad=2)
plt.title('Distribuição de pesos')
plt.boxplot(weight)
plt.show() |
8bd23d0b541b4f400b7b48ac74cd37010efa789f | norbiax/Python-training | /Sum of the largest even and odd number from an input.py | 1,216 | 4.09375 | 4 | import random
import numpy as np
A=[]
ans = "Y"
while ans == "Y":
try:
N = int(input("Please enter number of elements: "))
for i in range(0, N):
while True:
try:
elem = int(input("Enter number " + str(i+1) + ": "))
A.append(elem)
except:
print("Entered value is a string. Must be a number")
continue
break
ans = False
except ValueError:
print("Entered value is not an integer.")
ans = input("Would like to try again? [Y/N]")
def solution(A):
print(A)
largest_odd = 0
largest_even = 0
for num in A:
if num % 2 != 0 and num > largest_odd:
largest_odd = num
if largest_odd == 0:
print("There were no odd integers")
else:
print("The largest odd number is:", largest_odd)
for num in A:
if num % 2 == 0 and num > largest_even:
largest_even = num
if largest_even == 0:
print("There were no even integers")
else:
print("The largest even number is:", largest_even)
print("Sum:", largest_odd + largest_even)
solution(A) |
3f1065b572cc33b71913f8902dc6d2d3de540456 | dabaker6/Udacity_Statistics | /Regression.py | 448 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 11 20:25:59 2017
@author: bakerda
"""
import numpy as np
def xbar(data):
return sum(data)/len(data)
def reg(x,y):
numer = sum(np.multiply([i-xbar(x) for i in x],[i-xbar(y) for i in y]))
denom = sum([(i-xbar(x))**2 for i in x])
m = numer/denom
c = xbar(y)-(m*xbar(x))
return m,c
x = (0,1,2)
y = (0,2,2)
print(reg(x,y)) |
02b409be559281f65f29dce8b87643c83ba7ce20 | victorhslima98/Complexidade_de_Algoritmos | /max_crossing_subarray.py | 459 | 3.515625 | 4 | def max_crossing_subarray(a, low, mid, high):
left_sum= float('-inf')
sum = 0
for i in range(mid, low-1,-1):
sum += a[i]
if sum > left_sum:
left_sum = sum
max_left = i
right_sum = float('-inf')
sum = 0
for j in range(mid + 1, high+1):
sum += a[j]
if sum > right_sum:
right_sum = sum
max_right = j
return max_left, max_right, left_sum + right_sum
|
1117ab86b491eca4f879897af51ccc69112e854b | shaonsust/Algorithms | /sort/bubble_sort.py | 1,074 | 4.40625 | 4 | """
Python 3.8.2
Pure Python Implementation of Bubble sort algorithm
Complexity is O(n^2)
This algorithm will work on both float and integer type list.
Run this file for manual testing by following command:
python bubble_sort.py
Tutorial link: https://www.geeksforgeeks.org/bubble-sort/
"""
def bubble_sort(arr):
"""
Take an unsorted list and return a sorted list.
Args:
arr (integer) -- it could be sorted or unsorted list.
Returns:
arr (integer) -- A sorted list.
Example:
>>> bubble_sort([5, 4, 6, 8 7 3])
[3, 4, 5, 6, 7, 8]
"""
for i in range(len(arr) - 1):
flag = True
for j in range(len(arr) - i - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j] # Swaping here
flag = False
if flag:
break
return arr
if __name__ == '__main__':
# Taking input from user
USER_INPUT = [float(x) for x in input().split()]
# call bublesort to sort an unsorted list and print it.
print(bubble_sort(USER_INPUT))
|
075834be6723abdf00ba354f7ef8c82b05c90812 | cocazzz/Ctf-Library-and-writeups | /cryptography/Crackable/keycrack.py | 835 | 3.5 | 4 | #key must be the length of the flag header
#in our case, the header is "h4x0r{" nad the length is 6
#in encryption function we see that the random number is between 1 and 50
KEY=""
S="put cipher here"
for i in range(50) :
K=chr(ord(S[0])-i)
if (K == "h") :
KEY=KEY+chr(i)
break
for i in range(50) :
K=chr(ord(S[1])-i)
if (K == "4") :
KEY=KEY+chr(i)
break
for i in range(50) :
K=chr(ord(S[2])-i)
if (K == "x") :
KEY=KEY+chr(i)
break
for i in range(50) :
K=chr(ord(S[3])-i)
if (K == "0") :
KEY=KEY+chr(i)
break
for i in range(50) :
K=chr(ord(S[4])-i)
if (K == "r") :
KEY=KEY+chr(i)
break
for i in range(50) :
K=chr(ord(S[5])-i)
if (K == "{") :
KEY=KEY+chr(i)
break
print (KEY)
|
caef334f181e5054dbd8970b2392ad1daa280287 | destinysam/Python | /join and split.py | 226 | 3.8125 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 31/08/2019
# PROGRAM: USING OF JOIN AND SPLIT IN LIST
name = input('ENTER THE NAME AND AGE COMMA SEPARATED :').split(",")
print(name)
name = ["sameer", '21']
print(",".join(name)) |
3d14c9d32dcf8ddbde76853960bb4f9883f9a77c | destinysam/Python | /variebles.py | 333 | 3.703125 | 4 | # CODED BY SAM@SAMEER
# EMAIL:SAMS44802@GMAIL.COM
# DATE: 09/08/2019
# PROGRAM: USING OF VARIEBLES IN PYTHON
name = "sameer"
age = "20"
print("hyy my name is " + name)
print("i m " + age + " years old")
name = "faizan"
age = "21"
weight = "70.34"
print("hyy my name is " + name)
print("i m " + age + " years old")
print("my weight is " + weight) |
1dab602fe34496eb9795737beec063b8a47cef31 | destinysam/Python | /multithreading.py | 346 | 3.59375 | 4 | from threading import Thread
import threading
import os
class thread_class(threading.Thread):
def __init__(self,num):
threading.Thread._init_(self)
self.num = num
def run(self):
for i in num:
print(i)
thread1 = thread_class(10)
thread2 = thread_class(20)
thread1.start()
thread2.start() |
8a9da88010290617dba5a27ca3f9d61b63820c37 | destinysam/Python | /converting float into integer.py | 174 | 4.125 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 18/08/2019
# PROGRAM: CONVERTING OF FLOAT INTO INTEGER
float_var = float(input("ENTER THE FLOAT NUMBER"))
print(int(float_var)) |
79867b99116d1b057f1c364c103c249a7aad7081 | destinysam/Python | /default parameters.py | 445 | 3.71875 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 29/08/2019
# PROGRAM: WORKING OF DEFAULT PARAMETERS
def user_details(first_name="unknown", last_name="unknown", age=12):
print(f"FIRST NAME IS :{first_name}")
print(f"LAST NAME IS : {last_name}")
print(f"AGE IS : {age}")
name = input('ENTER THE NAME OF USER :')
last_na = input('ENTER THE LAST NAME OF USER :')
age = input('ENTER THE AGE OF USER :')
user_details(name, last_na, age) |
7e1910b806da8c88a1b6b6ac482ebfc077ae1412 | destinysam/Python | /for loop and strings.py | 294 | 4.0625 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 28/08/2019
# PROGRAM: PROGRAM TO ADD THE DIGITS
name = input('ENTER THE NUMBER :')
total = 0
for i in name: # NEW WAY
total += int(i)
print(total)
name = "sameer"
total = 0
for i in range(len(name)): # OLD WAY
total += int(i)
print(total) |
a0118ebfc3e690eb89439727e45ac0c5085c382d | destinysam/Python | /step_argument_slicing.py | 769 | 4.40625 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 15/08/2019
# PROGRAM: STEP ARGUMENT IN STRING SLICING
language = "programming language"
print("python"[0:6])
print("python"[0:6:1]) # SYNTAX STRING_NAME[START ARGUMENT:STOP ARGUMENT:STEP]
print("python"[0:6:2]) # TAKING 2 STEPS TO AHEAD TO PRINT POSITION[2] AND CONTINUE THIS PROCESS
print("python"[0:6:3]) # TAKING 3 STEPS TO AHEAD TO PRINT POSITION[4] AND CONTINUE THIS PROCESS
print("python"[0:6:4])
print("python"[0:6:5])
print("python"[::-1]) # REVERSING THE STRING
print(language[::-1])
print(language[0:20]) #
print(language[0:20:2]) # TAKING 2 STEPS TO AHEAD TO PRINT POSITION[2] AND CONTINUE THIS PROCESS
print(language[0:20:3])
name = input('ENTER THE NAME ')
print("THE REVERSE OF NAME IS " + name[::-1]) |
2f74b43054c8bae7699e92383ac0dfe9bf60fe47 | destinysam/Python | /time function.py | 311 | 3.75 | 4 | # CODED BY SAM @SAMEER
# EMAIL:SAMS44802@GMAIL.COM
# DATE: 21/10/2019
# PROGRAM: USING CLOCK FUNCTION TO FIND THE EXECUTION TIME OF PROGRAM
from time import clock
sum = 0
start_time = clock()
for i in range(1,10000001):
sum+= i
print(f"YOUR SUM IS {sum}")
print(f"YOUR EXECUTION TIME IS {clock() - start_time} SECONDS") |
62d306a7c98e3e69fd65d56d465c270795b808a2 | destinysam/Python | /while_loop.py | 264 | 3.640625 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 20/08/2019
# PROGRAM: TO FIND THE SUM OF N NATURAL NUMBERS
number = int(input('ENTER THE NUMBER '))
i = 0
add = 0
while i <= number:
add = add + i
i = i + 1
print(add) # DON'T CREATE ANY SPACE IN THE PREFIX
|
81a8bce1fd4ad1426104d8f4b662f0c0ca3c52c5 | destinysam/Python | /more inputs in one line.py | 435 | 4.15625 | 4 | # CODED BY SAM@SAMEER
# EMAIL: SAMS44802@GMAIL.COM
# DATE: 12/09/2019
# PROGRAM: TAKING MORE THAN ONE INPUT FROM THE USER
name, age, address = "sameer", "23", "tarigam" # ASSIGNING VALUES BY ORDER
print("YOUR NAME,AGE AND ADDRESS IS " + name + " " + age + " " + address)
x = y = z = 2
print(x+y+z)
name, age, address = input("ENTER YOUR NAME AND AGE ").split() # USING OF SPLIT FUNCTION TO TAKE MORE INPUTS
print(name)
print(age)
print(address) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.