blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dd61557516635e0dc67c67910478380c99c8d7a8 | josephjoju2/Automate-with-python | /dict/ex6.py | 276 | 3.546875 | 4 | import pprint
stuff={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
print('inventory: ')
total=0
inventory={}
for k,v in stuff.items():
total+=v
temp=k
k=v
v=temp
inventory[k]=v
pprint.pprint(inventory)
print('total items: '+str(total))
|
10c86fb510fa55f4072263bc37e686d12cf29c87 | Coursal/PyDFA | /scan_input_file.py | 1,899 | 4.125 | 4 | from dfa import *
def scan_input_file(input_file_name):
" A function that scans the input file line by line and returns a DFA object based on what's scanned "
input_file = open(input_file_name, 'r') # open the input file
# read the 1st line and turn it to an integer
num_of_states = int(input_file.readline())
print('Number of states: ', num_of_states)
# read the 2nd line, strip the front/end spaces
alphabet = input_file.readline().strip()
# split the characters to create a string list
alphabet = alphabet.split()
print('Alphabet symbols: ', alphabet)
# read the 3rd line, strip the front/end spaces
start_state = input_file.readline().strip()
print('Starting state: ', start_state)
# read the 1nd line, strip the front/end spaces
end_states = input_file.readline().strip()
# split the characters to create a string list
end_states = end_states.split()
print('Ending states: ', end_states)
print('Transfer function: ')
transfer_function = dict()
# read all the other lines, one line at a time
for line in input_file:
current_transition = line.strip() # strip the front/end spaces
# split the characters to create a string list
current_transition = current_transition.split()
print(current_transition)
# create a tuple out of the first two characters to create a dictionary key for the transfer
# function, and set the third character as the value for this specific key
transfer_function[tuple([current_transition[0], current_transition[1]])] = current_transition[2]
input_file.close() # close the input file
print('---------------')
# create an object of the DFA with the specifications of the input file
generated_dfa = DFA(num_of_states, alphabet, transfer_function, start_state, end_states)
return generated_dfa
|
e4562704b70269ddd6eccf5a58f01542198b3285 | green-fox-academy/Unicorn-raya | /week-03/day-02/Sum/sum_test.py | 648 | 3.609375 | 4 | import unittest
from sum import Sum
class Test_sum(unittest.TestCase):
def setUp(self):
self.sum = Sum([1,2,3,4,5]).getSum()
self.emp_sum = Sum().getSum()
self.one_element_list = Sum([2]).getSum()
self.multiple_list = Sum([2,3,4,5]).getSum()
self.none_list = Sum([None]).getSum()
def test_sum(self):
self.assertEqual(self.sum,15)
def test_diff_list(self):
self.assertEqual(self.emp_sum,0)
self.assertEqual(self.one_element_list,2)
self.assertEqual(self.multiple_list,19)
self.assertEqual(self.none_list,0)
if __name__ == '__main__':
unittest.main() |
e15bd043b24c9cd343f670c69d16d165f3806806 | kana986ike/python_practice1 | /dice_game.py | 454 | 3.515625 | 4 | import dice
num = int(input('4,6,8,12,20のどれで勝負しますか?:'))
my_dice = dice.Dice(num)
computer_dice = dice.Dice(num)
my_pip = my_dice.shoot()
cpu_pip = computer_dice.shoot()
print('CPU:'+str(cpu_pip)+'あなた:'+str(my_pip))
if my_pip > cpu_pip:
print('おめでとうございます。あなたの勝ちです。')
elif my_pip < cpu_pip:
print('残念!あなたの負けです。')
else:
print('引き分けです。')
|
965717d14c6f598105646e3b96e785c09de125bc | saddamEDocument123/AllDocumentEbook | /DocumentEbook/Python-Doc/PaythonProgramPractic/FileIO.py | 606 | 4 | 4 | #File I/O
#creating file
#Reading file
#open function
#
#open function taken two parameter
file1 = open("textFile.txt","r")
#this is for read for file
print file1.read()
#it is showing only space or
#cursor now is last thets why its showin
# space
#if onece we read the file then if we want to again read that file
#that time u have to reset the coursour postition
print file1.read()
#where are i am tell me
print file1.tell()
#now u have to set the position of cursar
file1.seek(0,0) #reset the ocursour position
print file1.read()
file1.seek(0,0)
#read some of character
print file1.read(5) |
55107eeb17f75f13862c9baed8222db613633cb8 | jigneshbhimani/SQL-Query | /6Query(And).py | 460 | 3.53125 | 4 | # 6.SQL AND Query:
# WHERE clause can be combined with AND operator.
# AND operator is used to filter records based on more than one condition:
# The AND operator displays a record if all the conditions separated by AND are TRUE.
# AND Syntax:
'''
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
'''
# AND Example:
'''
SELECT * FROM Customers
WHERE Country='India' AND City='Rajkot';
''' |
d9dc3d5721c4cb09715aba6752de598d80fade84 | jay6413682/Leetcode | /Linked_List_Cycle_141.py | 2,640 | 3.625 | 4 |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
""" https://leetcode-cn.com/leetbook/read/linked-list/jbex5/
https://leetcode-cn.com/problems/linked-list-cycle/solution/ckuai-man-zhi-zhen-dai-zhu-shi-by-xi-yu-shi-liu-gu/ (ljjTYJR):
关于快慢指针中两个指针的速度问题: 和龟兔赛跑问题不同的是,龟兔赛跑是一个连续性的问题,无论二者的速度差是多少,可以这样假设:假设赛道长度为s,v_f表示速度快的值,v_s表示速度慢的值,(假设二者初始位置相同),那么可以求出来:(v_f-v_s)t=s;这样求出来的t,是二者第一次相遇的时间; 本题不同的是:对于链表来说是一个离散的值,我们假设环内共有n个节点,同样假设快指针与慢指针分别是v_f,v_s;如果想要相遇(假设初始位置相同),同样有(v_f-v_s)k = n; ——这个时候 v_f,v_s 为正整数,k为循环次数,n为节点数目; k = n/(v_f-v_s)如果想要k为整数,那么可以看到二者的速度差是有要求的,必须能够被n整除;注意:这样求得是第一次相遇,也有可能v_f-v_s是n的整数倍;
"""
# latest try:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
if head is None:
return False
fast_pointer = slow_pointer = head
while True:
fast_pointer = fast_pointer.next
if fast_pointer is None:
return False
fast_pointer = fast_pointer.next
if fast_pointer is None:
return False
slow_pointer = slow_pointer.next
if slow_pointer is None:
return False
if fast_pointer is slow_pointer:
return True
'''
# try number 2
if not head:
return False
if not head.next:
return False
dummy = ListNode()
dummy.next = head
pointer_a = dummy
pointer_b = dummy
while pointer_a and pointer_b:
pointer_a = pointer_a.next
pointer_b = pointer_b.next
if pointer_b:
pointer_b = pointer_b.next
else:
return False
if pointer_a is pointer_b:
return True
'''
|
c57fca636440cc0e07bc92ae59828106b65686cc | andrii-bublyk/sigma-python-nov-20 | /homework02/task5.py | 574 | 3.953125 | 4 | cards_dict = {
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 0,
"8": 0,
"9": 0,
"10": -1,
"J": -1,
"Q": -1,
"K": -1,
"A": -1
}
user_cards_string = input("enter cards: ")
clear_cards_string = user_cards_string.replace(" ", "").replace("'", "")
user_cards = clear_cards_string.split(",")
user_cards_weight = 0
for card in user_cards:
if card in cards_dict:
user_cards_weight += cards_dict.get(card)
else:
raise ValueError(f"there is no card '{card}'")
print(f"total weight = {user_cards_weight}")
|
a90043bc6c8e2de89f2f57de44b6ff9c15d3e471 | mivargas/ejercicios-de-python | /graficos/entry_interface.py | 1,620 | 3.859375 | 4 | from tkinter import *
root=Tk()
root.title("primer entry")
miFrame=Frame(root, width=1200, height=600)
miFrame.pack()
nombreLabel=Label(miFrame, text="Nombre:")
#nombreLabel.place(x=80, y=100) #forma incorrecta para trabajar con varios elementos ya que se superponen
nombreLabel.grid(row=0, column=0, sticky="e", padx=10, pady=10) #row para fila column para columnas esto para ubicar de forma ordenada los elementos, sticky es para la alineacion en este caso n,s,e,w,ne,se,sw,nw. pad es el padding y para el vertical x para el horizontal
apellidoLabel=Label(miFrame, text="Apellido:")
apellidoLabel.grid(row=1, column=0, sticky="e", padx=10, pady=10)
passwordLabel=Label(miFrame, text="Contraseña:")
passwordLabel.grid(row=2, column=0, sticky="e", padx=10, pady=10)
direccionLabel=Label(miFrame, text="Direccion de Habitación:")
direccionLabel.grid(row=3, column=0, sticky="e", padx=10, pady=10)
cuadroNombre=Entry(miFrame) #declaramos la entrada de texto (textbox) y por parametro dentro de quien estara
#cuadroTexto.place(x=100, y=100) #forma incorrecta para trabajar con varios elementos ya que se superponen
cuadroNombre.grid(row=0, column=1)
cuadroNombre.config(fg="red", justify="center")# con esto cambio el color de la fuente que se escribira por entrada de teclado y desde donde se escribira en este caso desde el centro
cuadroApellido=Entry(miFrame)
cuadroApellido.grid(row=1, column=1)
cuadroPassword=Entry(miFrame)
cuadroPassword.grid(row=2, column=1)
cuadroPassword.config(show="*") #para ocultar caracteres
cuadroDireccion=Entry(miFrame)
cuadroDireccion.grid(row=3, column=1)
root.mainloop() |
a110e4878f8052389e97f05502058ab7a851e6f0 | Chainso/HLRL | /hlrl/core/experience_replay/binary_sum_tree.py | 3,247 | 4.0625 | 4 | import numpy as np
class BinarySumTree():
"""
A binary sum tree
"""
def __init__(self, num_leaves):
"""
Creates a binary sum tree with the given number of leaves
num_leaves : The number of leaves in the tree
"""
self.num_leaves = num_leaves
self.size = 0
self.current_index = 0
self.tree = np.zeros(2 * self.num_leaves - 1)
def __len__(self):
"""
Returns the number of values added up to the number of leaves in the
tree
"""
return self.size
def _update_parents(self, index, value):
"""
Updates all the parent nodes going up to the root to accomodate the
addition of a new node
index : The index of the new node
value : The value of the new node
"""
change_in_value = value - self.tree[index]
parent = index
# Keep updating until the root node is reached
while(parent != 0):
parent = (parent - 1) // 2
self.tree[parent] += change_in_value
def _leaf_start_index(self):
"""
Returns the starting index of the leaves
"""
return self.num_leaves - 1
def _leaf_idx_to_real(self, leaf_index):
"""
Converts the index of a leaf relative to the other leaves to the index
in the tree (num_leaves - 1 + leaf_index)
leaf_index : The index of the leaf to be convert to the tree index
"""
return self._leaf_start_index() + leaf_index
def add(self, value):
"""
Pushes the given value onto the sum tree. When the tree is at capacity,
the values will be replaced starting with the first one.
value: The value of the item
"""
self.set(value, self.current_index)
self.current_index = (self.current_index + 1) % self.num_leaves
if(self.size < self.num_leaves):
self.size += 1
def set(self, value, index):
"""
Sets the value of the leaf at the leaf index given
value : The value of the leaf
index : The index of the leaf
"""
tree_index = self._leaf_idx_to_real(index)
self._update_parents(tree_index, value)
self.tree[tree_index] = value
def get(self, index):
"""
Retrieves the node at the given index
index : The index of the node to retrieve
"""
return self.tree[index]
def get_leaf(self, leaf_index):
"""
Returns the leaf with the given index relative to the leaves
leaf_index : The index of the leaf relative to other leaves
"""
tree_index = self._leaf_idx_to_real(leaf_index)
return self.get(tree_index)
def get_leaves(self):
"""
Returns all the added leaves in the tree
"""
leaf_start = self._leaf_start_index()
return self.tree[leaf_start:leaf_start + self.size]
def sum(self):
"""
Returns the sum of the tree (the value of the root)
"""
return self.tree[0]
def next_index(self):
"""
Returns the leaf index of the next value added
"""
return self.current_index
|
2fc8288f036c172a2407c28873b868a28fe27522 | zhankq/pythonlearn | /alivedio/base2/employee.py | 2,540 | 3.828125 | 4 | #显示系统 的欢迎信息
print('-'*20,'欢迎使用员工管理系统','-'*20)
user_list = []
#user_list.append(['姓名','年龄','性别','住址'])
#根据用户选择做相关的操作
while True:
#显示 用户的选项
print("请选择要做的操作:")
print("\t1.查询员工")
print("\t2.添加员工")
print("\t3.删除员工")
print("\t4.退出系统")
user_choose = input("请选择【1-4】:")
if user_choose == '1':
print('序号\t姓名\t年龄\t性别\t住址')
k = 0
for useritem in user_list:
k += 1
print(k,end="\t")
for item in useritem:
print(item,end="\t")
print()
print("\n--------------------------------------")
elif user_choose == '2':
name = input("请输入员工的姓名:")
age = input("请输入员工的年龄:")
sex = input("请输入员工的性别:")
address = input("请输入员工的住址:")
print("---------------------------")
print('姓名\t年龄\t性别\t住址')
print(name,"\t",age,"\t",sex,"\t",address)
print("---------------------------")
isInput = input("是否确认该操作【Y/N】:")
if isInput == 'Y' or isInput == 'y':
user_list.append([name,age,sex,address])
print("添加成功!")
else:
print("添加已取消")
elif user_choose =='3':
user_sort = int(input("请输入要删除的员工的序号:"))
user_key = user_sort-1
if user_sort > len(user_list):
print("当前的用户序号不存在")
continue
print("---------------------------")
print('序号\t姓名\t年龄\t性别\t住址')
#print(name,"\t",age,"\t",sex,"\t",address)
print(user_sort,"\t",user_list[user_key][0],"\t",
user_list[user_key][1],"\t",user_list[user_key][2],
"\t",user_list[user_key][3])
print("---------------------------")
isInput = input("是否确认该操作【Y/N】:")
if isInput == 'Y' or isInput == 'y':
user_list.pop(user_key)
print("删除成功")
else:
print("取消删除")
elif user_choose == '4':
input("欢迎使用!再见,点击回车键退出")
break
else:
print("您的输入有误,请重新选择!")
print("--------------------------------------")
|
e6fc1fd55f0892a883cfe68d29bd92168ab19101 | shrddha-p-jain/Python | /Assignment 0/13.py | 254 | 3.703125 | 4 | s = input("enter a string: ")
y = int(input("Position where you want to delete:"))
if(y<0):
print("Position must be positive")
else:
output = ''
for i in range(len(s)):
if(i!=y-1):
output+=s[i]
print(output)
|
de559eeacd0530766bab9e20945da1403bb3967c | Hellofafar/Leetcode | /Medium/152.py | 1,642 | 4.0625 | 4 | # ------------------------------
# 152. Maximum Product Subarray
#
# Description:
# Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
# Example 1:
# Input: [2,3,-2,4]
# Output: 6
# Explanation: [2,3] has the largest product 6.
#
# Example 2:
# Input: [-2,0,-1]
# Output: 0
# Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
#
# Version: 1.0
# 08/25/18 by Jianfa
# ------------------------------
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
r = nums[0]
imax = r
imin = r # imax/imin stores the max/min product of subarray that ends with the current number A[i]
for i in range(1, len(nums)):
if nums[i] < 0:
imax, imin = imin, imax # multiplied by a negative makes big number smaller, small number bigger
imax = max(nums[i], nums[i] * imax)
imin = min(nums[i], nums[i] * imin)
r = max(r, imax)
return r
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# A very smart solution from https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity
#
# imax & imin is the current max/min product of subarray ends with current number nums[i]
# Key point 1: when nums[i] < 0, swap imax and imin
# Key point 2: maintain r, r = max(r, imax) |
2acc7a47cf9b0a0c5da05fa90183e61b9d681dfe | JohnStevensonWSU/Ranking | /main.py | 924 | 3.609375 | 4 | import IndexList
def main():
index = IndexList.indexList()
index.add("hello", 1)
index.add("hello", 1)
index.add("hello", 1)
index.add("hello", 2)
index.add("hello", 2)
index.add("hello", 3)
index.add("there", 1)
index.add("there", 1)
index.add("there", 2)
index.add("there", 2)
index.add("there", 3)
index.add("how", 3)
index.add("are", 3)
index.add("you", 3)
index.add("a", 3)
indexNode = index.head
while indexNode is not None:
print(indexNode.term)
docNode = indexNode.docList.head
while docNode is not None:
print("(" + str(docNode.docID) + "," + str(docNode.freq) + ")")
docNode = docNode.nextDocNode
indexNode = indexNode.nextIndexNode
return
print("Term: " + indexNode.term)
print("Document: " + str(docID))
print("Frequency: " + str(freq))
main()
|
24dbdf24511c11bab1986b134a86ac7d30f60fbb | Provinm/leetcode_archive | /problems1_100/7_Reverse_Integer.py | 778 | 3.984375 | 4 | # coding=utf-8
'''
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or not -1*(2**32) <= x <= 2**32 -1 :
return 0
if x > 0:
return self.rev_int(x)
else:
return -1 * self.rev_int(-1*x)
def rev_int(self, x):
l_int = list(reversed(str(x)))
while not l_int[0]:
l_int = l_int[1:]
res_int = int(''.join(l_int))
return res_int if -1*(2**31) <= res_int <= 2**31 -1 else 0
integer = 1563847412
s = Solution()
res = s.reverse(integer)
print(res)
|
28beb4a3e37bd17ac224a8e0e606d5da6ab961a1 | ARJUNRAJOP/PYTHON-MYCAPTAIN | /administration.py | 1,118 | 3.9375 | 4 | import csv
num=1
def write_csv(info_list):
with open('C:/Users/Shrinivas/Desktop/student.csv' , 'a', newline='') as f:
writer=csv.writer(f)
if(f.tell()==0):
writer.writerow(["Name","Age","Contact","E-mail ID"])
writer.writerow(info_list)
condition=True
while(condition):
student_info=input("Enter student information for student #{} in following manner(Name Age Phone Email):=".format(num))
print("Entered information:"+student_info)
info_list=student_info.split(" ")
print("Entered Information list:"+str(info_list))
print("\n The entered information is=\nName:{}\nAge:{}\nContact:{}\nEmail:{}".format(info_list[0],info_list[1],info_list[2],info_list[3]))
choice=input("Is entered information is right?? type yes/no:")
if choice=="yes":
write_csv(info_list)
condition_check=str(input("Do you want to enter information?type yes/no:"))
if(condition_check=="yes"):
condition=True
num=num+1
else:
condition=False
elif choice=="no":
print("Plz reenter choice value??")
|
2119aa05b2146c5e1ec3420b46c387eb690e458f | luiz158/Part-Manager | /computer_part_manager.py | 9,375 | 4.125 | 4 | from tkinter import *
#import database db module
#from db import Database class
from db import Database
#import messagebox library from tkinter
from tkinter import messagebox
#now here we will instanciate the db object
#it will create the table if not already present
db = Database('store.db')
#here are all the functions that will handle all the backend of our application
#this function is responsible for actually getting the data from the database
def populate_list():
print("populate")
#this will delete any previously stored information in our listBox
parts_list.delete(0, END)
# db.fetch() = def fetch(self): function inside our db.py module and we are accessing that using db object in this module
#so here in this for loop we are going to loop through all the rows of our table and populate our listBox
#beacause we know def fetch(self): is returning rows in db.py module
for row in db.fetch():
#END = the new info will be inserted at the end of the list box
#tnd the things we are inserting will be the row returned by the fetch() method
print(row)
parts_list.insert(END, row)
def add_item():
print("add")
#check if the input fields are empty or not is yest then do not add anything into the database
if part_entry.get()== "" or customer_entry.get()=="" or Retailer_entry.get() == "" or Price_entry.get() == "":
messagebox.showerror("Required Fields", "Input Fields are NULL!")
return
#inseting data into the database
db.insert(part_entry.get(),customer_entry.get(),Retailer_entry.get(),Price_entry.get())
# this will delete any previously stored information in our listBox
parts_list.delete(0, END)
parts_list.insert(END,(part_entry.get(),customer_entry.get(),Retailer_entry.get(),Price_entry.get()))
#clearing the input fields of our application
clear_input()
populate_list()
#now here the remove function will be a little bit different
#we want to select the record that we want to remove and press remove button to remove it
#so here before remove_item(): function we will be requiring a select_item function to add select record function
#from our list box widget in tkinter
#basically we will binding our listBox to this
selected_item_details =''
def select_item(event):
print("Select Item")
try:
global selected_item
global selected_item_details
global Selected_item_view
selected_item_details =''
#Selected_item_view.config(text="")
#now we will be getting the index of the selected item in the listBox
index = parts_list.curselection()[0]
selected_item = parts_list.get(index)
print(selected_item)
#here we will put the selected_item data into the input Fiedls
#but before we put in the data related to our selected_item data we need to remove anything present int the input fields
clear_input()
# inserting the selected record details from the lisBox widget to our input Fields
part_entry.insert(END, selected_item[1])
customer_entry.insert(END, selected_item[2])
Retailer_entry.insert(END, selected_item[3])
Price_entry.insert(END, selected_item[4])
selected_item_details = "Part Name = " + selected_item[1] + "\n" + "Customer Name = " + selected_item[2]+"\n" + "Retailer Name = "+ selected_item[3] +"\n"+ "Price = "+selected_item[4]
print(selected_item_details)
except IndexError:
pass
def show_selected_item_detail_in_a_newWindow():
if selected_item_details == "":
messagebox.showerror("Error120x20545", "Order details cannot be shown because nothing is selected!!")
return
window2 = Toplevel()
Selected_item_view = Label(window2, text=selected_item_details, font=("bold", 14))
Selected_item_view.grid(row=4, column=0, columnspan=4, sticky=W, padx=10, pady=10)
def remove_item():
print("remove")
db.remove(selected_item[0])
#clearing the input fields after delete operation
clear_input()
populate_list()
def update_item():
print("update")
# check if the input fields are empty or not is yest then do not add anything into the database
if part_entry.get() == "" or customer_entry.get() == "" or Retailer_entry.get() == "" or Price_entry.get() == "":
messagebox.showerror("Required Fields", "Input Fields are NULL!")
return
db.update(selected_item[0], part_entry.get(),customer_entry.get(),Retailer_entry.get(),Price_entry.get())
populate_list()
def clear_input():
print("clear")
#clearing the information present in the input fields of the application
part_entry.delete(0,END)
customer_entry.delete(0,END)
Retailer_entry.delete(0,END)
Price_entry.delete(0,END)
#here this function will pop up a message box containing the information related to the developer of this software
def Dev_info():
messagebox.showinfo("Developer Info", "Name = Aditya Kumar" +"\n"+ "Roll_no = 1901230100001" +"\n"+ "Course = B.tech" +"\n"+ "Branch = Computer Science" +"\n"+ "College Code = 123")
#app variable will allow us to create a window
#app = window object
app = Tk()
#setting up the window titile
app.title("Part manager")
#setting up the window size on first boot
app.geometry("800x600")
# setting up the minimum size and maximum size for the application window
# set minimum window size value
app.minsize(800, 600)
# set maximum window size value
app.maxsize(800, 600)
#creating the input field for the user where the user will insert the details related to a particular computer part
#part name input field
#textView
part_text = StringVar()
part_label = Label(app, text="Part Name", font = ("bold",14),pady=20)
part_label.grid(row=0,column=0,sticky=W)
#EditText
#textvariable = part_text where part_text is a string so textvariable will also be a string
part_entry = Entry(app,textvariable = part_text)
part_entry.grid(row=0,column=1)
#customer input field
#textView
customer_text = StringVar()
customer_label = Label(app, text="Customer", font = ("bold",14))
customer_label.grid(row=0,column=2,sticky=W)
#EditText
#textvariable = customer_text where part_text is a string so textvariable will also be a string
customer_entry = Entry(app,textvariable = customer_text)
customer_entry.grid(row=0,column=3)
#Retailer input field
#textView
Retailer_text = StringVar()
Retailer_label = Label(app, text="Retailer", font = ("bold",14))
Retailer_label.grid(row=1,column=0,sticky=W)
#EditText
#textvariable = Retailer_text where part_text is a string so textvariable will also be a string
Retailer_entry = Entry(app,textvariable = Retailer_text)
Retailer_entry.grid(row=1,column=1)
#Price input field
#textView
Price_text = StringVar()
Price_label = Label(app, text="Price", font = ("bold",14))
Price_label.grid(row=1,column=2,sticky=W)
#EditText
#textvariable = part_text where part_text is a string so textvariable will also be a string
Price_entry = Entry(app,textvariable = Price_text)
Price_entry.grid(row=1,column=3)
#now here we are creating a listBox widget which will show the list of computer parts
#border =0 will create a border less listbox tkinter widget height=10 , width=50
parts_list = Listbox(app,border=0)
parts_list.grid(row=3,column=0,columnspan=4,rowspan=6,padx=10,pady=10, sticky = W+E+S+N)
#now creating a scrollbar for our ListBox widget which will allow us to scroll the contents of our ListBox
Scrollbar = Scrollbar(app)
Scrollbar.grid(row=3,column=4,sticky = N+S)
#now here we are connecting our scrollbar to our ListBox
parts_list.configure(yscrollcommand=Scrollbar.set)
#command = parts_list.yview->is telling scrollbar wighet to scroll the listBox in y axis when scrollbar is scrolled
#by the user in y axis
Scrollbar.configure(command = parts_list.yview)
#binding our select item function '<<ListboxSelect>>' to our listBox and function that we are using is select_item()
parts_list.bind('<<ListboxSelect>>',select_item)
#now here we are going to add some buttons to our application
#add button will add new parts to the database and the list box conatining the list of computer parts
add_button = Button(app,text="Add Part",width=12,command=add_item)
add_button.grid(row=2,column=0,pady=20)
#remove button will remove the computer part selected from the listbox from the database
remove_button = Button(app,text="Remove Part",width=12,command=remove_item)
remove_button.grid(row=2,column=1)
#update button will update the existing computer part in the database
update_button = Button(app,text="Update Part",width=12,command=update_item)
update_button.grid(row=2,column=2)
#clear button will clear all the input field of the application so that suer can enter the next data
clear_button = Button(app,text="Clear Input",width=12,command=clear_input)
clear_button.grid(row=2,column=3)
#dreating a developer info button
Dev_button = Button(app,text="Developer info",command=Dev_info)
Dev_button.grid(row=2,column=4,sticky=E)
#creating a button that will show the detail of the order in a new window
detail_view_button = Button(app,text = "Show Detail",command = show_selected_item_detail_in_a_newWindow)
detail_view_button.grid(row = 1,column=4,sticky=E)
#now we want to populate our listbox with computer parts list if present any when our application boots up
populate_list()
#start program
app.mainloop() |
e15d04cb6ecde05459936684d554509d8b6e3903 | yejineer/Study | /BigData/Lab2/q4.py | 219 | 3.921875 | 4 | for i in range (0, 10):
for j in range(0, 10 - i - 1):
print(' ', end='')
for j in range(0, i*2+1):
print('*', end='')
for j in range(0, 10 - i - 1):
print(' ', end='')
print('')
|
151b79e16dcb12393d1ad4d6f982ec5d00eb357c | CaiJiJi/My_Dirty_Scripts | /md5_crack_challenge/h.py | 158 | 3.609375 | 4 | import crypt
salt = 'shishaclub'
with open('wordlist.txt','rb') as f:
for password in f:
print(crypt.crypt(password.strip(),salt))
|
4be3c67ed10d182172fc909e57226c60129d9988 | Spuntininki/Aulas-Python-Guanabara | /ex0096.py | 251 | 3.71875 | 4 | def area(x, y):
a = x * y
print(f'a aréa de um terreno {x}x{y} é {a}m²')
print('Controle de Terrenos')
print('-'*30)
l = float(input('Insira a largura do terreno (m): '))
c = float(input('Insira o comprimento do terreno (m): '))
area(l, c) |
7c4f04d8a9b8c5d9e9c1378fcdf9df5403924cb9 | PabloG6/COMSCI00 | /Lab3/emoticons.py | 330 | 4.15625 | 4 | user_input = input("Enter an emotion: ")
if (user_input=="happy" or user_input=="smiling"):
print(':-)')
elif (user_input=='sad'):
print(':-(')
elif (user_input=='happy'):
print(':-)')
elif(user_input=='crying'):
print(':-’(')
elif(user_input=='laughing'):
print(':D')
else:
print("Try another emotion")
|
0b7d3a91aa3a3d8ad24134d434de4528404417fa | MeisterKeen/Python-Projects | /abs1.py | 992 | 4.4375 | 4 |
import abc
from abc import abstractmethod # If I don't do this, I have to write the
# decorator as "@abc.abstractmethod"
# So this class will be the parent class:
class Abstract(object):
@abstractmethod
def abstractery(self):
pass
# So this is the method we're going to define in the child class
def anotherMethod(self):
print("This method was defined in the parent class")
# Here's a method with some actual content
class Concrete(Abstract):
def abstractery(self):
print("This method was defined in the child class")
# Isn't this basically the same as polymorphism?
c = Concrete() # instantiate an object
c.abstractery() # call the abstract method defined in the child
c.anotherMethod() # call the method defined in the parent.
# Wow! I was totally over-thinking this.
# I think I kinda-sorta get how this would be useful, but I'll need to
# practice with it to really get it.
|
976878bdbe2b0d3216f89654d26a96e1eeefbd45 | workready/pythonbasic | /sources/t03/t03ej23.py | 286 | 4.0625 | 4 | x,y = 8, 4
if x > y:
print("x es mayor que y")
print("x es el doble de y")
if x > y:
print("x es mayor que y")
else:
print("x es menor o igual que y")
if x < y:
print("x es menor que y")
elif x == y:
print("x es igual a y")
else:
print("x es mayor que y") |
81c6413fcdbccbd24d64239d9c972e52cff575d1 | modihere/intro-to-ml | /coding_standards/newtest1.py | 835 | 3.78125 | 4 | class FindChar:
def __init__(self, string):
# constructor initialization
self.string = string
def find_char(self, check, element):
# function to return the second element or the element being searched
if check == 0:
# returning the second element in this block
return self.string[1]
else:
# a exception handler to check whether the element searched is there or not.
try:
return self.string.index(element)
except ValueError as e:
return e
if __name__ == "__main__":
string = "aeiou"
find_character = FindChar(string)
check = int(input("1 - if a user defined element needs to be searched"
" else 0 - for showing 2nd element "))
if check == 1:
character = input("Enter the character ")
print(find_character.find_char(1,character))
else:
print(find_character.find_char(0,None))
|
88a4515a439dac8e4eea321d0721567598ea9c5c | BigPieMuchineLearning/python_study_source_code2 | /exercise_6_1.py | 114 | 3.734375 | 4 | n=int(input())
def absolute_number(n):
result=n if n>=0 else -1*n
print(result)
absolute_number(n)
|
c0d57f1b19a72b1232ee5399dba3c78352c6e0c8 | vinnav/Python-Crash-Course | /CheatSheets/3lists.py | 2,545 | 4.4375 | 4 | listExample = ["element0", "element1", "element2", "element3"]
listExample[0] = "element0" # First element of the list
listExample[-1] = "element3" # Last element of the list
# Changing, adding, removing elements
listExample[0] = "new_element0" # Change element 0
listExample.append("element4") # Append element to the end of the list
listExample.insert(0, "inserted") # Insert element at position 0
del listExample[0] # Remove element at position 0
popped_element = listExample.pop() # Assign removed element from end of the list
popped_element = listExample.pop(0) # Same as .pop but at position 0
listExample.remove("element1") # Remove by value (only the first instance
# of the element, unless you use loop)
# Organize a list
listEx = ["b", "a", "t", "s"]
listEx.sort() # Sort in alphabetical order
listEx.sort(reverse=True) # Reverse alphabetical order
print(sorted(listEx)) # Diplay the sorted list without affecting the order
listEx.reverse() # Reverse the list order
len(listEx) # Find the length of the list, starts from 1
# Loop through a List
cats = ["Mario", "Luke", "Bob"]
for cat in cats: # Loop through each element
print(cat)
for value in range(1, 5): # Loop through values in range, printing 1...4
print(value)https://github.com/vinnav/Python-Crash-Course.git
for value in range(5) # Loop printing 0...4
numbers = list(range(1, 6)) # Create the list [1, 2, 3, 4, 5]
even_numbers = list(range(2,11,2)) # The third value is the step size
# Statistics
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits) = 0
max(digits) = 9
sum(digits) = 45
# List comprehension
squares = [vualue**2 for value in range(1, 11)] # Generate a list in one line
squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# [expression to generate values, for loop to feed values]
# Slice a list
listExample[0:3] # elements 0, 1, 2
listExample[:3] # starts at the beginning
listExample[3:] # goes to the end
listExample[-3:] # last 3 elements
# Loop through a slice
for i in listExample[2:]:
print(i)
# Copy a list
listExample2 = listExample[:] # Copy the full list, without [:] you refence the list
# Tuple is a list that cannot change
tupleExample = (0, 1, 2) # tupleExample[0] = 1 won't work, you have to reassign
# entire tuple
|
5a88927ab7ea44f570dd66b58894c4a44a91c724 | Neveon/python-algorithms | /greedy_algorithm/optimal_task.py | 1,165 | 4.46875 | 4 | # Given a list of numbers with each number corresponding to a duration of a task
# assign each item to a 'worker' with each 'worker' taking 2 items/tasks maximum
# and contain the minimum max duration to wait
# EXAMPLE
# [6, 3, 2, 7, 5, 5]
# worker 1 (6, 3)
# worker 2 (2, 7)
# worker 3 (5, 5)
# max(6+3, 2+7, 5+5) = 10 (smallest number generated)
# Greedy approach
# pair the longest task with the shortest task
# [2, 3, 5, 5, 6, 7]
# (2,7), (3,6), (5,5)
# Time complexity is O(n log n) due to sorting
tasks = [1, 6, 3, 5, 2, 7]
def optimal_task(tasks):
tasks = sorted(tasks)
for i in range(len(tasks) // 2):
# ~ (not) -> ~0 = -1 ~1 = -2
print(tasks[i], tasks[~i])
optimal_task(tasks)
# What is a greedy algorithm? What makes this a greedy algorithm?
# A greedy algorithm is an algorithmic strategy that makes the best optimal choice at
# each small stage with the goal of this eventually leading to a globally optimum
# solution. This means that the algorithm picks the best solution at the moment
# without regard for consequences. It picks the best immediate output, but does
# not consider the big picture, hence it is considered greedy. |
0cc1a20a886dec2e2d65d8187a6eb1e6f92814b6 | Abhi7865/python-projects | /cal.py | 1,101 | 4 | 4 | import numpy
def add():
num1=int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1+num2;
def sub():
num1 = int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1-num2;
def multi():
num1 = int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1*num2;
def div():
num1 = int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1/num2;
def mod():
num1 = int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1%num2;
print("1. Addition")
print("2. Substraction")
print("3. Multiplication")
print("4. Division")
print("5. Mode")
op = int(input("enter operation number from above (1,2,3,4,5):"))
if (op==1):
print( "addition: ",add());
elif(op==2):
print("Substraction:", sub())
elif(op==3):
print("Multiplication:", multi())
elif(op==4):
print("division: ", div())
elif(op==5):
print("MODE: ", mod())
else:
print("invalid option...")
|
f5e80a16365a780e86abd909c7d50661a9501182 | Miguel2308/Analisis-de-Datos | /DiccionariosDA.py | 3,743 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 11 20:56:55 2020
@author: Admin
"""
# podemos crear una lista con tupla y transformarlas en un diccionario
diccionary = [(1,'uno'),(2,'dos'),(3,'tres'),(4,'cuatro'),(5,'cinco')]
mi_diccionario = dict(diccionary)
print(mi_diccionario,'Diccionario creado a partir de una lista con tuplas','\n')
cipher = {'p':'9', 'y':'6', 't':'5', 'h':'2', 'o':'1', 'n':'4'}
# con esta funcion obtengo los valores de las claves
def encrypt(word):
encrypted = []
for i in word:
encrypted += cipher[i]
return encrypted
palabra = 'python'
enc = encrypt(palabra)
#............
#cipher = enc
#...........:
print(enc,'\n')
#print(cipher)
# si queremos buscar una clave la cual no sabeos si se encuentra en el diccionario pero queremos intentar
# debemos llamar al metodo get()
print(cipher.get('t'),'.....es el valor para get("t")','\n')
print(cipher.get(1),'.....es lo que devuelve si la clave no esta en el diccionario get(1)','\n')
print(cipher.get(1,'t'),'.....si uno no esta en el diccionario devolvera el valor predeterminado que hemos indicado get(1,"t")','\n')
# Para asignar un nuevo valor a una clave existente.
cipher['p'] = 'g'
print(cipher,'Se ha modificado el valor para "p"','\n')
# tambien se puede agregar clave valor que no existan en el diccionario, con la misma sintaxis
# con la que hemos actualizado una clave.
cipher['m'] = 'i'
print(cipher,'Se agrego una nueva clave valor al diccionario','\n')
enc2 = encrypt(palabra)
print(enc2)
print('\n')
print('\n')
print('\n')
# DICCIONARY KEYS:
# CHECKING KEYS.
print('checking keys','\n')
# para averiguar si una clave se encuentra en un diccionario usamos in
print('m' in cipher) # para 'm devolvera true, en tal caso ya podemos mandar a imprimir su valor.
mapping = {1:100,2:120,3:240,4:520,5:89}
keys = [1,2,3,4,5,6] # 6 no se encuentra en el diccionario
# mapeamos las claves e imprimimos su valor correspondiente en el diccionario.
for key in keys:
if key in mapping:
print(key,mapping[key])
else:
print('{} no esta como clave en el diccionario mapping'.format(key))
# IMPORTTANTE: EN PYTHON LAS CLAVES DEBEN SER DEL MISMO TIPO PARA EVITAR QUE ELINTERPRETE
# MALINTERPRETE LO QUE QUEREMOS HACER CUANDO QUEREMOS AGREGAR UN NUEVO MAPEO O ACTUALIZAR UNO EXISTENTE.
#..............................
# HANDLING DICTIONARY ERRORS
print('\n')
print('\n')
print('\n','HANDLING DICTIONARY ERRORS')
# En los diccionarios las claves deben de ser inmutables, si las claves son mutables,
# python no sabra como hacer el hash.
# por ejemplo si la claves esta compuestas por nombre y apellido, debemos de colocarla dentro de
# parentesis curvo para representar una tula y no entre corchetes como una lista,
# ya que las tuplas son inmutables y las listas mutables.
# una funcion que devuelva el valor de una clave si se encuentra enel diccionario,
# si no es asi que devuelva un valor por default.
# el valor -1 es un quivalente a False, seria intuitivo si se lo asignamos como valor por defecto
# expresando que la clave no se encuentra en el diccionario.
def lookup(my_dict,my_key,default_value = None):
if my_key in my_dict:
return my_dict[my_key]
else:
return default_value
simple_dict = {'joe':1, 'scott':2, 'jhon':3}
'''
print(lookup(simple_dict,'joe',-1))
print(lookup(simple_dict,'stephen',-1))
print(simple_dict)
'''
print(simple_dict.get('scott',-1))
print(simple_dict.get('stephen',-1))
print(simple_dict.get('stephen'))
# de ninguna de las dos maneras se agrega un nuevo mapeo.
|
9694c5a1fd26e5ac11fd34b54fc3652827c62c8c | Samm0007/Prepas | /2.12_Cine.py | 298 | 3.546875 | 4 | edad = int(input('Bienvenido al CineUNIMET\n Ingrese su edad para determinar el costo de su boleto: '))
if(edad<4):
print('Tu entradas en GRATIS!!')
elif(edad>= 4 and edad<=18):
print('El precio de tu entrada es de $10')
elif(edad>18):
print('EL precio de tu entrada es de $14') |
806298f73d8ee7a630dc00c5ae5546446404f594 | SKO7OPENDRA/gb-algorithm | /cw/cw_6/cw_6_3_2.py | 316 | 3.609375 | 4 | allocated = 0
for newsize in range(100):
if allocated < newsize:
new_allocated = (newsize >>3) + (3 if newsize < 9 else 6) # старое значение newsize со сдвигом на 3 байта вправо + 3 или 6
allocated = newsize + new_allocated
print(newsize, allocated) |
d33c02fc17f4243934078956a9fbf5530eb3891b | ragatol/aulas_jogos | /aula02/exemplo02.py | 491 | 4.1875 | 4 | # aqui a expressão booleana é True, então vai aparecer OK!
if (True): print("OK!")
# aqui a expressão booleana é False, então não vai aparecer FALSO!
if (False): print("FALSO!")
# aqui a expressão de comparação tem resultado verdadeiro
if (2 == 2): print("2 == 2 é verdadeiro!")
# e aqui a expressão de comparação é falsa
if (2 != 2): print("2 != 2 é falso!")
# aqui o valor dentro da variável é True
bonito = True
if (bonito): print("Que beleza!")
|
c60f103959cb87ba38ab1a0a4d397f52c666efbe | sbsdevlec/PythonEx | /Hello/DataType/Day01/lotto2.py | 170 | 3.53125 | 4 | import random
game = int(input("몇게임?"))
for i in range(0,game):
lotto = random.sample(range(1,46),6)
lotto.sort()
print(i+1,"게임 : ", lotto)
|
5b16c75a8db9f48d1ec7b1ef1d54b862a0a593f2 | stuti-rastogi/leetcode-python-solutions | /1472_designBrowserHistory.py | 2,082 | 3.5 | 4 | class BrowserHistory:
def __init__(self, homepage: str):
self.history = [homepage]
self.curr = 0
self.bound = 0
def visit(self, url: str) -> None:
self.curr += 1
if self.curr == len(self.history):
self.history.append(url)
else:
self.history[self.curr] = url
self.bound = self.curr
def back(self, steps: int) -> str:
self.curr = max(self.curr - steps, 0)
return self.history[self.curr]
def forward(self, steps: int) -> str:
self.curr = min(self.curr + steps, self.bound)
return self.history[self.curr]
# class Node:
# def __init__(self, page):
# self.val = page
# self.next = None
# self.prev = None
# class DoublyLinkedList:
# def __init__(self, headNode):
# self.head = headNode
# def append(self, currNode, newNode):
# currNode.next = newNode
# newNode.prev = currNode
# def printList(self):
# curr = self.head
# while curr:
# print (curr.val, end=" ")
# curr = curr.next
# print ()
# class BrowserHistory:
# def __init__(self, homepage: str):
# self.curr = Node(homepage)
# self.pages = DoublyLinkedList(self.curr)
# def visit(self, url: str) -> None:
# newNode = Node(url)
# self.pages.append(self.curr, newNode)
# self.curr = newNode
# def back(self, steps: int) -> str:
# count = 0
# while count < steps and self.curr.prev:
# self.curr = self.curr.prev
# count += 1
# return self.curr.val
# def forward(self, steps: int) -> str:
# count = 0
# while count < steps and self.curr.next:
# self.curr = self.curr.next
# count += 1
# return self.curr.val
# # Your BrowserHistory object will be instantiated and called as such:
# # obj = BrowserHistory(homepage)
# # obj.visit(url)
# # param_2 = obj.back(steps)
# # param_3 = obj.forward(steps) |
598368daf9e77feabf1e9aebbafb0d275a7b7603 | Elmlea/pythonAuto | /ch2_q13.py | 906 | 4.34375 | 4 | type = "" # initialise the variable because it gets checked shortly
print("That's the variable initialised.") # so I know the program has started!
while ("for" not in type) and ("while" not in type):
type = input("Would you like to print your numbers using a FOR loop, or a WHILE loop? :> ")
if "for" in type:
# for loop practice
print("Here's a list of numbers!")
for num in range (1,11):
print(num)
print("These numbers were brought to you using a for loop.")
elif "while" in type:
# using a while loop
print("Have some numbers!")
num = 1
while num < 11:
print(num)
num += 1
print("These ones were made using a while loop.")
else:
print("Be nice if you specified a loop type pls?")
#as FOR or WHILE weren't entered, this will restart the external WHILE loop
|
3edd48b0464e138391ff31967b2f869d31654339 | MilanMolnar/Codecool_OW | /using_if/if_4.py | 812 | 3.734375 | 4 | def easter():
while True:
try:
T = int(input("Irjon be egy évet: "))
except ValueError:
print("Szamokkal adja meg az évet")
if T > 2099 and 1800 < T:
print("Kérem évszámot adjon meg 1800 ls 2099 között")
else:
break
A = T % 19
B = T % 4
C = T % 7
D = (19 * A + 24) % 30
E = (2 * B + 4 * C + 6 * D + 5) % 7
H = 22 + D + E
if H <= 31:
print(str(T) + ". évben " + "Március " + str(H) + "-ra esik húsvét első vasárnapja.")
else:
H = H - 31
print(str(T) + ". évben " + "Április " + str(H) + "-ra esik húsvét első vasárnapja.")
if E == 6 and D == 29:
H = 50
elif E == 6 and D == 28:
H = 49
easter()
|
f85e2f39dbbc6e760d195be2823dfeb3c8c62bd9 | Bray821/PythonProgram1 | /OOPCalc.py | 298 | 3.703125 | 4 | prices = {
"Strawberries" : "$1.50",
"Banana" : "$0.50",
"Mango" : "$2.50",
"Blueberries" : "$1.00",
"Raspberries" : "$1.00",
"Apple" : "$1.75",
"Pineapple" : "$3.50"
}
number = "$1.50"
new_num = ""
anwser = 0
for i in number
if i.isnumeric() or i == "." :
new_num +=
|
36e982f9ac8c26f86258cb8c4755811e79a2d8f2 | ccdv2and4dalao/CenterAirConditioner | /abstract/model/user.py | 1,257 | 3.953125 | 4 | from abc import abstractmethod
from abstract.model.model import Model
class User:
table_name = "user"
# 主键
id_key = "id"
# 身份证号
id_card_number_key = "id_card_number"
def __init__(self, user_id=0, id_card_number=''):
self.id = user_id # type: int
self.id_card_number = id_card_number # type: str
class UserModel(Model):
"""
操作user表
"""
@abstractmethod
def create(self) -> bool:
pass
@abstractmethod
def insert(self, id_card_number: str) -> int:
"""
:param id_card_number: 用户身份证号码
:return: user.id或返回None
"""
pass
# @abstractmethod
# def query(self, user_id: int):
# pass
@abstractmethod
def query_by_id_card_number(self, id_card_number: str) -> User:
"""
:param id_card_number: 用户身份证号码
:return: user或返回None
"""
pass
# @abstractmethod
# def delete(self, user_id: int):
# pass
@abstractmethod
def delete_by_id_card_number(self, id_card_number: str) -> bool:
"""
:param id_card_number: 用户身份证号码
:return: 删除是否成功
"""
pass
|
19dc23c65cd63abd45d1eafbb1a3d7f055183e4c | gabriellaec/desoft-analise-exercicios | /backup/user_162/ch44_2020_04_06_14_31_58_503502.py | 205 | 3.828125 | 4 | lista = {"janeiro":1, "fevereiro":2, "março":3, "abril":4, "maio":5,
"junho":6,"julho":7,"agosto":8, "setembro":9, "outubro":10,
"novembro":11, "dezembro":12}
a = input()
print(lista[a]) |
7a0ae88ce40c183c282e86b866d02bd38fc60aa8 | shubhkalani/MachineLearning | /CC36_SLR.py | 1,247 | 3.90625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
Foodtruck = pd.read_csv("Foodtruck.csv")
#Splitting into dependent and independent columns
X=Foodtruck.iloc[:,0:1]
Y=Foodtruck.iloc[:,1]
#Splitting into train and test data
from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state = 0)
#Generating linera regression prediction model
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
#Predicting the Test set Results
y_pred = regressor.predict(X_test)
#Visusalising the Training set Results
plt.scatter(X_train,Y_train,color='red')
plt.plot(X_train,regressor.predict(X_train),color='blue')
plt.title("Profit vs Population(Training set)")
plt.xlabel("population")
plt.ylabel("Profit")
plt.show()
#visualising the test set result
plt.scatter(X_test,Y_test,color='red')
plt.plot(X_train,regressor.predict(X_train),color='blue')
plt.title("Profit vs Population(Test set)")
plt.xlabel("population")
plt.ylabel("Profit")
plt.show()
#Estimated profit when population is 3.073million
populationjp = 3.073
Profit_jaipur = regressor.predict(populationjp)
print "profit of jaipur is",Profit_jaipur,"million"
|
c5f6d877ce389cb21bf097aa5f9eb3177769aa45 | bpnsingh/git_pract | /codeAcademy/Advancedloop/Max Num.py | 414 | 4.25 | 4 | """Create a function named max_num() that takes a list of numbers named nums as a parameter.
The function should return the largest number in nums"""
#Write your function here
def max_num(lst):
max = lst[0]
for num in lst:
if num < max:
continue
else:
max=num
return max
#Uncomment the line below when your function is done
print(max_num([50, -10, 0, 75, 20])) |
e4c0274fa0b7304e05c4c6842a5acdb76f7c59e9 | compsciprep-acsl-2020/2019-2020-ACSL-Python-Akshay | /Class9-28/variables.py | 164 | 4.0625 | 4 | a = int(input("Enter number 1"))
b = int(input("Enter number 2"))
#add
print(a+b)
#subtract
print(a-b)
#product
print(a*b)
#quotient
print(a/b)
#modulus
print(a%b)
|
4f3b6ed9fc29b5eaa09b9e1d76fe9a86d63513d4 | Inimesh/PythonPracticeExercises | /4 Function exercises/Ex_95.py | 709 | 4.03125 | 4 | ## A function that generates a random liscence plate in either an old style
# (three letters followed by three numbers), or new (four numbers followed by
# three letters). main() function runs function and displays liscence plate.
def randLiscence():
from random import randint
liscence = ""
isNew = randint(0,1)
if isNew:
for i in range(0,4):
liscence += chr(randint(48,57))
for i in range(0,3):
liscence += chr(randint(65,90))
else:
for i in range(0,3):
liscence += chr(randint(65,90))
for i in range(0,3):
liscence += chr(randint(48,57))
return liscence
def main():
print(randLiscence())
main()
|
72f7d7a673d4f8e8c64549aff73eabcbdcc82631 | Devansh2005/Tkinter | /tk.py | 4,047 | 3.96875 | 4 | # create a tkinter window
import tkinter as tk
from csv import DictWriter
import os
from tkinter import ttk
win =tk.Tk()
win.title("Devansh") # devansh as a title of window
# Create Labels -- ttk --> radio button, labels
# from tkinter import ttk
name_label=ttk.Label(win,text="Enter your name :")
name_label.grid(row=0, column=0, sticky=tk.W) # pack can also be used as grid
email_label=ttk.Label(win, text="Enter your email :")
email_label.grid(row=1, column=0, sticky=tk.W)
age_label=ttk.Label(win,text="Enter your age :")
age_label.grid(row=2, column =0, sticky=tk.W) # after the name_label so row =1
gender_label=ttk.Label(win, text="Select your gender")
gender_label.grid(row=3, column=0)
#CREATE ENTRY BOX
name_var=tk.StringVar() # to strore entered name
name_entrybox=ttk.Entry(win, width=16, textvariable= name_var)
name_entrybox.grid(row=0,column=1)
name_entrybox.focus() #--> automatic cursor on name
email_var=tk.StringVar()
email_entrybox=ttk.Entry(win, width=16, textvariable=email_var)
email_entrybox.grid(row=1, column=1)
age_var=tk.StringVar() # to strore entered name
age_entrybox=ttk.Entry(win, width=16, textvariable= age_var)
age_entrybox.grid(row=2,column=1)
#Create COMBOBOX- MALE/FEMALE
gender_var= tk.StringVar()
gender_combobox= ttk.Combobox(win, width=14,textvariable=gender_var, state="readonly") # state--> user cannot type in combobox
gender_combobox["values"]= ("Male","Female","Other")
gender_combobox.current(0)
gender_combobox.grid(row=3,column=1)
# Create a RADIO BUTTON --> select one from many
usertype=tk.StringVar()
radiobtn1=ttk.Radiobutton(win, text="Student", value="Student", variable=usertype)
radiobtn1.grid(row=4,column=0)
radiobtn2=ttk.Radiobutton(win, text="Teacher", value="Teacher", variable=usertype)
radiobtn2.grid(row=4,column=1)
#Create a CHECK BUTTON
checkbtn_var=tk.IntVar()
checkbtn=ttk.Checkbutton(win, text="Check if you love me",variable= checkbtn_var)
checkbtn.grid(row=5, columnspan=3) #columnspan--> take 3 columns but dont extend the other columns
# # SAVE THE DATA IN A FILE THAT USER HAVE ENTERED in txt file
# # CREATE BUTTON
# def action(): # action for submit button
# username=name_var.get()
# userage=age_var.get()
# useremail=email_var.get()
# usergender=gender_var.get()
# user_type=usertype.get()
# if checkbtn_var.get()==0:
# love_me="NO"
# else:
# love_me="Yes"
# print(usergender, user_type, love_me) #--> baad ke 3 variable
# print(f"{username} is {userage} years old and email is {useremail}")
# with open("file.txt", "a") as f:
# f.write(f"{username},{userage},{usergender},{useremail},{user_type},{love_me}\n")
# name_entrybox.delete(0, tk.END)
# age_entrybox.delete(0, tk.END)
# email_entrybox.delete(0, tk.END)
# name_label.config(foreground="Blue")
#TO WRITE ENTERED DATA IN CSV FILE
def action(): # action for submit button
username= name_var.get() #get the information From the variables
userage= age_var.get()
useremail= email_var.get()
usergender= gender_var.get()
user_type= usertype.get()
if checkbtn_var.get()==0:
love_me="NO"
else:
love_me="Yes"
#csv file as file1 is saved
with open("file1.csv","a", newline="") as f:
dict_writer= DictWriter(f, fieldnames=["UserName","EmailAddress","UserGender","Usertype","Love me"])
if os.stat("file1.csv").st_size==0:
dict_writer.writeheader()
dict_writer.writerow({
"UserName": username,
"EmailAddress": useremail,
"UserGender": usergender,
"Usertype" : user_type,
"Love me" : love_me
})
# To delete the values automatically from GUI
name_entrybox.delete(0, tk.END)
age_entrybox.delete(0, tk.END)
email_entrybox.delete(0, tk.END)
submit_button=ttk.Button(win, text="Submit", command=action) #command takes the function name
submit_button.grid(row=6,column=0)
win.mainloop() |
7c0ebb8658d2966ce0d4a15ed3a2585bfb8d98b3 | 1GBattle/gab_locator | /gag_functions/check_multi_line_comment.py | 449 | 3.53125 | 4 | # declares and function that takes in two args operators and data types
# function iterates through operators until the /* or */ operator is found
# once operators is found the correct data type is appended to the array
def check_multi_line_comment(operators, data_types_to_pass):
for operator in operators:
if operator == '/*':
data_types_to_pass.append('multi-line comment')
return True
return False
|
419170c48149d1b530d7eeca3d6f538f66f582d0 | ikramulkayes/Python-practice-codewars.com- | /untitled11.py | 408 | 3.53125 | 4 | def DNA_strand(dna):
p = list(dna)
k = list()
for word in p:
if word == "A":
k.append("T")
elif word == "T":
k.append("A")
elif word == "C":
k.append("G")
elif word == "G":
k.append("C")
str = ""
for ele in k:
str += ele
return str
print(DNA_strand("ATA")) |
5a6ca69f52389c89b253c1282432c5d81af3ebda | TMAC135/Summaries-By-Myself | /python/OO_in_python/5_描述对象的特征/private1.py | 161 | 3.546875 | 4 | class A:
def __init__(self):
self._ab = 0
def info(self):
print(self._ab)
a = A()
a.info()
a._ab = 3
a.info()
print(a._ab)
|
3024f25d2a4c1dbde85e568cc628b27bec3b803c | mateusz-kleszcz/Algorithms-and-Data-Structures | /list/merge from their end.py | 967 | 3.875 | 4 | class Node:
def __init__(self):
self.value = None
self.next = None
def printList(L):
while L is not None:
print(L.value, '->', end=' ')
L = L.next
print('|')
def tab2list(T):
H = Node()
C = H
for i in range(len(T)):
X = Node()
X.value = T[i]
C.next = X
C = X
return H.next
def merge(L1, L2):
L = None
while L1 is not None and L2 is not None:
if L1.value < L2.value:
tmp = L1.next
L1.next = L
L = L1
L1 = tmp
else:
tmp = L2.next
L2.next = L
L = L2
L2 = tmp
while L1 is not None:
tmp = L1.next
L1.next = L
L = L1
L1 = tmp
while L2 is not None:
tmp = L2.next
L2.next = L
L = L2
L2 = tmp
return L
A = tab2list([1, 3, 5])
B = tab2list([2, 6, 7, 10])
printList(merge(A, B)) |
c223257e355adcdc28e9afdff6ea97b621ccc6a5 | Jeaced/simulated_annealing | /annealing.py | 3,120 | 3.671875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import math
import random
NUMBER_OF_CITIES = 30
INITIAL_TEMPERATURE = 15000.0
COOLING_RATE = 0.004
columns = [6, 17, 18, 20]
df = pd.read_csv('cities.csv', header=0, usecols=columns)
df = df.sort_values('Население', ascending=False, na_position='last')
df = df[0:NUMBER_OF_CITIES]
df = df.reset_index(drop=True)
print(df)
def get_km(lat1, lat2, lon1, lon2):
radius = 6373.0
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
lon1 = math.radians(lon1)
lon2 = math.radians(lon2)
t = math.sin((lat2 - lat1)/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1)/2)**2
return 2 * radius * math.atan2(math.sqrt(t), math.sqrt(1 - t))
def get_distance(index1, index2):
lat1 = df.iloc[index1]['Широта']
lat2 = df.iloc[index2]['Широта']
lon1 = df.iloc[index1]['Долгота']
lon2 = df.iloc[index2]['Долгота']
return get_km(lat1, lat2, lon1, lon2)
def get_solution_length(solution):
length = 0.0
for i in range(NUMBER_OF_CITIES - 1):
length += get_distance(solution[i], solution[i+1])
length += get_distance(solution[NUMBER_OF_CITIES - 1], solution[0])
return length
# Returns true if we should change current solution, false otherwise
def choose_solution(current_length, new_length, temperature):
if new_length < current_length:
return True
return math.exp((current_length - new_length) / temperature) > random.random()
def perform_annealing():
temp = INITIAL_TEMPERATURE
current_solution = random.sample(range(NUMBER_OF_CITIES), NUMBER_OF_CITIES)
plot_points = list()
plot_points.append(list())
plot_points.append(list())
epochs = 0
while temp > 1:
epochs += 1
if random.random() < 0.01:
print('Current temperature', temp)
plot_points[0].append(epochs)
plot_points[1].append(get_solution_length(current_solution))
[first_index, second_index] = sorted(random.sample(range(NUMBER_OF_CITIES), 2))
first_city = current_solution[first_index]
second_city = current_solution[second_index]
new_solution = current_solution.copy()
new_solution[first_index] = second_city
new_solution[second_index] = first_city
if choose_solution(get_solution_length(current_solution), get_solution_length(new_solution), temp):
current_solution = new_solution.copy()
plot_points[0].append(epochs)
plot_points[1].append(get_solution_length(current_solution))
temp *= (1 - COOLING_RATE)
print('Best found solution:')
print(current_solution)
print('Length:')
print(get_solution_length(current_solution))
print('Number of epochs:')
print(epochs)
print("Cooling rate:")
print(COOLING_RATE)
fig = plt.figure()
ax = fig.subplots()
ax.set_xlabel('epochs')
ax.set_ylabel('total length')
ax.plot(plot_points[0], plot_points[1])
plt.show()
print('Annealing has started. Initial temperature is:', INITIAL_TEMPERATURE)
perform_annealing()
|
de68b1bbd9e21dcc2ac44109f93422eb941b1f75 | viQcinese/kanji_frequency | /kanji_frequency.py | 3,141 | 4.09375 | 4 | # Analyse a text file and sort most frequent Kanji
# Create a text file to store Kanji frequency
# Display 20 most frequent Kanji
import operator
# Get text from target file = source
def get_text(source):
with open(source, "r", encoding='utf-8') as f:
text_string = f.read()
return text_string
# Clean text noise
# Intended for text files from the site Aozora Bunko
def clean_text(text_string):
split = text_string.split("底本:")
text_string = split[0]
text_list = list(text_string)
return text_list
# Get kanji list
def get_kanji_list():
with open("japanese_texts/joyou_kanji.txt", "r", encoding='utf-8') as f:
kanji_string = f.read()
kanji_list = list(kanji_string)
return kanji_list
# Build Kanji frequency list
def build_kanji_frequency_list(text_list, kanji_list):
kanji_occurrences = {}
for kanji in kanji_list:
occurrences = text_list.count(kanji)
kanji_occurrences[kanji] = occurrences
kanji_frequency_list = sorted(kanji_occurrences.items(), key=lambda kv: kv[1])
kanji_frequency_list.reverse()
for i in range(len(kanji_frequency_list)):
if kanji_frequency_list[-1][1] == 0:
kanji_frequency_list.pop(-1)
return kanji_frequency_list
# Creates a .txt file to store the frequency list
def create_frequency_file(kanji_frequency, source):
target = source.replace(".txt", "") + "_kanji_frequency.txt"
kanji_frequency_formatted = ""
for i in range(len(kanji_frequency)):
kanji_frequency_formatted += str(kanji_frequency[i][0]) + " - " \
+ str(kanji_frequency[i][1]) + "\n"
with open(target, "w", encoding='utf-8') as f:
f.write(kanji_frequency_formatted)
# Call functions in order
def main(source):
text_list = clean_text(get_text(source))
kanji_list = get_kanji_list()
kanji_frequency = build_kanji_frequency_list(text_list, kanji_list)
print("\nMost frequent Kanjis:")
for i in range(0, 20):
print(str(kanji_frequency[i][0]) + " - " + str(kanji_frequency[i][1]))
print("\n" + str(len(kanji_frequency)) + " different Kanjis")
create_frequency_file(kanji_frequency, source)
# Alternative to "main" for pygal output
def pygal_kanji_list(source):
text_list = clean_text(get_text(source))
kanji_list = get_kanji_list()
kanji_frequency = build_kanji_frequency_list(text_list, kanji_list)
pygal_kanji_list = []
for i in range(len(kanji_frequency)):
pygal_kanji_list.append(kanji_frequency[i][0])
return pygal_kanji_list
# Alternative to "main" for pygal output
def pygal_frequency_list(source):
text_list = clean_text(get_text(source))
kanji_list = get_kanji_list()
kanji_frequency = build_kanji_frequency_list(text_list, kanji_list)
pygal_frequency_list = []
for i in range(len(kanji_frequency)):
pygal_frequency_list.append(kanji_frequency[i][1])
return pygal_frequency_list
main("japanese_texts\ginga_tetsudou_no_yoru.txt")
|
f581a2807efb2a1cfd4d08550f743f51e31b8163 | TheTechTeen/CIS-110-Portfolio | /line_properties.py | 1,286 | 4.03125 | 4 | # Properties of a Line
# Calculates the endpoints, length, and slope of a user-defined line
# Aiden Dow
# 9/26/2019 - Revised 12/20/2020
import datetime
from graphics import GraphWin, Text, Point, Line, Circle
import math
def main():
# Create graphics window
win = GraphWin("Properties of a line", 500, 500)
# Prompt user to click 2 times anywhere in box to create a line
text = Text(Point(250, 475), "Click on endpoints of a line segment")
text.draw(win)
# Get x, y for click 1
p1 = win.getMouse()
x1 = p1.getX()
y1 = p1.getY()
# Get x, y for click 2
p2 = win.getMouse()
x2 = p2.getX()
y2 = p2.getY()
# Calculate dx and dy
dx = x2 - x1
dy = y2 - y1
# Draw line
line = Line(p1, p2)
line.draw(win)
# Calculate and mark center
center = Circle(Point(x1 + (dx / 2), y1 + (dy / 2)), 2)
center.setFill("cyan")
center.draw(win)
# Calculate slope
slope = round(dy / dx, 2)
# Calculate length
length = round(math.sqrt(dx ** 2 + dy ** 2), 2)
# Print length and slope
string = "Length: " + str(length) + " Slope: " + str(slope)
text.setText(string)
# Close graphics window on mouse click
win.getMouse()
main()
print("Aiden Dow")
print(datetime.datetime.now()) |
83d185835b46f714df13ab7ddb54d6256cb6b19c | nugeat23/workspace | /01.python/ch03/ex03.py | 295 | 3.953125 | 4 | a = "Korea 서울 1234"
print(a)
# a = "I Say "Hello" to you" <-- 인용 부호 에러
# print(a)
a = 'I Say "Hello" to you'
print(a)
a = "I Say 'Hello' to you"
print(a)
a = "I Say \\ \t'Hello', \n\"Good Morning\" to you"
print(a)
print("hello")
print("world")
print("hello\nworld")
|
bd3a4b2fb0e550ff3f9ce8d794ad3733d07c87e6 | ArnavMohan/MiscCode | /Simultaneous_Equation_Solver/matrix.py | 5,574 | 3.875 | 4 |
#init, fill, add, sum,mult, transpose, determinant, sum_product
#_________________________________________________________________
class Matrix: #TODO replace errors with method error, better error descriptions
num_rows = 0#TODO improve printing -- __printRow with string manipulation
num_cols = 0
def __init__(self, r, c=0):
if r < 1 or c < 0:
print ("Dimentions are negative.")
else:
self.rows = {}
self.cols = {}
self.num_rows = r
self.num_cols = r if (c == 0) else c
for i in range(r):
self.rows[i] = []
for j in range(c):
self.rows[i].append(0)
for i in range(c):
self.cols[i] = []
for j in range(r):
self.cols[i].append(0)
def Error(self, s):
print (s)
sys.exit(1)
def setRow(self, r, row):
if r in range(self.num_rows) and len(row) == self.num_cols:
for i in range(self.num_cols):
self.setVal(r, i, row[i])
else:
print ("Args not in range")
def setCol(self, c, col):
if c in range(self.num_cols) and len(col) == self.num_rows:
for i in range(self.num_rows):
self.setVal(i, c, col[i])
else:
print ("Args not in range")
def setVal(self, r, c, val):
if r in range(self.num_rows) and c in range(self.num_cols):
self.rows[r][c] = val
self.cols[c][r] = val
else:
print ("Args not in range")
def getVal(self, r, c):
if r in range(self.num_rows) and c in range(self.num_cols):
return self.rows[r][c]
else:
print ("Args not in range")
def getRow(self, r):
if r in range(self.num_rows):
copy = []
for item in self.rows[r]:
copy.append(item)
return copy
else:
print ("Args not in range")
def getCol(self, c):
if c in range(self.num_cols):
copy = []
for item in self.cols[c]:
copy.append(item)
return copy
else:
print ("Args not in range")
def __printRow(self, l):
s = "| "
for i in l:
s += " %5d" %(i)
s += " |"
return s
def printMat(self):
for r in range(self.num_rows):
print (self.__printRow(self.getRow(r)))
print ()
#args: matrix, returns new matrix with sum of previous 2
def add(self, matrix):
if (self.num_rows, self.num_cols) != (matrix.num_rows, matrix.num_cols):
print ("Matrix dimensions do not match")
else:
result = Matrix(self.num_rows, self.num_cols)
for i in range(self.num_rows):
for j in range(self.num_cols):
result.setVal(i, j, self.getVal(i, j) + matrix.getVal(i, j))
return result
def sub(self, matrix):
if (self.num_rows, self.num_cols) != (matrix.num_rows, matrix.num_cols):
print ("Matrix dimensions do not match")
else:
result = Matrix(self.num_rows, self.num_cols)
for i in range(self.num_rows):
for j in range(self.num_cols):
result.setVal(i, j, self.getVal(i, j) - matrix.getVal(i, j))
return result
def transpose(self):
result = Matrix(self.num_cols, self.num_rows)
for i in range(self.num_rows):
result.setCol(i, self.getRow(i))
return result
def mult(self, matrix):
if self.num_cols != matrix.num_rows:
self.Error("Dimensions for matrix multiplications are not valid")
result = Matrix(self.num_rows, matrix.num_cols)
for i in range(self.num_rows):
for j in range(matrix.num_cols):
val = self.__sumProduct(self.getRow(i), matrix.getCol(j))
result.setVal(i, j, val)
return result
def __sumProduct(self, l1, l2):
if len(l1) != len(l2):
self.Error("Lengths of the matricies are not equal.")
result = 0
for i in range(len(l1)):
result += l1[i] * l2[i]
return result
def __isSquare(self):
if self.num_rows - self.num_cols == 0:
return True
else:
return False
def Determinant(self): #Add error
if (self.num_rows, self.num_cols) == (2, 2):
return (self.getVal(0, 0) * self.getVal(1, 1)) - (self.getVal(0, 1) * self.getVal(1, 0))
else:
result = 0
for i in range(self.num_cols):
result += self.getVal(0, i) * self.__subDeterminant(i).Determinant()
return result
def __subDeterminant(self, i):
mat = Matrix(self.num_rows - 1, self.num_rows - 1)
for j in range(self.num_cols - 1):
new_col = self.getCol((j+i+1)%(self.num_cols))
new_col.pop(0)
mat.setCol(j, new_col)
return mat
def copy(self):
new = Matrix(self.num_rows, self.num_cols)
for i in range(self.num_rows):
new.setRow(i, self.getRow(i))
return new
|
07b85aca9f570f885ec4dcad4f561539b350510f | DoctorLai/ACM | /binarysearch/Longest-Anagram-Subsequence/Longest-Anagram-Subsequence.py | 344 | 3.578125 | 4 | # https://helloacm.com/algorithm-to-find-the-longest-anagram-subsequence/
# https://binarysearch.com/problems/Longest-Anagram-Subsequence
# MEDIUM, HASH TABLE
class Solution:
def solve(self, a, b):
aa = Counter(a)
bb = Counter(b)
ans = 0
for i in aa:
ans += min(aa[i], bb[i])
return ans
|
262af4e389c09ab894ab8632c9b365af885e146d | ghonk/simsextet | /instructs.py | 1,896 | 4.25 | 4 | cond_instructs = (
" Hello! In this study, you are going to see a series of different sets of"
" items (words). For each set, your goal is to find the two items in the set"
" that are most similar to one another. When you've chosen the two items that"
" are most similar, use the mouse to select the items and then press continue to"
" confirm your selection.\n\n"
" Press any key to continue")
cond1_instructs = (
" Hello! In this study, you are going to see a series of different sets "
"of items (words). For each set,"
" your goal is to find two items in the set that are *most alike*."
" When you've chosen the two items that are most alike, use the mouse "
"to select the items and then press continue to confirm your selection.\n\n"
" Press any key to continue")
cond2_instructs = (
" Hello! In this study, you are trying to teach an alien from outer space "
"about life on earth. Specifically, you need to teach the alien about things "
"that we have on earth that are similar to each other. We will be showing you "
"a series of different sets of items (words). Can you demonstrate to your alien"
" friend which pair of items in each set are things that are similar to one another?\n\n"
" When you've chosen the two items that are most similar, use the mouse "
"to select the items and then press continue to confirm your selection.\n\n"
" Press any key to continue")
init2_instructs = (
"When you are ready, start the experiment by pressing any key.\n\n"
" Good Luck!")
trial_instructs_1 = (
"Choose the two items that are most alike.")
trial_instructs_2 = (
"Show your alien friend which two items are most similar.")
trial_instructs = (
"Choose the two items that are most similar.")
end_instructs = (
"That completes the experiment. Thank you very much for participating!") |
186871bc53d0f69d6ec747ac436eeba36db4ac6a | hellojessy/CSCI-1100 | /Homeworks/Homework 4/hw4Part3.py | 2,256 | 3.53125 | 4 | import hw4_util
# Function to read pokemon list and coordinates given to each pokemon
# Prints out list of pokemon with coordinates
def print_pokemon(pokemon, coord):
i = 0
print('Current pokemon:')
for i in range(len(pokemon)):
print(' ' * 4, pokemon[i], 'at', coord[i])
i += 1
# Function to complete movement of pokemon trainer around the field
def move(x, y, direction):
if direction == 'n':
if y - 1 < 0:
y = 0
else:
y -= 1
elif direction == 's':
if y + 1 > 11:
y = 11
else:
y += 1
elif direction == 'e':
if x + 1 > 11:
x = 11
else:
x += 1
elif direction == 'w':
if x - 1 < 0:
x = 0
else:
x -= 1
return [x,y]
# Read file to obtain pokemon
currentPokemon, locations = hw4_util.read_pokemon()
# Initialize variables
x1 = 5
y1 = 5
command = 0
count = 0
# Print list of current pokemon
print_pokemon(currentPokemon, locations)
print()
while command != 'end': # Go through conditions if input does not equal false
command = input("N,S,E,W to move, 'print' to list, or 'end' to stop ==> ")
print (command)
command = command.lower()
if command != 'end':
if command == 'print':
print_pokemon(currentPokemon, locations)
print()
print('Currently at {}'.format((x1,y1)))
else:
[x1,y1] = move(x1, y1, command)
print('Currently at {}'.format((x1,y1)))
i = 0
while i in range(len(locations)):
'''
Check if pokemon exists in the given list, if already
caught, remove it from the list and print what is left
If new pokemon being caught, print out which turn caught on
'''
if ((x1 == locations[i][0]) and (y1 == locations[i][1])):
print('You capture a', currentPokemon[i], 'on turn', count)
currentPokemon.remove(currentPokemon[i])
locations.remove(locations[i])
i += 1
count += 1 |
0dfc2fa2287f2cb5d6feeba6e6c02055f42d3eaa | komal-kumarii/python_basics | /if_else/water.py | 169 | 3.78125 | 4 | water=int(input("filter me kitna pani h"))
if water<1:
print("or bharna h")
elif water>1 and water<10:
print("ni bharna h")
else:
print("overflow ho jata h") |
f45bbeea0eeed0f2fa74ac433ba204a1f6b4dfc6 | DanielFernandoYepezVelez/Fundamentos-Python | /05-Condicionales/05-Ternario.py | 344 | 4.09375 | 4 | """ Muestra El Mensaje Por Pantalla Si x == 5, Por El Contrario Muestra El else """
x = 54
print('X Es Igual a 5') if x == 5 else print('X No Es Igual a 5')
""" Muestra El Valor De La Variable Si La Condición Se Cumple, Por El Contrario Muestra El else """
es_bonito = False
estado = "Es bonito" if es_bonito else "No es bonito"
print(estado) |
01d371399bc5726cf6cf0598f0227a7d3fc5c515 | colkipyeg/Python_Basics | /sololearn.py | 984 | 4 | 4 | # x=123.456
# print(x)
# x="This is a string"
# print(x+"!")
#
# spam=2
# eggs=3
# del spam
# eggs=4
# spam=5
# print(spam*eggs)
#
# x="a"
# x*=3
# print(x)
#
# spam="7"
# spam=spam+"0"
# eggs=int(spam)+3
# print(float(eggs))
#
# x=5
# y=x+3
# y=int(str(y)+"2")
# print(y)
#
# x=3
# num=17
# print(num%x)
#
#
# if 10>5:
# print("Grade A")
# print("program ended")
#
# spam=7
# if spam>5:
# print("five")
# if spam>8:
# print("eight")
#
# if 1+1==2:
# if 2*2==8:
# print("if")
# else:
# print("else")
#
# if not True:
# print("1")
# elif not(1+1==3):
# print("2")
# else:
# print("3")
#
# if 1+1*3==6:
# print("Yes")
# else:
# print("No")
#
# i=1
# while i<=5:
# print(i)
# i=i+1
# print("finished!")
# nums=[9,8,7,6,5]
# nums.append(4)
# nums.insert(2,11)
# print(len(words
words=["hello","my","name"]
for word in words:
print(word)
for p in range(8):
print("collo")
for i in range(0,20,2):
print(i) |
88f8f5956497eebf74751219160cc97790355744 | oceanpad/python-tutorial | /code/basic/closure.py | 222 | 3.65625 | 4 | def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
t = lazy_sum(1,3,5)
print(t())
t1 = lazy_sum(1,3,5)
t2 = lazy_sum(1,3,5)
print(t1 == t2)
|
69f0f771593f1138bf380e164e1649a79515e845 | Aasthaengg/IBMdataset | /Python_codes/p02999/s274696497.py | 79 | 3.515625 | 4 | a,b=input().split()
a=int(a)
b=int(b)
if a>=b:
print("10")
else:
print("0") |
473332adbebbe8bec777920ca422e43a5f02a9c3 | Robbot/w3resourcesPython | /Basic/1_20/Ex06.py | 502 | 3.625 | 4 | '''
Created on 24 mar 2018
Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list
and a tuple with those numbers
How to remove warnings from code?
Another option would be disabling that check altogether (for all variables) in
PyDev > Editor > Code Analysis > Others > Redefinition of builtin symbols
'''
values = input("Input some comma seprated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple) |
592aea87c6b5967bfda0ba47d1caed5f1fcc1304 | flaviasilvaa/ProgramPython | /50.AddSixEvenNumbers.py | 377 | 4.21875 | 4 | ###this program is going to read 6 numbers if show the sum only of those who are even. If the value entered is odd, disregard it.
total = 0
sum = 0
for count in range(1, 7):
number = int(input(f'Enter the {count} value?\n'))
if number % 2 == 0:
sum = sum + number
total = total + 1
print(f'You typed {total} Even numbers and the sum of them are {sum}') |
338464a52f92b97be6cd7967fca949fc7987abce | rafhaelom/Python | /PythonBrasil/EstruturaSequencial/10.py | 245 | 4.25 | 4 | # 10. Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit.
temCelsius = float(input("Digite a temperatura em Celsius: "))
print("A temperatura em Fahrenheit eh: ", (1.8 * temCelsius) + 32, "ºF") |
71185b8868ef5974eb87f217086b328b8d5ab56b | remotephone/lpthw | /26thru30/ex30-01.py | 1,140 | 4.21875 | 4 | # Set up the numbers, define what = what
people = 30
cars = 40
trucks = 15
## FIRST BLOCK
# If cars are more than people, then print we should take the cars
if cars > people:
print "We should take the cars."
# If that's not true and cars are more than people, print do not take cars
elif cars < people:
print "We should not take the cars."
#If anything else is true, print We can't decide.
else:
print "We can't decide."
## SECOND BLOCK
# If there are more trucks than cars, print too many trucks.
if trucks > cars:
print "That's too many tucks."
# If more cars than trucks, then recommend taking trucks.
elif trucks < cars:
print "Maybe we could take the trucks."
# If none of that is true, then print it can't be decided. So like if cars =
# trucks then undecided.
else:
print "We still can't decide."
## THIRD BLOCK
# If there are more poeple than trucks, they should take the trucks. Throw em
# all in the back I guess?
if people > trucks:
print "Alrigth, let's just take the trucks."
# But if there's not enough trucks, then don't go at all.
else:
print "Fine, let's stay home then."
|
6e17db32822b14dc668980f69ab922cb7fe4f9c5 | lost-person/Leetcode | /99.恢复二叉搜索树.py | 5,120 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=99 lang=python3
#
# [99] 恢复二叉搜索树
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
# predecessor is a Morris predecessor.
# In the 'loop' cases it could be equal to the node itself predecessor == root.
# pred is a 'true' predecessor,
# the previous node in the inorder traversal.
x = y = predecessor = pred = None
while root:
# If there is a left child
# then compute the predecessor.
# If there is no link predecessor.right = root --> set it.
# If there is a link predecessor.right = root --> break it.
if root.left:
# Predecessor node is one step left
# and then right till you can.
predecessor = root.left
while predecessor.right and predecessor.right != root:
predecessor = predecessor.right
# set link predecessor.right = root
# and go to explore left subtree
if predecessor.right is None:
predecessor.right = root
root = root.left
# break link predecessor.right = root
# link is broken : time to change subtree and go right
else:
# check for the swapped nodes
if pred and root.val < pred.val:
y = root
if x is None:
x = pred
pred = root
predecessor.right = None
root = root.right
# If there is no left child
# then just go right.
else:
# check for the swapped nodes
if pred and root.val < pred.val:
y = root
if x is None:
x = pred
pred = root
root = root.right
x.val, y.val = y.val, x.val
# morris 遍历(中序遍历)
def morris(root):
cur = root
while cur:
# 寻求当前节点的前驱节点
if cur.left:
prev = cur.left
while prev.right and prev.right != cur:
prev = prev.right
if not prev.right:
prev.right = cur
cur = cur.left
else:
prev.right = None
print(cur.val)
cur = cur.right
else:
print(cur.val)
cur = cur.right
# morris 遍历(前序遍历)
def morris(root):
cur = root
while cur:
# 寻求当前节点的前驱节点
if cur.left:
prev = cur.left
while prev.right and prev.right != cur:
prev = prev.right
if not prev.right:
print(cur.val)
prev.right = cur
cur = cur.left
continue
else:
prev.right = None
cur = cur.right
else:
print(cur.val)
cur = cur.right
# 后序遍历
def morris(root):
dummy = TreeNode(-1)
dummy.left = root
cur = dummy
while cur:
if cur.left:
prev = cur.left
while prev.right and prev.right != cur:
prev = prev.right
if not prev.right:
prev.right = cur
cur = cur.left
else:
print_reverse(cur.left, prev)
prev.right = None
cur = cur.right
else:
cur = cur.right
def print_reverse(left, prev):
reverse(left, prev)
p = prev
while True:
print(p.val)
if p == left:
break
p = p.right
reverse(prev, left)
def reverse(left, prev):
if left == prev:
return
x, y = left, left.right
while True:
z = y.right
y.right = x
x = y
y = z
if x == prev:
break
# @lc code=end
|
d919f0d018289ab7e19cdba008632c9de15da86d | Geovane-Baldan/AP1 | /Dicionario.py | 5,302 | 3.734375 | 4 | from time import sleep
main = []
class Palavra:
def __init__(self):
self.termo = ''
self.sinonimos = []
self.classe = ''
def menu():
print('\n\033[30m')
print('='*30)
print('Menu:')
print('0 - Sair')
print('1 - Cadastrar')
print('2 - Listar')
print('3 - Novo sinonimo')
print('4 - Termo com mais sinonimos')
print('5 - Buscar palavra pela classe')
print('6 - Excluir termo')
print('7 - Excluir sinonimo')
print('='*30)
print('\n\033[0m')
def testarRepeticao(termo):
jaExiste = False
for x in main:
if termo == x.termo:
jaExiste = True
return jaExiste
def cadastro():
novaPalavra = Palavra()
termoPalavra = input('Digite o termo: ').capitalize()
termoValido = testarRepeticao(termoPalavra)
if termoValido is False:
sinonimoPalavra = input('Digite um sinonimo dessa palavra: ').capitalize()
classePalavra = input('Digite a classe gramatical dessa palavra: ').capitalize()
novaPalavra.termo = termoPalavra
novaPalavra.sinonimos.append(sinonimoPalavra)
novaPalavra.classe = classePalavra
main.append(novaPalavra)
print('\n\033[32mPalavra cadastrada com sucesso!\033[0m')
else:
print('\n\033[31mErro! Palavra ja cadastrada!\033[0m')
def listar():
num = 1
if len(main) != 0:
for x in main:
print("\n\033[30mDados da palavra {}:".format(x.termo))
sleep(0.3)
print('A palavra {} possui {} caracteres.'.format(x.termo, len(x.termo)))
sleep(0.3)
print('Essa palavra possui {} sinonimos que sao: '.format(len(x.sinonimos)))
sleep(0.3)
for y in x.sinonimos:
print('{}. {}'.format(num, y))
num += 1
sleep(0.2)
print('Classe: {}\033[0m'.format(x.classe))
sleep(0.2)
else:
sleep(0.3)
print('\n\033[31mNenhuma palavra cadastrada!\033[0m')
sleep(0.2)
def novoSinonimo():
palavra = input('Digite a palavra que deseja adicionar um novo sinonimo: ').capitalize()
for x in main:
if palavra == x.termo:
print('\n\033[30mEsse termo ja tem os seguintes sinonimos cadastrados: \n{}\n\033[0m'.format(x.sinonimos))
novosin = input('Digite o novo sinonimo: ').capitalize()
x.sinonimos.append(novosin)
sleep(0.3)
print('\n\033[32mSinonimo adicionado com sucesso!\033[0m')
sleep(0.2)
else:
sleep(0.3)
print('\n\033[31mPalavra nao encontrada!\033[0m')
sleep(0.2)
def maisSinonimos():
termoMaisSin = ''
numSin = 0
for x in main:
if len(x.sinonimos) > numSin:
numSin = len(x.sinonimos)
termoMaisSin = x.termo
print('O termo {} tem a maior quantidade de sinonimos, possuindo {} sinonimos.'.format(termoMaisSin, numSin))
sleep(0.3)
def buscaPorClasse():
num = 1
existe = False
classeBusca = input('Digite a classe desejada: ').capitalize()
print('Foram encontradas as seguintes palavras da classe {}:'.format(classeBusca))
for x in main:
if x.classe == classeBusca:
sleep(0.2)
print('{}. {}'.format(num, x.termo))
num += 1
existe = True
sleep(0.3)
if existe is False:
print('\n\033[31mNenhuma palavra dessa classe foi encontrada!\033[0m')
def excluirTermo():
if len(main) != 0:
foiEncontrado = False
termoExcl = input('Digite o termo que deseja excluir: ').capitalize()
for x in main:
if x.termo == termoExcl:
main.remove(x)
foiEncontrado = True
print('\n\033[32mTermo exluido com sucesso!\033[0m')
if foiEncontrado is False:
print('\n\033[31mTermo nao encontrado!\033[0m')
else:
print('\n\033[31mNenhuma palavra cadastrada!\033[0m')
def excluirSinonimo():
foiEncontrado = False
sinExcl = input('Digite o sinonimo que dejesa excluir: ').capitalize()
if len(main) != 0:
for x in main:
for y in x.sinonimos:
if y == sinExcl:
x.sinonimos.remove(y)
foiEncontrado = True
print('\n\033[32mSinonimo exluido com sucesso!\033[0m')
if foiEncontrado is False:
print('\n\033[31mSinonimo nao encontrado!\033[0m')
else:
print('\n\033[31mNenhuma palavra cadastrada!\033[0m')
while True:
menu()
op = int(input('\033[30mDigite a opcao desejada: \033[0m'))
if op == 0:
print('Ate logo!')
break
elif op == 1:
cadastro()
elif op == 2:
listar()
elif op == 3:
novoSinonimo()
elif op == 4:
maisSinonimos()
elif op == 5:
buscaPorClasse()
elif op == 6:
excluirTermo()
elif op == 7:
excluirSinonimo()
else:
print('Selecione uma opcao disponivel!')
|
165687739cc23466a26e287d303d3457401d2216 | huaxiaojilzg/python-Spider-learning | /多线程/多线程类.py | 396 | 3.734375 | 4 | # 多线程 法2
from threading import Thread
class MyThread(Thread):
def run(self): # 固定的,线程可以执行之后,被执行的就是 run()
for i in range(100):
print(f'子线程1:{i}')
if __name__ == '__main__':
t = MyThread()
# t.run() #方法的调用
t.start()
for i in range(100):
print(f'主线程:{i}') |
87ba6582c9107f951e726b7f313284f123a5a0bd | matthew-cen/schedule-creator | /schedule.py | 4,667 | 3.703125 | 4 | import itertools
def create_schedule(nestedlist):
# nested list of sections
total_schedules = []
for combinations in itertools.product(*nestedlist):
time_conflicts = {}
good_schedule = True
for sections in combinations: # there is an extra tuple layer that this for loop goes thorugh
for i in range(7): # gets the day number as a key
if sections.days[i] == 1:
if i not in time_conflicts.keys(): # if there is no key yet, create one
time_conflicts[i] = [(sections.timeslot[0], sections.timeslot[1])] # gets the time zones of the days
else: # if there is a key
for timeslots in time_conflicts[i]:
# if the curr low and high time is between the curr low and high in dictionary
if (timeslots[0] < sections.timeslot[0] < timeslots[1]) or (timeslots[0] < sections.timeslot[1] < timeslots[1]):
good_schedule = False # if time conflict, flip bad schedule
break
if good_schedule is True: # if no time conflicts, add it to total possible schedules
#print("This is the current combination: ", combinations)
total_schedules.append(combinations)
return total_schedules
def create_schedule2(nestedlist):
# nested list of sections
total_schedules = []
for combinations in itertools.product(*nestedlist):
time_conflicts = {}
good_schedule = True
for sections in combinations: # there is an extra tuple layer that this for loop goes through
for i in range(7): # gets the day number as a key
add_to_dict = False
if i == 1:
if sections.Monday is True:
add_to_dict = True
if i == 2:
if sections.Tuesday is True:
add_to_dict = True
if i == 3:
if sections.Wednesday is True:
add_to_dict = True
if i == 4:
if sections.Thursday is True:
add_to_dict = True
if i == 5:
if sections.Friday is True:
add_to_dict = True
if i == 6:
if sections.Saturday is True:
add_to_dict = True
if i == 7:
if sections.Sunday is True:
add_to_dict = True
if add_to_dict is True: # if the section is on the day
if i not in time_conflicts.keys(): # if there is no key yet, create one
print("the this is adding to dict")
time_conflicts[i] = [(sections.time_start, sections.time_end)] # gets the time zones of the days
print("testing out this code")
else: # if there is a key
for timeslots in time_conflicts[i]:
# if the curr low and high time is between the curr low and high in dictionary
if (timeslots[0] < sections.time_start < timeslots[1]) or (timeslots[0] < sections.time_end < timeslots[1]):
good_schedule = False # if time conflict, flip bad schedule
break
if good_schedule is True: # if no time conflicts, add it to total possible schedules
#print("This is the current combination: ", combinations)
total_schedules.append(combinations)
return total_schedules
# def main():
# alist1 = [(1,2), (2,3), (4,5)]
# alist2 = [(1,2,3),(4,5,6),(7,8,9)]
# alist3 = [1,2,3,4,5,6]
# alist5 = [7,8,9,10,11,12]
#
# # (1, 2) # (3, 4)
# timeslots = (((1000, 2000), (2000, 3000), (3000, 4000)), ((5000,6000), (0000, 7000), (7000,8000)))
#
# for i in create_schedule((((([1, 0, 1, 0, 0, 0, 0], 1000, 2000),), (([1, 0, 1, 0, 0, 0, 0], 2000, 3000),), (([1, 0, 1, 0, 0, 0, 0], 3000, 4000),),),
# ((([0, 1, 0, 1, 0, 0, 0], 5000, 6000),), (([0, 1, 0, 1, 0, 0, 0], 0000, 7000),), (([0, 1, 0, 1, 0, 0, 0], 7000, 8000),),))):
# displaySchedule(i)
#
# create_schedule((((((1, 2), 1000, 2000),), (((1, 2), 2000, 3000),), (((1, 2), 3000, 4000),),),
# ((((1, 2), 1500, 2500),), (((3, 4), 0000, 7000),), (((3, 4), 7000, 8000),),)))
# # ((3,4), 5000, 6000)
|
c03718163bf5a7c27570b5d61dc6db5c81f57017 | jiaziming/oldboy | /上课练习2/day-7面向对象/高级面向对象—进阶篇/类的方法.py | 797 | 3.84375 | 4 | #!/usr/bin/env python
#-*-conding:utf-8-*-
class Animal:
def __init__(self,name,):
self.name = name
self.num = None
hpbbie = "meat"
@classmethod #类方法 不能访问实例变量
def talk(self):
print("%s is talking....." %self.name)
@staticmethod #静态方法,不能访问类变量和实例变量
def walk(self):
print("%s is walking....." %self.name)
@property #把方法变成属性
def habit(self):
print("%s habit xxoo" %self.name)
@property
def total_players(self):
return self.num
@total_players.setter
def total_players(self,num):
self.num =num
print("total players:",self,num)
d =Animal("SNAJIANG")
#d.talk()
print(d.total_players)
d.total_players = 3
|
98369bd886e51df1a211536aa8e71ac97d36c915 | Pabloc98/Regresion_Predictiva | /Def/Graph/Func_graph.py | 1,753 | 3.53125 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
def BoxPlot(data, remover = None):
"""Esta función realiza un boxplot por cada variable numerica que contenga el dataset y que no este incluida en la lista remover
Parametros
------------
df: pandas dataframe
Dataframe
remover: lista
Lista que indica las columnas que no seran tenidas en cuenta para la elaboración del grafico
Returns
------------
BoxPlot
Gráfico de cajas y bigotes para cada variable
"""
if remover == None:
plt.figure(figsize=(10, 6))
sns.boxplot(data=data)
plt.xticks(rotation=90);
else:
columnas = list(data.columns)
columnas_opt = [col for col in columnas if col not in remover]
plt.figure(figsize=(10, 6))
sns.boxplot(data=data[columnas_opt])
plt.xticks(rotation=90);
plt.show()
def MatCor (df):
"""Esta función realiza una matriz de correlación por cada variable numerica que contenga el dataset
Parametros
------------
df: pandas dataframe
Dataframe
Returns
------------
Matriz de correlación
Mapa de calor de una matriz de correlación
"""
mcor = df.corr()
sns.heatmap(mcor, annot = True)
plt.show()
def pairplot(df, agregacion):
"""Esta función realiza un pairplot
Parametros
------------
df: pandas dataframe
Dataframe procesado con columnas que aporten valor
agregación: columna del df
Variable por la cual se realizara la agregación para generar los colores del gráfico
Returns
------------
Pairplot
Gráfico pairplot de dispersiones entre variables y distribuciones en la diagonal principal
"""
sns.pairplot(df, hue=agregacion)
|
427aef3b5fa1d234252b29d183595411b34ab6f6 | Long0Amateur/Self-learnPython | /Chapter 6 Strings/Problem/20. timezone (unfinished).py | 590 | 4.5625 | 5 | # A programs converts a time from one time zone to another
#
# 1. Taking input
# 2. Create a datetime
# 3. Get the timezones (Eastern, Central, Mountain or Pacific)
# 4. Convert to timezones and store it
# 5. Print the time
# Visit: https://www.youtube.com/watch?v=3DT5_A9X7TM
# For instance
# Time: 11:48 pm
# Starting zone: Pacific
# Ending zone: Eastern
# 2:48 am
from datetime import datetime
from pytz import timezone
t = input('Enter a time in 24-hour format: \n')
time = datetime.strptime(t,'%H:%M')
print(time.strftime('%I:%M %p'))
|
a8702f91e12d71684050e7a5e2af4f93a5701358 | brandhaug/decision-tree | /decision-tree.py | 5,741 | 3.53125 | 4 | import math
import random
class Node:
def __init__(self, value):
self.value = value
self.children = {}
def print_tree(self):
a = [self.value]
for key, test in self.children.items():
a.append(self.children[key].print_tree())
return a
def print_tree_test(self):
if len(self.children) == 0:
return str(self.value)
else:
temp = str(self.value)
for key, test in self.children.items():
temp += self.children[key].print_tree()
return temp
def read_data_text_file(file_name):
"""
Reads the file and returns the data
"""
file = open(file_name, 'r')
data = []
for line in file:
data.append(line.rstrip('\n').split('\t'))
return data
def get_outputs(data):
"""
Get list of outputs from data
"""
outputs = []
for example in data:
outputs.append(example[-1])
return outputs
def is_same_output(examples):
"""
Checks if all data have the same classification/output
"""
outputs = get_outputs(examples)
last_output = outputs[0]
for output in outputs:
if last_output is not output:
return False
last_output = output
return True
def plurality_value(examples):
"""
Get the most common output value among a set of examples, breaking ties randomly
"""
outputs = get_outputs(examples)
max_count = 0
most_common_output = None
for x in set(outputs):
count = examples.count(x)
if count > max_count:
max_count = count
most_common_output = x
return most_common_output
def B(q):
if q == 0 or q == 1:
return q
else:
return -(q * math.log(q, 2) + (1 - q) * math.log((1 - q), 2))
def entropy(examples, attribute):
"""
Calculate entropy of attribute
"""
position = 0
if len(examples) == 0:
return 0
for i in examples:
if i[attribute] == examples[0][attribute]:
position += 1
return B(position / len(examples))
def importance(examples, attributes):
"""
Get attribute with lowest entropy
"""
attribute_entropy = {}
for attribute in attributes:
attribute_entropy[attribute] = entropy(examples, attribute)
min_value = 10
chosen_attribute = None
for e in attribute_entropy:
if attribute_entropy[e] < min_value:
min_value = attribute_entropy[e]
chosen_attribute = e
return chosen_attribute
def random_attribute(attributes):
"""
Get a random attribute
"""
return attributes[random.randint(0, len(attributes) - 1)]
def get_attribute_value_set(examples, chosen_attribute):
"""
Returns a set of possible values for an attribute
"""
possible_attribute_values = []
for example in examples:
if example[chosen_attribute] not in possible_attribute_values:
possible_attribute_values.append(example[chosen_attribute])
possible_attribute_values.sort()
return possible_attribute_values
def decision_tree_learning(examples, attributes, parent_examples, importance_enabled):
"""
Recursive function that creates trains a decision tree based on data examples.
"""
if not examples:
return Node(plurality_value(parent_examples))
elif is_same_output(examples):
return Node(examples[0][-1]) # Return classification
elif not attributes:
return Node(plurality_value(examples))
else:
if importance_enabled:
chosen_attribute = importance(examples, attributes)
else:
chosen_attribute = random_attribute(attributes)
tree = Node(chosen_attribute)
attribute_value_set = get_attribute_value_set(examples, chosen_attribute)
for possible_attribute_value in attribute_value_set:
chosen_examples = []
for example in examples:
if example[chosen_attribute] == possible_attribute_value:
chosen_examples.append(example)
updated_attributes = list(attributes)
updated_attributes.remove(chosen_attribute)
subtree = decision_tree_learning(chosen_examples, updated_attributes, examples, importance_enabled)
tree.children[possible_attribute_value] = subtree
return tree
def classify(tree, example):
"""
Classify example with tree
"""
while tree.children:
print("Example: ", example)
print("Tree.value:", tree.value)
print("Tree.children", tree.children)
tree = tree.children[example[tree.value]]
return tree.value
def test(tree, examples):
"""
Returns results of testing for a tree
"""
correct_count = 0
for example in examples:
if example[-1] == classify(tree, example):
correct_count += 1
print("Tests matching: " + str(correct_count) + " of " + str(len(examples)) + ". Accuracy: " + str(
(correct_count / len(examples)) * 100) + "%")
if __name__ == '__main__':
# Get training data and attributes
training_data = read_data_text_file('training.txt')
attributes = [x for x in range(len(training_data[0]) - 1)]
# Get test data
test_data = read_data_text_file('test.txt')
# Random tree
print("Random Tree")
random_tree = decision_tree_learning(training_data, attributes, [], False)
print(random_tree.print_tree())
test(random_tree, test_data)
# Importance tree
print("\nImportance tree")
importance_tree = decision_tree_learning(training_data, attributes, [], True)
print(importance_tree.print_tree())
test(importance_tree, test_data)
|
8696a50df5134d0963693aeaae1d49d8d011726b | XihangJ/leetcode | /hash/347_Top K Frequent Elements.py | 1,687 | 3.671875 | 4 | '''
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
'''
class Solution:
#method 3. Using frequency array. O(n), S(n).
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
d = {}
freq = [[] for i in range(len(nums) + 1)]
for num in nums:
if num in d:
d[num] += 1
else:
d[num] = 1
for key in d:
freq[d[key]].append(key)
count = 0
i = -1
res = []
while count < k:
if freq[i]:
for key in freq[i]:
if count < k:
res.append(key)
count += 1
else:
break
i -= 1
return res
'''
#method 2. hashmap + heap. O(dlogk), S(d)
import heapq
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
d = {}
for num in nums:
if num in d:
d[num] += 1
else:
d[num] = 1
pairs = []
for key in d:
pairs.append([d[key], key])
largest = heapq.nlargest(k, pairs)
res = []
for pair in largest:
res.append(pair[1])
return res
'''
'''
#method 1. hashmap. O(dlogd), S(d). d: distinc number in nums
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
d = {}
for num in nums:
if num in d:
d[num] += 1
else:
d[num] = 1
pairs = []
for key in d:
|
73b83d1dfa2fd2bb83c97a9b146ace61849a0ed0 | vinaybhosale/Python | /MatplotLibPieChart/PieChartFromCSV.py | 636 | 3.671875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
class DrawChartFromCSV:
@staticmethod
def csvPiePlot():
df = pd.read_csv('medal.csv')
country_data = df["country"]
medal_data = df["gold_medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = (0.1, 0, 0, 0, 0)
plt.pie(medal_data, labels=country_data, explode=explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Gold medal achievements of five most successful\n"+"countries in 2016 Summer Olympics")
plt.show()
DrawChartFromCSV.csvPiePlot()
|
e91cd949f6abaee4ec8341f6b05fc0e9ae59e785 | Kolmogorova/python_Lesson2 | /lesson2.py | 2,638 | 3.9375 | 4 | """ Задача 1
i = 0
while i < 5:
i = i +1;
print(i, 0)
"""
""" Задача 2
Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5.
number = 0
for i in range(1, 11):
a = input("Введите цифру: ")
if a == "5":
number += 1
print('Количество введенных цифр 5 составляет',number)
"""
""" Задача 4
Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран.
pro = 1
for i in range(1,11):
pro *=i
print(pro)
"""
""" Задача 6
Найти сумму цифр числа.
integer_number = 5679
print('Сумма числа',integer_number,"равна: ")
sum = 0
while integer_number>0:
sum += integer_number % 10
integer_number = integer_number//10
print(sum)
"""
""" Задача 7
Найти произведение цифр числа.
integer_number = 679
print('Произведение числа',integer_number,"равно: ")
pro = 1
while integer_number>0:
pro *= integer_number % 10
integer_number = integer_number//10
print(pro)
"""
""" Задача 9
Найти максимальную цифру в числе
number = 8976543
print('Максимальной цифрой в числе',number,'является: ')
digit = 0
while number>0:
if number % 10 > digit:
digit = number % 10
number = number//10
print(digit)
"""
""" Задача 10
Найти количество цифр 5 в числе
integer_number = 43256789553493
print('Количество введенных цифр 5 в числе',integer_number,'составляет: ')
number = 0
while integer_number>0:
if integer_number % 10 == 5:
number += 1
integer_number = integer_number//10
print(number)
"""
|
851e444c6e65dfc65d597656b4bea9c918ba350e | abhaydhiman/Pyalgo | /Linked_List/Add_1_to_a_number_represented_as_linked_list/solution.py | 1,715 | 3.9375 | 4 | class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class LinkedList:
def __init__(self) -> None:
self.head = self.start = None
def insert(self, item):
temp = Node(item)
if self.head == None:
self.head = self.start = temp
return
self.head.next = temp
self.head = temp
def display(self, node=None):
if not node:
temp = self.start
else:
temp = node
while temp:
print(temp.data, end='')
temp = temp.next
def reverse(self):
curr_node = self.start
prev_node = self.start
next_node = self.start.next
curr_node.next = None
while next_node:
curr_node = next_node
next_node = next_node.next
curr_node.next = prev_node
prev_node = curr_node
self.start, self.head = self.head, self.start
return curr_node
def addOne(self):
self.reverse()
temp = self.start
carry = 0
prev = None
temp.data += 1
while temp and (temp.data > 9 or carry > 0):
temp.data += carry
carry = temp.data // 10
temp.data = temp.data % 10
temp = temp.next
if carry != 0:
self.insert(1)
self.reverse()
head = LinkedList()
head.insert(9)
head.insert(9)
head.insert(9)
head.insert(9)
print('-'*50)
print('Original Number:- ', end=' ')
head.display()
print()
print('After Adding One:- ', end=' ')
head.addOne()
head.display()
print()
print('-'*50)
|
d06629ac7f5c75a74e18188e17268403e155de12 | IHarmers/python101 | /lesson_4/flow_control.py | 1,330 | 4.3125 | 4 |
# Basic if statements
#
# Execute an operation if certain conditions are met.
#
happy = True # Try changing this to True
if happy == True:
print(":)")
if happy != True:
print(":(")
# if-else statements
drink = "Fanta" # Try changing this to values like: "Beer", "Fanta" or "Fristi"
soft_drinks = ["Cola", "Pepsi", "Sprite", "Fanta"]
if drink == "Water":
print("Water is very healthy. Good choice!")
elif drink == "Tea":
print("Tea makes you feel warm inside")
elif drink == "Beer" or drink == "Wine":
print("Don't drink too much or you will get drunk")
elif drink in soft_drinks:
print("These drinks contain a lot of sugar")
else:
print("I don't know this drink, but I bet it's delicious!")
# While loops
#
# Repeat an operation while a certain condition
# is not met.
#
# Try setting different numbers for these counters
current_count = 8
maximum_count = 10
while current_count <= maximum_count:
print("The current count is {}".format(current_count))
current_count = current_count + 1
# For loops
#
# Repeat an operation for every element in a collection
#
# Try adding and removing items from the list
checklist = ["Clothes", "Tent", "Shoes", "Drinks","Marshmellows", "Pizza!"]
print("Things to bring on a camping trip:")
for item in checklist:
print("- {}".format(item))
|
461b8478d884dc4f7bfc709c54f49614d78c59b2 | eilyi/IS685_Week5 | /MultiplyThese.py | 147 | 3.859375 | 4 | #multiply these
num1= 1
num2 = 2
def MultiplyThese(num1, num2):
print(num1)
print(num2)
multiply = num1*num2
return MultiplyThese(multiply) |
2d80a6f4050e58f46ea193f0e1ea4f86c6403bb0 | pololee/oj-leetcode | /companies/airbnb/p336/Solution.py | 1,855 | 3.640625 | 4 | class Solution:
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
if not words:
return []
# The words are unique as said in the question
# we can set up a table to achieve O(1) look up time
table = {}
for idx, word in enumerate(words):
table[word] = idx
results = []
for idx, word in enumerate(words):
length = len(word)
for i in range(length + 1):
left_sub = word[:i]
right_sub = word[i:]
if self.is_palindrome(left_sub):
reversed_right_sub = right_sub[::-1]
if reversed_right_sub in table and table[reversed_right_sub] != idx:
pair = [table[reversed_right_sub], idx]
results.append(pair)
if len(right_sub) != 0 and self.is_palindrome(right_sub):
reversed_left_sub = left_sub[::-1]
if reversed_left_sub in table and table[reversed_left_sub] != idx:
pair = [idx, table[reversed_left_sub]]
results.append(pair)
return results
def is_palindrome(self, word):
if not word:
return True
left = 0
right = len(word) - 1
while left <= right:
if word[left] != word[right]:
return False
left += 1
right -= 1
return True
def main():
sol = Solution()
test = ["abcd", "dcba", "lls", "s", "sssll"]
print(sol.palindromePairs(test))
test = ["bat", "tab", "cat"]
print(sol.palindromePairs(test))
test = ['a', '']
print(sol.palindromePairs(test))
if __name__ == '__main__':
main()
|
833817b34943d44c05dc3023e84db0d51d553b03 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/GenerateParentheses2.py | 543 | 3.546875 | 4 | from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
dp = []
dp.append([""])
for i in range(1, n + 1):
cur = []
for j in range(i):
for left in dp[j]:
for right in dp[i - j - 1]:
cur.append("(" + left + ")" + right)
dp.append(cur)
return dp[n]
if __name__ == "__main__":
n = int(input())
solution = Solution()
print(solution.generateParenthesis(n)) |
5cda498e72bc1ccb415a1e9c5e956406057bd266 | j5int/j5basic | /j5basic/Colours.py | 1,703 | 3.59375 | 4 | #!/usr/bin/env python
# -*- noplot -*-
# Code taken from http://matplotlib.sourceforge.net/examples/pylab_examples/colours.py
# under new BSD-style license
"""
Some simple functions to generate colours.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
import numpy as np
def pastel(colour, weight=2.4):
""" Convert colour into a nice pastel shade"""
rgb = np.asarray(tuple(colour))
# scale colour
maxc = max(rgb)
if maxc < 1.0 and maxc > 0:
# scale colour
scale = 1.0 / maxc
rgb = rgb * scale
# now decrease saturation
total = rgb.sum()
slack = 0
for x in rgb:
slack += 1.0 - x
# want to increase weight from total to weight
# pick x s.t. slack * x == weight - total
# x = (weight - total) / slack
x = old_div((weight - total), slack)
rgb = [c + (x * (1.0-c)) for c in rgb]
return rgb
base = np.asarray([[1,0,0], [0,1,0], [0,0,1]])
def get_colours(n):
""" Return n pastel colours. """
if n <= 3:
return base[0:n]
# how many new colours to we need to insert between
# red and green and between green and blue?
needed = (old_div(((n - 3) + 1), 2), old_div((n - 3), 2))
colours = []
for start in (0, 1):
for x in np.linspace(0, 1, needed[start]+2)[:-1]:
colours.append((base[start] * (1.0 - x)) +
(base[start+1] * x))
colours.append(base[2])
return [pastel(c) for c in colours[0:n]]
|
7659debcb24e3f5e29e87dfff8b872bc3c51a6e5 | makrist2/python | /test_8.py | 144 | 3.65625 | 4 | lst = [1, 2, 3, 4]
print(lst)
lst[lst.index(max(lst))], lst[lst.index(min(lst))] = lst[lst.index(min(lst))], lst[lst.index(max(lst))]
print(lst) |
021b9a48688527f64911249657d26b88dd703bb0 | daweibai/PCBS-langevo | /Language_evo_ILM.py | 8,309 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 24 03:39:42 2019
@author: Dawei
"""
#Reproduce Kirby's (2001) Iterated Learning Model simulating language evolution
import random
from random import randint
import string
import numpy as np
n_of_iterations = 100
#Number of iterations wanted
rules = {
#Initial rule spaces. A is for lefthand rules (prefix). B for righthand rules (suffix).
"A":[
["a0","a1","a2","a3","a4"],
["","","","",""],
["","","","",""],
["","","","",""],
["","","","",""],
["","","","",""]
],
"B":[
["b0","","","","",""],
["b1","","","","",""],
["b2","","","","",""],
["b3","","","","",""],
["b4","","","","",""]
]
}
def str_gen(size, chars=string.ascii_lowercase):
#Generate a random string of length between 1 and 10 defined later
return ''.join(random.choice(chars) for x in range(size))
def empty_meaning_space():
#Generate an empty meaning space that will be the initial meaning space of every learner
matrix = []
row = []
for b in range(5):
row = []
for a in range(5):
row.append('')
matrix.append(row)
return matrix
def substr_finder(s1,s2):
# takes two strings and extract the common substrings in the beginning or at the end
m = len(s1)
n = len(s2)
counter = [[0]*(n+1) for x in range(m+1)]
longest = 0
common = ''
prefix = ''
suffix = ''
for i in range(m):
for j in range(n):
if s1[i] == s2[j]:
c = counter[i][j] + 1
counter[i+1][j+1] = c
if c > longest:
common = ''
longest = c
common = s1[i-c+1:i+1]
elif c == longest:
common = s1[i-c+1:i+1]
if common == s1[:len(common)] and common == s2[:len(common)]:
# for prefix rules
prefix = common
if common == s1[-len(common):] and common == s2[-len(common):]:
# for suffix rules
suffix = common
return prefix,suffix
#Notice that my rules don't allow circumfixes. if there's a common string in th
#e middle, and a shorter common string in the beginning or in the end, it doesn
#'t count
#first agent
first_agent = []
for b in range(5):
row = []
for a in range(5):
row.append(str_gen(randint(1, 10)))
first_agent.append(row)
def row_parser(utter):
# Grammar induction for the rows. The function takes utterances and modifies the rules.
global rules
for b in range(5): #row
for a in range(5): #column
for a2 in np.arange(a,5):
# compare two elements in the same row
if substr_finder(utter[b][a],utter[b][a2])[0] != '' \
and substr_finder(utter[b][a],utter[b][a2])[1] == '':
# if find common prefix and not common suffix
rules["B"][b][a+1] = 'P' + substr_finder(utter[b][a],utter[b][a2])[0]
rules["B"][b][a2+1] = 'P' + substr_finder(utter[b][a],utter[b][a2])[0]
# then add the common prefix to the grammar
# 'P' is a functional character indicating it's a prefix
elif substr_finder(utter[b][a],utter[b][a2])[0] == '' \
and substr_finder(utter[b][a],utter[b][a2])[1] != '':
# if find common suffix and not common prefix
rules["B"][b][a+1] = 'S' + substr_finder(utter[b][a],utter[b][a2])[1]
rules["B"][b][a2+1] = 'S' + substr_finder(utter[b][a],utter[b][a2])[1]
# then add the common suffix to the grammar
# 'S' is a functional character indicating it's a suffix
def column_parser(utter):
# Grammar induction for the columns
global rules
for a in range(5): #column
for b in range(5): #row
for b2 in np.arange(b,5):
# compare two elements
if substr_finder(utter[b][a],utter[b2][a])[0] != '' \
and substr_finder(utter[b][a],utter[b2][a])[1] == '':
# if find common prefix
rules["A"][b+1][a] = 'P' + substr_finder(utter[b][a],utter[b2][a])[0]
rules["A"][b2+1][a] = 'P' + substr_finder(utter[b][a],utter[b2][a])[0]
if substr_finder(utter[b][a],utter[b2][a])[0] == '' \
and substr_finder(utter[b][a],utter[b2][a])[1] != '':
# if find common suffix
rules["A"][b+1][a] = 'S' + substr_finder(utter[b][a],utter[b2][a])[1]
rules["A"][b2+1][a] = 'S' + substr_finder(utter[b][a],utter[b2][a])[1]
def production(n_of_utter):
# produce utterances. If there's a rule, produce as the rule says. If there isn't, generate random string
global rules
produc = empty_meaning_space()
for n in range(n_of_utter):
col = randint(0, 4)
row = randint(0, 4)
# randomly choose a meaning to produce a string for
if rules["A"][row+1][col] != '' and rules["A"][row+1][col][0] == 'P' and\
rules["B"][row][col+1] != '' and rules["B"][row][col+1][0] == 'S':
# if A rule is for prefix, B for suffix
produc[row][col] = rules["A"][row+1][col][1:] +rules["B"][row][col+1][1:]
# merge two rules prefix + suffix to for a word
# doesn't take the shortest one, but the last one for that meaning
elif rules["A"][row+1][col] != '' and rules["A"][row+1][col][0] == 'S' \
and rules["B"][row][col+1] != '' and rules["B"][row][col+1][0] == 'P':
# if A rule is for suffix, B for prefix
produc[row][col] = rules["B"][row][col+1][1:] + rules["A"][row+1][col][1:]
elif rules["A"][row+1][col] == '' and rules["B"][row][col+1] != '' and \
rules["B"][row][col+1] == 'P':
# if A rule is empty, B rule is for prefix
# could be more than 10 characters
produc[row][col] = rules["B"][row][col+1][1:] + str_gen(randint(1, 9))
elif rules["A"][row+1][col] == '' and rules["B"][row][col+1] != '' and \
rules["B"][row][col+1] == 'S':
# if A rule is empty, B rule is for suffix
produc[row][col] = str_gen(randint(1, 9)) + rules["B"][row][col+1][1:]
elif rules["A"][row+1][col] != '' and rules["A"][row+1][col] == 'P' and\
rules["B"][row][col+1] == '':
# if A rule is for prefix, B rule is empty
produc[row][col] = rules["A"][row+1][col][1:] + str_gen(randint(1, 9))
elif rules["A"][row+1][col] != '' and rules["A"][row+1][col] == 'S' and\
rules["B"][row][col+1] == '':
# if A rule is for suffix, B rule is empty
produc[row][col] = str_gen(randint(1, 9)) + rules["A"][row+1][col][1:]
elif rules["A"][row+1][col] == 'S' and rules["A"][row+1][col] == 'S' and\
rules["B"][row][col+1] == '':
# if A and Brule are for suffix
produc[row][col] = rules["A"][row+1][col][1:]
elif rules["A"][row+1][col] == 'P' and rules["A"][row+1][col] == 'P' and\
rules["B"][row][col+1] == '':
# if A and Brule are for prefix
produc[row][col] = rules["B"][row][col+1][1:]
else :
# if both rules are empty, generate a random string
# should I do this for the latter two cases?
produc[row][col] = str_gen(randint(1, 10))
return produc
def iteration(n_of_iteration):
for i in range(n_of_iteration):
if i == 0:
prod = first_agent
column_parser(prod)
row_parser(prod)
else:
prod = production(50)
column_parser(prod)
row_parser(prod)
for i in np.arange(10,10,100):
for j in range (5):
print(prod[j])
return prod
i = iteration(n_of_iterations)
print('Production after', n_of_iterations, "iterations:")
for j in range (5):
print(i[j])
print('')
print('A rules:')
for j in range (6):
print(rules["A"][j])
print('')
print('B rules:')
for j in range (5):
print(rules["B"][j])
|
d51a54ade9afa834b1f7b383dc4650a5883daea8 | mcgranam/projecteuler | /projecteuler031.py | 1,577 | 3.59375 | 4 | #!/usr/bin/env python
# File name: projecteuler031.py
# Author: Matt McGranaghan
# Date Created: 2014/05/06
# Date Modified: 2014/05/06
# Python Version: 2.7
# In England the currency is made up of pound, and pence, p, and there are eight coins in general circulation:
# How many different ways can 2 be made using any number of coins?
def sum_coins(coins, coin_values):
coin_total = 0
for i in range(len(coins)):
coin_total += coins[i]*coin_values[i]
return coin_total
def solution031():
coin_values = [200,100,50,20,10,5,2,1]
target = 200
valid_partitions = 0
for p200 in range(target/coin_values[0]+1):
total = sum_coins([p200],coin_values)
for p100 in range((target-total)/coin_values[1]+1):
total = sum_coins([p200,p100],coin_values)
for p50 in range((target-total)/coin_values[2]+1):
total = sum_coins([p200,p100,p50],coin_values)
for p20 in range((target-total)/coin_values[3]+1):
total = sum_coins([p200,p100,p50,p20],coin_values)
for p10 in range((target-total)/coin_values[4]+1):
total = sum_coins([p200,p100,p50,p20,p10],coin_values)
for p5 in range((target-total)/coin_values[5]+1):
total = sum_coins([p200,p100,p50,p20,p10,p5],coin_values)
for p2 in range((target-total)/coin_values[6]+1):
total = sum_coins([p200,p100,p50,p20,p10,p5,p2],coin_values)
for p1 in range((target-total)/coin_values[7]+1):
coins = [p200,p100,p50,p20,p10,p5,p2,p1]
if sum_coins(coins,coin_values) == target:
valid_partitions += 1
return valid_partitions
print solution031() |
f041f8bd2aa503fa474ca028d688d518dc133eab | sahmad11/ROC-HCI-SmileyCluster-Data-Analysis | /Data Mining/kmeans.py | 1,293 | 3.59375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn import preprocessing
def main():
# Elbow method to compute the average score of the k-means on different k values in the range [1,10]
#The visualization generated helps in selecting the best k value.
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, init='k-means++')
kmeans.fit(df)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
#Used PCA to select the most influencial attributes from the dataset to visualize the clustering results on the best k-value.
df=pd.DataFrame(pd.read_csv("winequality_white.csv"))
#df=df.drop(columns=["id","Mammal_Richness"],axis=1)
kmeans=KMeans(n_clusters=3,init='k-means++').fit(df)
centroids=kmeans.cluster_centers_
pca=PCA(2)
pca.fit(df)
pca_data=pd.DataFrame(pca.transform(df))
pca.fit(centroids)
pca_cen=pd.DataFrame(pca.transform(centroids))
print(pca_data.head())
plt.scatter(pca_data[0], pca_data[1], c= kmeans.labels_.astype(float), s=50, alpha=0.5)
plt.scatter(pca_cen[0], pca_cen[1], c='red', s=50)
plt.show()
main()
|
64677cf21e67f81d697d09a9dc150627636834d9 | omegajudith/pythonPro | /ex13.py | 313 | 4.25 | 4 | number_of_sequence = int(input("Enter the length of sequence: "))
def fibonacci(a):
if a == 0:
return None
elif a == 1:
print([1])
else:
fibo = [1, 1]
while len(fibo) < a:
elem = int(fibo[-2]) + int(fibo[-1])
fibo.append(elem)
print(fibo)
fibonacci(number_of_sequence) |
9726e89dfa36ad7ad8abf9f61bbd64fd31c69c77 | agj4/FishGame | /game.py | 6,748 | 3.5625 | 4 | '''Creates Fish Game
made Fall 2017
Final Project
@author Annika Johnson (agj4)'''
from tkinter import *
from random import randint
from fish import *
class Game:
''' Creates Fish Game'''
def __init__ (self, window):
self.window = window
self.window.protocol('WM_DELETE_WINDOW', self.safe_exit)
self._width = 1000
self._hight = self._width // 2
self._canv = Canvas(self.window, bg='sky blue',
width=self._width, height=self._hight)
self._canv.pack()
button = Button(self.window, text='New Game', command=self.new_game)
button.pack()
self._game_over = False
self._game_won = False
self._fish_list = []
self._player = Fish(self._canv, self._width/2, self._hight/2, 0, 0, 15, self.get_random_color(), 'right')
self._canv.bind("<Key>", self.player_move)
self._canv.bind("<KeyRelease>", self.player_stop)
self._canv.bind("<space>", self.new_game)
self._canv.focus_set()
self.animate()
def animate (self):
''' Animates fish'''
if not self._game_over and not self._game_won:
self.add_fish( )
self._canv.delete(ALL)
self._player.move()
self._player.draw_fish()
for fish in self._fish_list:
fish.move()
fish.draw_fish()
self.check_off_screen()
self.check_collision()
self.check_win_condition()
self._canv.after(40, self.animate)
elif self._game_over:
self._canv.create_text(self._width/2, self._hight * 3/8, text = "Game Over", font = ('Arial', 30))
self._canv.create_text(self._width/2, self._hight/2, text = "you've been eaten", font = ('Arial', 20))
elif self._game_won:
self._canv.create_text(self._width/2, self._hight * 3/8, text = "Victory", font = ('Arial', 30))
self._canv.create_text(self._width/2, self._hight/2, text = "you've become the largest fish in the pond", font = ('Arial', 20))
def add_fish (self):
''' Adds fish along the y access on either side of the screen
staggers fish creation, only 16 fish max
when there are at least 15 fish on screen the last fish is more likely to be smaller than player'''
if len(self._fish_list) < 16:
if randint(0, 100) > 80:
if len(self._fish_list) == 15 and self._player.get_size() < 40 and randint(0, 100) > 80:
sz = randint(10, self._player.get_size())
else:
sz = randint(10, 175)
if randint(0, 1) == 0: #left side of screen
self._fish_list.append(Fish(self._canv, -1/2 * sz, randint(5, self._hight - 5),
randint(2, 6), 0, sz, self.get_random_color(), 'right'))
else: #right side of the screen
self._fish_list.append(Fish(self._canv, self._width + 1/2 * sz, randint(5, self._hight - 5),
-(randint(2, 6)), 0, sz, self.get_random_color(), 'left'))
def check_off_screen (self):
''' Checks if any fish is off screen
if player is off screen then player is moved to the opposite side
if any other fish then it is deleted'''
for fish in self._fish_list[:]:
if fish.get_x() < -fish.get_size()/2 or fish.get_x() > self._width + fish.get_size()/2:
self._fish_list.remove(fish)
if self._player:
if self._player.get_x() < -(3/4 * self._player.get_size()):
self._player.set_x(self._width + self._player.get_size()/4)
elif self._player.get_x() > self._width + 3/4 * self._player.get_size():
self._player.set_x(-(self._player.get_size()/4))
if self._player.get_y() < -(3/8 * self._player.get_size()):
self._player.set_y(self._hight + self._player.get_size()/8)
elif self._player.get_y() > self._hight + 3/8 * self._player.get_size():
self._player.set_y(-(self._player.get_size()/8))
def check_collision (self):
''' Checks if player hits another fish and if so compares the two fish
if the player is larger it eats other fish
if the player is smaller it causes a game over'''
for fish in self._fish_list[:]:
if self._player.hit(fish):
if self._player > fish:
self._player.set_size(self._player.get_size() + fish.get_size() // 10)
self._fish_list.remove(fish)
else:
self._game_over = True
def check_win_condition (self):
''' Causes player to win when it gets past a certain size'''
if self._player.get_size() > self._hight / 2:
self._game_won = True
def player_move (self, event):
''' Changes player fish's X/Y velocities based on arrow keys'''
if event.keysym == 'Up':
self._player.set_Yvel(-7)
elif event.keysym == 'Down':
self._player.set_Yvel(7)
if event.keysym == 'Right':
self._player.set_direction('right')
self._player.set_Xvel(7)
elif event.keysym == 'Left':
self._player.set_direction('left')
self._player.set_Xvel(-7)
def player_stop (self, event):
''' When arrow key is released X/Y velocities are reset to 0'''
if event.keysym == 'Up' or event.keysym == 'Down':
self._player.set_Yvel(0)
if event.keysym == 'Right' or event.keysym == 'Left':
self._player.set_Xvel(0)
def new_game (self, event = None):
''' Resets the entire game'''
self._fish_list = []
self._player = Fish(self._canv, self._width/2, 1/2 * self._hight, 0, 0, 15, self.get_random_color(), 'right')
if self._game_over or self._game_won:
self._game_won = False
self._game_over = False
self.animate()
def get_random_color(self):
''' Generate random color intensities for red, green & blue and convert them to hex. '''
return '#{:02X}{:02X}{:02X}'.format(randint(0,255), randint(0,255), randint(0,255))
def safe_exit(self):
''' Turn off the event loop before closing the GUI '''
self.terminated = True
self.window.destroy()
if __name__ == '__main__':
root = Tk()
root.title('Fish Game')
app = Game(root)
root.mainloop()
|
7be76a774c55aeb253087872c5d006d703b4042b | ml18fksa/Assessment1 | /agentframework.py | 2,968 | 3.5625 | 4 |
"""
This file Create by Fawziah Almutairi
Created on Mon Dec 16 01:25:40 2019.
Programming for Geographical Information Analysts: Core Skills.
@author: ml18fksa, the Student ID is 201288865.
Geography Programming Courses at University of Leeds.
"""
"""
agentframework.py defines a class Agents.
1. The initialisation of the class takes arguments environment, agents
2. The calss has methods move, eat at 2D environment.
This file called the agentframework which has agents at the environment.
The main task for this model is class agent to moving and eating to sharing resources and exchange resources with agents neighbourhood.
"""
"""
import the agent with function random.
________________________________________________
"""
import random
"""
class the agents at the environment in the in.txt file.
_________________________________________________________
"""
class Agents():
def __init__(self,i,agents,environment):
self.i = i
self.x = random.randint(0,250)
self.y = random.randint(0,250)
self.environment = environment
self.agents =agents
self.store = 0
#################################
#deinition to move the agents #
#The Agents have y and x coordinates.#
######################################
def __str__(self):
return "Agent(i=" + str(self.i)+ ", store=" + str(self.store) + ", x=" + str(self.x) + ", y=" + str(self.y) + ")"
def move(self): #Move function
r = random.random()
if r < 0.5:
self.y += 1
else:
self.y -= 1
r = random.random()
if r < 0.5:
self.x += 1
else:
self.x -= 1
##################################################
##deinition to eat the agents at 2D environment.#
#################################################
def eat(self): #eat function
if self.environment[self.y][self.x] > 10:
self.environment[self.y][self.x] -= 10
self.store += 10
#######################################################
#deinition to get distance the agents with coordinates.#
#######################################################
def get_distance(self, agent): #distance function
return (((self.x - agent.x)**2) + ((self.y - agent.y)**2))**0.5
#############################################################
# deinition to share the agents distance with neighbourhood#
##############################################################
def share(self, d):
for agent in self.agents:
if agent != self:
dis = self.get_distance(agent)
if (dis < d):
print(self, "is sharing with", agent, "as distance is", dis)
total = self.store + agent.store
ave = total/2
self.store = ave
agent.store = ave
|
0b6cf59560c702748c04891272b4326a876ba072 | GoogleCloudPlatform/training-data-analyst | /quests/dei/census/predictor.py | 1,697 | 3.734375 | 4 | import os
import pickle
import numpy as np
class MyPredictor(object):
"""An example Predictor for an AI Platform custom prediction routine."""
def __init__(self, model):
"""Stores artifacts for prediction. Only initialized via `from_path`.
"""
self._model = model
def predict(self, instances, **kwargs):
"""Performs custom prediction.
Preprocesses inputs, then performs prediction using the trained
scikit-learn model.
Args:
instances: A list of prediction input instances.
**kwargs: A dictionary of keyword args provided as additional
fields on the predict request body.
Returns:
A list of outputs containing the prediction results.
"""
inputs = np.asarray(instances)
outputs = self._model.predict_proba(inputs)
return outputs.tolist()
@classmethod
def from_path(cls, model_dir):
"""Creates an instance of MyPredictor using the given path.
This loads artifacts that have been copied from your model directory in
Cloud Storage. MyPredictor uses them during prediction.
Args:
model_dir: The local directory that contains the trained
scikit-learn model and the pickled preprocessor instance. These
are copied from the Cloud Storage model directory you provide
when you deploy a version resource.
Returns:
An instance of `MyPredictor`.
"""
model_path = os.path.join(model_dir, 'model.pkl')
with open(model_path, 'rb') as f:
model = pickle.load(f)
return cls(model) |
c5b4551a3bd27991e70358944d560cd903aa10a6 | Devendra33/Machine-Learning | /Pandas/Practice/Data Analysis/ipynb_to_py/P_pandas_groupby.py | 414 | 3.671875 | 4 | import pandas as pd
ds = pd.read_csv("wheather.csv")
# now applying the groupby method
# for selecting a perticular city domain
# gives all details of mumbai city
# gives the maximum value of cities
# gives the minimum value of cities
# gives the averag
# gives all the details of all the cities.
# it will plot the graph for each group.
|
678fff5f2af39d635503a29edb405549911ae923 | rkolyan/DBLabs | /lab_06/linq.py | 2,399 | 3.5625 | 4 | class AbstractTable:
def __init__(self, **kwargs):
for key in kwargs:
self.__dict__[key] = list();
def insert(self, values):
for key in self.__dict__.keys():
for i in range(len(values[key])):
self.__dict__[key].append(values[key][i]);
def __len__(self):
key = self.__dict__.keys()[0];
return len(self.__dict__[key]);
#Ou Эта функция работает стабильно
def fill_tablice(somefile, tablice):
for row1 in somefile:
tablice.append(row1.split(','));
return tablice;
def print_tablice(tablice):
for i in range(len(tablice)):
print("|", end='');
for element in tablice[i]:
print('{:20s}'.format(element), end='|');
print("");
if __name__ == "__main__":
albums = list();
musicians = list();
genres = list();
labels = list();
f = open("../lab_01/csv/albums.csv", "r");
albums = fill_tablice(f, albums);
f.close();
f = open("../lab_01/csv/musicians.csv", "r");
musicians = fill_tablice(f, musicians);
f.close();
f = open("../lab_01/csv/genres.csv", "r");
genres = fill_tablice(f, genres);
f.close();
f = open("../lab_01/csv/labels.csv", "r");
labels = fill_tablice(f, labels);
f.close();
#1)Get Dead Music Groups
print("QUERY01:");
query01 = list(filter(lambda row: int(row[2]) > 1 and int(row[4]), musicians));
print_tablice(query01);
del query01;
print("\n\n\n");
#2)Get Alive Musician's Names
print("QUERY02:");
query02 = list(filter(lambda row: not int(row[4]), musicians));
print_tablice(query02);
del query02;
print("\n\n\n");
#3)All Dead Musicians (with order desc)
print("QUERY03:");
query03 = sorted(list(filter(lambda row: int(row[4]), musicians)), key=lambda row: int(row[0]), reverse=True);
print_tablice(query03);
del query03;
print("\n\n\n");
#4)Add something
print("QUERY04:");
query04 = list(zip(sorted(musicians[1]), sorted(musicians[1], reverse=True)));
print_tablice(query04);
print("\n\n\n");
#5)Add something
print("QUERY05:");
query05 = list(zip(map(lambda x, y: str(int(x) + int(y)),[album[4] for album in albums], list(sorted([album[4] for album in albums], reverse=True))), [album[4] for album in albums]));
print_tablice(query05);
|
a0c1d0ae37de33bae1c8b5c9cb3ad378c81640de | fzr72725/GalvanizePre | /Unit2/Assignment_1d.py | 3,312 | 4.34375 | 4 | def count_match_index(L):
'''
Use enumerate and other skills to return the count of the number
of items in the list whose value equals its index.
Parameters
----------
L : {list} of {int}
Returns
-------
int : {int}
Example
-------
>>> count_match_index([0, 2, 2, 3, 6, 5])
4
'''
return len([e for i,e in enumerate(L) if i==e])
def invert_list(L):
'''
Use enumerate and other skills to return a dictionary which has
the values of the list as keys and the index as the value. You may assume
that a value will only appear once in the given list.
Parameters
----------
L : {list}
Returns
-------
dict : keys are entries in L, vallues are the index
Example
-------
>>> invert_list(['a', 'b', 'c', 'd'])
{'a': 0, 'c': 2, 'b': 1, 'd': 3}
'''
return {key:value for value,key in enumerate(L)}
def concatenate(L1, L2, connector=""):
'''
L1 and L2 have the same length. Use zip and other skills from above to
return a list of the same length where each value is the two strings from
L1 and L2 concatenated together with connector between them.
Parameters
----------
L1 : {list} of {str}
L2 : {list} of {str}
connector : {str} (optional)
Returns
-------
list : {list} of {str}
Example
-------
>>> concatenate(["A", "B"], ["b", "b"])
['Ab', 'Bb']
>>> concatenate(["San Francisco", "New York", "Las Vegas", "Los Angeles"], \
["California", "New York", "Nevada", "California"], ", ")
['San Francisco, California', 'New York, New York', 'Las Vegas, Nevada', 'Los Angeles, California']
'''
return [a+connector+b for a,b in zip(L1,L2)]
def transpose(mat):
'''
Return the transpose of the matrix. You may assume that the matrix is not
empty. You can do this using a double for loop in a list comprehension.
There is also a solution using zip.
Parameters
----------
mat : {list} of {list} of {int}
Returns
-------
list : {list} of {list} of {int}
Example
-------
>>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> transpose(M)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
'''
return [[row[i] for row in mat] for i in xrange(len(mat[0]))]
def acronym(phrase):
'''
Given a phrase, return the associated acronym by breaking on spaces and
concatenating the first letters of each word together capitalized.
Parameters
----------
phrase : {str}
Returns
-------
str : {str}
Example
-------
>>> acronym("data science immersive")
'DSI'
'''
return ''.join([word[0].upper() for word in phrase.split(' ')])
def sort_by_ratio(L):
'''
Sort the list L by the ratio of the elements in the 2-tuples.
For example, (1, 3) < (2, 4) since 1/3 < 2/4.
Use the key parameter in the sort method.
Parameters
----------
L : {list} of 2-tuples ({tuple}) of {int}
Returns
-------
None
Example
-------
>>> L = [(2, 4), (8, 5), (1, 3), (9, 4), (3, 5)]
>>> sort_by_ratio(L)
>>> L
[(1, 3), (2, 4), (3, 5), (8, 5), (9, 4)]
'''
L.sort(key = lambda x:x[0]/float(x[1]))
if __name__ == '__main__':
print sort_by_ratio(L)
|
9528b6c4422fc33e37d370ef95309e2111069e91 | AhmedRaja1/Python-Beginner-s-Starter-Kit | /Code only/3- Control Flow/Even Odd using For loop Exercise.py | 185 | 4.0625 | 4 | even_number_counter = 0
for number in range(1, 30):
if number % 2 == 0:
print(number)
even_number_counter += 1
print(f"We have {even_number_counter} Even Numbers")
|
d4a6b7095cd42a45b9d63f398f7e71c2e43f99e1 | gogocruz/projecto_imfj1_2020 | /viewer_aplication/mesh.py | 16,398 | 3.90625 | 4 | """Mesh class definition"""
# Just import time if we need statistics
import time
import math
import pygame
from vector3 import Vector3
import matrix4
import numpy
class Mesh:
"""Mesh class.
Stores a list of polygons to be drawn
"""
stat_vertex_count = 0
"""Vertex count for statistics. This code that actually tracks the statistics
is normally commented out for performance reasons (see render method)"""
stat_transform_time = 0
"""Time spent on vertex transforming for statistics. This code that actually tracks
the statistics is normally commented out for performance reasons (see render method)"""
stat_render_time = 0
"""Time spent in rendering for statistics. This code that actually tracks the statistics
is normally commented out for performance reasons (see render method)"""
def __init__(self, name="UnknownMesh"):
"""
Arguments:
name {str} -- Name of the material, defaults to 'UnknownMesh'
"""
self.name = name
""" {str} Name of the mesh"""
self.polygons = []
""" {list[list[Vector3]]} List of lists of polygons. A polygon is a closed shape,
hence the need for a list of lists, if we want more complex shapes."""
def offset(self, v):
"""
Offsets this mesh by a given vector. In practice, adds v to all vertex in all polygons
Arguments:
v {Vector3} -- Ammount to displace the mesh
"""
new_polys = []
for poly in self.polygons:
new_poly = []
for p in poly:
new_poly.append(p + v)
new_polys.append(new_poly)
self.polygons = new_polys
def render(self, screen, clip_matrix, material):
"""
Renders the mesh.
Arguments:
screen {pygame.surface} -- Display surface on which to render the mesh
clip_matrix {Matrix4} -- Clip matrix to use to convert the 3d local space coordinates
of the vertices to screen coordinates.
material {Material} -- Material to be used to render the mesh
Note that this function has the code that tracks statistics for the vertex count and
render times, but it is normally commented out, for performance reasons. If you want
to use the statistics, uncomment the code on this funtion.
"""
# Convert Color to the pygame format
c = material.Color.tuple3()
w = screen.get_width() * 0.5
h = screen.get_height() * 0.5
# For all polygons
for poly in self.polygons:
# Create the list that will store (temporarily) the transformed vertices
tpoly = []
# Uncomment next 2 lines for statistics
Mesh.stat_vertex_count += len(poly)
t0 = time.time()
for v in poly:
# Multiply vertex it by the clip matrix - This function is slightly faster than doing
# vout = v * clip_matrix, since it doesn't have to check types or create additional
# Vector4 objects
vout = clip_matrix.premultiply_v3(v, 1)
# Finalize the transformation by converting the point from homogeneous NDC to
# screen coordinates (divide by w, scale it by the viewport resolution and
# offset it)
tpoly.append((w + vout.x / vout.w,
h - vout.y / vout.w))
# Uncomment next line for statistics
t1 = time.time()
# Render
pygame.draw.polygon(screen, c, tpoly, material.line_width)
# Uncomment next 3 lines for statistics
t2 = time.time()
Mesh.stat_transform_time += (t1 - t0)
Mesh.stat_render_time += (t2 - t1)
'''Function to create a model from given coordinates of vertices and faces of .obj or .json files'''
@staticmethod
def create_mesh(path, mesh=None):
#create mesh if there isn't one
if mesh is None:
mesh = Mesh("UnknownMesh")
#initialize the vertices and faces lists
vertices = []
faces = []
#if there is a model file
try:
#opening file
f = open(path)
#for each line of the file
for line in f:
#if theres a v alone, without anything after
if line [:2] == "v ":
#program will find the first number being it will always appear after the " "
index1 = line.find(" ") + 1
# the second
index2 = line.find(" ", index1 + 1)
#and the third
index3 = line.find(" ", + index2 + 1)
# create the vertices by joining the 3 coordinates given by the file
vertex = Vector3(float(line[index1:index2]), float(line[index2:index3]), float(line[index3:-1]))
vertex = Vector3(round(vertex.x, 2), round(vertex.y, 2), round(vertex.z, 2))
# append those vertice onto the vertices list
vertices.append(vertex)
#if there a f
#since only the v's can have other letters after we can only put "f"
elif line[0] == "f":
#for .obj files theres only one "/" separing the numbers but for .json theres two "/" so we transform the two "/" into only one
string = line.replace("//", "/")
# finds the number that we will use that are just the first from the given 3 separated by "/"
i = string.find(" ") + 1
#makes a list for the faces of the object
face = []
#they can have multiple face coordinates separated by " "
for item in range(string.count(" ")):
# will put only the first number on the 3 in the list because we only need that one
if string.find(" ", i) == - 1:
face.append(string[i:-1])
break
face.append(string[i:string.find(" ",i)])
i = string.find(" ", i) + 1
#we only need the first numbers
if line.find("/") == -1:
#using that numbers make a face of the object
faces.append(Vector3(int(face[0]), int(face[1]), int(face[2])))
#here we're making the faces(and then appending it to the faces list) two times, one from the start and another until the end because
#the program wasnt making the last two faces if we only went throught them once so we decided to fix that problem
#by making it append the faces twice staring from different point and it fixes the problem
else:
faces.append(Vector3(int(face[0][:face[0].find("/")]), int(face[1][:face[1].find("/")]), int(face[2][:face[2].find("/")])))
#for each
if len(face) > 3:
faces.append(Vector3(int(face[1][:face[1].find("/")]), int(face[2][:face[2].find("/")]), int(face[3][:face[3].find("/")])))
# closes the files that was being read
f.close()
except IOError:
print(".obj/json file not found.")
#create triangles from the faces and vertices given by the files
for face in faces:
Mesh.create_tri(vertices[face.x -1], vertices[face.y -1], vertices[face.z -1], mesh)
return mesh
''' function to create a n-sided pyramid'''
@staticmethod
#defining sides, radius and height of pyramid
def create_pyramid(numSides=6, radius=1, height=1, mesh=None):
#if theres no mesh create one
if mesh is None:
mesh = Mesh("UnknownPyramid")
#creates vertices clean list
vertices = []
# for each side of the pyramid append the needed vertices
for j in range(numSides):
vertices.append(Vector3(radius * numpy.cos(j *(2 * numpy.pi / numSides)), -1, radius * numpy.sin(j*(2 * numpy.pi / numSides))))
#initialize i variable
i = 0
#for each vertice
for vertex in vertices:
#if it isnt the first vertice
if i >=1:
#creat the triangles from the given vertice
Mesh.create_tri(vertices[i-1], Vector3(0, height, 0), vertex, mesh)
Mesh.create_tri(vertices[i-1], Vector3(0, -1, 0), vertex, mesh)
i = i + 1
#if its the first vertice
#create the triangles from the given vertices
Mesh.create_tri(vertices[numSides-1], Vector3(0, height, 0), vertices[0], mesh)
Mesh.create_tri(vertices[numSides-1], Vector3(0, -1, 0), vertices[0], mesh)
#return the function
return mesh
@staticmethod
def create_cube(size, mesh=None):
"""
Adds the 6 polygons necessary to form a cube with the given size. If a source mesh is
not given, a new mesh is created.
This cube will be centered on the origin (0,0,0).
Arguments:
size {3-tuple} -- (x,y,z) size of the cube
mesh {Mesh} -- Mesh to add the polygons. If not given, create a new mesh
Returns:
{Mesh} - Mesh where the polygons were added
"""
# Create mesh if one was not given
if mesh is None:
mesh = Mesh("UnknownCube")
# Add the 6 quads that create a cube
Mesh.create_quad(Vector3(size[0] * 0.5, 0, 0),
Vector3(0, -size[1] * 0.5, 0),
Vector3(0, 0, size[2] * 0.5), mesh)
Mesh.create_quad(Vector3(-size[0] * 0.5, 0, 0),
Vector3(0, size[1] * 0.5, 0),
Vector3(0, 0, size[2] * 0.5), mesh)
Mesh.create_quad(Vector3(0, size[1] * 0.5, 0),
Vector3(size[0] * 0.5, 0),
Vector3(0, 0, size[2] * 0.5), mesh)
Mesh.create_quad(Vector3(0, -size[1] * 0.5, 0),
Vector3(-size[0] * 0.5, 0),
Vector3(0, 0, size[2] * 0.5), mesh)
Mesh.create_quad(Vector3(0, 0, size[2] * 0.5),
Vector3(-size[0] * 0.5, 0),
Vector3(0, size[1] * 0.5, 0), mesh)
Mesh.create_quad(Vector3(0, 0, -size[2] * 0.5),
Vector3(size[0] * 0.5, 0),
Vector3(0, size[1] * 0.5, 0), mesh)
return mesh
@staticmethod
def create_sphere(size, res_lat, res_lon, mesh=None):
"""
Adds the polygons necessary to form a sphere with the given size and resolution.
If a source mesh is not given, a new mesh is created.
This sphere will be centered on the origin (0,0,0).
Arguments:
size {3-tuple} -- (x,y,z) size of the sphere
or
size {number} -- radius of the sphere
res_lat {int} -- Number of subdivisions in the latitude axis
res_lon {int} -- Number of subdivisions in the longitudinal axis
mesh {Mesh} -- Mesh to add the polygons. If not given, create a new mesh
Returns:
{Mesh} - Mesh where the polygons were added
"""
# Create mesh if one was not given
if mesh is None:
mesh = Mesh("UnknownSphere")
# Compute half-size
if isinstance(size, Vector3):
hs = size * 0.5
else:
hs = Vector3(size[0], size[1], size[2]) * 0.5
# Sphere is going to be composed by quads in most of the surface, but triangles near the
# poles, so compute the bottom and top vertex
bottom_vertex = Vector3(0, -hs.y, 0)
top_vertex = Vector3(0, hs.y, 0)
lat_inc = math.pi / res_lat
lon_inc = math.pi * 2 / res_lon
# First row of triangles
lat = -math.pi / 2
lon = 0
y = hs.y * math.sin(lat + lat_inc)
c = math.cos(lat + lat_inc)
for _ in range(0, res_lon):
p1 = Vector3(c * math.cos(lon) * hs.x, y, c * math.sin(lon) * hs.z)
p2 = Vector3(c * math.cos(lon + lon_inc) * hs.x, y, c * math.sin(lon + lon_inc) * hs.z)
Mesh.create_tri(bottom_vertex, p1, p2, mesh)
lon += lon_inc
# Quads in the middle
for _ in range(1, res_lat - 1):
lat += lat_inc
y1 = hs.y * math.sin(lat)
y2 = hs.y * math.sin(lat + lat_inc)
c1 = math.cos(lat)
c2 = math.cos(lat + lat_inc)
lon = 0
for _ in range(0, res_lon):
p1 = Vector3(c1 * math.cos(lon) * hs.x,
y1,
c1 * math.sin(lon) * hs.z)
p2 = Vector3(c1 * math.cos(lon + lon_inc) * hs.x,
y1,
c1 * math.sin(lon + lon_inc) * hs.z)
p3 = Vector3(c2 * math.cos(lon) * hs.x,
y2,
c2 * math.sin(lon) * hs.z)
p4 = Vector3(c2 * math.cos(lon + lon_inc) * hs.x,
y2,
c2 * math.sin(lon + lon_inc) * hs.z)
poly = []
poly.append(p1)
poly.append(p2)
poly.append(p4)
poly.append(p3)
mesh.polygons.append(poly)
lon += lon_inc
# Last row of triangles
lat += lat_inc
y = hs.y * math.sin(lat)
c = math.cos(lat)
for _ in range(0, res_lon):
p1 = Vector3(c * math.cos(lon) * hs.x, y, c * math.sin(lon) * hs.z)
p2 = Vector3(c * math.cos(lon + lon_inc) * hs.x, y, c * math.sin(lon + lon_inc) * hs.z)
Mesh.create_tri(top_vertex, p1, p2, mesh)
lon += lon_inc
return mesh
@staticmethod
def create_quad(origin, axis0, axis1, mesh):
"""
Adds the vertices necessary to create a quad (4 sided coplanar rectangle).
If a source mesh is not given, a new mesh is created.
Arguments:
origin {Vector3} -- Center of the quad
axis0 {Vector3} -- One of the axis of the quad. This is not normalized, since the
length specifies half the length of that side along that axis
axis1 {Vector3} -- One of the axis of the quad. This is not normalized, since the
length specifies half the length of that side along that axis
mesh {Mesh} -- Mesh to add the polygons. If not given, create a new mesh
Returns:
{Mesh} - Mesh where the polygons were added
"""
if mesh is None:
mesh = Mesh("UnknownQuad")
poly = []
poly.append(origin + axis0 + axis1)
poly.append(origin + axis0 - axis1)
poly.append(origin - axis0 - axis1)
poly.append(origin - axis0 + axis1)
mesh.polygons.append(poly)
return mesh
@staticmethod
def create_tri(p1, p2, p3, mesh):
"""
Adds the vertices necessary to create a triangle
If a source mesh is not given, a new mesh is created.
Arguments:
p1 {Vector3} -- First vertex of the triangle
p2 {Vector3} -- Second vertex of the triangle
p3 {Vector3} -- Third vertex of the triangle
mesh {Mesh} -- Mesh to add the polygons. If not given, create a new mesh
Returns:
{Mesh} - Mesh where the polygons were added
"""
if mesh is None:
mesh = Mesh("UnknownQuad")
poly = []
poly.append(p1)
poly.append(p2)
poly.append(p3)
mesh.polygons.append(poly)
return mesh
|
9d3e30b2db1ea9ecdeb7a4dcfce7173b5c556ac6 | vitorln/AntSystens-Threads | /Cidades.py | 2,018 | 3.765625 | 4 | # -*- coding: utf-8 -*
import math
class Cidades:
def __init__(self): #construtos de Cidades
self.cidades = [] #vetor com todas as cidades
self.matriz_dist = [] #matriz com as distancias emtre as cidades
self.matriz_feromonios = [] #matriz com os feromonios entre as cidades
def setCidades(self, x, y): #adciona uma nova cidade no vertor de cidades
self.cidades.append((x, y)) #cada cidade tem uma tupla com as coordenadas X e Y
def printCidades(self): #printa vetor de cidades
print(self.cidades)
def printMatrizDistancia(self): #printa vetor de cidades
print(self.matriz_dist)
def printMatrizFeromonios(self): #printa vetor de cidades
print(self.matriz_feromonios)
def geraMatrizes(self): #calcula a distancia euclidiana entre cada cidade e iniciliza os feromonios com 1
qtd = len(self.cidades)
for i in range(qtd):
aux, aux2 = [], []
for j in range(qtd):
aux.append(math.sqrt((self.cidades[i][0] - self.cidades[j][0])**2 + (self.cidades[i][1] - self.cidades[j][1])**2))
aux2.append(1)
self.matriz_dist.append(aux)
self.matriz_feromonios.append(aux2)
def getSize(self): #retorna a quantidade de cidades
return len(self.cidades)
def getDistancia(self, x, y): #retorna a distancia entre a as cidades X e Y
return self.matriz_dist[x][y]
def getFeromonio(self, x, y): #retorna os feromonios entre a cidade X e Y
return self.matriz_feromonios[x][y]
def evaporaFeromnonio(self):
qtd = len(self.cidades)
for x in range(qtd):
for y in range(qtd):
self.matriz_feromonios[x][y]=((1-0.6)*self.matriz_feromonios[x][y])
def depositaFeromnonio(self, x, y, valor):
self.matriz_feromonios[x][y]+=valor
self.matriz_feromonios[y][x]+=valor
|
9ede0c1c3501c7d6d739dcd597763589a43c0b26 | tsodapop/UIC_Courses | /CS401/Project/CS401_Project_jtso2.py | 2,635 | 3.609375 | 4 | projdata1 = open("Projdata1.txt","r")
contents = projdata1.readlines()
votes = []
region = []
for row in contents:
rowline = row.split(" ")
votes.append(rowline[0])
region.append(rowline[1])
for row in new_content:
rowline = row.split(" ")
votes.append(rowline[0])
region.append(rowline[1])
votes_int = []
for row in votes:
votes_int.append(int(row))
memoization = {} #the dictionary that we will use to store already saved values
smallest_subset_size = 0
min_subsets = 0
def num_of_subsets(data, desired_total):
num_subsets = recursive_call(data, desired_total, len(data)-1, memoization, smallest_subset_size)
if (num_subsets == 0):
print("Not Feasible")
else:
print("Found subsets.")
print("Number of subsets that sum to total", desired_total, " is ", num_subsets)
print("Smallest subset size is", smallest_subset_size)
print("Num of distinct smallest subsets is", min_subsets)
def recursive_call(data, desired_total, i, memoization, smallest_subset):
#we store to reduce runtime by not needing recursion
key = str(desired_total) + "-" + str(i)
if (key in memoization):
return memoization[key]
#the actual recursion
if (desired_total == 0): #the empty set is technically a total of 0
global min_subsets
min_subsets= min_subsets + 1
calculate_smallest_subset(smallest_subset_size, smallest_subset)
return 1
elif (desired_total < 0): #can't possibly have negatives in votes
return 0
elif (i < 0): #we've reached the end of the data list
return 0
elif (desired_total < data[i]): #we move on to the next one since data[i] is larger than our desired_total
to_memoize = recursive_call(data, desired_total, i-1, memoization, smallest_subset)
else: #it is possibly in either tree branch, so we look at both of them
to_memoize = (recursive_call(data, desired_total, i-1, memoization,smallest_subset)
+
recursive_call(data, desired_total - data[i], i-1, memoization,smallest_subset+1))
memoization[key] = to_memoize
return to_memoize
def calculate_smallest_subset(curr_size, smallest_subset):
global smallest_subset_size
if (smallest_subset <= 0):
return
elif ((curr_size != 0) & (curr_size < smallest_subset)):
return
else:
smallest_subset_size = smallest_subset
num_of_subsets(votes_int, 9) |
c26768f28c2d90a790b39a5814c0b1bb41d1a9e2 | JohnNurthen/cp1404practicals2020 | /cp1404practicals2020/prac_04/quick_picks.py | 580 | 3.953125 | 4 | import random
NUMBERS_PER_LINE = 6
MIN = 1
MAX = 25
def main():
quick_picks = int(input("How many quick picks would you like?: "))
while quick_picks <= 0:
print("Please enter a valid number: ")
quick_picks = int(input("How many quick picks would you like?: "))
for i in range(quick_picks):
numbers = []
for j in range(NUMBERS_PER_LINE):
number = random.randint(MIN,MAX)
while number in numbers:
number = random.randint(MIN,MAX)
numbers.append(number)
print(numbers)
main()
|
51d569a192de7b5cbf0ea5e042981511661183e4 | Tanmay53/cohort_3 | /submissions/sm_015_lalit/week_13/day_4/session_1/count_occurances_string.py | 189 | 3.5625 | 4 | inputX=input("Provide a string here : ")
dictX={}
for i in inputX:
if i in dictX:
dictX[i]=dictX[i]+1
else:
dictX[i]=1
for k,v in dictX.items():
print(k,v)
|
e3af8f8ba177a843f5d8720f9d282205986ec2e0 | UKVeteran/Adventures-in-Python | /Adventure 3/2/password.py | 579 | 3.625 | 4 | import tkinter as tk
window = tk.Tk()
def checkPassword():
password = "Oranges"
enteredPassword = passwordEntry.get()
if password == enteredPassword:
confirmLabel.config(text="Correct")
else:
confirmLabel.config(text="Incorrect")
passwordLabel = tk.Label(window, text="Password:")
passwordEntry = tk.Entry(window, show="*")
button = tk.Button(window, text="Enter", command=checkPassword)
confirmLabel = tk.Label(window)
passwordLabel.pack()
passwordEntry.pack()
button.pack()
confirmLabel.pack()
window.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.