blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
2b57053ce8d80b2bccea2037613a8b03bac2eaf2 | daniela-mejia/Python-Net-idf19- | /Python2/1.py | 285 | 4.25 | 4 | #! /usr/bin/env python3
def main():
argument = float(input("Enter a value to be multiplied by 10: "))
times_ten(argument)
def times_ten(num):
product = num * 10
print("The Output is", product)
show_value(12)
def show_value(quantity):
print(quantity)
main() |
c7deb48e1949208a6d13ce36e0e3bcc6fd4b3f7f | kylapurcell/A01088856_1510_assignments | /A2/test_choose_inventory.py | 1,423 | 3.609375 | 4 | from unittest import TestCase
from A2 import dungeonsanddragons
import random
class TestChooseInventory(TestCase):
def test_choose_inventory(self):
self.assertEqual([], dungeonsanddragons.choose_inventory([], 0)) # Tests that 0 as selection
# returns empty list
def test_choose_inventory2(self):
self.assertIsNone(dungeonsanddragons.choose_inventory([1, 2], -1)) # Tests that negative selection is None
def test_choose_inventory3(self):
self.assertIsNone(dungeonsanddragons.choose_inventory([1, 2, 3], 4)) # Tests that selection
# greater than list index is None
def test_choose_inventory4(self):
self.assertEqual([1, 2, 3], dungeonsanddragons.choose_inventory([1, 2, 3], 3)) # Tests selection =list length,
# output will return copy
def test_choose_inventory5(self):
self.assertEqual(2, len(dungeonsanddragons.choose_inventory([1, 2, 3, 4], 2)))
# Tests that length of list = selection
def test_choose_inventory6(self):
self.assertEqual(list, type(dungeonsanddragons.choose_inventory([1, 2], 2)))
# Tests that output is of type list
def test_choose_inventory7(self): # Tests random output
random.seed(3)
self.assertEqual(['Ring', 'Staff'], dungeonsanddragons.choose_inventory(['Ring', 'Staff', 'Scroll'], 2))
random.seed()
|
5cf43c44ed701e3c2ba5b1da8c80c428e0c8f92a | SpencerHarper/python | /csvScrapeExample.py | 3,711 | 3.75 | 4 | #!/usr/bin/env python3
'''This module contains functions for web scraping off KEGG pages'''
import pandas as pd
import urllib.request
import re
def kegg_gene_scraper(myfile,baseurl,output_file):
'''This is a script for scraping gene symbols and gene Entrez ids from KEGG pathway web pages.
Input is a csv file (myfile) with at least two columns. One column has the KEGG Ids for pathways ("KEGG ID")
while the other ('Pathway Name') has corresponding pathway names. Base url is url without the pathway variable part.
(e.g. http://www.genome.jp/dbget-bin/www_bget?pathway+mmu for mouse pathways). The code does webscraping
and retrieves gene lists (Entrez Ids, and Gene symbols) for all pathways (here, 45 pathways)
listed in the input file. It then writes the genes lists per pathway as separate .csv files to a
specified local disk (output_file)'''
# Read in the data
mydata = pd.read_csv(myfile)
assert myfile.endswith(".csv")
url_base = baseurl
x = 0
row_index = 0
Pathway = ""
# Get kegg ids and pathway names form the csv file
num_of_pathways = mydata.shape[0]
for i in range (0,num_of_pathways):
x = mydata['KEGG ID'][row_index]
pathway = mydata['Pathway Name'][row_index]
x = str(x)
if len(x) == 2:
x = "000"+x
elif len(x) == 3:
x = "00"+x
row_index = row_index+1
#Access the webpage using urllib, and scrape pages using python re module. Since in ome cases gene ids may not have
#corresponding gene symbols, we will use only those (with the if statement) where we have both'''
full_url = url_base+x
web_page = urllib.request.urlopen(full_url)
my_webpage_data = str(web_page.read())
pattern_list = re.findall("mmu:(\d+)",my_webpage_data)
pattern_list_2 = re.findall("<div>(\w+\s*\w*);\s",my_webpage_data)
if len(pattern_list) == len(pattern_list_2):
mydataframe = pd.DataFrame()
mydataframe['Entrez Id'] = pattern_list
mydataframe['Gene symbol'] = pattern_list_2
pathway = pathway.replace("/","")
mydataframe.to_csv(output_file+"/"+pathway +".csv",index = False)
print("KEGG scraping in progress")
full_url = ""
return "KEGG Scraping complete"
def kegg_image_scraper(url_list,output_file):
'''Given a list of kegg pathway urls (.txt file, "url_list"),scrapes the colored pathway image from the
webpage, writes it to aspecified folder. This function was originally written to retrieve
PathWave diagrams (metabolic analysis)'''
# Read in url list file
url_file = open(url_list,"r")
assert url_list.endswith(".txt")
# Web Scraping for images
local_url_file = url_file.read()
url = re.findall("http.+",local_url_file)
x = 1
for i in url:
x = str(x)
resp = urllib.request.urlopen(i)
respdata = resp.read()
respdata = str(respdata)
image_url_part2 = re.findall("/tmp/mark_pathway.+png",respdata)
image_url_part2 = image_url_part2[0]
image_url_part1 = "http://www.kegg.jp"
full_image_url = image_url_part1 + image_url_part2
part_of_outfile_name = re.findall("DEFINITION\s+(\w+\s\w+)",respdata)
if part_of_outfile_name:
urllib.request.urlretrieve(full_image_url,output_file+"/"+part_of_outfile_name[0]+".png") ##Specify target path
else:
urllib.request.urlretrieve(full_image_url,output_file+"/"+x+".png")
x = int(x)
x = x+1
return "KEGG image scraping complete"
|
ef42dd924e9c256661b893c8c1341898d734ebd2 | sankaranarayanankj/python | /linkedlistatdiffposition.py | 931 | 4.25 | 4 | class Node:
def __init__(self,node):
self.node=node
self.next=None
class List:
def __init__(self):
self.head=None
def display(self):
node1=self.head
while(node1):
print(node1.node)
node1=node1.next
list1=List()
#Insert at node to the linked list
list1.head=Node(1)
list2=Node(2)
list1.head.next=list2
list3=Node(3)
list2.next=list3
list4=Node(5)
list3.next=list4
#Insert the node at beginning of the list
list5=Node(8)
list5.next=list1.head
list1.head=list5
#Insert the node at middle of the list
list6=Node(89)
list2.next=list6
list6.next=list3
#Insert the node at the end of the list
list7=Node(90)
list4.next=list7
list1.display()
#Delete the node at beginning of the list
list1.head=list2
#Delete the node at Middle of the list
list2.next=list4
#Delete the node at the last of the list
list4.next=None
|
d1bccefd640bad658f94e076a6d6aef7078a94f6 | parlovich/hashcode | /2019/pizza/pizza.py | 8,041 | 3.5625 | 4 | #! /usr/bin/python
import sys
import copy
M_INT = 1
T_INT = 2
class SliceType:
BIG = "big"
SMALL = "small"
GOOD = "good"
class PizzaSlicer:
def __init__(self, pizza, L, H):
self.pizza = copy.deepcopy(pizza)
self.R = len(pizza)
self.C = len(pizza[0])
self.L = L
self.H = H
@staticmethod
def _slice_size(slice):
R, C = slice[0], slice[1]
return (abs(R[0] - R[1]) + 1) * (abs(C[0] - C[1]) + 1)
def _check_slice_type(self, slice):
if self._slice_size(slice) > self.H:
return SliceType.BIG
T, M = 0, 0
R, C = slice[0], slice[1]
for i in range(R[0], R[1] + 1):
for j in range(C[0], C[1] + 1):
if self.pizza[i][j] == M_INT:
M += 1
elif self.pizza[i][j] == T_INT:
T += 1
else:
return SliceType.BIG
if T >= self.L and M >= self.L:
return SliceType.GOOD
return SliceType.GOOD if T >= self.L and M >= self.L \
else SliceType.SMALL
def _cut_slice(self, cur_slice):
state = self._check_slice_type(cur_slice)
if state == SliceType.BIG:
return None
if state == SliceType.GOOD:
return cur_slice
# Try to grow slice
R, C = cur_slice[0], cur_slice[1]
cur_slice = None
cur_size = 0
# right
if C[1] < self.C - 1:
next_slice = self._cut_slice((R, (C[0], C[1] + 1)))
if next_slice:
next_size = self._slice_size(next_slice)
if not cur_slice or next_size > cur_size:
cur_slice = next_slice
cur_size = next_size
# down
if R[1] < self.R - 1:
next_slice = self._cut_slice(((R[0], R[1] + 1), C))
if next_slice:
next_size = self._slice_size(next_slice)
if not cur_slice or next_size > cur_size:
cur_slice = next_slice
cur_size = next_size
# left
# if C[0] > 0:
# next_slice = self._cut_slice((R, (C[0] - 1, C[1])))
# if next_slice:
# next_size = self._slice_size(next_slice)
# if not cur_slice or next_size > cur_size:
# cur_slice = next_slice
# cur_size = next_size
# # up
# if R[0] > 0:
# next_slice = self._cut_slice(((R[0] - 1, R[1]), C))
# if next_slice:
# next_size = self._slice_size(next_slice)
# if not cur_slice or next_size > cur_size:
# cur_slice = next_slice
# cur_size = next_size
return cur_slice
def _extend_slice(self, orig_slice, new_slice=None):
if new_slice:
# check if candidate slice is validity
if self._slice_size(new_slice) > self.H:
return None
for i in range(new_slice[0][0], new_slice[0][1] + 1):
for j in range(new_slice[1][0], new_slice[1][1] + 1):
if (i < orig_slice[0][0] or i > orig_slice[0][1] or
j < orig_slice[1][0] or j > orig_slice[1][1]) and \
self.pizza[i][j] == 0:
return None
cur_slice = new_slice
else:
cur_slice = orig_slice
cur_size = self._slice_size(cur_slice)
# go down
if cur_slice[0][1] < self.R - 1:
next_slice = self._extend_slice(orig_slice, ((cur_slice[0][0], cur_slice[0][1] + 1), cur_slice[1]))
if next_slice:
next_size = self._slice_size(next_slice)
if next_size > cur_size:
cur_slice = next_slice
cur_size = next_size
# go right
if cur_slice[1][1] < self.C - 1:
next_slice = self._extend_slice(orig_slice, (cur_slice[0], (cur_slice[1][0], cur_slice[1][1] + 1)))
if next_slice:
next_size = self._slice_size(next_slice)
if next_size > cur_size:
cur_slice = next_slice
cur_size = next_size
# go up
if cur_slice[0][0] > 0:
next_slice = self._extend_slice(orig_slice, ((cur_slice[0][0] - 1, cur_slice[0][1]), cur_slice[1]))
if next_slice:
next_size = self._slice_size(next_slice)
if next_size > cur_size:
cur_slice = next_slice
cur_size = next_size
# go left
if cur_slice[1][0] > 0:
next_slice = self._extend_slice(orig_slice, (cur_slice[0], (cur_slice[1][0] - 1, cur_slice[1][1])))
if next_slice:
next_size = self._slice_size(next_slice)
if next_size > cur_size:
cur_slice = next_slice
cur_size = next_size
self._fill_in_slice_area(cur_slice)
return cur_slice
def _fill_in_slice_area(self, slice):
R, C = slice[0], slice[1]
for i in range(R[0], R[1] + 1):
for j in range(C[0], C[1] + 1):
self.pizza[i][j] = 0
def cut(self):
slices = []
# Cut Small slices
for r in range(0, self.R):
for c in range(0, self.C):
if self.pizza[r][c] != 0:
slice = self._cut_slice(((r, r), (c, c)))
if slice:
slices.append(slice)
self._fill_in_slice_area(slice)
# extend slices
if slices:
for i in range(0, len(slices)):
slices[i] = self._extend_slice(slices[i])
self._fill_in_slice_area(slices[i])
return slices
def read_input_data(file_name):
with open(file_name, "r") as f:
(R, C, L, H) = [int(c) for c in f.readline().split()]
pizza = []
for i in range(0, R):
pizza.append([T_INT if c == 'T' else M_INT for c in f.readline().strip()])
return pizza, L, H
def print_slices(slices, file_out):
with open(file_out, "w") as f:
f.write("%d\n" % len(slices))
for s in slices:
f.write("%d %d %d %d\n" % (s[0][0], s[1][0], s[0][1], s[1][1]))
def check_slices_calc_score(pizza, slices, L, H):
tmp_pizza = copy.deepcopy(pizza)
score = 0
for slice in slices:
T, M, size = 0, 0, 0
for i in range(slice[0][0], slice[0][1] + 1):
for j in range(slice[1][0], slice[1][1] + 1):
score += 1
size += 1
val = tmp_pizza[i][j]
if val == 0:
raise RuntimeError("slices overlap")
elif val == T_INT:
T += 1
elif val == M_INT:
M += 1
tmp_pizza[i][j] = 0
if size > H:
raise RuntimeError("slice is to big: slice %s, size: %d" % (slice, size))
if T < L:
raise RuntimeError("Too few tomatoes: slice %s" % slice)
if M < L:
raise RuntimeError("Too few mushrooms: slice %s" % slice)
return score
def main(in_file, out_file):
(pizza, L, H) = read_input_data(in_file)
slicer = PizzaSlicer(pizza, L, H)
slices = slicer.cut()
score = check_slices_calc_score(pizza, slices, L, H)
print "%s Score: %d" % (in_file, score)
print_slices(slices, out_file)
return score
if __name__ == "__main__":
score = 0
files = {
"a_example.in": "a_example.out",
"b_small.in": "b_small.out",
"c_medium.in": "c_medium.out",
"d_big.in": "d_big.out"
}
for f_in, f_out in files.items():
score += main(f_in, f_out)
print "Total: %d" % score
# if len(sys.argv) < 2:
# print "No file name"
# else:
# main(sys.argv[1])
|
44d6b59e154d8641d0657ad1891722cf90600754 | jvm269/Python-Challenge | /PyPoll/main.py | 2,326 | 3.734375 | 4 | #import modules
import os
import csv
#output file
output_path="/Users/jihanmckenzie/Desktop/Python-Challenge/PyPoll/PyPoll.txt"
#input path
election_data = os.path.join("election_data.csv")
# list for candidates`
candidates = []
# list for number of votes each candidate receives
num_votes = []
# list for votes each candidate garners
percent_votes = []
# total number of votes
total_votes = 0
with open(election_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csv_header = next(csvreader)
for row in csvreader:
# Add to our vote-counter
total_votes += 1
# If candidate is NOT on list, add name to list, along with vote added to total
# If on our list, add a vote to their name
if row[2] not in candidates:
candidates.append(row[2])
index = candidates.index(row[2])
num_votes.append(1)
else:
index = candidates.index(row[2])
num_votes[index] += 1
# Add to percent_votes list
for votes in num_votes:
percentage = (votes/total_votes) * 100
percentage = round(percentage)
percentage = "%.3f%%" % percentage
percent_votes.append(percentage)
# Find the winning candidate
winner = max(num_votes)
index = num_votes.index(winner)
winning_candidate = candidates[index]
#print results
print("Election Results")
print("--------------------------")
print(f"Total Votes: {str(total_votes)}")
print("--------------------------")
for i in range(len(candidates)):
print(f"{candidates[i]}: {str(percent_votes[i])} ({str(num_votes[i])})")
print("--------------------------")
print(f"Winner: {winning_candidate}")
print("--------------------------")
#open write file
with open(output_path, 'w', newline='') as pypfile:
writer= csv.writer(pypfile, delimiter=' ', escapechar=" " , quoting= csv.QUOTE_NONE)
#print analysis to file
writer.writerow("--------------------------")
writer.writerow(f"Total Votes: {total_votes}")
writer.writerow(f"Khan: 63%")
writer.writerow(f"Correy: 20%")
writer.writerow(f"Li: 14%")
writer.writerow(f"O'Tooley: 3%")
writer.writerow("---------------------------")
writer.writerow(f"Winner: {winning_candidate}")
writer.writerow("---------------------------")
|
bb9527a0b6eafa8ee233ca7832881b06d8ab7535 | jorzel/codefights | /arcade/python/checkPassword.py | 1,136 | 3.640625 | 4 | """
Medium
Recovery
100
Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.
You're implementing a web application. Like most applications, yours also has the authorization function. Now you need to implement a server function that will check password attempts made by users. Since you expect heavy loads, the function should be able to accept a bunch of requests that will be sent simultaneously.
In order to validate your function, you want to test it locally. Given a list of attempts and the correct password, return the 1-based index of the first correct attempt, or -1 if there were none.
Example
For attempts = ["hello", "world", "I", "like", "coding"] and
password = "like", the output should be
checkPassword(attempts, password) = 4.
"""
def checkPassword(attempts, password):
def check():
while True:
_password = yield
yield True if _password == password else False
checker = check()
for i, attempt in enumerate(attempts):
next(checker)
if checker.send(attempt):
return i + 1
return -1
|
3b932f16b7ab0f9afefb4df7dd1e23167cfe67e2 | fengxiaolong886/leetcode | /1544整理字符串.py | 1,000 | 3.90625 | 4 | """
给你一个由大小写英文字母组成的字符串 s 。
一个整理好的字符串中,两个相邻字符 s[i] 和 s[i+1],其中 0<= i <= s.length-2 ,要满足如下条件:
若 s[i] 是小写字符,则 s[i+1] 不可以是相同的大写字符。
若 s[i] 是大写字符,则 s[i+1] 不可以是相同的小写字符。
请你将字符串整理好,每次你都可以从字符串中选出满足上述条件的 两个相邻 字符并删除,直到字符串整理好为止。
请返回整理好的 字符串 。题目保证在给出的约束条件下,测试样例对应的答案是唯一的。
注意:空字符串也属于整理好的字符串,尽管其中没有任何字符。
"""
def makeGood(s):
res = []
for i in s:
if res and res[-1].lower() == i.lower() and res[-1] != i:
res.pop()
else:
res.append(i)
return "".join(res)
print(makeGood(s = "leEeetcode"))
print(makeGood(s = "abBAcC"))
print(makeGood(s = "s"))
|
84998e8797eac44ac87438d5ba0c7cb6bd491eb4 | projeto-de-algoritmos/D-C_Dupla10B | /merge.py | 1,771 | 3.859375 | 4 | count = 0
tam = 0
def mergeSort(arr):
global count, tam
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
if count == 0:
tam = len(arr)
print('Divide-se o array:', L, R)
count += 1
mergeSort(L)
mergeSort(R)
if count == tam - 1:
print('Ordena-se os sub-arrays:', L, R)
count += 1
i = j = k = 0
if count == tam:
print('Juntando e ordenando os sub-arrays:')
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
if count == tam:
print(arr[:i+j+1], '(Indíce {} do array Esquerdo)'.format(i))
i += 1
else:
arr[k] = R[j]
if(count == tam):
print(arr[:i+j+1], '(Indíce {} do array Direito)'.format(j))
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
if count == tam:
print(arr[:i+j], '(Indíce {} do array Esquerdo)'.format(i-1))
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
if(count == tam):
print(arr[:i+j], '(Indíce {} do array Direito)'.format(j-1))
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
from random import randint
size = randint(5,25)
if size%2 == 0:
size += 1
arr = [randint(0, 100) for x in range(0,size)]
print("", end="\n")
print('Array fornecido: {}'.format(arr))
mergeSort(arr)
print("Vetor ordenado é: ", end="")
printList(arr) |
07c2f4df4c0d97df93c7cbca628e8eed628a1d25 | wangzhankun/python-learn | /basic/code/test.py | 1,540 | 3.53125 | 4 | class Product():
def __init__(self,id,name,price,yieldly):
self.id = id
self.name = name
self.price = price
self.yieldly = yieldly
class Cart():
def __init__(self):
self.product = {}
self.products = []
self.total_price = 0
def buy_product(self,product,quantity):
self.product['name'] = product.name
self.product['quantity'] = quantity
self.product['price'] = product.price
self.products.append(self.product)
def delete_product(self,product,quantity):
if product in self.products[][name]:
if quantity >= self.products[product][quantity]:
self.products.remove[product]
else:
self.products[product][quantity] -= quantity
else:
pass
def cal_total_price(self):
for i in self.products:
self.total_price += self.products[product][quantity] * self.products[product][price]
return self.total_price
class Account():
def __init__(self):
self.username = ''
self.passwd = ''
self.cart = ''
def create_account(self,username,passwd):
self.username = username
self.passwd = passwd
self.cart = Cart()
def login(self,username,passwd):
if username != self.username:
print("Username Error!")
else:
if passwd != self.passwd:
print("Passwd Error!")
else:
print("Log In!")
|
7e18d5352cee0abcf38ef82447b2e3cdb23c24de | nfernando-io/speedreader | /Documents/Programming/python/Speedreader/speedreader.py | 1,743 | 3.78125 | 4 | #Speedreader program
#TODO LIST:
#Should either be able to upload text file or copy paste text
#Print a certain amount of words specified by user
#Make a gui
#Have a text box that you upload file
#A lightbox pops up and displays the text
#make previous words disappear
#Scan
import time
fileToScan = 'inputText1.txt' #input("Scan File: ")
speedOfDisplay = 1.0 #float(input("Enter word speed: "))
amountOfWords = 4 #int(input("Enter amount of words: "))
class Text_Scanner(object):
def __init__(self, fileToScan, speedOfDisplay, amountOfWords):
self.fileToScan = fileToScan
self.speedOfDisplay = speedOfDisplay
self.amountOfWords = amountOfWords
def scan_file(self):
# Places words in text file into a list
with open(fileToScan,'r') as readFile:
wordList = [ word for line in readFile for word in line.split()]
# Print words in certan range
position = 0
storedIdx = 0
while position < len(wordList):
for i in range(position, storedIdx):
position = i + 1
try:
print(wordList[i], end=" ")
except IndexError:
break
# Delays the time a word will appear
print(storedIdx)
time.sleep(speedOfDisplay)
if storedIdx > len(wordList):
storedIdx = len(wordList)
else:
storedIdx += amountOfWords
print(position) #REMOVE
print(wordList) #REMOVE
test = Text_Scanner(fileToScan, speedOfDisplay, amountOfWords)
test.scan_file()
|
62a442b0a2d85b599bbb3957110bff1ca0a048d1 | sonam2905/My-Projects | /Python/Exercise Problems/prefix_for_new_line.py | 621 | 3.734375 | 4 | import textwrap
sample_text = '''
Python is an interpreted, high-level and general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
'''
text_without_Indentation = textwrap.dedent(sample_text)
wrapped = textwrap.fill(text_without_Indentation, width=50)
#wrapped += '\n\nSecond paragraph after a blank line.'
final_result = textwrap.indent(wrapped, '> ')
print()
print(final_result)
print()
|
dfd365abbeb80796a76a7811d97d9b8467592d97 | Itseno/PythonCode | /1st.py | 293 | 4.21875 | 4 | total = 0.0
number1=float(input("Enter the first number: "))
total = total + number1
number2=float(input("Enter the second number: "))
total = total + number2
number3=float(input("Enter the third number: "))
total = total + number3
average = total / 3
print ("The average is " + str(average))
|
6e1628b86f2cf97483fb07cee92a0510d1a96d07 | abdiassantos/estudosPython | /djangoPython/python/tipos_de_dados.py | 1,722 | 4.25 | 4 | ##LISTAS
lista = []
print(type(lista))
lista.append("Python")
lista.append("Java")
lista.append("Javascript")
lista.append("PHP")
print(lista)
#Inverte os dados da lista.
lista.reverse()
print(lista)
##Insere no local indicado e move para a direita todos os outros termos da lista.
lista.insert(0, "Android")
print(lista)
##Remove o último elemento da lista e retorna ele.
lista.pop()
print(lista)
##Conta a ocorrência de um determinado objeto da lista.
print(lista.count("Python"))
##Remove um determinado elemento da lista.
lista.remove("PHP")
print(lista)
##Adicionando outros tipos de dados a uma lista Str.
lista2 = []
lista.append(lista2)
lista2.append(1)
lista2.append(2)
lista.append(3)
lista.append(11)
print(lista)
##------------------------------------
##TUPLAS
tupla = ("Python", "Java", "Android", 12, [1, 2, 3], (1, 2))
print(type(tupla))
print(tupla[5])
##Contar a ocorrência de um objeto dentro da tupla.
print(tupla.count("Python"))
##Adicionar valor a uma lista que existe dentro da tupla.
tupla[4].append(4)
print(tupla)
##------------------------------------
##DICIONÁRIOS
##Criando Dicionário e gerando a chave e o valor para cada chave.
dic = {"chave1": "valor1", 2: "valor2", (1, 2): "valor3"}
##Retorna o tipo da estrutura de dados.
print(type(dic))
##Retorna todos os métodos que podemos utilizar junto ao tipo de dados.
print(dir(dic))
##Retorna todos os itens com suas chaves e valores.
print(dic.items())
##Retorna todas as chaves do dicionário.
print(dic.keys())
##Remove o valor determinado pela chave.
dic.pop("chave1")
print(dic)
##Remove o valor do último item do nosso dicionário.
dic.popitem()
print(dic)
##Limpa todo o dicionário.
dic.clear()
print(dic) |
79e1b626df68a5d7ab44f049372f0cf6fc343c58 | BenMtl/python-csv | /python-merge-multiple-csv-files-into-one-csv-file/merge-csv-files.py | 1,515 | 3.515625 | 4 | import csv
csv1_header = []
csv1_data = []
csv2_header = []
csv2_data = []
with open('csv1.csv') as csv1:
reader = csv.reader(csv1)
csv1_header = next(reader, None)
with open('csv2.csv') as csv2:
reader = csv.reader(csv2)
csv2_header = next(reader, None)
#print(csv1_header)
#print(csv2_header)
set_1 = set(csv1_header)
set_2 = set(csv2_header)
list_2_items_not_in_list_1 = list(set_2 - set_1)
csv_header = list(csv1_header) + list_2_items_not_in_list_1
#print(csv_header)
with open('csv.csv', 'w') as csvfile:
fieldnames = csv_header
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
with open('csv1.csv') as csv1:
reader = csv.DictReader(csv1)
for row in reader:
#writer.writerow({'NAME': row['NAME'], 'MIDDLENAME': row['MIDDLENAME'], 'SURNAME': row['SURNAME'], 'AGE': row['AGE']})
writer.writerow({fieldnames[0]: row[fieldnames[0]], fieldnames[1]: row[fieldnames[1]], fieldnames[2]: row[fieldnames[2]], fieldnames[3]: row[fieldnames[3]]})
with open('csv2.csv') as csv2:
reader = csv.DictReader(csv2)
for row in reader:
#writer.writerow({'NAME': row['NAME'], 'MIDDLENAME': row['MIDDLENAME'], 'SURNAME': row['SURNAME'], 'AGE': row['AGE'], 'EMAIL': row['EMAIL']})
writer.writerow({fieldnames[0]: row[fieldnames[0]], fieldnames[1]: row[fieldnames[1]], fieldnames[2]: row[fieldnames[2]], fieldnames[3]: row[fieldnames[3]], fieldnames[4]: row[fieldnames[4]]}) |
17a916edc61a1740ccdda27f28255e891cbe9a8a | asd153866714/Data-structure | /python/09-sort/InsertSort02.py | 264 | 3.984375 | 4 | # InsertSort
def InsertSort(data):
for i in range(1, len(data)):
j = i - 1
while data[j] > data[j+1] and j >= 0:
data[j], data[j+1] = data[j+1], data[j]
j -= 1
return data
data = [5, 3, 2, 9]
print(InsertSort(data)) |
6790635f3e5466584c1537f49a791fe0c7ad3689 | bbuluttekin/MSc-Coursework | /PoPI/mock_two.py | 228 | 3.625 | 4 | def sqrProd(x, y):
return (x * y) ** 2
def power(a, n):
if n == 0:
return 1
else:
return power(a, n - 1) * a
if __name__ == "__main__":
assert sqrProd(2, 5) == 100
assert power(2, 3) == 8
|
3cb1b8121073a0b5bba382c99cf4873a58d9c39e | Indiana3/python_exercises | /wb_chapter5/exercise130.py | 1,633 | 4.34375 | 4 | ##
# Read, tokenize and mark the unary operators
# in a mathematical expression
#
from exercise129 import tokenGenerator
## Identify unary operators "+" and "-" in a list of tokens
# @param t a list of tokens
# @return a new list where unary operators have been replaced
# by "u+" and "u-" respectively
#
def unaryIdentifier(t):
# Create a new list to store tokens
mod_tokens = []
# For each element of the tokens list
i = 0
while i < len(t):
# Check if the element is "+" or "-"
if t[i] == "+" or t[i] == "-":
# Check if it's the first element of the list or
# if preceded by an operator or an open parenthesis
if i == 0 or t[i-1] == "(" or \
t[i-1] == "[" or t[i-1] == "{" or \
t[i-1] == "+" or t[i-1] == "-" or \
t[i-1] == "*" or t[i-1] == "/" or \
t[i-1] == "**":
# Mark the operator with "u" char
mod_token = "u" + t[i]
mod_tokens.append(mod_token)
i = i+1
continue
# If the last conditions are false, add
# the element without modifications
mod_tokens.append(t[i])
i = i+1
return mod_tokens
# Read a string from user, tokenize it and
# mark the unary operators
def main():
exp = input("Please enter a valid mathematical expression: ")
# Display the tokens list
tokens = tokenGenerator(exp)
# print(tokens)
# Display the tokens list with unary operators marked (if any)
print(unaryIdentifier(tokens))
# Call the main function
if __name__ == "__main__":
main()
|
c602ea5c64e8085349ed046158f934cdd0d0d0c4 | markus-seidl/pybutcherbackup | /backup/terminal/table.py | 1,136 | 3.609375 | 4 | import texttable
class TableColumn:
def __init__(self, name):
self.name = name
self.min_len = None
self.max_len = None
self.align = "l"
self.type = "t"
class Table:
def __init__(self, table_data: list, columns: [TableColumn]):
self.table_data = table_data
self.columns = columns
min_len = [10000] * len(self.columns)
max_len = [-1] * len(self.columns)
for td in self.table_data:
for i in range(len(self.columns)):
str_len = len(str(td[i]))
min_len[i] = min(min_len[i], str_len)
max_len[i] = max(max_len[i], str_len)
for i in range(len(self.columns)):
c = self.columns[i]
c.min_len = min_len[i]
c.max_len = max_len[i]
def print(self):
table = texttable.Texttable()
cols_align = list()
cols_type = list()
for c in self.columns:
cols_align.append(c.align)
cols_type.append(c.type)
for row in self.table_data:
table.add_row(row)
print(table.draw())
|
18b7c42caa3e46040d03444e2a5dfd8155eefee8 | argpass/coding_life | /ai/decision_tree/utils/tree_plot.py | 3,798 | 4.03125 | 4 | #!coding: utf-8
from matplotlib import pyplot as plt
class PLTNode(object):
def __init__(self, tag, area, depth, parent_x, arrow_text=None):
self.parent_x = parent_x
self.depth = depth
self.area = area
self.tag = tag
self.arrow_text = arrow_text
def show_tree(plot, tree):
""" Draw the tree on the plot
Examples:
{
"tag": "root",
"children": {
"yes": {"tag": "A"},
"no": {
"tag": "B",
"children": {"yes": {"tag": "B1"}, "no": {"tag": "B2"}}
}
}
}
root
/ \
yes no
/ \
A B
/ \
yes no
/ \
B1 B2
Args:
plot:
tree(dict):
Returns:
"""
if not tree:
return
area = (0, 1)
depth = 1
nodes = []
prt_x = (area[0] + area[1]) / 2.0
scan_nodes(nodes, '', tree, area, depth, prt_x)
nodes.sort(key=lambda x: x.depth, reverse=True)
max_depth_node = max(nodes, key=lambda x: x.depth)
max_depth = max_depth_node.depth
for node in nodes:
draw_node(plot, node, max_depth)
def draw_node(plot, node, max_depth):
"""Draw the node on a subplot
Args:
node(PLTNode):
Returns:
"""
# calculate x, y of the node text
area_l, area_r = node.area
x = float(area_l + area_r) / 2.0
y_l = 1.0 - 1.0 / max_depth * node.depth
y_h = 1.0 - 1.0 / max_depth * (node.depth - 1)
y = (y_h + y_l) / 2.0
# calculate the arrow start point x y, same with x y of parent's
p_x = node.parent_x
if node.depth > 1:
p_y_l = 1.0 - 1.0 / max_depth * (node.depth - 1)
p_y_h = 1.0 - 1.0 / max_depth * (node.depth - 2)
p_y = (p_y_h + p_y_l) / 2.0
else:
p_y = 1.0
sub = plot.subplot()
# draw the arrow and node text
sub.annotate(node.tag, (p_x, p_y), xytext=(x, y),
bbox=dict(boxstyle="circle", color='#FF6633'),
arrowprops=dict(arrowstyle="<-", color='g'),
va="center", ha="center")
# draw the arrow_text if necessary
if node.arrow_text is not None:
arrow_mid_x, arrow_mid_y = (p_x + x) / 2.0, (p_y + y) / 2.0
rotation = None
sub.text(arrow_mid_x, arrow_mid_y, node.arrow_text,
va="center", ha="center", rotation=rotation)
def scan_nodes(nodes, arrow_text, tree, area, depth, parent_x):
"""Scan tree dict to create `PLTNode` nodes list
Args:
nodes(list):
arrow_text(str):
tree(dict):
area(tuple):
depth(int):
parent_x(float):
Returns:
"""
tag = tree["tag"]
children = tree.get("children") or dict()
area_lft, area_rgt = area
node = PLTNode(tag, area, depth, parent_x, arrow_text)
nodes.append(node)
if children:
area_offset = float(area_rgt - area_lft) / (len(children))
cur = area[0]
prt_x = (area_rgt + area_lft) / 2.0
for child_arrow, child in children.items():
scan_nodes(nodes, child_arrow, child, (cur, cur + area_offset),
depth + 1, prt_x)
cur += area_offset
if __name__ == '__main__':
tree = {
"tag": "root",
"children": {
"yes": {"tag": "A"},
"no": {
"tag": "B",
"children": {
"yes": {
"tag": "B1",
"children": {"+1": {"tag": "B1+1"}, "-1": {"tag": "B1-"}}
},
"no": {"tag": "B2"}
}
}
}
}
show_tree(plt, tree)
plt.show()
|
f5edbdac7b5ff053f73da7c92c23c5737c117243 | likhitha5101/DAA | /Assignment-4/Point.py | 747 | 3.71875 | 4 | # -*- coding: utf-8 -*-
class Point(object):
__slots__ = ['_x', '_y']
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def __str__(self):
return "(" + str(self._x) + "," + str(self._y) + ")"
def __add__(self, other):
return Point(self._x + other._x, self._y + other._y)
def __sub__(self, other):
return Point(self._x - other._x, self._y - other._y)
def get_x(self):
return self._x
def get_y(self):
return self._y
def distance(self, other):
x_diff = (self._x - other._x) ** 2
y_diff = (self._y - other._y) ** 2
return (x_diff + y_diff) ** 0.5
def translate(self, x=0, y=0):
self._x += x
self._y += y
|
717cdf06013ec54a4a8bbb91a96ab92fe360732a | QinmengLUAN/Daily_Python_Coding | /wk2_TwoSum_v1.py | 557 | 3.875 | 4 | #Given an array of integers,
#return indices of the two numbers such that they add up to a specific target.
#You may assume that each input would have exactly one solution,
#and you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
def TwoSum(inp, target):
for i in range(len(inp)):
second_num = target - inp[i]
for j in range(1,len(inp)):
if inp[j] == second_num:
return [i,j]
inp = [2, 7, 11, 15]
target = 17
print(TwoSum(inp, target)) |
1bf38cc373359cf286d7ac63ceb650001dd64b5d | thelmuth/cs110-spring-2020 | /Class07/warmup.py | 114 | 3.859375 | 4 |
# What does this print:
test = "This is a test."
a = test.find("is")
b = test.find(".")
print(test[a:b])
|
8ea4d323c5bef46fa7d336e149bcacbcb9bbb597 | raysmith619/Introduction-To-Programming | /exercises/functions/figures/polygon_mod.py | 2,545 | 3.671875 | 4 | #my_polygon_mod.py 21Jan2022 crs, from my_polygon_keyw_2.py
"""
Module to Make a regular polygons
"""
from turtle import *
# Previous values
prev_color = "black" # color
prev_side = 200 # side in pixels
prev_nside = 4 # number of sides
prev_width = 4 # line width
def polygon(nside=None,
x=0, y=0,
side=None,
clr=None,
wid=None):
""" Draw a square
:nside: number of sides default:previous (e.g. 4-square)
:x: x position default: 0
:y: y position default: 0
:side: length of side default: previous side
:clr: figure color default: previous color
:wid: figure line width default: previous width
"""
global prev_nside # Don't create local variable
global prev_side # Don't create local variable
global prev_color # Don't create local variable
global prev_width # Don't create local variable
penup() # raise pen
goto(x,y)
pendown() # lower pen
if nside is None:
nside = prev_nside
prev_nside = nside
if side is None:
side = prev_side
prev_side = side
if clr is None:
clr = prev_color
prev_color = clr # Record for future
if wid is None:
wid = prev_width
prev_width = wid # Record for future
color(clr)
width(wid)
angle = 360/nside
for i in range(nside):
forward(side)
right(angle)
"""
Self testing
"""
if __name__ == '__main__':
print("Selftest")
colors = ["red", "orange", "yellow",
"green", "blue", "indigo",
"violet"]
nfig = 6
xbeg = -600
xend = 600
xrange = xend-xbeg
ybeg = -600
yend = 600
yrange = yend-ybeg
side = .80*min(xrange,yrange)/nfig
wid = 4
xoff = 40 # offsets for second polygon
yoff = 20
for i in range(nfig):
nside = i + 3 # Start with triangle
x = xbeg + i*side
y = ybeg + side/2 +(i+1)*side
polygon(nside=nside, x=x, y=y,
side=side*(1-((i-1)/nfig)), # Shrink polygons
clr=colors[i%len(colors)], wid=wid)
# Second with defaults
# except for offset position
# and line width
polygon(x=x+2*xoff, y=y+yoff, wid=wid+2)
polygon(x=x+4*xoff, y=y+2*yoff)
|
eafd651285f500bc3d19128a09f0652175ae3a4c | sujeet05/python-code | /lession5.py | 741 | 3.53125 | 4 | #x = "There are many dogs in this society %d ", 10
x = "There are %d types of people." % 10
print x
# before 10 % is mising in line no 1 . % is mandatory
binary ="binary"
dont ="dont"
#y = "those who knows %r can't say %s" (%binary,%dont)
y = "those who knows %r can't say %s" %(binary,dont)
# % should be before bracket in line no 7
print y
print "i said %r " %x
print "i also said %s " %y
hilarious = False
innovative_joke = " i am doing %r "
print "it is %s to do some %r" %(hilarious,innovative_joke)
print "simply testing printing %r " %(innovative_joke)
print innovative_joke % hilarious
s= " this is the last sample"
t = " to be tested "
print s+t
print s+t+"sujeet"
print s+t+innovative_joke % hilarious |
51af4f58574d5300a9b5beecad583b0c55016513 | Evilzlegend/Structured-Programming-Logic | /Chapter 06 - Arrays/Instructor Samples/sort_function.py | 251 | 3.75 | 4 | myList = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
print('Original order:', myList)
myList.sort()
print('Sorted order:', myList)
myList = ['beta', 'alpha', 'delta', 'gamma']
print('Original order:', myList)
myList.sort()
print('Sorted order:', myList) |
e849afe585c0d25de97fbe749f49c5c34a0b092c | saratkumar17mss040/Python-lab-programs | /Classes_and_Object_Programs/cls9.py | 251 | 3.71875 | 4 | # encapsulation - protected members - 1
class Person:
def __init__(self):
self._name = 'sam'
class Student(Person):
def __init__(self):
Person.__init__(self)
print(self._name)
s = Student()
p = Person()
print(p._name)
print(s._name)
|
86eed08745d81e2cafdff1e93b734350b04f56a5 | u98106/Python-learning-notebooks | /References.py | 468 | 3.65625 | 4 |
# coding: utf-8
# ## What is a reference?
# Very similar to a pointer in C
#
# ### A different var name pointing to the same data
# In[ ]:
# In[ ]:
# Let's look at the following code:
# In[1]:
x = [1,2,3,4,5]
# In[2]:
x
# In[3]:
y = x
# In[4]:
x.pop()
# In[5]:
x
# In[6]:
y
# In[7]:
id(x)
# In[8]:
id(y)
# How do we fix this?
# In[9]:
y = x[:]
# In[10]:
x.pop()
# In[11]:
x
# In[12]:
y
# In[13]:
id(y)
# In[ ]:
|
34c2e4709e8a3163856dfa0306debdf6899ef297 | mattb33/BC-Hours-Request-Checker | /Hours Request Checker.py | 1,879 | 3.6875 | 4 | # Import modules
import csv
# Initialise output list
results = []
header = ["Employee Code", "Hours", "Percentage"]
# Define the starting variables
z = 0.70 # Threshold that must be met to qualify for increase in hours
# Import CSV - file called 'hours' should be employee code in first column, then one year's worth of fortnightly hours (26 instances)
f = open('hours.csv')
csv_f = csv.reader(f)
next(csv_f) # Ignore the header row
# Loop through rows of the csv
for row in csv_f:
emp_code = row[0]; # capture the employee code so it can be appended to the results list
j = row[1:]; # the row with the employee code removed (list has strings though - the next line will convert to float)
j2 = [float(i) for i in j if i]; # convert the list of strings to floating point numbers
for M in range(80,19,-1): # iterate through the working hours - decrementing from 80 to 20 hours
j3 = (sum(i >= M for i in j2) / len(j2)); # count the instances that are equal or greater than the working hours, and divide by the total number of instances
if (j3 >= z): # if the threshold (z - currently 70%) is met, write the results to the list and break the loop
print(emp_code, M, j3);
results.append([emp_code, M, j3]);
break
print("Results have been finalised")
# Write to CSV
print('writing to CSV...')
with open('results.csv', mode='w') as csv_file:
writer = csv.writer(csv_file);
writer.writerow(i for i in header); # add the header row
# Add scraped data to csv file
for item in results:
writer.writerow(item); # add the results from the loop
print('Writing to CSV complete')
|
301a0d6e924987f8392f9950268dee14eead2025 | haiou90/aid_python_core | /day08/homework_personal/04_chuanjiang.py | 296 | 3.515625 | 4 | # list01 = [1,2,3,4]
# list02 = list01
# list03 = list01[:]
# print(list03)
# list03[0] = 100
# print(list03)
# print(list01)
# list01[:] = []#修改列表元素
# print(list03)
# print(list01)
# print(list02)
message = "to have people"
list01 = message.split(" ")[::-1]
print(" ".join(list01)) |
b399941806dc85a2f11bc33f59ead53b0d61b25f | Mtmh/py.1nivel1 | /98ListaValorCero.py | 524 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 7 13:20:05 2017
@author: tizianomartinhernando
"""
lista=[[100,7,85,8], [4,8,56,25], [67,89,23,1], [78,56]]
print(lista)
for x in range(len(lista[0])):
if lista[0][x]>50:
lista[0][x]=0
print(lista)
'''
Se tiene la siguiente lista:
lista=[[100,7,85,8], [4,8,56,25], [67,89,23,1], [78,56]]
Imprimir la lista. Luego fijar con el valor cero todos los elementos mayores a 50 del primer elemento de "lista".
Volver a imprimir la lista.
'''
|
4be536608ca338cae08a905b8ab50c378d91683d | Commandoz/Portif-lio | /Desafio06.py | 291 | 4 | 4 | print('Desafio 06 - Dobro - Triplo e Raiz Quadrada')
print('Escolha um número para sabermos o Dobro, Triplo e Raiz Quadrada')
n1 = int(input('Escolha um número: '))
d = n1 * 2
t = n1 * 3
rq = n1 ** (1/2)
print('O Dobro é {}, o Triplo é {} e a Raiz Quadrada é {}'.format(d, t, rq)) |
9db3f31a9220e816cd7756e61eba7cfd3b5b2611 | cyril-lav/osu-learn | /Osu!Learn/untitled100.py | 244 | 3.515625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn as sk
rng = np.random.RandomState(42)
x = 10 * rng.rand(50)
print('la taille de notre ehantillon est :',x.shape)
y=2*x-1+ rng.randn(50)
plt.scatter(x,y); |
66c60b30659f683b67cd379657aad9f902d8b9e2 | xXxSovereign/WorldOfPlus | /commands/mapStuff.py | 2,627 | 3.9375 | 4 | import os
import random as r
def display_Map(world_map): # Function to display the world map, parameter is the current explored map
os.system("cls") # Clears previous text in the Terminal
os.system("chcp 65001") # sets current code page to UTF-8 to display chars
for i in world_map:
output = "" # For loop to access and print individual items in the map list
for j in i:
output += j + " "
print(output) # Outputs the map in a square
def to_2d(world_map, n):
return [world_map[i:i+n] for i in range(0, len(world_map), n)] # slices the list in n sizes, where n is the length
# of the rows in the 2D map
# noinspection PyUnboundLocalVariable
def gen_Map(size):
# Determine map size off of user input "size" and center of the map
if size == 0:
mapSize = 3
center = [1, 1]
elif size == 1:
mapSize = 7
center = [3, 3] # Middle of square will be: [3][3]
elif size == 2:
mapSize = 11 # Middle: [5][5]
center = [5, 5]
elif size == 3:
mapSize = 15 # Middle: [7][7]
center = [7, 7]
mapv1 = [["+" for _ in range(mapSize)] for _ in range(mapSize)]
# Creating the map as a list, _ means that no var is needed
mapv1[center[0]][center[1]] = "H" # sets the center of mapv1 to H
areas = ["F", "M", "T", "S", "C"] # list of the area's, excluding dungeon and final dungeon
mapv2 = [] # initializing the list for the fully discovered map
for _ in mapv1:
for _ in mapv1: # accesing each item to get correct amount of areas
mapv2.append(r.choice(areas)) # making random areas
for _ in range(4):
mapv2[r.randint(0, len(mapv2) - 1)] = u"\u0468" # Ѩ , setting the 4 dungeons at random points on map
mapv2[r.randint(0, len(mapv2) - 1)] = u"\u046A" # Ѫ, setting final dungeon at random point on map
midPoint = (len(mapv2) - 1) // 2 # detemine midpoint of 1D array mapv2 using midpoint formula (x1 + x2) / 2 = mid
# the formula is a little modified by just getting the length of the list
for _ in range(1000):
r.shuffle(mapv2) # shuffles the world map a few times
while mapv2[midPoint] == u"\u046A" or mapv2[midPoint] == u"\u0468": # Making sure middle is not a dungeon
r.shuffle(mapv2)
mapv2[midPoint] = u"\u058D" # Setting the center of the world map to H
# constructing the non-flattened list, making the 1D list into 2D
mapv3 = to_2d(mapv2, mapSize)
del mapv2, areas, midPoint # deleting unnecessary lists to free memory
return mapv3
display_Map(gen_Map(1)) |
3afac317c3d09d13465bd2403f57a5f7122b3ae0 | Shiva2095/Pattern_python | /5.py | 421 | 3.59375 | 4 | """Pattern-5:
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J
A B C D E F G H I J"""
r=int(input("Enter Number Of Rows : "))
c=int(input("Enter Number Of Column : "))
for i in range(1,r+1):
for j in range(1,c+1):
print(chr(64+j),end=" ")
print()
|
27398de528e753c805beeab33d0fd69d38c9423b | heenamkim/Basic-programming | /python/3주차/파이썬 연습_3주차_추가 공부 자료_실습9.py | 194 | 3.703125 | 4 | #파이썬 연습_3주차_추가 공부 자료_실습9.py
a=3
b=9
a=b
b=a
print(a)
print(b)
#2 임시 변수를 하나 더 만들어서 바꾸는 방법
a=3
b=9
x=a
a=b
b=x
print(a)
print(b)
|
f970b4cf61ca8704252c728f7f555042fa90871d | howarding/interviews_py | /leetcode/208_implement-trie-prefix-tree.py | 1,667 | 4.25 | 4 | # Implement a trie with insert, search, and startsWith methods.
#
# Note:
# You may assume that all inputs are consist of lowercase letters a-z.
class TrieNode:
def __init__(self):
self.isEnd = False
self.child = dict()
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
if not self.root.isEnd:
self.root.isEnd = False
node = self.root
for c in word:
if c not in node.child:
node.child[c] = TrieNode()
node = node.child[c]
# node = node.child.setdefault(c, TrieNode())
node.isEnd = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for c in word:
if c not in node.child:
return False
node = node.child[c]
return node.isEnd
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for c in prefix:
if c not in node.child:
return False
node = node.child[c]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) |
72749234a83fd86b08000408ae24d31a790be7de | zyhsna/Leetcode_practice | /problems/remove-duplicate-node-lcci.py | 805 | 3.578125 | 4 | # _*_ coding:UTF-8 _*_
# 开发人员:zyh
# 开发时间:2020/8/25 10:02
# 文件名:remove-duplicate-node-lcci.py
# 开发工具:PyCharm
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeDuplicateNodes(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur, next_node = None, head
num = {}
while next_node:
if next_node.val not in num.keys():
num[next_node.val] = 1
cur, next_node = next_node, next_node.next
else:
cur.next = next_node.next
next_node = next_node.next.next
head = head.next
return head |
6995285aca86a20c600d1814e1535438a2e0bda0 | Hasnake/lc101 | /initials.py | 600 | 4.09375 | 4 | def get_initials(fullname):#if you haven't argument,then you have to call your function name to end.
""" Given a person's name, returns the person's initials (uppercase) """
# TODO your code here
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
return initials
def main():
strName = str(input("What is your full name?:"))
answer = get_initials(strName)
print("The initials of" , strName , "are" , answer)
if __name__ == '__main__':
main() |
222337324281ee9092c9139cbce0c0122a4e9c23 | RHARO-DATA/DataStructure--Algorithms | /Find Subtree.py | 587 | 3.734375 | 4 | """
Find Subtree
Given 2 binary trees t and s, find if s has an eaqul subtree in t,
where the structure and the values are the same. Return True is it exist,
otherwise return False
"""
class Node:
def __init__(self, value, left = None, right = None):
self.value = value
self.left = left
self.right = right
def __repr(self):
return f"(Value: {self.value} Left:{self.left} Right: {self.right})"
def find_subtree(s,t):
t3 = Node (4, Node(3), Node(2))
t2 = Node (5, Node(4), Node(-1))
t = Node(1,t2, t3):
s = Node(4, Node(3), Node(2))
|
58cd10a448ebd2efeed5077874db310ec42e9a37 | LawerenceLee/coding_dojo_projects | /python_stack/hospital.py | 1,776 | 3.59375 | 4 | import hashlib
class Patient():
def __init__(self, name, allergies=""):
self.name = name
self.allergies = allergies
self.bed_number = None
self.id = hashlib.sha512(name + allergies).hexdigest()[-8:].upper()
def __str__(self):
return "PATIENT-ID: {}\nNAME: {}\nALLERGIES: {}\nBED No.: {}".format(
self.id, self.name, self.allergies, self.bed_number)
class Hospital():
patients = []
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
self.beds = range(1, self.capacity+1)
def admit(self, patient):
if len(self.patients) == self.capacity:
print("Hospital is Full, Sorry")
else:
patient.bed_number = self.beds.pop()
self.patients.append(patient)
print("Patient has been successfully admitted")
def discharge(self, patient_name):
for patient in self.patients:
if patient.name == patient_name:
self.beds.append(patient.bed_number)
self.patients.remove(patient)
print("Patient Successfully Discharged")
else:
print("Patient Not Found")
def __str__(self):
return "Hospital: {}\nCapacity: {}\nNo. of Patients: {}".format(
self.name, self.capacity, len(self.patients)
)
joe = Patient("Joe Shmoe")
print(joe)
bates_hospital = Hospital("Bates Hospital", 2)
print(bates_hospital)
print("")
bates_hospital.admit(joe)
print(bates_hospital)
print("")
print(joe)
print("")
betty = Patient("Betty")
print(betty)
print("")
bates_hospital.admit(betty)
print(bates_hospital)
print("")
print(betty)
print("")
bates_hospital.discharge("Joe Shmoe")
print(bates_hospital)
|
2cd08e8ceea8345153c6b45c8ff61839435aa33c | iutzeler/NumericalOptimization | /Lab7_StochasticMethods/algoProx.py | 1,544 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Proximal algorithms
#
# In this notebook, we code our proximal optimization algorithms.
# # 1. Proximal Gradient algorithm
#
# For minimizing a function $F:\mathbb{R}^n \to \mathbb{R}$ equal to $f+g$ where $f$ is differentiable and the $\mathbf{prox}$ of $g$ is known, given:
# * the function to minimize `F`
# * a 1st order oracle for $f$ `f_grad`
# * a proximity operator for $g$ `g_prox`
# * an initialization point `x0`
# * the sought precision `PREC`
# * a maximal number of iterations `ITE_MAX`
# * a display boolean variable `PRINT`
#
# these algorithms perform iterations of the form
# $$ x_{k+1} = \mathbf{prox}_{\gamma g}\left( x_k - \gamma \nabla f(x_k) \right) $$
# where $\gamma$ is a stepsize to choose.
#
#
# Q. How would you implement the precision stopping criterion?
import numpy as np
import timeit
def proximal_gradient_algorithm(F , f_grad , g_prox , x0 , step , PREC , ITE_MAX , PRINT ):
x = np.copy(x0)
x_tab = np.copy(x)
if PRINT:
print("------------------------------------\n Proximal gradient algorithm\n------------------------------------\nSTART -- stepsize = {:0}".format(step))
t_s = timeit.default_timer()
for k in range(ITE_MAX):
g = f_grad(x)
x = g_prox(x - step*g , step) ####### ITERATION
x_tab = np.vstack((x_tab,x))
t_e = timeit.default_timer()
if PRINT:
print("FINISHED -- {:d} iterations / {:.6f}s -- final value: {:f}\n\n".format(k,t_e-t_s,F(x)))
return x,x_tab
|
8d43be3a0fe91988e037e8144748861d9609bedc | sy-jamal/Machine-Learning | /datasets_questions/explore_enron_data.py | 2,079 | 3.640625 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import itertools
import pickle
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
print "There are total ",len(enron_data), " people in the dataset"
print "There are ",len(enron_data[next(iter(enron_data))]), "Features of each person in the dataset"
count =0
for item in enron_data:
if(enron_data[item]['poi']): count+=1
print "There are ",count,"person of interests"
print "James Prentice has $", enron_data["PRENTICE JAMES"]['total_stock_value'], " in stocks"
print "Wesley Colwell sent", enron_data["COLWELL WESLEY"]['from_this_person_to_poi'], " emails to POI"
print "Jeffrey K Skilling has exercised ", enron_data["SKILLING JEFFREY K"]['exercised_stock_options'], " stock options"
print "Jeffrey K Skilling took $",enron_data["SKILLING JEFFREY K"]['total_payments']
print "Kenneth Lay took $", enron_data["LAY KENNETH L"]['total_payments']
print "Andrew Fastow took $", enron_data["FASTOW ANDREW S"]['total_payments']
salary = list( v['salary'] for k,v in enron_data.items() if str(v['salary'])!='NaN')
print "There are total", len(salary), "salaries"
email_addresses = list( v['email_address'] for k,v in enron_data.items() if v['email_address']!='NaN')
print "There are total", len(email_addresses), "email addresses"
total_payment = list( v['total_payments'] for k,v in enron_data.items() if str(v['total_payments'])!='NaN')
print "There are total", len(total_payment), "payments"
total_poi_payment = list( v['total_payments'] for k,v in enron_data.items() if str(v['total_payments'])!='NaN' and v['poi'])
print "There are total", len(total_poi_payment), "payments for poi" |
e7f28b245d26d132c107ad0b925227ab71374605 | Sinha-Ujjawal/LeetCode-Solutions | /StudyPlans/Algorithms/Algorithms1/combinations.py | 436 | 3.640625 | 4 | from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
stack = [([], 1)]
while stack:
xs, i = stack.pop()
if len(xs) == k:
yield xs
else:
for j in range(i, n + 1):
stack.append((xs + [j], j + 1))
if __name__ == "__main__":
solver = Solution()
print(list(solver.combine(4, 2)))
|
18292f279526f4a9bd07143b5517ab0655d3258f | rafaelperazzo/programacao-web | /moodledata/vpl_data/104/usersdata/250/50761/submittedfiles/av1_2.py | 120 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import math
N=int(input('digite numero de linhas e colunas:'))
x1=int(input('cordenada da linha
|
66352731d8b952a633dea499c56cc58903051b4d | nikitakumar2017/Assignment-4 | /assignment-4.py | 1,450 | 4.3125 | 4 | #Q.1- Reverse the whole list using list methods.
list1=[]
n=int(input("Enter number of elements you want to enter in the list "))
for i in range(n):
n=int(input("Enter element "))
list1.append(n)
print(list(reversed(list1)))
#Q.2- Print all the uppercase letters from a string.
str1=input("Enter string ")
for i in str1:
if (i>='A' and i<='Z'):
print(i)
#Q.3- Split the user input on comma's and store the values in a list as integers.
str1=input("Enter some numbers seperated by comma's ")
list1=[]
list2=[]
list1=str1.split(',')
for i in list1:
i=int(i)
list2.append(i)
print(list2)
#Q.4- Check whether a string is palindromic or not.
str1=input("Enter a string ")
length=len(str1)
high=length-1
i=0
low=0
flag=0
while (i<length and flag==0):
if(str1[low]==str1[high]):
high-=1
low+=1
flag=0
else:
flag=1
i+=1
if(flag==0):
print("Yes")
else:
print("No")
#Q.5- Make a deepcopy of a list and write the difference between shallow copy and deep copy.
import copy as c
list1=[1,2,[3,4],5]
list2=c.deepcopy(list1)
list1[2][0]=7
print(list1)
print(list2)
''' Difference between shallow copy and deep copy is that in shallow copy if the original object contains any references to mutable object
then the duplicate reference variable will be created pointing to the old object and no duplicate object is created whereas in deep copy a duplicate object
is created. '''
|
3058db44e858b4e84ac998bdc52adf4fb5b22988 | rhaxlwo21/Python_Sunrin | /practice29.py | 177 | 3.515625 | 4 | def cal_area(radius):
area = 3.14*radius**2
return area
user = int(input("반지름을 입력하세요:"))
c_area = cal_area(user)
print("원의 넓이는 :",c_area)
|
cccded751a245d6498486330f1202dbcb6020243 | SeavantUUz/LC_learning | /LowestCommonAncestorofaBinarySearchTree.py | 463 | 3.5625 | 4 | # coding: utf-8
__author__ = 'AprocySanae'
__date__ = '15/10/14'
def lowestCommonAncestor(root, p, q):
lower, higher = sorted([p.val, q.val])
while root:
if not root:
return None
val = root.val
if val == higher or val == lower or (val > lower and val < higher):
return root
elif val > higher:
root = root.left
else:
root = root.right
else:
return None
|
856d1eec286ec74b172f57c2af23d14890361820 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/zach_thomson/lesson05/comprehensions_lab.py | 1,104 | 3.984375 | 4 | def count_evens(nums):
return len([num for num in nums if num % 2 == 0])
#print(count_evens([2,5,3,4]))
#print(count_evens([2,4,5,6,8,10]))
food_prefs = {"name": "Chris",
"city": "Seattle",
"cake": "chocolate",
"fruit": "mango",
"salad": "greek",
"pasta": "lasagna"}
#print(food_prefs.values())
#test = '{} is from {}, and he likes {} cake, {} fruit, {} salad, and lasagna {}'
#print(test.format(food_prefs.values()))
range15 = [i for i in range(15)]
hex15 = [hex(i) for i in range15]
new_dict_from_list = {i:v for i,v in zip(range15, hex15)}
#print(new_dict_from_list)
new_dict_oneliner = {i: hex(i) for i in range(15)}
#print(new_dict_oneliner)
food_copy = {k: v.count('a') for k, v in food_prefs.items()}
#print(food_copy)
#print(food_prefs)
s2 = {num for num in range(20) if num % 2 == 0}
s3 = {num for num in range(20) if num % 3 == 0}
s4 = {num for num in range(20) if num % 4 == 0}
print(s2)
print(s3)
print(s4)
a_list = [2, 3, 4]
test = {num for num in range(20) for a in a_list if num % a == 0}
print(test)
|
49baa75b2582bc9919a1db6d3fe50686bb1451c5 | JIAWea/Python_cookbook_note | /03grouping_records_based_on_a_Field.py | 1,539 | 4.53125 | 5 | # Python cookbook学习笔记
# 1.15 Grouping Records Together Based on a Field
# You have a sequence of dictionaries or instances and you want to iterate over the data
# in groups based on the value of a particular field, such as date.
# The itertools.groupby() function is particularly useful for grouping data together like this:
from operator import itemgetter
from itertools import groupby
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date': '07/03/2012'},
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
{'address': '1060 W ADDISON', 'date': '07/02/2012'},
{'address': '4801 N BROADWAY', 'date': '07/05/2012'},
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]
# Now suppose you want to iterate over the data in chunks grouped by date. To do it, first
# sort by the desired field (in this case, date) and then use itertools.groupby():
rows.sort(key=itemgetter('date'))
print(rows)
# Iterate in groups
for date, items in groupby(rows, key=itemgetter('date')):
print(date)
for i in items:
print(' ', i)
# 使用defaultdict()可将数据分组:
from collections import defaultdict
rows_by_date = defaultdict(list)
for row in rows:
rows_by_date[row['date']].append(row)
print(rows_by_date) # defaultdict(<class 'list'>, {'07/01/2012': [{'address': ' ', ...}], ...})
|
171259ac64c71a2ecfaf17e65f49f7854b4a0db9 | gyenana/pythoniii | /github/make_calculator/make caculator_ver1.py | 1,652 | 4.03125 | 4 | # 계산기 내에서 사용할 사칙연산 함수 만들기
def sum(a,b):
return a+b
def diff(a,b):
return a-b
def multiple(a,b):
return a*b
def divide(a,b):
return a/b
#계산기 함수 만들기
def caculator():
try:
# 첫번째 초기 값
result=int(input('숫자를 입력하세요:'))
while True:
c=str(input('연산자를 입력하세요:'))
if c == '=':
print(result)
break
else:
if c=='+':
b = int(input('숫자를 입력하세요:'))
result=sum(result,b)
elif c=='-':
b = int(input('숫자를 입력하세요:'))
result=diff(result,b)
elif c=='*':
b = int(input('숫자를 입력하세요:'))
result=multiple(result,b)
elif c=='/':
b = int(input('숫자를 입력하세요:'))
result=divide(result,b)
else:
# 연산자 이상한거 넣었을 때
print("올바른 연산자를 입력해야지요!")
break
print(result)
except ValueError:
# 이상한값 넣었을 때, 숫자에 문자 넣었을 때
print("올바른 값을 넣어야지요!")
except ZeroDivisionError:
# 영으로 나누었을 때
print("0으로 나누면 안되지요 !")
except:
# 그 외의 모든 에러
print("뭔진모르지만 뭔가 잘못한게 분명하다!")
caculator()
|
17beb6717f0b752d12dbb4479e91520bad2dce41 | David-Sangojinmi/Adventure-Game-PY | /adventure.py | 3,645 | 3.890625 | 4 | #Name: David S
#Date: 20/07/2016
#Project: Simple Text Based Game
import time
import sys
print """
---------------------------------
---------------------------------
-- Hello my friend! --
-- Welcome to my game, --
-- Adventure! --
---------------------------------
---------------------------------
"""
time.sleep(2)
def retry3():
print "Due to your choice, you cannot carry on. GAME OVER\n"
print "Do you want to retry or quit?"
option = raw_input('Type "retry" to retry or "quit" to quit-> ')
if option == "retry":
stage3()
elif option == "quit":
sys.exit()
def pathway3():
print "To be continued"
option = raw_input('To be continued...')
def retry2():
print "Due to your choice, you cannot carry on. GAME OVER\n"
print "Do you want to retry or quit?"
option = raw_input('Type "retry" to retry or "quit" to quit-> ')
if option == "retry":
stage2()
elif option == "quit":
sys.exit()
def pathway2b():
print "To be continued"
def pathway2():
print "Pathway 2 leads you into a tunnel\n"
time.sleep(1)
print "the tunnel is lighted and you can see it is very long.\n"
time.sleep(1)
print "Suddenly the tunnel begins to collapse!"
time.sleep(1)
print "What do you do?"
option = raw_input('Type "turn back" to turn back or "run ahead" to run ahead? ')
if option == "turn back":
print "You tried, but failed.\n"
time.sleep(1)
print "You are crushed and suffocate\n"
time.sleep(1)
retry2()
elif option == "run ahead":
print "You see a opening to the right and duck into it\n"
time.sleep(1)
print "You are transported outside, safe and sound!\n"
time.sleep(1)
pathway2b()
def retry1():
print "Due to your choice, you cannot carry on. GAME OVER\n"
print "Do you want to retry or quit?"
option = raw_input('Type "retry" to retry or "quit" to quit-> ')
if option == "retry":
pathway()
elif option == "quit":
sys.exit()
def pathway1b():
print "-"
def pathway1():
print "You are walking down pathway 1\n"
time.sleep(1)
print "It is very dark and you hear a noise\n"
time.sleep(1)
print "It sounds like it is coming closer to you!\n"
time.sleep(1)
print "Do you stop moving or carry on?\n"
option = raw_input('Type "stop moving" to stop moving or "carry on" to carry on-> ')
if option == "stop moving":
print "You see the object, it is a whirling blade!!\n"
time.sleep(1)
print "Your body frozen, the blade hits you square on,\n"
time.sleep(1)
retry1()
elif option == "carry on":
print "You see the object, it is a whirling blade!!\n"
time.sleep(1)
print "But because you carried on you have just enough time to dodge it,\n"
time.sleep(1)
print "Hurrah!!"
time.sleep(1)
pathway1b()
def pathway():
print"What pathway do you want to pick?"
option = raw_input('1, 2, or 3? ')
if option == "1":
pathway1()
elif option == "2":
pathway2()
else:
pathway3()
def retry():
print "Due to your choice, you cannot carry on. GAME OVER\n"
print "Do you want to retry or quit?"
option = raw_input('Type "retry" to retry or "quit" to quit-> ')
if option == "retry":
start()
elif option == "quit":
sys.exit()
def start():
print "You have been transported to this new earth,\n"
time.sleep(1)
print "you look around yourself and all you can see is three pathways.\n"
time.sleep(1)
print "What do you do?"
option = raw_input('Type "pick a pathway" to pick a pathway or "run" to run-> ')
if option == "pick a pathway":
pathway()
elif option == "run":
retry()
print "Do you want to play my game?"
option = raw_input('Type "yes" or "no"-> ')
if option == "yes":
start()
elif option == "no":
sys.exit()
|
834ae082145358382d1754e19b08509abbfd39eb | MakarFadeev/PythonTasks | /TK15/TEST.py | 2,333 | 3.703125 | 4 | from tkinter import *
#Настройки окна
window = Tk()
window.geometry('400x300')
window.title('Ввод-вывод данных')
window.resizable(False, False)
smallLetter = False
bigLetter = False
number = False
nice = False
def show():
global smallLetter
global bigLetter
global number
global nice
password = inputbox.get()
for i in range(len(password)):
if (password[i].isupper()):
bigLetter = True
elif (password[i].islower()):
smallLetter = True
elif (password[i].isdigit()):
number = True
elif (number and bigLetter and smallLetter):
nice = True
if (len(password) < 10):
if (not smallLetter and bigLetter and number):
label2.config(text = 'Не хватает строчных букв!', fg = 'red')
elif (not bigLetter and smallLetter and number):
label2.config(text = 'Не хватает заглавных букв!', fg = 'red')
elif (not number and bigLetter and smallLetter):
label2.config(text = 'Не хватает цифр!', fg = 'red')
else:
label2.config(text = 'Пароль не подходит!', fg = 'red')
elif (nice and len(password) >= 10):
label2.config(text = 'Пароль подходит!', fg = 'green')
def theme():
passwordbox.config(bg = '#353535', fg = 'white')
label1.config(bg = '#353535', fg = 'white')
label2.config(bg = '#353535')
showbutton.config(bg = '#535353', fg = 'white')
themebutton.config(bg = '#535353', fg = 'white', state = DISABLED)
window.config(bg = '#353535')
#Виджеты
passwordbox = LabelFrame(text = 'Пароль')
label1 = Label(passwordbox, text = 'Введите пароль:', fg = '#000000', width = 20, height = 1)
inputbox = Entry(passwordbox, width = 20, show = '*', justify = CENTER, bg = '#000000', fg = '#ffffff')
label2 = Label(passwordbox, fg = '#000000', width = 30, height = 1)
showbutton = Button(passwordbox, text = 'Проверить пароль', command = show)
themebutton = Button(passwordbox, text = 'Сменить тему', command = theme)
passwordbox.pack()
label1.pack()
inputbox.pack()
label2.pack()
showbutton.pack()
themebutton.pack()
#Конец программы
window.mainloop()
|
5f8ed03e94b139527ac44011e02d2ad0d467aa8a | HemantSinghEdu/MachineLearningPython | /002. Regression/02.MultipleLinearRegression/main.py | 4,058 | 4.125 | 4 | #Multiple Linear Regression - multiple features, one label
#General Equation is that of a straight line with multiple features: y = b0 + b1x1 + b2x2 + ... + bnxn
#sourced from superdatascience.com
#-------------------------------- Preprocessing -----------------------
#import the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,4].values.reshape(-1,1)
print("features X\n",X, "\n labels y \n",y)
#handle missing data
from sklearn.preprocessing import Imputer
imputer = Imputer()
imputer = imputer.fit(X[:,0:3]) #handle only first three columns
X[:,0:3] = imputer.transform(X[:,0:3])
print("X after handling missing data",X)
#Encode categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelEncoder = LabelEncoder()
X[:,3] = labelEncoder.fit_transform(X[:,3])
onehotencoder = OneHotEncoder(categorical_features=[3]) #column to be one-hot encoded
X = onehotencoder.fit_transform(X).toarray()
X = X[:,1:] #ignore column 0 so as to avoid dummy variable trap
print("X after encoding categorical data",X)
#Split dataset into training and test sets
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)
print("Splitting dataset into training and test sets \n X_train \n",X_train, '\n X_test \n', X_test, '\n y_train \n', y_train, '\n y_test \n', y_test)
#-------------------------------------END------------------------------
#------------------------------------ Model ---------------------------
#Create the regressor and fit it to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor = regressor.fit(X,y)
#predict test set results
y_pred = regressor.predict(X_test)
print('y_pred for X_test\n',y_pred)
#Building the optimal model using backward elimination
#One by one, remove all columns that have a p-value above 0.05 significance level
import statsmodels.formula.api as sm
X = np.append(arr=np.ones((50,1)).astype(int), values=X, axis=1) #add a column of 1's, the bias term in the equation of line
#Iteration #1
X_opt = X[:,[0,1,2,3,4,5]] #initially, we add all columns to X_optimal
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary() #P-values: x1=0.948, x2=0.777, x3=0.000, x4=0.943, x5=0.056
#Iteration #2 - remove column with highest p-value i.e. x1 (second column)
X_opt = X[:,[0,2,3,4,5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary() #P-values: x1=0.769, x2=0.000, x3=0.944, x4=0.050
#Iteration #4 - remove column with highest p-value i.e. x3 (fourth column)
X_opt = X[:,[0,2,4,5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary() #P-values: x1=0.610, x2=0.010, x3=0.000
#Iteration #5 - remove column with highest p-value i.e. x1 (second column)
X_opt = X[:,[0,4,5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary() #P-values: x1 = 0.009, x2=0.000
#-------------------------------------END------------------------------
#----------------------------------- Graphs ---------------------------
#Since there are multiple features, we can't show a feature vs . label graph
#You can use Principal Component Analysis (PCA) or LDA to reduce the number of features
#But for now, we will just show the predicted vs. actual value graph
#Predicted vs. actual graph for training set
y_pred_train = regressor.predict(X_train)
plt.figure("train")
plt.scatter(y_pred_train,y_train)
plt.title("Predicted vs. Actual Profit: Training set")
plt.xlabel("Predicted Profit")
plt.ylabel("Actual Profit")
plt.show()
plt.savefig("train.png")
#Predicted vs. actual graph for training set
plt.figure("test")
plt.scatter(y_pred,y_test)
plt.title("Predicted vs. Actual Profit: Test set")
plt.xlabel("Predicted Profit")
plt.ylabel("Actual Profit")
plt.show()
plt.savefig("test.png")
#-------------------------------------END------------------------------
|
8ccd74719ddc3591031088bf53d66b1a4a435300 | minapetr/test | /.vscode/ProblemSet0.py | 157 | 3.53125 | 4 | import numpy as np
x=int(input("Please enter value for x"))
y=int(input("Please enter value for y"))
z=x**y
print("x**y=",z)
p=np.log2(x)
print("log(x)=",p)
|
115af2e4885d150f20827305416759225f47de00 | jonag-code/python | /file_reader.py | 821 | 3.6875 | 4 |
#filename = 'pi_1000.txt'
filename = 'pi_100.txt'
#filename = 'pi_30.txt'
##Store lines of .txt file into a list,
with open(filename) as f:
lines = f.readlines()
print("%s \n" %lines)
##print an element at a time, stripping
## off the insisible newline characters
## from the original .txt file.
for line in lines:
#print(line)
#print(line.strip())
print(line.rstrip())
##Store lines of .txt file into a list,
## stripping newline and blank spaces.
lines_stripped = [line.strip() for line in lines]
print("\n %s" %lines_stripped)
##Store the contents of txt file as one string (y)
pi_string = ''
for line in lines:
pi_string = pi_string + line.strip()
#pi_string += line.strip()
print("\n %s " %pi_string)
print("\n This is Pi to %i decimal places\n" %(len(pi_string) -2 ))
print(type(pi_string))
|
96d097a608004e9bbdb43004345e0bb393d28bbd | nielsonnp/CursoemVideo | /resumos/lembretes_strings.py | 680 | 4.15625 | 4 | frase = "Curso em Vídeo Python"
print(frase[3:13:2]) #Vai de 3 até 13 pulando de 1 em 1
print(frase.count('u')) #Conta quantas vezes tem o 'u' minusculo na variavel frase
print(len(frase)) #Conta quantos tamanhos tem a frase
print(len(frase.strip())) #Remove os espaço em branco
print(frase.upper()) #Coloca a frase em maiuscula
print(frase.replace('Python','Android')) #Substitui Python por Android
print('Curso' in frase) #Se a palavra curso está dentro da frase Vai mostrar True or False
print(frase.find("Vídeo"))#Vai dizer em qual posicao tá a palavra Curso
print(frase.lower().find('vídeo'))#Vai colocar a frase em minusculo e localizar em qual posicao ta o no curso |
a4f6d076c4b22c375a6448f3c3bf89864fa63904 | stefan1123/newcoder | /合并两个排序的链表.py | 1,148 | 3.796875 | 4 | # -*- coding:utf-8 -*-
"""
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
代码情况:accepted
"""
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
# 写的过程中要注意不要使得链表断开之后找不到下一节点了。
def Merge(self, pHead1, pHead2):
# write code here
# 递归停止条件写法一
#if not pHead1 and not pHead2:
# return None
#elif not pHead1 and pHead2:
# return pHead2
#elif not pHead2 and pHead1:
# return pHead1
# 写法二,都不用考虑所有情况。但是推荐写法一,更加明确
if not pHead1:
return pHead2
elif not pHead2:
return pHead1
if pHead1.val >= pHead2.val:
pHead2.next = self.Merge(pHead1,pHead2.next)
return pHead2
else:
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1
|
c254eb64b60e8bb81f052eb3a8d2341c6b4e85da | molliegoforth818/py-ch4prac-lists | /planets.py | 906 | 4.0625 | 4 | # Ch 4 example
# import random
# """
# Print a message to the console indicating whether each value of
# `number` is in the `my_randoms` list.
# """
# my_randoms = list()
# for i in range(10):
# my_randoms.append(random.randrange(1, 6))
# Generate a list of numbers 1..10
# numbers_1_to_10 = range(1, 11)
# Iterate from 1 to 10
# for number in numbers_1_to_10:
# the_numbers_match = False
# Iterate your random number list here
# Does my_randoms contain number? Change the boolean.
# print(f'{number} is in the random list')
planet_list = ["Mercury", "Mars"]
planet_list_2 = ["Neptune", "Uranus"]
planet_list.append("Jupiter")
planet_list.append("Saturn")
planet_list.extend(planet_list_2)
planet_list.insert(1,"Venus")
planet_list.insert(2,"Earth")
planet_list.append("Pluto")
rocky_planets = planet_list[0:4]
del planet_list[8]
print(planet_list)
print(rocky_planets)
|
f28bffd0246bb036669a3a023a22ff1aab4127ce | vertig0d/PythonProgrammingExercise | /Q3L1M2.py | 549 | 4.15625 | 4 |
"""
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such
that is an integral number between 1 and n (both included). and then the program should print the
dictionary.
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
"""
#Method2
num = input("Enter a number: ")
dicti = dict()
key = range(1, num + 1)
value = map(lambda x: x * x, key)
final = map(lambda k,v : dicti.update({k:v}), key, value)
print(dicti) |
18c1eaf8597cd79ca046e47b3885c3b288f30104 | codeAligned/codingChallenges | /Courses/algorithms_illuminated_part_1/Chapter 1/KaratsubaMultiplication.py | 2,169 | 3.984375 | 4 | """
Input: two n-digit positive integers x and y
Output: the product x · y
Assumption: n is a power of 2.
n = length of digits
"""
import math
def recIntMult(x, y):
xDigits = str(x)
yDigits = str(y)
n = min(len(xDigits), len(yDigits))
if len(xDigits) <= 1 or len(yDigits) <= 1:
return x * y
xMid = math.ceil(len(xDigits) / 2)
yMid = math.ceil(len(yDigits) / 2)
a, b = int(xDigits[:xMid]), int(xDigits[xMid:])
c, d = int(yDigits[:yMid]), int(yDigits[yMid:])
print(f"a:{a}, b:{b}, c:{c}, d:{d}")
result = 10**n * recIntMult(a, c) + 10 ** (n / 2) * (recIntMult(a, d) + recIntMult(b, c)) + recIntMult(b, d)
return int(result)
def KaratsubaMultiplication(x, y):
xDigits, yDigits = str(x), str(y)
length = min(len(xDigits), len(yDigits))
if len(xDigits) <= 1 or len(yDigits) <= 1:
return x * y
# Set Mid point - if odd length, the longer digit needs to be in the first half,
# rather than the second half. For example, `yMid = len(yDigits) // 2` won't work!
xMid = math.ceil(len(xDigits) / 2)
yMid = math.ceil(len(yDigits) / 2)
a, b = int(xDigits[:xMid]), int(xDigits[xMid:])
c, d = int(yDigits[:yMid]), int(yDigits[yMid:])
p, q = (a + b), (c + d)
ac = KaratsubaMultiplication(a, c)
bd = KaratsubaMultiplication(b, d)
pq = KaratsubaMultiplication(p, q) # pq = p * q (use this line to debug if this doesn't work)
adPlusbc = pq - ac - bd # Stands for ad + bc ; equivlent to this code with 1 less recursive call: adbc = KaratsubaMultiplication(a, d) + KaratsubaMultiplication(b, c)
result = ((10 ** length) * ac) + ((10 ** (length / 2)) * adPlusbc) + bd
print(f"n (length): {length}, a: {a}, b: {b}, c: {c}, d: {d}, p: {p}, q: {q}, ac: {ac}, bd: {bd}, pq: {pq}, adbc:{adPlusbc}, result: {result}")
return result
# Test Recursive Integer Multiplication
X, Y = 1111, 33333 # Result => 7006652
# X, Y = 1234, 5678 # Result => 7006652
# # X, Y = 1234, 5678
result = recIntMult(X, Y)
print(result)
# Test KaratsubaMultiplication
X, Y = 1234, 5678 # Result Should be => 7006652
result = KaratsubaMultiplication(X, Y)
print(result)
|
dceaefb05dcf2e68b27b28d961b2c9ebf40d100f | Jiezhi/myleetcode | /src/739-DailyTemperatures.py | 1,968 | 3.703125 | 4 | #!/usr/bin/env python
"""
Github: https://github.com/Jiezhi/myleetcode
Created on 2019/10/17
Leetcode: https://leetcode.com/problems/daily-temperatures/
https://leetcode.com/explore/learn/card/queue-stack/230/usage-stack/1363/
Difficulty: Medium
"""
from typing import List
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ret = []
for i in range(len(T) - 1):
found = False
for j in range(i + 1, len(T)):
if T[i] < T[j]:
ret.append(j - i)
found = True
break
if not found:
ret.append(0)
ret.append(0)
return ret
def dailyTemperatures2(self, temperatures: List[int]) -> List[int]:
"""
Runtime: 1239 ms, faster than 67.44%
Memory Usage: 24.4 MB, less than 97.35%
如果顺序处理,虽然能得出结果,但肯定超时
所以要反过来处理,通过观测可以发现,如果当前处理的数 T[i]大于后面比较的数T[j],则可以直接比较T[j]对应的结果 s 个位数后的结果 T[j+s]
此外,可以用一个变量标识当前处理数T[i]右边最大的数max,如果 T[i] >= max,那么 T[i] 对应的数肯定是0了。
:param temperatures:
:return:
"""
ret = [0]
l = len(temperatures)
for i in range(l - 2, -1, -1):
j = i + 1
while j <= l:
if temperatures[j] > temperatures[i]:
ret.append(j - i)
break
elif ret[l - j - 1] == 0:
ret.append(0)
break
else:
j += ret[l - j - 1]
ret.reverse()
return ret
def test():
assert Solution().dailyTemperatures2([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
if __name__ == '__main__':
test()
|
6c3728db4e39c83647c7d045ba131af0f5b35521 | SimretA/CPV | /quicksort.py | 625 | 4.0625 | 4 | def quick_sort(list1):
if len(list1) > 1:
left = list()
right = list()
pivot = list1[-1]
for i in range(0, len(list1)-1):
if list1[i] > pivot:
right.append(list1[i])
else:
left.append(list1[i])
print("left pivot right", left, pivot, right)
if len(left) > 0:
left = quick_sort(left)
if len(right) > 0:
right = quick_sort(right)
return left + [pivot] + right
else:
return list1
if __name__ == '__main__':
list1 = [3, 10, 22, 9, 11]
print(quick_sort(list1)) |
576ddb993ed3b221798b6530cb11bcacb92e8b2d | vaclav0411/algorithms | /Задания 13-го спринта/Простые задачи/F. Стек - Max.py | 640 | 3.6875 | 4 | class StackMax:
def __init__(self):
self.items = []
def push(self, x):
self.items.append(x)
def pop(self):
if self.items:
return self.items.pop()
else:
print('error')
def get_max(self):
if self.items:
print(max(self.items))
else:
print('None')
if __name__ == "__main__":
c = int(input())
s = StackMax()
for i in range(c):
k = input().split()
if k[0] == 'get_max':
s.get_max()
elif k[0] == 'pop':
s.pop()
elif k[0] == 'push':
s.push(int(k[1]))
|
33583d7ddcd40ae0303255c123e7062d076045f3 | dongbo910220/leetcode_ | /Dynamic Programming/322. Coin Change Medium.py | 771 | 3.625 | 4 | '''
https://leetcode.com/problems/coin-change/
'''
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
n = amount + 1
dp = [amount + 1] * n
dp[0] = 0
for i in range(1, n):
minval = float('inf')
for coin in coins:
if i >= coin:
dp[i] = min(dp[i], dp[i - coin] + 1)
if dp[amount] == amount + 1:
return -1
else:
return dp[amount]
'''
Success
Details
Runtime: 1068 ms, faster than 60.56% of Python online submissions for Coin Change.
Memory Usage: 13.1 MB, less than 12.50% of Python online submissions for Coin Change.
''' |
c23f5dd4d508f0bafc278fa903bb038be8d9fb84 | DavidArmendariz/data-structures-hse | /week3/fibonacci.py | 203 | 3.6875 | 4 | count = 0
def foo(n):
global count
count += 1
if n == 0 or n == 1 or n == 2:
return 1
return foo(n - 1) + 2 * foo(n - 3)
if __name__ == "__main__":
foo(6)
print(count) |
003cf2b5c7d94ae86de8eb430551c1e808a81f35 | diegoasanch/Fundamentos-de-Progra-2019 | /TP5 Funciones/TP5.13 Extraccion de los ultimos N digitos.py | 1,360 | 3.96875 | 4 | # Devolver los últimos N dígitos de un número entero pasado como parámetro. El valor de N también
# debe ser pasado como parámetro. Devolver el número completo si N es demasiado grande. Ejemplo:
# ultimosdigitos(12345,3) devuelve 345, y ultimosdigitos(12345,8) devuelve 12345.
#funcion extraer digito
def extraerdigito(entero,extraer):
cont=1
digitosinv=0
while cont <= extraer:
digitosinv = digitosinv * 10 + (entero % 10) #extraccion de los ultimos digitos pero invertidos
entero = entero // 10 #y se le quita el ultimo digito al entero para repetir el ciclo
cont = cont + 1
digitoscorrectos = inversor(digitosinv)
return digitoscorrectos
#funcion para invertir el numero extraido
def inversor(n):
inv=0
while n>0:
inv= (inv*10) + n % 10
n=n//10
return inv
#verificador de positividad de un numero
def verifnum(tipo):
print('>>> Ingrese',tipo,': ',end='')
n=int(input())
while n<0:
print('\nNo ingreso un numero valido!!!')
print('>>> Ingrese',tipo,': ',end='')
n=int(input())
return n
#programa principal
print('Ingrese un numero entero y extraiga los ultimos n digitos de el')
A=verifnum('un numero') #primer numero
B=verifnum('la cantidad a extraer') #digitos a extraer
extraido=extraerdigito(A,B)
print(extraido)
|
b234511c394f2cf35fbeb34f18c869895ae9c07c | sjdlloyd/piProjects | /time-lapse/timer.py | 495 | 3.8125 | 4 | import datetime
import time
def time_in_range(start, end, x):
"""Return true if x is in the range [start, end]"""
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end
def sleep_in_time_range(start,end, sleep_len= 600):
now = datetime.datetime.now()
nowt = now.time()
while time_in_range(start, end, nowt):
now = datetime.datetime.now()
nowt = now.time()
print(nowt,'zzzz')
time.sleep(sleep_len)
|
00918245f13c27a1ec4ea2f1df8d35a87262c0b5 | JasonLuis/python-basico | /dicionarios_e_conjuntos.py | 1,125 | 3.84375 | 4 | """
##Coleções
#Dicionários
"""
coleta = {
'Aedes aegypt': 32,
'Aedes albopictus': 22,
'Anopheles darlingi': 14
}
print(coleta['Aedes aegypt'])
coleta['Rhodnius montenegrensis'] = 11
print(coleta)
del(coleta)['Aedes albopictus']
print(coleta)
#retorna os items do dicionario
print(coleta.items())
#retorna as chaves
print(coleta.keys())
#retorna os valores
print(coleta.values())
coleta2 = {'Anopheles gambiae': 13,'Anopheles deaneorum': 14}
print(coleta2)
coleta.update(coleta2)
print(coleta)
print(coleta.items())
for especie, num_especimes in coleta.items():
print(f'Espécie: {especie}, número de espécimes coletados: {num_especimes}')
"""
##Conjuntos(set)
"""
biomoleculas = ('proteína','ácidos nucleicos','carboidrato', 'lipídeo',
'ácidos nucleicos','carboidrato','carboidrato','carboidrato')
print(biomoleculas)
print(set(biomoleculas))
c1 = {1,2,3,4,5}
c2 = {3,4,5,6,7}
#so retornarão os numeros que se encontram nos conjuntos em c1 e tambem em c2
c3 = c1.intersection(c2)
print(c3)
#so retornarão os numeros que tem no conjunto c1, mas não no c2 e tem no c2, mas não se encontram em c1
c3 = c1.difference(c2)
print(c3) |
48ae76611afc50260e874c6c39844db85004d040 | cubeyang/python_15 | /test_0221/xyz.py | 221 | 3.796875 | 4 | #huash12
sum=0
for i in range(1, 5):
for j in range(1, 5):
for z in range(1, 5):
if i != j and i != z and j != z:
print("{}{}{}".format(i,j,z))
sum=sum+1
print(sum)
|
7f33fb8cfaba04d49f97be9e9a93f253fb3b7fbb | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex017.py | 329 | 3.8125 | 4 | import math
co = float(input('Digite o valor do cateto \033[1;31moposto\033[m: '))
ca = float(input('Digite o valor do cateto \033[1;32mdjacente\033[m: '))
h = math.sqrt((co ** 2) + (ca ** 2))
print('\033[1;31mCateto oposto: {}\033[m\n\033[1;32mCateto adjacente: {}\033[m\n\033[1;35mHipotenusa: {}\033[m'.format(co, ca, h))
|
f08e438f08d7ad115e13679acf9a523289343a73 | Abhijit070590/Evaluation-of-python-program | /2013-09-30-Midterm/checkChessCheck/IMT2013038checkChessCheck.py | 8,918 | 4.21875 | 4 | def find_kings(board):
'''
Find the positions of the two kings
return a hash that has a tuple (x,y) associated with 'k' and 'K' (black and white kings) respectively
'''
kings = {}
for row in board:
for column in row:
if(column=='k'):
kings['k']=(row,column)
if(column=='K'):
kings['K']=(row,column)
return kings
def check_pawn_attack(board, k, king_pos):
'''
Check if the king (argument k - it is 'k' if it is black king and 'K' for white king) at position king_pos
- king_pos is a tuple (row, col) - is being attacked by a opposite color pawn
black king -- check positions (1, +/- 1) away from king_pos and see if any of them is a white pawn
white king -- check positions (-1, +/- 1) away from king_pos and see if any of them is a black pawn
You need to of course first check that these are legal board positions
Return a tuple (k, attacker, attacker_x, attacker_y) - attacker will be 'P' or 'p' depending on
whether k is 'k' or 'K' - if the king is under check, else return None
'''
check = None
if k=='k':
i=king_pos[0]
j=king_pos[1]
for row in board:
if(row==i):
attacker_x=row
prev= row-1
for column in prev:
c1=j-1
c2=j+1
if c1=='P':
attacker='p'
attacker_y=c1
if c2=='p':
attacker='p'
attacker_y=c2
after=row+1
for column in row:
c1=j-1
c2=j+1
if c1=='P':
attacker='p'
attacker_y=c1
if c2=='p':
attacker='p'
attacker_y=c2
check=(k,attacker,attacker_x,attacker_y)
if k=='K':
i=king_pos[0]
j=king_pos[1]
for row in board:
if(row==i):
prev=row-1
for column in prev:
c1=column-1
c2=column+1
if c1=='P':
attacker='P'
attacker_y=c1
if c2=='p':
attacker='P'
attacker_y=c2
after=row+1
for column in after:
c1=column-1
c2=column+1
if c1=='P':
attacker='P'
attacker_y=c1
if c2=='p':
attacker='P'
attacker_y=c2
check=(k,attacker,attacker_x,attacker_y)
return check
def check_knight_attack(board, k, king_pos):
'''
Check if the king (argument k - it is 'k' if it is black king and 'K' for white king) at position king_pos
- king_pos is a tuple (row, col) - is being attacked by a opposite color knight
check positions (+/- 1, +/- 2), (+/- 2, +/- 1) away from king_pos and see if any of them is a opposite color knight
You need to of course first check that these are legal board positions
Return a tuple (k, attacker, attacker_x, attacker_y) - attacker will be 'N' or 'n' depending on
whether k is 'k' or 'K' - if the king is under check, else return None
'''
check = None
''' You code comes here '''
knightpos=()
if k=='k':
i=king_pos[0]
j=king_pos[1]
for rowk in board:
for columnk in rowk:
if columnk=='N':
knightpos=(rowk,columnk)
if cmp((i+1,j+2),knightpos)==0:
attacker='n'
attacker_x=rowk
attacker_y=columnk
if cmp((i-1,j+2),knightpos)==0:
attacker='n'
attacker_x=rowk
attacker_y=columnk
if cmp((i+1,j-2),knightpos)==0:
attacker='n'
attacker_x=rowk
attacker_y=columnk
if cmp((i-1,j-2),knightpos)==0:
attacker='n'
attacker_x=rowk
attacker_y=columnk
check = (k,attacker,attacker_x,attacker_y)
if k=='K':
i=king_pos[0]
j=king_pos[1]
for rowk in board:
for columnk in rowk:
if columnk=='n':
knightpos=(rowk,columnk)
if cmp((i+1,j+2),knightpos)==0:
attacker='N'
attacker_x=rowk
attacker_y=columnk
if cmp((i-1,j+2),knightpos)==0:
attacker='N'
attacker_x=rowk
attacker_y=columnk
if cmp((i+1,j-2),knightpos)==0:
attacker='N'
attacker_x=rowk
attacker_y=columnk
if cmp((i-1,j-2),knightpos)==0:
attacker='N'
attacker_x=rowk
attacker_y=columnk
check = (k,attacker,attacker_x,attacker_y)
return check
def check_check(board):
'''
Check if the black or the white king on the board is being attacked by a opposite color piece
Find the position of the kings. For each color king
1. Check if it is being attacked by an opposite color pawn
2. Check if it is being attacked by an opposite color knight
3. Try Moving in directions (0,1), (0,-1), (1,0), (-1,0) from the king_position and check if the first non-blank
square is occupied by an opposite color Rook or Queen
4. Try Moving in directions (1,1), (1,-1), (-1,1), (-1,-1) from the king_position and check if the first non-blank
square is occupied by an opposite color Bishop or Queen
You need to of course first check that these are legal board positions
Return a tuple (k, attacker, attacker_x, attacker_y) if a king is under check - else return None
'''
check = None
''' You code comes here '''
kings = {}
kingpos=()
for row in board:
for column in row:
if(column=='k'):
kings['k']=(row,column)
if(column=='K'):
kings['K']=(row,column)
kingpos=kings['k']
pos1=kingpos[0][0]
pos2=kingpos[0][1]
for rowr in board:
for columnr in rowr:
if columnr=='R':
rookpos=(rowr,columnr)
for rowq in board:
for columnq in rowr:
if columnq=='Q':
queenpos=(rowq,columnq)
if cmp((pos1,pos2+1),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1,pos2+1),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
if cmp((pos1,pos2-1),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1,pos2-1),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
if cmp((pos1+1,pos2),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1+1,pos2),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
if cmp((pos1-1,pos2),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1-1,pos2),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
check=('k',attacker,attacker_x,attacker_y)
kingpos=kings['K']
pos1=kingpos[1][0]
pos2=kingpos[1][1]
for rowr in board:
for columnr in rowr:
if columnr=='R':
rookpos=(rowr1,columnr1)
for rowq in board:
for columnq in rowq:
if columnq=='Q':
queenpos=(rowq,columnq)
if cmp((pos1,pos2+1),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1,pos2+1),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
if cmp((pos1,pos2-1),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1,pos2-1),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
if cmp((pos1+1,pos2),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1+1,pos2),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
if cmp((pos1-1,pos2),rookpos)==0:
attacker='R'
attacker_x=rowr
attacker_y=columnr
if cmp((pos1-1,pos2),queenpos)==0:
attacker='Q'
attacker_x=rowq
attacker_y=columnq
check('K',attacker,attacker_x,attacker_y)
return check
if __name__ == '__main__':
pass
|
32c4ee6896dfd3b985c965c977e8d0f73379e746 | IngridFCosta/Exercicios-de-Python-Curso-em-video | /Strings/ex023_separarDigitos.py | 390 | 3.984375 | 4 | """023- faça um programa que leia um numero
de 0 a 9999 e mostre na tela cada um dos digitos
separados."""
numero=int(input('Escreva um numero inteiro: '))
unidade=numero//1%10
dezena=numero//10%10
centena=numero//100%10
milhar=numero//1000%10
print('Unidade: {}'.format(unidade))
print('Dezena: {}'.format(dezena))
print('Centena: {}'.format(centena))
print('Milhar: {}'.format(milhar)) |
1c4b8a8d34ceb431c38f30764258ffa6c078bc26 | KiruthikaGopalsamy/GraduateTrainingProgram2018 | /Python/Day4.py | 2,572 | 4.21875 | 4 | <PROBLEM SET 04> SEPTEMBER 05,2018
SUBMITTED BY kiruthika.gopalsamy
"""You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
alison heck => Alison Heck
Given a full name, your task is to capitalize the name appropriately.
Input Format:-
A single line of input containing the full name, S .
Constraints:-
* 0<len(S)<1000
* The string consists of alphanumeric characters and spaces."""
name=raw_input("enter name")
new=""
c_name=name.split(' ')
for i in range(len(c_name)):
new=new+c_name[i].capitalize()+" "
print new
import string
name=raw_input("enter name")
print string.capwords(name)
"""
You have a record of students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer followed by the names and marks for students. You are required to save the record in a dictionary data type. The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places.
Input Format:-
The first line contains the integer N, the number of students. The next lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed.
Constraints:-
* 2<=N<=10
* 0<=MARKS<=100
"""
def sum_stu():
sum_s={}
for k,v in student_details.iteritems():
sum_s[k]=sum(v)
print("total mark%s"%sum_s)
def avg(new):
avg_s={}
k1=new
for k,v in student_details.iteritems():
if(k==k1):
print(float(sum(v)/len(v)))
#print("average mark%s"%avg_s[k])
student_details={}
std_count=raw_input("enter no student")
for i in range(int(std_count)):
name=raw_input("enter student name")
sub_count=raw_input("enter no of subject")
student_marklist=[]
for j in range(int(sub_count)):
j=j+1
v=input("enter marks of subject"+str(j)+":")
student_marklist.append(v)
student_details[name]=student_marklist
print(student_details)
sum_stu()
new=raw_input("enter name to find avg")
avg(new)
"""
Exceptions
----------
Errors detected during execution are called exceptions."""
def div(n1,n2):
try:
p=n1/n2
print(p)
except Exception as error:
print error
n= raw_input("enter range")
for i in range(int(n)):
n1=raw_input("enter number 1")
try:
div(int(n1),int(n2))
except Exception as error:
print error
|
2669789aca50c3d6a4bfc0d46f2a621b584a0b35 | wngus9056/Datascience | /Python&DataBase/5.17/hou/Python06_23_Chap02_김주현.py | 1,788 | 3.828125 | 4 |
'''
#1.
grade = [1, 2, 3]
1.loop 적용
2. 합계
3. 평균 : len()
'''
grade = [80, 75, 55]
gsum = 0
for x in grade:
gsum += x
ave = (gsum/len(grade))
print('# 문제 1.')
print('합계 : ', gsum)
print('평균 : ', ave)
print()
print('-'*15)
'''
#2.
int(input()) 숫자 입력
짝수 입니다.
홀수 입니다.
'''
print('# 문제 2.')
number = int(input('숫자를 입력하세요 : '))
if number % 2 == 0:
print('짝수입니다.')
elif number % 2 ==1:
print('홀수입니다.')
print()
print('-'*15)
'''
#3.
슬라이스
'''
print('# 문제 3.')
pin = '881120-1068234'
yyyymmdd = pin[:5]
num = pin[7:]
print('yyyymmdd : ',yyyymmdd, '\n'+'num : ', num)
print()
print('-'*15)
'''
#4.
1, 3 남자
2, 4 여자
'''
print('# 문제 4.')
pin01 = '881120-1068234'
gender = pin01[7]
if gender == '1' or gender == '3':
print('남자입니다.')
elif gender == '2' or gender == '4':
print('여자입니다.')
print()
print('-'*15)
'''
#5.
replace
'''
print('# 문제 5.')
a_5 = 'a:b:c:d'
a_5 = a_5.replace(':','#')
print(a_5)
print()
print('-'*15)
'''
#6.
sort
reverse
'''
print('# 문제 6.')
a_6 = [1, 3, 5, 4, 2]
a_6.sort()
a_6.reverse()
print(a_6)
print()
print('-'*15)
'''
#7.
join
'''
print('# 문제 7.')
a_7 = ['Life', 'is', 'too', 'short']
result_7 = " ".join(a_7)
print(result_7)
print()
print('-'*15)
'''
#8.
a + (4,)
'''
print('# 문제 8.')
a_8 = (1, 2, 3)
a_8 = a_8 + (4,)
print(a_8)
print()
print('-'*15)
'''
#9.
오류 이유
'''
print('# 문제 9.')
a_9 = dict()
print(a_9)
a_9['name'] = 'python'
a_9[('a',)] = 'python'
#a_9[[1]] = 'python' #리스트는 딕셔너리로 만들 수 없다.
a_9[250] = 'python'
print(a_9)
|
ba085c3bffc229e511eb2476504863e423380e66 | Nitesh101/test | /assignments/python_ assignments/command_line_argu.py | 1,341 | 4.0625 | 4 | #!/usr/bin/python
"""
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
#/!usr/bin/python
import sys
print "command line argument are: ",
total_nums = len(sys.argv)
if total_nums > 1:
for index in range(1,total_nums):
num = (sys.argv[index])
if num.isdigit():
print num ,"it is number"
elif num.isalpha():
print num ,"it is string"
else:
print ("No argument passed")
"""
import sys
from sum_num import sumNum
from stringadd import addString
if len(sys.argv) == 1:
print("Pass cmd arguments (either num or string)")
else:
count = 0
for val in sys.argv[1:]:
if val.isdigit():
count += 1
pass
else:
break
else:
sumNum(sys.argv[1:])
if count == 0:
if all(isinstance(e, str) for e in sys.argv[1:]):
for val in sys.argv[1:]:
if val.isdigit():
print("Pass cmd arguments (either num or string)")
sys.exit()
addString(sys.argv[1:])
else:
print("Pass cmd arguments (either num or string)")
|
3b33abec5143deccf9227511e5af51e1ad592a78 | AyelenDemaria/frro-soporte-2019-23 | /practico_01/ejercicio-05.py | 327 | 3.640625 | 4 | # Implementar la función es_vocal, que reciba un carácter y
# devuelva un booleano en base a si letra es una vocal o no.
# Resolver utilizando listas y el operador in.
def es_vocal(letra):
if letra in ['a','e','i','o','u']:
return True
return False
assert (es_vocal('a')) == True
assert (es_vocal('b')) == False
|
166f0746a2f7ba2dac3d8e94738d7e78f74217e1 | taruchit/CodeChef_Beginner | /Pall01.py | 310 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 12:29:28 2021
@author: pc
"""
#Number of testcases
T=int(input())
#Input, Computation and output
for i in range(T):
N=input()
N1=int(N)
temp=N[::-1]
N2=int(temp)
if(N1==N2):
print("wins")
else:
print("loses")
|
719bc3f463435654f6a838b059a59b43c55701c1 | nazlitemur/oware | /players/oware/oware_human.py | 1,416 | 3.625 | 4 | import game_state
import game_player
import oware
class OwarePlayer(game_player.GamePlayer):
def __init__(self, name, game_id):
game_player.GamePlayer.__init__(self, name, game_id)
def minimax_move(self, state):
# see what the valid moves are so we can check the human's answer
successors = state.successor_moves()
successors = [x.get_move() for x in successors]
# Keep looping until the human gives us valid input
while True:
# Ask
s = raw_input("What pit would you like to move (1-6, q to quit)? ")
# Human wants to quit
if s == 'q':
# so return a forfeit move
return oware.OwareMove(self.game_id, None, True)
# Human may not have input an integer
try:
s = int(s)
except:
print "Please input an integer 1-6, or q to quit "
continue
# Human may not have input a value on the board
if s >= 1 and s <= 6:
s -= 1
else:
print "Please input an integer 1-6, or q to quit "
continue
# Human may not have input a valid move
if s not in successors:
print "That is not a valid move. Please choose a pit "\
"containing stones or which does not deprive the opponent "\
"of moves."
continue
# Return the valid move
return oware.OwareMove(self.game_id, s)
def alpha_beta_move(self, state):
return self.minimax_move(state)
def tournament_move(self, state):
return self.minimax_move(state) |
2500331d622071e6a2d52b03af667091ec17ea45 | MichalChim/PW_Python | /Zmienne, funkcje/1. Typy danych/exercise_1.py | 417 | 3.546875 | 4 | a = 1
print("Zmienna a typu int =>", type(a))
b = 5.32
print("Zmienna b typu float =>", type(b))
c = "test"
print("Zmienna c typu string =>", type(c))
d = """
Test Test
wielolinijkowy długi napis
"""
print("Zmienna d typu string =>", type(d))
e = True
print("Zmienna d typu bool =>", type(e)) # komentarz
# input() => funkcja która pyta na konsoli o dane
# type() => funkcja ktora zwraca typ zmiennej
|
474300a61b014513acda2cfe82cb6024014ad7e4 | n0ma/code | /3.py | 243 | 3.78125 | 4 | def primes(limit)
i = 7
primes = [2, 3, 5]
while len(primes) <= limit:
prime = True
for x in primes:
if i % x == 0: prime = False
if prime: primes.append(i)
i += 2
return primes
|
fed7b075cc121eeb3bcd6369185bd16273709dbe | 2453302416/py1 | /day8/eml.py | 292 | 3.546875 | 4 | # 编写函数,判断输入参数字符串是否为邮箱地址,
# 检验条件为:字符串中间用@分隔,末尾是.com或者.net(
arr1 = input('请输入字符串邮箱:')
arr2 = 'com'
if arr2 in arr1:
print('邮箱正确')
else:
print('邮箱不正确请重新输入') |
5749e822a7016fab678ad217cb5ddcd047e19434 | Kirkules/Python-Challenges | /linkedlist.py | 920 | 3.828125 | 4 | # Kirk Boyer
# Sunday, Dec. 29
# This challenge is a sequence of sites with url
# www.pythonchallenge.com/pc/def/linkedlist.php?nothing=#####
# where the last part is a 5-digit number.
# My guess is that eventually they'll stop the pattern at some point and either
# give another hint about the next challenge's url, or give it directly.
# Either way, there are only so many 5-digit numbers.
import urllib.request
import re
# original starting point: nothing = "12345"
nothing = "25357"
theUrl = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
site = urllib.request.urlopen(theUrl+nothing)
pattern = re.compile("the next nothing is ([0-9]+)")
result = pattern.findall(site.read().decode())
while result != []:
print("nothing is now: ")
print(nothing)
nothing = result[0]
site = urllib.request.urlopen(theUrl+nothing)
result = pattern.findall(site.read().decode())
print(nothing)
|
915033e9e98cff67f8dca15589ae6602192bd7b8 | bilal8171/file_based_key_value_datastore | /code_Module.py | 2,625 | 3.53125 | 4 | from threading import*
import time
database={} #Actually its dictionary
def create(k,v,timeout=0):
if k in database:
print("error: this key already exists")
else:
if(k.isalpha()):
if len(database)<(1024*1024*1024) and v<=(16*1024*1024):
if timeout==0:
l=[v,timeout]
else:
l=[v,time.time()+timeout]
if len(k)<=32:
database[k]=l
print('Key, value has been inserted in Databases')
else:
print("error: Memory limit exceeded!! ")
else:
print("error: Invalind key_name!! key_name must contain only alphabets and no special characters or numbers")
def read(k):
if k not in database:
print("error: given key does not exist in database. Please enter a valid key")
else:
b=database[k]
if b[1]!=0:
if time.time()<b[1]:
stri=str(k)+":"+str(b[0]) #to return the value in the format of JasonObject i.e.,"key_name:value"
print(stri)
else:
print("error: time-to-live of",k,"has expired")
else:
stri=str(k)+":"+str(b[0])
print(stri)
def delete(k):
if k not in database:
print("error: given key does not exist in database. Please enter a valid key") #error message4
else:
b=database[k]
if b[1]!=0:
if time.time()<b[1]: #comparing the current time with expiry time
del database[k]
print("key is successfully deleted")
else:
print("error: time-to-live of",k,"has expired") #error message5
else:
del database[k]
print("key is successfully deleted")
def modify(k,v):
b=database[k]
if b[1]!=0:
if time.time()<b[1]:
if k not in database:
print("error: given key does not exist in database. Please enter a valid key") #error message6
else:
l=[]
l.append(v)
l.append(b[1])
database[k]=l
else:
print("error: time-to-live of",k,"has expired")
else:
if k not in database:
print("error: given key does not exist in database. Please enter a valid key") #error message6
else:
l=[]
l.append(v)
l.append(b[1])
database[k]=l
print('Database after Modification key --> {} '.format(database)) |
17e7694a091ff362f3eb436e9fdea1925d34db1f | Trismeg/python_beg | /circlesrand.py | 257 | 3.59375 | 4 | from graphics import *
wind=GraphWin()
wind.setCoords(0,0,10,11.2)
centers=[]
for i in range(10):
centers=centers+[Point(5,1+i)]
circles=[]
for i in range(10):
circles=circles+[Circle(centers[i],1)]
for i in range(10):
circles[i].draw(wind)
|
6a6b828072ff809269408f1a88e5427a6a8876ab | Jessicammelo/cursoPython | /tipo_booleano.py | 284 | 3.71875 | 4 | #True -> verdadeiro
#False -> falso
ativo = True
logado = False
print(ativo)
print(not ativo)
print(ativo or logado)
"""
Ou (or)
Um deve ser verdadeiro
True or False
False or True
True or True
E (end)
Se tiver algume false é false tudo
se for tudo false é verdadeiro
"""
|
1c9247f5d4679880f33b52f73ba9508d27600ca2 | jasminro/2021python | /Week5/h3.py | 799 | 4.09375 | 4 | def palindrome(word):
word = word.lower()
word = "".join(word.split())
if len(word) <= 1:
return True
elif word[0] != word[-1]:
return False
return palindrome(word[1:-1])
strn = 'Saippuakauppias'
result = palindrome(strn)
if result==True:
print("a palindrome!")
else:
print("not a palindrome!")
'''
Harjoitus 3
Alla oleva funktio tarkistaa, onko sana palindromi. Kirjoita funktiosta rekursiivinen versio.
Ratkaisu voi olla helpompi, jos jaat sen useampaan funktioon.
def isPalindrome(word):
word = word.lower()
# Poistaa kaikki white spacet
word = "".join(word.split())
start = 0
end = len(word) - 1
while start <= end:
if word[start] != word[end]:
return False
start += 1
end -= 1
return True
''' |
afa962dbe99e88ea066f69e9247d8b57f175b2a0 | walonso/Python_Estudio | /3 Temas avanzados/1 Modulos/3 Paquetes Comunes/Ejercicios/3 Generador/generador.py | 1,150 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 15:06:57 2019
@author: walonsor
"""
import random
import math
def leer_numero(ini, fin, mensaje):
while True:
try:
valor = int(input(mensaje))
except:
print("Error: Número no válido")
else:
if valor >= ini and valor <= fin:
break;
return valor;
def generador():
numeros = leer_numero(1,20,"¿Cuantos numeros quieres generar? [1,20]")
modo = leer_numero(1,3,"¿Cómo quieres redondear los números? [1]Al alza [2]A la baja [3]Normal:")
lista = []
for i in range(numeros):
numero = random.uniform(0,101) #0 - 100 numeros
if modo == 1:
print("{} => {}".format(numero, math.ceil(numero)))
numero = math.ceil(numero)
elif modo == 2:
print("{} => {}".format(numero, math.floor(numero)))
numero = math.floor(numero)
elif modo == 3:
print("{} => {}".format(numero, round(numero)))
numero = round(numero)
lista.append(numero)
return lista
generador() |
c4a7b1be43e2f5069083698329eb7274bf918e42 | summer-vacation/AlgoExec | /tencent/array_and_str/longest_palindrome.py | 2,022 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
File Name: longest_palindrome
Author : jing
Date: 2020/3/18
https://leetcode-cn.com/explore/interview/card/tencent/221/array-and-strings/896/
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
if s is None or len(s) == 0:
return ""
result = s[0]
max_len = 1
lens = len(s)
for i in range(lens):
j = i+1
while j < lens:
pp = s[i:j+1]
if pp == pp[::-1]:
if j + 1 - i > max_len:
max_len = j - i
result = pp
j += 1
return result
def longestPalindrome2(self, s: str) -> str:
n = len(s)
if n < 2 or s == s[::-1]:
return s
max_len = 1
start = 0
for i in range(1,n):
even = s[i-max_len:i+1]
odd = s[i-max_len-1:i+1]
if i-max_len-1 >= 0 and odd == odd[::-1]:
start = i-max_len-1
max_len += 2
continue
if i-max_len >= 0 and even == even[::-1]:
start = i-max_len
max_len += 1
return s[start:start+max_len]
def longestPalindrome3(self, s: str) -> str:
if s is None or len(s) == 0:
return ""
if len(s) == 1 or self.isPalindrome(s):
return s
start, end = 0, 0
max_len = 0
result = None
while start < len(s):
end = start
while end < len(s):
if self.isPalindrome(s[start:end+1]):
if max_len < end-start+1:
result = s[start:end+1]
max_len = end-start+1
end = end + 1
start += 1
return result
def isPalindrome(self, inputs):
return inputs == inputs[::-1]
if __name__ == '__main__':
print(Solution().longestPalindrome3("ac"))
|
39c6770ff43b8876791540bcaaa99e08fe1268d4 | algebra-det/Python | /DataStructures/Total_of_non_diagonal.py | 1,844 | 3.90625 | 4 | # Here we are making lists for each diagonal
# One list for the top-left to right-bottom diagonal
# Second list for bottom-left to top-right diagonal
# Than Iterating through each row and column and checking if the (row number, column number) is in the diagonal list
# If it's in the diagonal list than "PASS" otherwise ADD to the TOTAL
def non_diagonals(arr): # To get zipped list of both diagonals
first_row = []
second_column = []
backward_first_row = []
backward_second_column = []
for i in range(len(arr)): # top-left to right-bottom diagonal
first_row.append(i)
second_column.append(i)
for j,k in enumerate(range((len(arr)-1),-1,-1)): # bottom-left to top-right diagonal
backward_first_row.append(j)
backward_second_column.append(k)
mello = list(zip(first_row,second_column)) # # top-left to right-bottom diagonal
bello = list(zip(backward_first_row,backward_second_column)) # bottom-left to top-right diagonal
return mello, bello
arr=[[1, 2, 3, 4], [5, 6, 7, 8],[9, 10, 11, 12], [13, 14, 15, 16]]
# Getting the diagonals list
first_zip, second_zip = non_diagonals(arr)
total = 0 # Having a variable to hold the total
for i in range(len(arr)): # 0,1,2,3,...
for j in range(len(arr)): # 0,1,2,3,...
for k in first_zip: # Checking for the first_zip(diagonal)
if i==k[0] and j==k[1]: # if (i,j) are in first_zip(diagonal) than break here and don't go further
break
else: # If (i,j) are NOT in first_zip(diagonal) than Go to check for second_zip(diagonal)
for l in second_zip: # Checking for second_zip(diagonal)
if i==l[0] and j==l[1]: # If (i,j) are in second_zip(diagonal) than break here and don't go further
break
else: # If not in second_zip(diagonal) than add the value of this certain index [i][j]
total += arr[i][j]
print(total)
|
3fc2da8fc0f70ab303510c890a43f3ec20ffdae4 | ZachMillsap/PyCharm | /Module2/main/camper_age_input.py | 551 | 4.1875 | 4 | """
Program: camper_age_input.py
Author: Zach Millsap
Last date modified: 06/03/2020
The purpose of this program is to accept any integer(years), and
convert to months(integer).
"""
def convert_to_months(x):
return
if __name__ == '__main__': ''
years = int(50)
convert_to_months = int(years * 12)
print(years, " years is ", convert_to_months, " months")
# Input Expected Output Actual Output
# 8 96 96
# 26 312 312
# 50 600 600
|
689f38f10d85f0f6a7a1ade2a4a773b4796b22f0 | rgjha/Useful_Scripts | /multiplicative_order_compute.py | 385 | 4.03125 | 4 | import numpy as np
from math import *
def multiplicative_group(n):
# Returns the multiplicative group (MG) modulo n.
# n: Modulus of the MG.
assert n > 1
group = [1]
for x in range(2, n):
if gcd(x, n) == 1:
group.append(x)
return group
n = 21
print(f"The multiplicative group modulo n = {n} is:")
print(multiplicative_group(n))
|
9b257cdc5fe30b6bb1b8cc13684dd9c5e11b8657 | hstefek/Wikipedia_BDD | /features/pages/log_in.py | 1,184 | 3.5 | 4 | #Name: Wikipedia website test
#Author: Hrvoje Stefek
#Tools: Python, Behave, Nose, Selenium
#Note: Feel free to edit and reuse the code, it is made as tutorial and quick showcase
from selenium.webdriver.common.by import By
from browser import Browser
class LogInLocator(object):
HEADER_TEXT = (By.XPATH, "//h1")
USERNAME = (By.ID, "wpName1")
PASSWORD = (By.ID, "wpPassword1")
SUBMIT_BUTTON = (By.ID, "wpLoginAttempt")
class LogIn(Browser):
def get_element(self, *locator):
return self.driver.find_element(*locator)
def fill(self, text, *locator):
self.driver.find_element(*locator).send_keys(text)
def click_element(self, *locator):
self.driver.find_element(*locator).click()
def navigate(self, address):
self.driver.get(address)
def get_page_title(self):
return self.driver.title
def login(self, user, paswd):
self.driver.find_element(*LogInLocator.USERNAME).clear()
self.driver.find_element(*LogInLocator.PASSWORD).clear()
self.fill(user, *LogInLocator.USERNAME)
self.fill(paswd, *LogInLocator.PASSWORD)
self.click_element(*LogInLocator.SUBMIT_BUTTON)
|
b783b6fbba31fbe7b6fa6032f2c8729c0969eded | miohsu/CodingInterviews | /07/07_1.py | 1,831 | 3.734375 | 4 | """
输入一个二叉树的前序遍历和中序遍历的结果,请重建二叉树,假设输入的前序遍历和中序遍历的结果中不含重复的值。
例如,输入前序遍历[1, 2, 4, 7, 3, 5, 6, 8],中序遍历[4, 7, 2, 1, 5, 3, 8, 6],则重建二叉树并输出它的头结点。
"""
class BinaryTreeNode(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def construct_core(preorder, inorder):
root_node = BinaryTreeNode(preorder[0])
if len(preorder) == 1:
if len(inorder) == 1 and preorder == inorder:
return root_node
else:
raise NameError('Error')
index = 0
length = len(inorder)
while index < length and inorder[index] != root_node.value:
index += 1
if index >= length:
raise NameError('Error')
left_length = index
right_length = length - index - 1
if left_length > 0:
root_node.left = construct_core(preorder[1:left_length + 1], inorder[0:left_length])
if right_length > 0:
root_node.right = construct_core(preorder[length - right_length:length],
inorder[length - right_length:length])
return root_node
def construct(preorder, inorder):
if len(preorder) != len(inorder) or len(preorder) == 0:
return None
return construct_core(preorder, inorder)
def get_postorder(root):
if root != None:
get_postorder(root.left)
get_postorder(root.right)
print(root.value)
if __name__ == '__main__':
preorder = [1, 2, 4, 7, 3, 5, 6, 8]
inorder = [4, 7, 2, 1, 5, 3, 8, 6]
# preorder = [1, 3, 4, 5]
# inorder = [5, 4, 3, 1]
root = construct(preorder, inorder)
# print(root.value)
get_postorder(root)
|
d8cc1d911923575060d62c6325bd511b9646ef96 | JoacoDiPerna/frro-soporte-2019-12 | /practico_01/ejercicio-10.py | 571 | 3.828125 | 4 | # Escribir una función mas_larga() que tome una lista de palabras y devuelva la más larga.
# La función devolverá la primer palabra "más larga".
def mas_larga(lista):
length = 0
index = 0
for i in range(0, len(lista)):
if len(lista[i]) > length:
length = len(lista[i])
index = i
return lista[i]
pass
lista = ["caldo", "pepas", "manolo", "diaspora"]
assert (mas_larga(lista) == "diaspora")
assert (mas_larga(lista) != "manolo")
# Otra forma.
def mas_larg(lista1):
return sorted(lista1, key=len)
pass
|
3d8d2765afaa54cfa68f3fc97fa2330651c4d3a7 | zsJacky/CorePython | /python-ex8/8-2.py | 152 | 3.59375 | 4 | def myrange(froms, to, increment):
start = froms
while start <= to:
print start,
start += increment
if __name__ == '__main__':
myrange(2, 26, 4) |
f87c7045623675a99b7541c1552dac641b1b78ee | winiz/Galennor | /final 1.0.5 vertically printed table.py | 3,708 | 3.921875 | 4 |
def welcomeMesg():
print "Welcome to the Survival and Surprises CMPT 120 Games!"
print "========================================================="
def askTwoValues(val1,val2,question):
while True:
truthValue1 = raw_input(question)
if truthValue1 == val1 or truthValue1 == val2:
break
else:
print "Sorry, was it yes or no?(y/n)"
continue
return truthValue1
def eXit(val):
if val == 'n':
raw_input("OK,Bye, press any key to exit the game then")
s.exit()
def read_string_list_from_file(the_file):
fileRef = open(the_file,"r") # opening file to be read
localList=[]
for line in fileRef:
string = line[0:len(line)-1] # eliminates trailing '\n'
# of each line
localList.append(string) # adds string to list
fileRef.close()
return localList
def whichFile():
fileName = ''
while True:
fileName = raw_input("Type the name of board file including '.txt' or type d for default: ")
if fileName == "d":
fileName = "biomesData1.txt"
break
elif not ".txt" in fileName:
print "file with '.txt' please or just d for default........."
continue
elif ".txt" in fileName:
break
return fileName
def create_lists_board(aList): #[['0', '0', '0', '0'], ['1', '10', '0', '1'], ['2', '10', '1', '3'],
#['3', '4', '2', '2'], ['4', '10', '3', '1'], ['5', '10', '1', '1'],
#['6', '10', '3', '3'], ['7', '10', '2', '3']]
i = -1
result = []
for item in aList:
i = i + 1
result += [[str(i)] + item.split('-')]
return result
def biomeList(): #name of biome generator
a = []
for item in listOfList:
a.append(item[0])
return a
def diamon():
a = []
for item in listOfList:
a.append(item[1])
return a
def sword():
a = []
for item in listOfList:
a.append(item[2])
return a
def enemy():
a = []
for item in listOfList:
a.append(item[3])
return a
def show_board(mssg):
print "\nShowing board... " + mssg
print "\n The board at this point contains..."
print "Biome# Diam Sword Enemy"
for i in range (len(listOfList)):
print listOfList[i][0]+' '+listOfList[i][1]+' '+listOfList[i][2]+' '+listOfList[i][3]
#########################################################
#import level
import turtle as t
import math as m
import sys as s
#white level
welcomeMesg() #saying hello
truthValueGame = askTwoValues ('y','n',"Do you want to play? (y/n): ")
eXit(truthValueGame) # it would check the value of truthValueGame and then decide weather to quit or not
truthValueBoard = askTwoValues('y','n',"Do you want to draw the board? (y/n): ") #wheater to show the board?
fileName = whichFile() # fileName could be sth.txt or d for default
listStrings = read_string_list_from_file(fileName) # this reads the flie and out put it as a list
listOfList = create_lists_board(listStrings) # i combined all the little lists into this big one
if truthValueBoard == "y": # some user just don't want to see the board :(
show_board("just created")
print biomeList ()
|
34966b64a827740657952e37fb40ca35902f1929 | yangzongwu/leetcode | /20200215Python-China/0896. Monotonic Array.py | 1,078 | 3.859375 | 4 | '''
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
'''
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if not A:
return True
if len(A)==1:
return True
if A[0]==A[1]:
return self.isMonotonic(A[1:])
if A[0]<A[1]:
for k in range(1,len(A)):
if A[k]<A[k-1]:
return False
return True
if A[0]>A[1]:
for k in range(1,len(A)):
if A[k]>A[k-1]:
return False
return True
|
cfde67af03c2cc3c7ebf11fba210bd075d035f61 | aiden-david-coker/python_crash_course | /working_with_lists.py | 1,395 | 4.25 | 4 | print('-----slicing a list-----')
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# print(players[0:3])
# print(players[1:4])
# print(players[:4])
# print(players[2:])
print('\n-----looping through a slice-----')
print("Here are the first 3 players on my team:")
for players in players[:3]:
print(players.title())
print('\n-----copying a list-----')
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('canoli')
friend_foods.append('ice cream')
print('My favorite foods are:')
print(my_foods)
print('\nMy friends favorite foods are:')
print(friend_foods)
print('\n-----working with tuples-----')
print('\n\n-----dimensions-----')
dimensions = (200, 50)
# print(dimensions[0])
# print(dimensions[1])
#
# # Looping through all values in a Tuples
# for dimension in dimensions:
# print(dimension)
print('Original dimensions:')
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print('\nModified dimensions:')
for dimension in dimensions:
print(dimension)
print('\n-----Tuples Try It Yourself-----')
menu = ('fried eggs', 'hamburgers', 'steak', 'shakes', 'waffles')
print('ORIGINAL MENU:')
for menu in menu:
print(menu)
print('\nNEW MENU:')
menu = ('grilled cheese', 'hamburgers', 'steak', 'shakes', 'fish')
for menu in menu:
print(menu) |
aefa7def75338b969db10ab67df074e8bba28e3a | tanmaya191/Mini_Project_OOP_Python_99005739 | /6_OOP_Python_Solutions/set 4/date_string.py | 228 | 3.71875 | 4 | dates= "45/08/2018"
days=[31,28,31,30,31,30,31,31,30,31,30,31]
dd = 10*int(dates[0]) + int(dates[1])
mm = 10*int(dates[3]) + int(dates[4])
if dd> days[mm]:
dd=dd- days[mm]
mm+=1
print(dd,"/",mm,"/ "+dates[6:10]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.