blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
01db21a5b4469edf3192d8913ee7d2bb62019be9
rogeriosilva-ifpi/teaching-tds-course
/programacao_estruturada/20192_186/Bimestral2_186_20192/Parte 1/prova harife e herbert/4°questao.py
1,126
4.15625
4
print('o animal é vetebrado ou invertebrado?') palavra = input('resposta \n >>>>>>> ') if palavra == 'vertebrado': tipo_de_animal = input('o animal é ave ou mamifero? \n >>>>>') if tipo_de_animal == 'ave': alimento = input('é carnivoro ou onivoro? ') if alimento == 'carnivoro': print('é uma aguia') else: print('é um pombo') elif tipo_de_animal == 'mamifero': alimento = input('é onivoro ou herbivoro?') if alimento == 'onivoro': print('é um homem') else: print('é uma vaca') elif palavra == 'invertebrado': tipo_de_animal = input('o animal é inseto ou anelideo?') if tipo_de_animal == 'inseto': alimento = input('é hematofogo ou herbivoro?') if alimento == 'hematofogo': print('é uma pulga') else: print('é uma lagarta') elif tipo_de_animal == 'anelideo': alimento = input('é hematofogo ou onivoro?') if alimento == 'hematofogo': print('é um sanguessuga') else: print('é uma minhoca')
808e7451794566a0ac3bbf13ae0c9f08555c79e4
skonienczwy/OOP_Python
/Car_Example.py
297
3.703125
4
class Car: def __init__(self,marca,modelo): self.marca = marca self.modelo = modelo def mostrarCarro(self): print(f'A marca do carro é {self.marca} e o modelo é {self.modelo}') x = Car('Audi','A3') y = Car('Teste','Teste 2') x.mostrarCarro() y.mostrarCarro()
2bd274c6d4940ac53fd7e0cfecec71579d3b2511
anjor/Coding-Problems
/ascii_ruler/ascii_ruler.py
1,024
4.375
4
#!/usr/bin/python def populate_last_row(n): """ Populates the last row for a size n ruler.""" row = [] for i in xrange(2**n+1): if i%2==0: row.append('|') else: row.append('_') return row def populate_prev_row(row, n): """ This function is used to populate rows bottom up. The i^th row is populated using the (i+1)^st row. """ newrow = [] first_vert = True for i in xrange(2**n+1): if row[i] == '|': if first_vert: newrow.append('|') first_vert = False else: newrow.append(' ') first_vert = True else: newrow.append(' ') return newrow def main(n): """ For a given n, prints out an ascii ruler of size n. """ all_rows = [] all_rows.append(populate_last_row(n)) for i in xrange(1, n): all_rows.append(populate_prev_row(all_rows[i-1], n)) for row in all_rows[::-1]: print ''.join(row)
b4bfa9dc5e3c371e4d215953835b0f273127442f
neharathig/Comprinno-Technologies
/catsanddog.py
691
3.578125
4
def main(): #Taking input for no of test cases noc = int(input()) #check for validity of no of test cases if noc < 1 or noc > pow (10,5): print("Invalid no of Test cases. Please try again") return else: test_cdl(noc) def test_cdl(noc): for item in range(noc): c , d , l = input().split() c , d , l = int(c), int(d), int(l) maxno = 4 * c + 4 * d #twocatno = 4 * (c-2) + 4 * d minno = 4 * d if (l <= maxno or l >= minno ) and (l %4 ==0): print("yes") else: print("no") if __name__=="__main__": main()
fb67e689e7106c0768e2626bf1f209eb0623b74d
HampusMLTH/pypylon
/producer_consumer.py
1,103
3.5625
4
from queue import Queue import random import threading MAX_QSIZE = 10 # max queue size BUF_SIZE = 100 # total number of iterations/items to process class Producer: def __init__(self, queue, buf_size=BUF_SIZE): self.queue = queue self.buf_size = buf_size def run(self): for _ in range(self.buf_size): self.queue.put(random.randint(0, 100)) # here we do the cont acq class Consumer: def __init__(self, queue): self.queue = queue def run(self): while not self.queue.empty(): item = self.queue.get() self.queue.task_done() print(item) # here we either display or display&save images def main(): q = Queue(maxsize=MAX_QSIZE) producer = Producer(q) producer_thread = threading.Thread(target=producer.run) consumer = Consumer(q) consumer_thread = threading.Thread(target=consumer.run) producer_thread.start() consumer_thread.start() producer_thread.join() consumer_thread.join() q.join() if __name__ == "__main__": main()
e9fe6f4aeed3ae684917f559f5d184b5fe058486
liuyf8688/python-2.7.4-demos
/src/builtinModule/itertools.py
393
3.921875
4
# -*- coding: utf-8 -*- ''' Created on 2017年12月15日 @author: tony ''' import itertools, time # 产生无限迭代器 ''' natuals = itertools.count(1) for n in natuals: print n time.sleep(0.1) ''' # 通过itertools.cycle('ABC'),产生一个无限循环这三个字符的迭代器 # 有限循环迭代器 ns = itertools.repeat('ABC', 10) for n in ns: print n
1fbc6e3de5f0c3d39ceaa2d0463e4d5320bb80ec
haleekyung/python-coding-pratice
/baekjoon/2/Solution2562.py
716
3.515625
4
## 20210720 - Bronze 2 2562번 문제 최대값 찾기 # 9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오. # 예를 들어, 서로 다른 9개의 자연수 # 3, 29, 38, 12, 57, 74, 40, 85, 61 # 이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다. # 첫째 줄에 최댓값을 출력하고, 둘째 줄에 최댓값이 몇 번째 수인지를 출력한다. # testcase : 3, 29, 38, 12, 57, 74, 40, 85, 61 numbers = [] for i in range(9): number = int(input("자연수를 쓰시오:")) numbers.append(number) print(max(numbers)) print(numbers.index(max(numbers))+1)
2e0b9b55997035ec3c7d3c453663583fed434623
sroy8091/daily_coding_problem
/n_orders.py
968
4.0625
4
""" This problem was asked by Twitter. You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. You should be as efficient with time and space as possible. """ class Log(object): def __init__(self, n): self._log = [] self.n = n self.current = 0 def record(self, order_id): if len(self._log) >= self.n: self._log[self.current] = order_id else: self._log.append(order_id) self.current = (self.current + 1) % self.n def get_last(self, i): return self._log[self.current-i] def main(): l = Log(3) for i in range(5): l.record(i) print(l.get_last(1), l._log) if __name__=="__main__": main()
670a7c36c575d237933edb095a5946fb78a0adaf
turuga-2/pythonbysci2pro
/week3/problem2.py
402
3.765625
4
import sys def main(): a = [] n = int(input("Enter the number of elements in list:")) for x in range(0, n): element = int(input("Enter element" + str(x + 1) + ":")) a.append(element) b = [sum(a[0:x + 1]) for x in range(0, len(a))] print("The original list is: ", a) print("The new list is: ", b) return 0 if __name__ == "__main__": sys.exit(main())
239a914e72729c7158162298c98cc98791737de5
merrb/python-challange
/PyBank/main.py
1,404
3.84375
4
import os import csv #path to folder path = "03-Python_02-Homework_Instructions_PyBank_Resources_budget_data.csv" #variables months = [] net_amount = [] changes = [] increase = [] decrease = [] #csvfile with open(path) as csvfile: #csv reader specifies delimter and varible that holds data csvreader = csv.reader(csvfile) #header row first csvheader = next(csvreader) #python list data_list = [row for row in csvreader] #total number of months in the data set num_months = (len(data_list)) #profits and losses over the entire period net = 0 for _ in range(num_months): net = net + int(data_list[_][1]) months.append(data_list[_]) m_change = int(data_list[_][1]) - int(data_list[_-1][1]) changes.append(m_change) #an extra zero is not needed in making the list changes.pop(0) avg_change = round(sum(changes)/len(changes), 2) increase = max(changes) decrease = min(changes) # for row in changes: # if row[1] == increase: # high = row # if row[1] == decrease: # low = row # print(changes.index(max(changes))) # print(net) # print(num_months) # print(changes) # print(avg_change) # print(max(changes)) # print(min(changes)) # print(data_list) print(f'month: {num_months}') print(f'amount: {net}') print(f'change: {avg_change}') print(f'increase: {increase}') print(f'decrease: {decrease}')
988387cfaf8a66d7dc89d03413f32fd97aabeda0
bnm91/FantasyScraperAPI
/FantasyScraperAPI/fantasyScraperUtils/utils.py
961
3.53125
4
# transforms list of rows of csv strings into a single "cvs file" string that is presentable on the web def csv_list_to_csv_string(csv_list): csv_string = '' for row in csv_list: csv_string += row csv_string += ' <br />' return csv_string def find_between_r(s, first): try: start = s.rindex(first) + len(first) end = s.find(u'\xa0') return s[start:end] except ValueError: return "" # breaks dictionary describing a League Scoreboard row into a csv row def comma_separate_values(row_dict): row_string = '' for key in row_dict.keys(): row_string += str(row_dict[key]) + ',' return row_string def create_csv_from_list(rowdict_list, header_row): csv_list = [] csv_list.append(comma_separate_values(header_row)) for rowdict in rowdict_list: csv_list.append(comma_separate_values(rowdict)) return csv_list_to_csv_string(csv_list)
7b0c5bf3e235538f402a1f7ba44c0473852fb6c5
Alan-Liang-1997/CP1404-Practicals
/prac_04/warp_up.py
572
4.15625
4
""" numbers = [3, 1, 4, 1, 5, 9, 2] First, write down your answers to these questions without running the code, then use Python to see if you were correct. What values do the following expressions have? """ numbers = ["ten", 1, 4, 1, 5, 9, 1] print(numbers[0]) print(numbers[-1]) print(numbers[3]) print(numbers[:-1]) print(numbers[3:4]) print(5 in numbers) print(7 in numbers) print("3" in numbers) print(numbers + [6, 5, 3]) # TODO Get all the elements from numbers except the first two print(numbers[2:]) # TODO Check if 9 is an element of numbers print(9 in numbers)
ea6baabfb8c90cad855066f98dba3502abaadf74
VladGPine/stepik_python_course
/lesson2_5_step10.py
1,279
3.921875
4
""" Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся список "1 3 5 6 10", то на выход ожидается список "13 6 9 15 7" (без кавычек). Если на вход пришло только одно число, надо вывести его же. Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом. """ a = [1, 1, 5, 6, 10] # print(a) b = [] for i in range(len(a)): if len(a) > 1: if i == 0: b.append(a[-1] + a[1]) elif i == len(a) - 1: b.append(a[-2] + a[0]) else: b.append(a[i - 1] + a[i + 1]) else: b.append(a[i]) print(*b, end='')
5941a94780ff4158011b2792c16d6ed3773fffd6
IamSadiq/web-scraping
/special-sequences.py
563
3.546875
4
import re # special sequences # \d --- matches any decimal digit [0-9] regex = re.compile('\d') # print(regex.match('6352778')) # \D --- matches any non-digit character [^0-9] regex = re.compile('\D') # print(regex.match('adfdfg')) # \s --- matches any whitespace character regex = re.compile('\s') # print(regex.match(' hello you')) # \w --- matches any alphanumeric character [a-zA-Z0-9_] regex = re.compile('\w') # print(regex.match('_a664')) # \W --- matches any non-alphanumeric character [^a-zA-Z0-9_] regex = re.compile('\W') # print(regex.match('*'))
9fd7fa66c7f756936d5369fe0185266548950865
edmilsonlibanio/Ola-Mundo-Python
/iapcompython/prog_4_7.py
436
3.84375
4
#Programa categoria x preço (com 5 categorias) utilizando #elif. categoria = int(input('Digite a categoria do produto: ')) if categoria == 1: preco = 10 elif categoria == 2: preco = 18 elif categoria == 3: preco = 23 elif categoria == 4: preco = 26 elif categoria == 5: preco = 31 else: print('Categoria inválida, digite um valor entre 1 e 5!') preco = 0 print(f'O preço do produto é: R$ {preco:.2f}')
5d5d6be924f29cea9d3ffde5bcb81999d7c39eee
samcan/nes-rle-decompress
/compress_rle.py
2,786
3.5625
4
import argparse import os MAX_BYTE_COUNT = 255 def main(input_file, output_file): print('Input file:', input_file) print('Output file:', output_file) if os.path.isfile(output_file): os.remove(output_file) with open(input_file, 'rb') as f: bytes_read = f.read() prev_byte = '' count = 0 for byte in bytes_read: if prev_byte == '': prev_byte = byte count = 1 elif byte == prev_byte: count += 1 # I may modify this at some point to use negative # numbers to represent a list of bytes which should # be copied as-is. For example, a count of -6 would mean # that the next six bytes should be copied as-is. # # I could convert a negative number n to an 8-bit two's complement # number for conversion to hex by doing the following per the Wikipedia # article: # # = 2^8 - n # # For n = -5 # = 2^8 - 5 # = 251 # # This means I would need to limit the following count to 127 if count == MAX_BYTE_COUNT: write_byte(output_file, count, prev_byte) prev_byte = byte count = 0 if byte != prev_byte: write_byte(output_file, count, prev_byte) #print('setting prev_byte to',byte) prev_byte = byte count = 1 # write final byte to file write_byte(output_file, count, prev_byte) # tack on terminating #$00 bytes write_byte(output_file, 0, 0) # print file compression info input_file_num_bytes = os.stat(input_file).st_size output_file_num_bytes = os.stat(output_file).st_size print('Input file size (bytes):', input_file_num_bytes) print('Output file size (bytes):', output_file_num_bytes) compression_pct = 1 - (output_file_num_bytes / input_file_num_bytes) print(f"Compression (%): {compression_pct * 100:.1f}") print() def write_byte(output, count, byte): #print('writing',count,'of',bytes([byte])) with open(output, 'ba') as g: g.write(bytes([count])) g.write(bytes([byte])) parser = argparse.ArgumentParser(description='Take bin file and RLE encode it.') parser.add_argument('--input', required=True, type=str, help='Input bin file') parser.add_argument('--output', required=True, type=str, help='Output bin file') args = parser.parse_args() main(args.input, args.output)
62f274a02b7e65fd0608554cb73514e830f145ee
rahelbelay/list_exercises
/prompt.py
426
4.28125
4
user_name = input("What is your name?") # input -need to take it and save it somewhere #variable names in python has _ #snake case #java script camelCase #print("Hello, ") #print (user_name) print ("Hello,", user_name, "!") # String interpolating has three parts #1 place holder greeting = "Hello, %s!" % (user_name,) #print(greeting) #print("Hello, " + user_name + "!") greeting = f"Hello, %s! {user_name}!" print (greeting)
74207adc27b29fa128f448fc109f53ebe5a9924f
PatrickJou/Machine-Learning
/Project1 - Supervised Learning/KNN_classifier.py
2,213
3.546875
4
import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import validation_curve from sklearn.model_selection import ShuffleSplit from sklearn.neighbors import KNeighborsClassifier from plot_learning_curve import plot_learning_curve def KNN_classifier(X, Y, datasource): param_range = range(1,20,1) train_scores, test_scores = validation_curve( KNeighborsClassifier(), X, Y, param_name="n_neighbors", param_range=param_range, scoring="accuracy", n_jobs=1) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) print("train_scores_mean") print(train_scores_mean) print("test_scores_mean") print(test_scores_mean) print(np.argmax(test_scores_mean)) print(test_scores_mean[np.argmax(test_scores_mean)]) print(param_range[np.argmax(test_scores_mean)]) n_neighbors_number = param_range[np.argmax(test_scores_mean)] plt.title("KNN Validation Curve on "+ datasource) plt.xlabel("n_neighbors") plt.ylabel("Score") plt.ylim(0.0, 1.05) lw = 2 plt.plot(param_range, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(param_range, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.plot(param_range, test_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(param_range, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") plt.show() KNN_Learning_Curves(X, Y, datasource, n_neighbors_number) def KNN_Learning_Curves(X, Y, datasource, n_neighbors_number): title = "KNN Learning Curves on" + datasource cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=626) estimator = KNeighborsClassifier(n_neighbors = n_neighbors_number) plt = plot_learning_curve(estimator, title, X, Y, ylim=(0.0, 1.05), cv=cv) plt.show()
5ca83cb4d75c13e1402b4c363f7346369638ac4f
edithturn/Data-Structures-Algorithms
/stacks-queues/716-MaxStack.py
1,455
3.828125
4
''' LeetCode: 716. Max Stack Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element. Implement the MaxStack class: MaxStack() Initializes the stack object. void push(int x) Pushes element x onto the stack. int pop() Removes the element on top of the stack and returns it. int top() Gets the element on the top of the stack without removing it. int peekMax() Retrieves the maximum element in the stack without removing it. int popMax() Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one. Example: Input ["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"] [[], [5], [1], [5], [], [], [], [], [], []] Output [null, null, null, null, 5, 5, 1, 5, 1, 5] ''' class MaxStack: def __init__(self): self.stack = [] def push(self, x:int) -> None: self.stack.insert(0,x) def pop(self) -> int: return self.stack.pop(0) def top(self) -> int: return self.stack[0] def peekMax(self) -> int: return max(self.stack) def popMax(self) -> int: m = max(self.stack) self.stack.remove(m) return m # Tests obj = MaxStack() obj.push(5) param1 = obj.push(1) param2 = obj.push(5) param3 = obj.top() param4 = obj.popMax() param5 = obj.top() param6 = obj.peekMax() param7 = obj.pop() param8 = obj.top() print(param1, param2, param3, param4, param5, param6, param7, param8)
3a5f4038c4eec7223b6db8066d5059aa6057900b
NathanKinney/class_ocelot
/Code/tim/Python/lab03_grades.py
712
3.890625
4
while True: try: answer = float(input('What did you get on the test? > ')) break except ValueError: print('LIES! Try again.') continue if answer > 100: mod_grade = 9 else: mod_grade = answer % 10 if answer >= 90: answer = 'A' congrats = 'Good Job!' elif answer >= 80: answer = 'B' congrats = 'Good Job!' elif answer >= 70: answer = 'C' congrats = '' elif answer >= 60: answer = 'D' congrats = 'Booooo!' else: answer = 'F' congrats = 'Booooo!' mod_grade = 5 if mod_grade >= 7: mod_grade = '+' elif mod_grade <= 3: mod_grade = '-' else: mod_grade = '' print('You got a', answer + mod_grade + '.', congrats)
20cc6e7783976b1255e54f3198325b6bedb65a0f
nearwalden/caltemp
/cal.py
5,016
3.84375
4
# Routines to create, analyze and plot different calendard models of temperature import math # we'll want pandas to structure the datasets import pandas as p # use numpy to do vector work import numpy as np # plotting routines # import mapplotlib as plt # months in order months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] # months and how many days in them (except feb) # be careful with this, no guarantee of order days_month = {'january': 31, 'february': 28, 'march': 31, 'april': 30, 'may': 31, 'june': 30, 'july': 31, 'august': 31, 'september': 30, 'october': 31, 'november': 30, 'december': 31 } minutes_day = 1440 minutes_solar_year = 525969 # returns true if year is a leap-year def is_leap_year (year): if (year % 4) != 0: return False elif (year % 400) == 0: return True elif (year % 100) == 0: return False else: return True # returns the number of days in a month for a given year def days_in_month (mo, year): # if not feb, just lookup the result above if mo != 'february': return days_month[mo] # if leap year, return 29 elif is_leap_year(year): return days_month['february'] + 1; else: return days_month['february'] # returns an array of minutes_solar_year with a temp per minute # value is a sinusouid around mean_temp century_temp = {"year": 1950, "january": 12.0, "february": 12.1, "march": 12.7, "april": 13.7, "may": 14.8, "june": 15.5, "july": 15.8, "august": 15.6, "september": 15.0, "october": 14.0, "november": 12.9, "december": 12.2} century_max_temp = 15.8 century_min_temp = 12.0 century_simple_mean_temp = (century_max_temp + century_min_temp)/2 # 3 months, 15 days offset to put bottom in middle of january offset_minutes = 153092 def temp_array(): res = [] for i in range(0, minutes_solar_year): res.append(century_simple_mean_temp + (century_max_temp - century_simple_mean_temp) * math.sin(2 * math.pi * (i - offset_minutes)/minutes_solar_year)) return res # given a dictionary of year data including the year, calculates the mean for the year def year_mean(year_data): year = year_data['year'] total_days = 0 total_temp = 0 for month in months: data = year_data[month] days = days_in_month(month, year) # multiply average temp by days, add to total total_temp = total_temp + data * days # sum up days total_days = total_days + days return total_temp/total_days # print out a non-leap year (1999) starting at beginning of temp_array def print_temp_array(): # make an np.array from temp_array() temp = np.array(temp_array()) # keeping track of where we are start_minute = 0 # year to use (1999) year = 1999 # iterate through teh months for month in months: days = days_in_month(month, year) minutes = minutes_day * days mean_temp = temp[start_minute:start_minute + minutes].mean() print month + ": " + str(mean_temp) start_minute = start_minute + minutes print "\nMean for year: " + str(temp[0:start_minute].mean()) # need to fix this, not really right print "20th Century mean: " + str(year_mean(1950, century_temp)) def model (start_year, years): temp = np.array(temp_array()) start_minute = 0 res = [] for year in range(start_year, start_year + years): year_res = {"year": year} for month in months: days = days_in_month(month, year) minutes = minutes_day * days # check if cross solar year if start_minute + minutes < minutes_solar_year: # within solar year mean_temp = temp[start_minute:start_minute + minutes].mean() start_minute = start_minute + minutes else: # crosses solar years # compute minutes in this year v. next this_year = minutes_solar_year - start_minute next_year = minutes - this_year # connect the pieces and take the mean mean_temp = np.append(temp[start_minute:minutes_solar_year], temp[0: next_year]).mean() start_minute = next_year # save the vaule for the month year_res[month] = mean_temp year_res['year_avg'] = year_mean(year_res) # add the year record to the result array res.append(year_res) df = p.DataFrame(res) df.to_csv('model_' + str(start_year) + "_" + str(years) + ".csv") print "complete"
0564800b508cd52b3485a3aec7273ff3fa12b568
GuyRobot/AIPythonExamples
/AILearning/NaturalLanguageProcessing/TextSentimentClassification.py
3,914
3.609375
4
from d2l import AllDeepLearning as d2l from mxnet import nd, init, autograd, gluon from mxnet.gluon import nn, rnn from mxnet.contrib import text from AI.AILearning.NaturalLanguageProcessing import TextClassification as loader """ In this model, each word first obtains a feature vector from the embedding layer. Then, we further encode the feature sequence using a bidirectional recurrent neural network to obtain sequence information. Finally, we transform the encoded sequence information to output through the fully connected layer. Specifically, we can concatenate hidden states of bidirectional long-short term memory in the initial timestep and final timestep and pass it to the output layer classification as encoded feature sequence information. In the BiRNN class implemented below, the Embedding instance is the embedding layer, the LSTM instance is the hidden layer for sequence encoding, and the Dense instance is the output layer for generated classification results. """ batch_size = 64 train_iter, test_iter, vocab = loader.load_data_imdb(batch_size) class BiRNN(nn.Block): def __init__(self, vocab_size, embed_size, num_hiddens, num_layers, **kwargs): super(BiRNN, self).__init__(**kwargs) self.embedding = nn.Embedding(vocab_size, embed_size) # Set Bidirectional to True to get a bidirectional recurrent neural # network self.encoder = rnn.LSTM(num_hiddens, num_layers, bidirectional=True, input_size=embed_size) self.decoder = nn.Dense(2) def forward(self, inputs): # The shape of inputs is (batch size, number of words). Because LSTM # needs to use sequence as the first dimension, the input is # transformed and the word feature is then extracted. The output shape # is (number of words, batch size, word vector dimension). embeddings = self.embedding(inputs.T) # Since the input (embeddings) is the only argument passed into # rnn.LSTM, it only returns the hidden states of the last hidden layer # at different timestep (outputs). The shape of outputs is # (number of words, batch size, 2 * number of hidden units). outputs = self.encoder(embeddings) # Concatenate the hidden states of the initial timestep and final # timestep to use as the input of the fully connected layer. Its # shape is (batch size, 4 * number of hidden units) encoding = nd.concat(*(outputs[0], outputs[-1]), dim=1) outs = self.decoder(encoding) return outs def predict_sentiment(net, vocab, sentence): sentence = nd.array(vocab[sentence.split()], ctx=d2l.try_gpu()) label = nd.argmax(net(sentence.reshape(1, -1)), axis=1) return 'positive' if label == 1 else 'negative' embed_size, num_hiddens, num_layers, ctx = 100, 100, 2, d2l.try_gpu() net = BiRNN(len(vocab), embed_size, num_hiddens, num_layers) net.initialize(init.Xavier(), ctx=ctx) glove_embedding = text.embedding.create('glove', pretrained_file_name='glove.6B.100d.txt') embeds = glove_embedding.get_vecs_by_tokens(vocab.idx_to_token) print(embeds.shape) net.embedding.weight.set_data(embeds) net.embedding.collect_params().setattr('grad_req', 'null') lr, num_epochs = 0.01, 5 trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': lr}) loss = gluon.loss.SoftmaxCrossEntropyLoss() d2l.train_ch12(net, train_iter, test_iter, loss, trainer, num_epochs, ctx) """ ##################### SUMMARY ################################ Text classification transforms a sequence of text of indefinite length into a category of text. This is a downstream application of word embedding. We can apply pre-trained word vectors and recurrent neural networks to classify the emotions in a text. """
a7f2199415de8a89c91e4927eacfe009998fdd65
mercurist/Coursera
/Python Data Structures/strings.py
235
3.859375
4
str1 = "hello" str2 = "world" str3 = str1 + str2 print(str3) str = "123" istr = int(str) + 1 print(istr) name = input("Enter: ") print(name) apple = input("Enter: ") cost = int(apple) - 0.5 * int(apple) print(cost)
549190dd4e839c758a943ebc14dbf848f6a6be7a
acp3012/utilities
/Find_Word_File.py
597
3.6875
4
import os def find(lst, file): lst = [ x.lower() for x in lst ] found = False if os.path.isfile(file): print('it is a file') with open(file,'r') as fh: for line in fh: line = line.lower() found_text = [ x for x in lst if x in line ] if len(found_text) > 0: print('found..') found = True return found file_list = [r"D:\MyTasks\2020\SQL tuning\Registry_files\Registry_files\LRK1WGRPERPSQ01_ODBC.reg" \ ] words = ['database','LRK1WGRPERPSQ01','Windows'] for file in file_list: r = find(words,file) print(f'{file} ==> {r}')
10c178e55f5c3e6f848548989ff3b98b1b4a2470
PARKINHYO/Algorithm
/BOJ/1546/1546.py
400
3.546875
4
N = int(input()) score = [] score = input().split() score = [int (i) for i in score] score.sort() for i in range(0, N-1): score[i] = float(score[i])/float(score[N-1])*100 score[N-1] = 100 sum = 0 for i in range(0, N): sum += float(score[i]) average = float(sum)/N if len(str(average))>=10: print("%0.6f" % average) else: print("%0.2f" % average)
0001a8300daeb9be2bf8e1f62a667301a43710b8
hgargan/python_test_gargan
/hello.py
1,613
3.609375
4
#!/usr/bin/env python a = "Once upon a time, a family of %d bears lived in the woods." % 3 mamabear = "Mrs. Bear" papabear = "Mr. Bear" babybear = "Lil Fuzzy" b = "Their names were %s, %s and %s." % (mamabear, papabear, babybear) print a print b x = 3 y = x+2 print "One day, the", x, "bears encountered another, larger family of", y, "bears while cavorting around the wilderness." z = x + y print "The %d families converged upon a grove of backscratching trees." % 2 print "To their horror, they discovered that their were", z, "bears and only %d trees." % 7 print "'Oh No,'", mamabear,"cried out. 'However will we all adequately scratch our backs?'" t = z % 7 print "The bears knew there would be %r bear left out of backscratching." % t v = z / 2 print "So they decided to combine the %d families and arbitrarily divide them into new families of %r for the purposes of fairness." % (2, v) tug = "tug of war" brawl = "boxing match" print "They initially considered settling things with a %r on %r %s." % (v, v, brawl) print "But finally, they settled on a more peaceful %s." % tug print "The winning team, being composed of members of either family, would have to come to a mutual agreement on allotting the remaining %r trees to the losers." % (v - 1 ) print "But such diplomacy was unnecessary. Almost immediately,", babybear,"tugged so hard that he slipped free from the rope and tumbled off the side of a ravine, never to be seen again." u = 7 % 7 print "The bears rejoiced, for each was now secure in his or her possession of a scratching tree." print "~~~~!!!!~~~~THE ~~ END ~~~~!!!!~~~~"
56407a5762950816008c7827036a9d103d5771db
fritzy/SleekXMPP
/sleekxmpp/util/misc_ops.py
4,292
3.640625
4
import sys import hashlib def unicode(text): if sys.version_info < (3, 0): if isinstance(text, str): text = text.decode('utf-8') import __builtin__ return __builtin__.unicode(text) elif not isinstance(text, str): return text.decode('utf-8') else: return text def bytes(text): """ Convert Unicode text to UTF-8 encoded bytes. Since Python 2.7 and Python 3+ have similar but incompatible signatures, this function unifies the two to keep code sane. :param text: Unicode text to convert to bytes :rtype: bytes (Python3), str (Python2.7) """ if text is None: return b'' if sys.version_info < (3, 0): import __builtin__ return __builtin__.bytes(text) else: import builtins if isinstance(text, builtins.bytes): # We already have bytes, so do nothing return text if isinstance(text, list): # Convert a list of integers to bytes return builtins.bytes(text) else: # Convert UTF-8 text to bytes return builtins.bytes(text, encoding='utf-8') def quote(text): """ Enclose in quotes and escape internal slashes and double quotes. :param text: A Unicode or byte string. """ text = bytes(text) return b'"' + text.replace(b'\\', b'\\\\').replace(b'"', b'\\"') + b'"' def num_to_bytes(num): """ Convert an integer into a four byte sequence. :param integer num: An integer to convert to its byte representation. """ bval = b'' bval += bytes(chr(0xFF & (num >> 24))) bval += bytes(chr(0xFF & (num >> 16))) bval += bytes(chr(0xFF & (num >> 8))) bval += bytes(chr(0xFF & (num >> 0))) return bval def bytes_to_num(bval): """ Convert a four byte sequence to an integer. :param bytes bval: A four byte sequence to turn into an integer. """ num = 0 num += ord(bval[0] << 24) num += ord(bval[1] << 16) num += ord(bval[2] << 8) num += ord(bval[3]) return num def XOR(x, y): """ Return the results of an XOR operation on two equal length byte strings. :param bytes x: A byte string :param bytes y: A byte string :rtype: bytes """ result = b'' for a, b in zip(x, y): if sys.version_info < (3, 0): result += chr((ord(a) ^ ord(b))) else: result += bytes([a ^ b]) return result def hash(name): """ Return a hash function implementing the given algorithm. :param name: The name of the hashing algorithm to use. :type name: string :rtype: function """ name = name.lower() if name.startswith('sha-'): name = 'sha' + name[4:] if name in dir(hashlib): return getattr(hashlib, name) return None def hashes(): """ Return a list of available hashing algorithms. :rtype: list of strings """ t = [] if 'md5' in dir(hashlib): t = ['MD5'] if 'md2' in dir(hashlib): t += ['MD2'] hashes = ['SHA-' + h[3:] for h in dir(hashlib) if h.startswith('sha')] return t + hashes def setdefaultencoding(encoding): """ Set the current default string encoding used by the Unicode implementation. Actually calls sys.setdefaultencoding under the hood - see the docs for that for more details. This method exists only as a way to call find/call it even after it has been 'deleted' when the site module is executed. :param string encoding: An encoding name, compatible with sys.setdefaultencoding """ func = getattr(sys, 'setdefaultencoding', None) if func is None: import gc import types for obj in gc.get_objects(): if (isinstance(obj, types.BuiltinFunctionType) and obj.__name__ == 'setdefaultencoding'): func = obj break if func is None: raise RuntimeError("Could not find setdefaultencoding") sys.setdefaultencoding = func return func(encoding) def safedict(data): if sys.version_info < (2, 7): safe = {} for key in data: safe[key.encode('utf8')] = data[key] return safe else: return data
237ba877d2f6e871311a101ba90247b4a0b1817c
jacquerie/leetcode
/leetcode/0090_subsets_ii.py
916
3.734375
4
# -*- coding: utf-8 -*- class Solution: def subsetsWithDup(self, nums): result = [] self._subsetsWithDup(sorted(nums), [], result) return result def _subsetsWithDup(self, nums, current, result): if not nums: if current not in result: result.append(current) else: self._subsetsWithDup(nums[1:], current, result) self._subsetsWithDup(nums[1:], current + [nums[0]], result) if __name__ == "__main__": solution = Solution() assert [ [], [2], [2, 2], [1], [1, 2], [1, 2, 2], ] == solution.subsetsWithDup([1, 2, 2]) assert [ [], [4], [4, 4], [4, 4, 4], [4, 4, 4, 4], [1], [1, 4], [1, 4, 4], [1, 4, 4, 4], [1, 4, 4, 4, 4], ] == solution.subsetsWithDup([4, 4, 4, 1, 4])
1d46f0c34e39046145e2d32119d6f4745b27cb50
jade0300/PYTHON_C109156229
/6.兩數差值.py
254
3.5
4
tt=[] tt=eval(input("輸入值為:")) one=list(tt) a=len(one) one.sort() two="" for i in range(a): two += str(one[i]) one.reverse() yy="" for i in range(a): yy+=str(one[i]) print("最大值數列與最小值數列差值為:%d"%(int(yy)-int(two)))
18ad6d0864c40ae84f010eaad2f936bf39395f05
vishnupsingh523/python-learning-programs
/calculateElectricityBill.py
722
4.125
4
# defining main function here: def main(): print("**** WELCOME TO THE ELECTRICITY BILL CALCULATOR ****\n") units = int(input("Enter the number of units: ")) # calling the function calculateBill with the parameter units: rateOfCharge = 0 if units>=0: if units <= 150: rateOfCharge = units*3 elif units<=350: rateOfCharge = 100 + units*(3.75) elif units<=450: rateOfCharge = 250 + units*4 elif units<=600: rateOfCharge = 300 + units*(4.25) elif units > 600: rateOfCharge = 400 + units*5 # printing the amount of money print("Total amount: Rs.",rateOfCharge) main()
d48b7dc8bddf6750accf3f7c6aa9f3818ca7e85f
ucsb-cs8-s18/LECTURE-05-29-Recursion-part-2
/addToEach_recursive.py
293
3.609375
4
def addToEach(value,aList): if aList==[]: return [] first = aList[0] rest = aList[1:] return [ first + value ] + addToEach(value,rest) def test_addToEach_1(): assert addToEach(1,[3,4,5])==[4,5,6] def test_addToEach_10(): assert addToEach(10,[3,4,5])==[13,14,15]
1fcfe9261eb441be7a4158d3d38474c731ec3e80
Edceebee/python_practice
/Lists/checkElement.py
440
4.09375
4
# someList = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] # newList = [] # # for items in someList: # if items not in newList: # newList.append(someList) # else: # print(items, end=' ') some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] # my_list = sorted(some_list) duplicates = [] for i in some_list: if some_list.count(i) > 1: if i not in duplicates: duplicates.append(i) print(duplicates)
e3057ce8d6fff12e7e7ea599c93e0780a1c4b506
Shumpy09/kurs-uDemy
/LVL 2/SEKCJA 4/52. Funkcja jako zmienna - LAB.py
339
3.8125
4
def double(x): return 2 *x def root(x): return x**2 def negative(x): return -x def div2(x): return x/2 number = 8 transformations = [double, root, div2, negative] tmp_return_value = number for transformation in transformations: tmp_return_value = transformation(tmp_return_value) print(tmp_return_value)
d2d6a8dca4f45902c0fe0b7bc68ea224edab7ba2
quyixiao/python_lesson
/sortTest/SortTest.py
298
3.953125
4
# 依次接收用户输入的3个数 ,排序后打印 # 1.转换int后,判断大小的排序,使用分支结构完成 # 2.使用max函数 # 3.使用列表的sort方法 # 冒泡法 nums = [] for i in range(3): nums.append(int(input('{}:'.format(i)))) nums.sort(reverse=True) print(nums)
62d96e42feed009565a43f94c501bef01e0a06d0
luismvargasg/holberton-system_engineering-devops
/0x16-api_advanced/0-subs.py
712
3.59375
4
#!/usr/bin/python3 """Function that queries the Reddit API and returns the number of subscribers for a given subreddit. If an invalid subreddit is given, the function should return 0. """ import requests def number_of_subscribers(subreddit): """Function that returns the number of subscribers""" url = "https://www.reddit.com/r/{}/about.json".format(subreddit) headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) \ Gecko/20100401 Firefox/3.6.3 (FM Scene 4.6.1)'} r = requests.get(url, headers=headers, allow_redirects=False) try: subs = r.json().get('data').get('subscribers') return subs except: return 0
ee033722a288fd177d0caa7de45a949f135f38f2
RajeevSawant/PYthon-Programming
/Functions_Homework.py
2,074
3.703125
4
# Question 1 def vol(rad): return((4.0/3)*3.14159*(rad*rad*rad)) pass print "\nThe Volume of the Sphere is: %1.3f\n" %(vol(3)) # Question 2 def ran_check(num,low,high): if num > low and num < high: return True else: return False print "Is the Number in Range? %s\n"%(ran_check(4,2,7)) # Question 3 upp, loow = 0,0 def up_low(s): global upp, loow for x in s: if x.isupper(): upp += 1 elif x.islower(): loow += 1 print "No. of Upper Case Characters: %d" %(upp) print "No. of Lower Case Characters: %d" %(loow) s = "Hello Mr. Rogers, how are you doing this fine Tuesday?" up_low(s) # Question 4 l = [1,1,1,1,2,2,2,3,3,3,3,3,4,5] def unique_list(l): return set(l) print "The Unique List is: {x}\n".format(x = unique_list(l)) # Question 5 numbers = [1,2,3,-4] def multiply(numbers): mul = 1 for x in numbers: mul *= x return mul print "The Result is: %d\n" %(multiply(numbers)) # Questions 6 s = "nursesrun" def palindrome(s): y = s[::-1] if s == y: return True else: return False print "Is this a Palindrome? %s \n"%(palindrome(s)) # Question 7 str = "The quick brown fox jumps over the lazy dog" import string def ispangram(str1, alphabet = string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(str1.lower()) ''' global count y = str.lower() trn = [word[0] for word in y.split()] for x in trn: for z in string.ascii_lowercase: if x == z: count += 1 else: continue if count == 26: return True else: return False print "The value of the count: %d" %(count) ''' ''' for x in y: print "The value of x: %s"%(x) for z in string.ascii_lowercase: print "The value of z: %s"%(z) if x == z: count += 1 else: continue if count == 26: return True else: return False print "The value of count is %d" %(count) ''' print"Is the statement Pangram? %s\n" %(ispangram(str))
f5ee60fad7c2d543ead7e507fb2d83cdb67500b9
dnmcginn57/2143-OOP-McGinn
/Assignments/homework-01.py
2,984
4
4
""" Name: David McGinn Email: nicholasmcginn57@yahoo.com Assignment:Homework 1 - Lists and Dictionaries Due: 31 Jan 2016 @ classtime """ # 1.1 Basics #A a = [1, 5, 4, 2, 3] print(a[0], a[-1]) # Prints: (1,3) a[4] = a[2] + a[-2] Print(a) # Prints: [1,5,4,2,6] print(len(a)) # Prints: 5 print(4 in a) # Prints: true a[1] = [a[1], a[0]] print(a) # Prints: [1,(5,1),4,2,6] #1.2 List Methods #B def remove_all(el, lst): """Removes all instances of el from lst. Given: x = [3, 1, 2, 1, 5, 1, 1, 7] Usage: remove_all(1, x) Would result in: [3, 2, 5, 7] """ while el in lst: lst.remove(el) #C def add_this_many(x, y, lst): """ Adds y to the end of lst the number of times x occurs in lst. Given: lst = [1, 2, 4, 2, 1] Usage: add_this_many(1, 5, lst) Results in: [1, 2, 4, 2, 1, 5, 5] """ for i in range(x): lst.append(y) #1.3 Slicing #D a = [3, 1, 4, 2, 5, 3] print(a[:4]) # Prints: [3,1,4,2] print(a) # Prints: [3,1,4,2,5,3] print(a[1::2]) # Prints: [1,2,3] print(a[:]) # Prints: [3,1,4,2,5,3] print(a[4:2]) # Prints: [] print(a[1:-2]) # Prints: [1,4,2] print(a[::-1]) # Prints: [3,5,2,4,1,3] #1.4 For loops #E def reverse(lst): """ Reverses lst in place. Given: x = [3, 2, 4, 5, 1] Usage: reverse(x) Results: [1, 5, 4, 2, 3] """ tmp = 0 for i in range(len(lst)//2): tmp = lst[i] lst[i] = lst[-1-i] lst[-1-i] = tmp #F def rotate(lst, k): """ Return a new list, with the same elements of lst, rotated to the right k. Given: x = [1, 2, 3, 4, 5] Usage: rotate(x, 3) Results: [3, 4, 5, 1, 2] """ return lst[-k:] + lst[:-k] #2.0 Dictionaries #H print('colin kaepernick' in superbowls) #Prints: false print(len(superbowls)) #Prints: 4 print(superbowls['peyton manning'] == superbowls['joe montana']) #Prints: false superbowls[('eli manning', 'giants')] = 2 print(superbowls) #Prints: {('eli manning','giants'): 2 'peyton manning': 1, 'tom brady': 3, 'joe flacco': 1, 'joe montana': 4} superbowls[3] = 'cat' print(superbowls) #Prints: {('eli manning','giants'): 2 'peyton manning': 1, 'tom brady': 3, 'cat', 'joe flacco': 1, 'joe montana': 4} superbowls[('eli manning', 'giants')] = superbowls['joe montana'] + superbowls['peyton manning'] print(superbowls) #Prints: {('eli manning','giants'): 5 'peyton manning': 1, 'tom brady': 3, 'cat', 'joe flacco': 1, 'joe montana': 4} superbowls[('steelers', '49ers')] = 11 print(superbowls) #Prints: {('steelers','49ers'): 11, ('eli manning','giants'): 5 'peyton manning': 1, 'tom brady': 3, 'cat', 'joe flacco': 1, 'joe montana': 4} #I def replace_all(d, x, y): """Replaces all values of x with y. Given: d = {1: {2:3, 3:4}, 2:{4:4, 5:3}} Usage: replace_all(d,3,1) Results: {1: {2: 1, 3: 4}, 2: {4: 4, 5: 1}} """ for k in d.keys(): if isinstance(d[k],dict): replace_all(d[k], x, y) elif d[k] == x: d[k] = y #J def rm(d, x): """Removes all pairs with value x. Given: d = {1:2, 2:3, 3:2, 4:3} Usage: rm(d,2) Results: {2:3, 4:3} """ remove = [k for k, v in d.items() if v == x] for k in remove: del d[k]
acba7bbab9b24588a9831941b7b6c9e9c02b5b70
jasminsaromo/reinforcement_assignments
/reinforcement_jun24.py
492
3.90625
4
print("Please enter a number") number = input() firstpart, secondpart = number[:int(len(number)/2)], number[int(len(number)/2):] def luck_check(number): try: sum1 = 0 for i in firstpart: sum1 += int(i) sum2 = 0 for i in secondpart: sum2 += int(i) if sum1 == sum2: print("This is a lucky number set!") elif sum1 != sum2: print("This ain't your luck. =(") except ValueError: print("Enter a NUMBER bruh.") luck_check(number)
b5db1041f5d68bf692fd5144550b0d4daff8d823
DeepakRathod14/TestPython
/src/office/05DeclaredMainMethod.py
729
3.703125
4
# Empty class sample class EmpltyClass: def setterTest(self,x): self.x=x def getterTest(self): print(self.x) # Sample of Bean (Getter & Setter) class Bean: def __init__(self): print("Const") def setter(self, x,y,z): self.x=x self.y=y self.z=z def getter(self): print(self.x, self.y, self.z) if __name__ == '__main__': e= EmpltyClass() # Creating object of Empty Class & invoke Initializer Method print(e.setterTest(55)) print(e.getterTest()) p3 = Bean() # Creating object of Bean Class & invoke constructor/ Initializer method p3.setter(11, 12, 13) print(p3.getter())
d0ea125743777ea8586b660440dd652e10ba47da
zozni/PythonStudy
/Regex/grouping4.py
176
3.671875
4
# 그룹핑된 문자열에 이름 붙이기 ?P<name> import re p = re.compile(r"(?P<name>\w+)\s+((\d+)[-]\d+[-]\d+)") m = p.search("park 010-1234-1234") print(m.group("name"))
4bce5f49c82972c9e7dadd48794bcc545e25095b
miketwo/euler
/p7.py
704
4.1875
4
#!/usr/bin/env python ''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' from math import sqrt, ceil def prime_generator(): yield 2 yield 3 num = 3 while True: num += 2 if is_prime(num): yield num def is_prime(num): for i in xrange(2, int(ceil(sqrt(num))) + 1): if num % i == 0: return False return True def main(): print is_prime(9) loop = 0 for prime in prime_generator(): loop += 1 print "{}: {}".format(loop, prime) if loop == 10001: break if __name__ == '__main__': main()
57abf5d58c9a55043dccc51d9beba9156ac60ec9
Wolverinepb007/Python_Assignments
/Python/perimeter.py
250
4.0625
4
l=int(input("Enter length of rectangle="))#Entering length. b=int(input("Enter breadth of rectangle="))#Entering Breadth. print("Area of the rectangle=",l*b)#Printing area. print("Perimeter of the recatange=",2*(l+b))#printing Perimeter.
d5b98d6df8f3bd89486c9442933019bb84452b44
stevemman/FC308-Labs
/Lab3/A1.py
344
4.25
4
# Ask the user to enter their age. age = int(input("Please enter your age :")) # Depending on the age group display a different ticket price. if age > 0 and age < 18: print("The ticket costs : 1.50£") elif age >= 18 and age < 65: print("The ticket costs : 2.20£") elif age >= 65 and age < 100: print("The ticket costs : 1.20£")
b7e963fb4cd7e452545ae46c50ef036bc0a97e60
cynthziawong/python_for_everyone
/a_ex_6.5/a_ex_6.5.py
358
4.09375
4
# 6.5 Write code using find() and string slicing # (see section 6.10) to extract the number at the end of the line below. # Convert the extracted value to a floating point number and print it out. text = "X-DSPAM-Confidence: 0.8475"; xyz = text.find('0') # Find 0 in text abc = text[xyz : ] # Look up 0 and extract everything after 0 print(float(abc))
3af1ee0f10178adbb0628f6c4476108524f2b1ba
yogalin910731/studytest
/twokindstrees/printupanddown.py
2,661
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/24 10:38 # @Author : fangbo #三种难度 #打印 [1,2,3,4,5,6,7], #打印 [[1], [2,3], [4,5,6,7]] #打印 [[1], [3,2], [4,5,6,7]] 偶数层倒序 # class Treenode: def __init__(self,val): self.val = val self.lchild = None self.rchild = None def printTree1(Nodetest): root = Nodetest queue = [] testresult = [] queue.append(root) while (len(queue) > 0): popnode = queue.pop(0) testresult.append(popnode.val) if popnode.lchild : queue.append(popnode.lchild) if popnode.rchild : queue.append(popnode.rchild) print (testresult) def printTree2(Nodetest): if Nodetest is None : return None root = Nodetest queue = [] testresult = [] queue.append(root) while (len(queue) > 0): poplist = [] poplistval =[] while (len(queue) > 0): popnode = queue.pop(0) poplist.append(popnode) poplistval.append(popnode.val) testresult.append(poplistval) for i in poplist: if i.lchild : queue.append(i.lchild) if i.rchild : queue.append(i.rchild) print (testresult) def printTree3(Nodetest): if Nodetest is None : return None root = Nodetest queue = [] testresult = [] queue.append(root) count = 0 while (len(queue) > 0): poplist = [] poplistval =[] while (len(queue) > 0): popnode = queue.pop(0) poplist.append(popnode) poplistval.append(popnode.val) count += 1 if count%2 == 1: testresult.append(poplistval) else: testresult.append(poplistval[::-1]) for i in poplist: if i.lchild : queue.append(i.lchild) if i.rchild : queue.append(i.rchild) print (testresult) if __name__=='__main__': testnode1 = Treenode(1) testnode2 = Treenode(2) testnode3 = Treenode(3) testnode4 = Treenode(4) testnode5 = Treenode(5) testnode6 = Treenode(6) testnode7 = Treenode(7) testnode1.lchild = testnode2 testnode1.rchild = testnode3 testnode2.lchild = testnode4 testnode2.rchild = testnode5 testnode3.lchild = testnode6 testnode3.rchild = testnode7 #第一种打印 #printTree1(testnode1) #第一种打印 #printTree2(testnode1) #第三种打印 #printTree3(testnode1)
fa64141ea139a1e457bbf94956ea9957651b2967
e1four15f/python-intro
/lesson2/ExC.py
132
4
4
n = int(input()) def factorial(n): curr = 1; for i in range(1, n+1): curr *= i return curr print(factorial(n))
b7f8b4c60d8a6ceee742a905f03302c2906192b4
alexchao/problems
/python/tree_problems_test.py
807
3.546875
4
# -*- coding: utf-8 -*- import unittest from tree_problems import find_lowest_common_ancestor from tree_problems import TreeNode class FindLowestCommonAncestorTest(unittest.TestCase): def test_immediate_ancestor(self): tree1 = TreeNode(1) tree2 = TreeNode(2) tree3 = TreeNode(3) tree2.left = tree1 tree2.right = tree3 lca = find_lowest_common_ancestor(tree2, tree3, tree1) self.assertEqual(lca.val, 2) def test_immediate_ancestor_reverse(self): tree1 = TreeNode(1) tree2 = TreeNode(2) tree3 = TreeNode(3) tree2.left = tree1 tree2.right = tree3 lca = find_lowest_common_ancestor(tree2, tree1, tree3) self.assertEqual(lca.val, 2) if __name__ == '__main__': unittest.main()
77093e76c811582aff67d0c1ffeccc3e287c137a
lhm0421/codetest1
/0303.py
257
3.59375
4
def solution(n): sam3 = list() answer = 0 while n >=3: sam3.append(n%3) n = n//3 sam3.append(n) sam3.reverse() for i in range(len(sam3)): answer = answer + (sam3[i] * 3**i) return answer
e673925252e4877dff5f08a14b54318e9251d068
KevinMichaelCamp/Python-HardWay
/Algorithms/Chapter4_Strings/09_Roman Numerals_to_Integer.py
514
3.890625
4
# Given a string containinga Roman Numeral representation of a positive integer, return the integer. def romanNumeralToInteger(str): rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} integer = 0 for i in range(len(str)): if i > 0 and rom_val[str[i]] > rom_val[str[i-1]]: integer += rom_val[str[i]] - 2 * rom_val[str[i-1]] else: integer += rom_val[str[i]] return integer # Test Cases print(romanNumeralToInteger("MMMCMLXXXVI"))
3c29950027644851ffb2a3e24db1b2ad653d4d0f
matoken78/python
/LP100Knocks/03-20.py
519
3.75
4
# 20. JSONデータの読み込み # Wikipedia記事のJSONファイルを読み込み,「イギリス」に関する記事本文を表示せよ. # 問題21-29では,ここで抽出した記事本文に対して実行せよ. # https://docs.python.jp/3/library/json.html import codecs import json def read(word): for line in codecs.open(".\jawiki-country.json", "r", "utf-8"): article = json.loads(line) if article["title"] == word: print(article["text"]) read("イギリス")
77a16720e92c25df25fe1ef57b1a4b107ef83e61
CameronAF/Python
/Clustering/Simple/Simple_KMeans.py
1,032
3.625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.cluster import KMeans # Load the Data if 1 == 0: data = pd.read_csv('Country Clusters 1.csv') else: data = pd.read_csv('Country Clusters 2.csv') print('The Data:\n', data, '\n') # Plot the Data plt.scatter(data['Longitude'], data['Latitude']) plt.title('Data') plt.xlim(-180,180) plt.ylim(-90,90) plt.show() # Select the features (Longitude & Latitude) x = data.iloc[:,1:3] #[rows to keep, cols to keep] x = x[['Latitude','Longitude']] # k-Means Clustering with 3 clusters kmeans = KMeans(7) kmeans.fit(x) # Clustering Results identified_clusters = kmeans.fit_predict(x) data_with_clusters = data.copy() data_with_clusters['Cluster'] = identified_clusters print('Clustering Results:\n', data_with_clusters) plt.scatter(data_with_clusters['Longitude'], data_with_clusters['Latitude'],c=data_with_clusters['Cluster'],cmap='rainbow') plt.title('Clustered Data') plt.xlim(-180,180) plt.ylim(-90,90) plt.show()
39de57699a2c867b80a4325230d840722c6de07c
nat-sharpe/Python-Exercises
/Day_4/pair4.py
221
3.59375
4
msg = raw_input('msg:') word_histogram = {} entry = '' for char in msg: if char != ' ': entry = entry + char elif char == ' ': break word_histogram[entry] = 0 print entry print word_histogram
4a766db54c590c126b8064336f27eed4296211bd
marcelogomesrp/python
/Classes/Pessoa.py
295
3.921875
4
#!/usr/bin/python class Pessoa: _nome = None def __init__(self): print("Pessoa criada") def setNome(self, nome): self._nome = nome; print("Definido o nome como " + self._nome); def getNome(self): print(self._nome); pessoa = Pessoa() pessoa.setNome("Marcelo") pessoa.getNome()
57076dd600591bd0761345c6b8d1cb8d300fa2fb
holdermatthew5/caesar-cipher
/tests/test_caesar_cipher.py
1,004
3.546875
4
from caesar_cipher.caesar_cipher import encrypt, decrypt, crack # encrypt a string with a given shift def test_encrpyt(): assert encrypt('best of times', 732) == 'ybpq lc qfjbp' # decrypt a previously encrypted string with the same shift def test_decrypt(): assert decrypt('ybpq lc qfjbp', 732) == 'best of times' # encryption should handle upper and lower case letters def test_enc_case(): assert encrypt('It was the best of times', 732) == 'Fq txp qeb ybpq lc qfjbp' # encryption should allow non-alpha characters but ignore them, including white space def test_enc_nonalpha(): assert encrypt('It was the best of times, it was the worst of times.', 732) == 'Fq txp qeb ybpq lc qfjbp, fq txp qeb tlopq lc qfjbp.' # decrypt encrypted version of It was the best of times, it was the worst of times. WITHOUT knowing the shift used. def test_crack(): assert crack('Fq txp qeb ybpq lc qfjbp, fq txp qeb tlopq lc qfjbp.') == 'It was the best of times, it was the worst of times.'
c5f95eedf16aec9d017675d1f57ff769a964d992
utkarsht724/PythonBasicPrograms
/String/Add_ing.py
134
4.15625
4
#program to add ing in a string str=("bridgelabz") print("Orginal string:",str) str2=("ing") str3=str+str2 print("new string::",str3)
4c562f4719bd74d295d03778bb8c125c192e3c17
JaiJun/Codewar
/8 kyu/Short Long Short.py
635
4
4
""" Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty ( length 0 ). I think best solution: def solution(a, b): return a+b+a if len(a)<len(b) else b+a+b https://www.codewars.com/kata/50654ddff44f800200000007 """ def solution(a, b): if len(a) > len(b): Result = b + a + b else: Result = a + b + a print(Result) return Result if __name__ == '__main__': a = "45" b = "1" solution(a,b)
7975202d35c8c608c2c29b2d950a06244168cf1b
ekaropolus/metodos_rigurosos-1
/tareas/test_intervalo_luis.py
763
3.59375
4
# -*- coding: utf-8 -*- # Escribimos funciones con el nombre test_ALGO from intervalo_luis import * import numpy as np def test_adicion(): a = Intervalo(1, 2) b = Intervalo(2, 3) c = a + b # Quiero checar que c, definido asi, esta bien: assert c.lo == 3 and c.hi == 5 def test_comparacion_lt(): '''Se verifica el test < de intervalos''' #Faltan los casos interesantes cuando se #comparan con un intervalo que tenga # al cero. a=Intervalo(2,3) b=Intervalo(0,1) c=Intervalo(-1,1) assert (a<b) == False and (b<a) == True assert (a<c) def test_comparacion_gt(): '''Se verifica el test > de intervalos''' a=Intervalo(2,3) b=Intervalo(0,1) assert (a>b) == True and (b>a) == False
fdde61aed122cc7acce8cc59b35dbff0312d3871
Nicolas-Turck/POO_debutant
/ex3/library.py
750
3.71875
4
from book import * from books_list import * class Library(): """class for range book objet and select it and return it """ def __init__(self): self.book_all = list() def add_book(self, book): """method for add book in the library """ self.book_all.append(book) def get_book(self, title): """method for verify is book is in library and return it to reader""" print(title) for book in self.book_all: if title == book.title: return book else: print("not found")
7f947754383074882157df20e8ea2b524ccbe614
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
/training_api/application/data_preparation/models/converter_configuration_enum.py
456
3.828125
4
from enum import Enum class ConverterConfigurationEnum(Enum): """ A class Enum used to get supported labels type and corresponding format """ xml: str = "pascal" json: str = "json" @classmethod def is_name_valid(cls, requested_format_name: str) -> bool: format_name: bool = any(requested_format_name.lower().strip() == formats.value for formats in cls) return format_name
a01f9c145dd19c1a98a69116ba97feb525b10f0f
TsubasaKiyomi/python
/src/Closure.py
1,516
4.4375
4
""" 引数piを初めに決めてしまう!後々用途によって使い分ける。 # f = outer(1,2)はdef outer(a,b):に入り、return a + b 1 + 2 となるが、return inner がまだ実行されていない # return innerの返した物が f = outer(1,2)の f にあるのでまだ、実行されない。 # r = f()を実行すると。def inner() return a + b が実行される a + b には 1 と 2 が入っているので 3 が返ってくる。 #return innerでさらに返すので r = f() の r に 3 が入る。 def outer(a,b): def inner(): return a + b # innerを実行するのではなく、ファンクションのオブジェクトを返す return inner f = outer(1,2) r = f() print(r) # どんな時に使うのか? def outer(a,b): def inner(): return a + b return inner # () に入れた値を気にせずに実行したい場合に使用する f = outer(1,2) r = f() print(r) """ # 例えば円の面積を調べたい時 # 引数をパイ pi def circle_area_func(pi): # インナーは半径 def circle_area(radius): return pi * radius * radius return circle_area # cl1には3.14の半径をca2にはさらに細かい数字を ca1 = circle_area_func(3.14) ca2 = circle_area_func(3.141592) # 3.14を使いたい時はca1を もっと細かい数字を使いたい時はca2を。 print(ca1(10)) print(ca2(10)) # 引数piを初めに決めてしまう!後々用途によって使い分ける。
07b24ad324e24cb0477aab45ec31f0283621aa8a
Valiter/Learning_Repository
/Learning/lesson_2_task_1.py
1,549
3.78125
4
ls = [1, "А", 1.3, False, 24] print("Создать список и заполнить его элементами различных типов данных.\nРеализовать скрипт проверки типа данных каждого элемента.\nИспользовать функцию type() для проверки типа.\nЭлементы списка можно не запрашивать у пользователя, а указать явно, в программе.") print("\n2 варианта в программе:\n1) Ввод пользователем вручную;\n2) Работа с уже заданным списком.") type_of_prog = input("Введите вариант программы: ") null = 0 if type_of_prog == "1": ls.clear() cycles = input("Сколько элементов вы ходите в списке?\nВведите значение: ") while null < int(cycles): el = input(f"Введите что-нибудь ({null+1}): ") ls.append(el) null += 1 print(ls) null = 0 ls_len = len(ls) while null < ls_len: print(type(ls[null])) null += 1 elif type_of_prog == "2": ls_len = len(ls) print(ls) while null < ls_len: print(type(ls[null])) null += 1 null = 0 else: print("Вы не выбрали варианта ответа.") print("Будет запущена стандартная программа.") null = 0 print("Программа заваршена.")
0aa548da5918b11d9d920ebb85b2523464046b2d
tinashechihoro/python_control_flow
/control_flow.py
518
3.609375
4
# ## control flow # import os # # domain_list = ['www.yahoo.com', 'www.telone.co.zw', 'www.cnn.com'] # for domain in domain_list: # downloaded_page = os.system('wget {0}'.format(domain)) # print(downloaded_page) ## the fomatting of python source code is based on PE for n in range(2,10): for x in range(2,10): if n == 1: print(n) elif n == 2: print(n) elif n == 3: break print(n) elif n == 8: print(n)
e05c8600549e4cd551996681d4ba5c82580bb9c3
ConnorBrereton/Python-Design-Patterns
/template.py
1,865
4.15625
4
from abc import ABC, abstractmethod class AbstractClass(ABC): """Implement the prototypes.""" def template_method(self): self.base_operation1() self.required_operation1() self.base_operation2() self.hook1() self.required_operation2() self.base_operation3() self.hook2() """Implement the classes.""" def base_operation1(self): print("Base operation 1") def base_operation2(self): print("Base operation 2") def base_operation3(self): print("Base operation 3") """Implement subclasses.""" @abstractmethod def required_operation1(self): pass @abstractmethod def required_operation2(self): pass """Hooks that are used as extensions.""" def hook1(self): pass def hook2(self): pass class ConcreteClass(AbstractClass): """Implement all abstract operations of the base class.""" def required_operation1(self): print("Concrete class 1") def required_operation2(self): print("Concrete class 2") class ConcreteClassWithHook(AbstractClass): """Implement all abstract operations of the base class while overwriting the hook class.""" def required_operation1(self): print("Concrete required operation 1.") def required_operation2(self): print("Concrete required operation 2.") def hook1(self): print("Concrete class hook overwritten.") def client_code(AbstractClass): """Call the template method which calls all of the other methods in the order of the prototyping.""" AbstractClass.template_method() if __name__ == "__main__": print("Execute concrete class 1") client_code(ConcreteClass()) print("") print("Executing concrete class 2") client_code(ConcreteClassWithHook())
8ce926e3933e73729b9067cf8f051b4fb2945904
shivrajek7/Demo
/Emp.py
1,365
3.984375
4
import datetime print(datetime.datetime.now().year) class Emp : company = 'Infy' def __init__(self,id,nm,age,address='Mumbai'): self.eid = id self.ename = nm self.eage = age self.eaddress = address def showempdetails(self): print('Emp Id -- ',self.eid) print('FirstName -- ', self.ename) print('Emp Age -- ', self.eage) print('Emp Address -- ', self.eaddress) print('Emp Companay name', self.company) emp1 = Emp(10,'Amit',29) emp2 = Emp(10,'Amit',29,'Pune') #emp1 == emp2 emp1.showempdetails() print('-----------------------------') emp2.showempdetails() print(emp1.__dict__,'Emp1 info \n\n') # Cogni print(emp2.__dict__,'Emp2 info \n\n') # Infy print(Emp.__dict__,'Emp info \n\n') #Infy print('\n\n\n\n\n') print(id(emp1),'Hashcode of Emp1') print(id(emp2),'Hashcode of Emp2') print(id(emp1) == id(emp2),"Emp1 id == Emp2 id") emp3 = emp2 print(id(emp1)) print(id(emp2))+print(id(emp3)) print(emp1==emp2) print(emp2==emp3) print(emp1 is emp2) print(emp2 is emp3) ''' id is == constructor default value globle variable module == python file package == folder in which we have modules //logical structure of your proj import followed by module name from followed by package name '''
de69295b5df1d0a3664ecfab5eba02cdda7f5d84
Pankhuriumich/EECS-182-System-folder
/Homeworks/HW8/GRADE/filterlines.py
1,125
4.21875
4
import sys import pdb def filterlines(filterstring): ''' Print lines containing filterstring, ignoring characters prior to filterstring on the line. Reads from standard input and writes to standard output. Example: If filterstring is "SEARCH OUTPUT: ", it will look for this string on each line and output the text starting from "SEARCH OUTPUT: ". ''' for line in sys.stdin: pos = line.find(filterstring); if (pos == -1): continue; else: line = line[pos:]; sys.stdout.write(line); def main(argv): #pdb.set_trace(); if (len(argv) != 2): print "Error: usage: filterlines.py filterfile"; return; # filterfile should contain the starting string for valid lines that should be compared # with reference output. filterlines filters out any output from student code that # does not start with those lines. f = open(argv[1]); contents = f.read(); contents = contents.strip(); f.close(); filterlines(contents); if __name__ == "__main__": main(sys.argv);
1d3ccd5fbde0dc5b227c1600843b50cbd8f838de
lemonataste/DataScience
/python/21-05-13format,문자열함수/Python04_13_strEx02_김기태.py
327
4.1875
4
# 문자열 인덱싱이란? 문자를 가리키는것 a="Life is too short, You need Python" print(a[3],a[0],a[12],a[-1],a[-0],a[-2],a[-5]) #문자열 슬라이싱이란? 문자열을 잘라내는것. print(a[0:4]) print(a[0:2],a[5:7],a[12:17]) print(a[19:]) print(a[:5]) print(a[:]) print(a[19:-7])
bc39873adb924fd4bf659d6331ebbeb7b6ab05da
sshleifer/cs231n_a2
/assignment2/cs231n/torch_scratch.py
3,574
4
4
import torch.nn.functional as F import torch from torch import nn import numpy as np def three_layer_convnet(x, params): """ Performs the forward pass of a three-layer convolutional network with the architecture defined above. Inputs: - x: A PyTorch Tensor of shape (N, 3, H, W) giving a minibatch of images - params: A list of PyTorch Tensors giving the weights and biases for the network; should contain the following: - conv_w1: PyTorch Tensor of shape (channel_1, 3, KH1, KW1) giving weights for the first convolutional layer - conv_b1: PyTorch Tensor of shape (channel_1,) giving biases for the first convolutional layer - conv_w2: PyTorch Tensor of shape (channel_2, channel_1, KH2, KW2) giving weights for the second convolutional layer - conv_b2: PyTorch Tensor of shape (channel_2,) giving biases for the second convolutional layer - fc_w: PyTorch Tensor giving weights for the fully-connected layer. Can you figure out what the shape should be? - fc_b: PyTorch Tensor giving biases for the fully-connected layer. Can you figure out what the shape should be? Returns: - scores: PyTorch Tensor of shape (N, C) giving classification scores for x """ conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b = params ################################################################################ # TODO: Implement the forward pass for the three-layer ConvNet. # ################################################################################ # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** x = F.relu(F.conv2d(x, conv_w1, bias=conv_b1, padding=2)) x = F.relu(F.conv2d(x, conv_w2, bias=conv_b2, padding=1)) print(x.shape) x = torch.flatten(x, 1, -1) x = F.linear(x, fc_w, bias=fc_b) # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ################################################################################ # END OF YOUR CODE # ################################################################################ return x dtype = None def init_default(m: nn.Module, func=nn.init.kaiming_normal_) -> None: "Initialize `m` weights with `func` and set `bias` to 0." if func: if hasattr(m, 'weight'): func(m.weight) if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.) return m def conv_layer(in_channels, nf, ks, padding, **kwargs): c1 = init_default( nn.Conv2d(in_channels, nf, ks, padding=padding, **kwargs) ) model = nn.Sequential(c1, nn.LeakyReLU(inplace=True, negative_slope=.1), nn.BatchNorm2d(nf)) model.outshape = c1.outshape return model class ConvFun(nn.Module): def __init__(self, in_channel, channel_1, channel_2, num_classes): super().__init__() self.conv1 = conv_layer(in_channel, channel_1, 5, padding=2, bias=True) self.conv2 = conv_layer(channel_1, channel_2, 3, padding=1, bias=True) self.lin = nn.Linear(np.prod(self.conv2.outshape), num_classes) def forward(self, x): x = self.conv1(x) x = self.conv2(x) scores = self.lin(Flatten()(x)) return scores def compute_outshape(c, H=32, W=32): nf, _, HH, WW = c.weight.shape P1, P2, stride1, stride2 = c.padding + c.stride Hp = int(1 + (H + 2 * P1 - HH) / stride1) Wp = int(1 + (W + 2 * P2 - WW) / stride2) out = (nf, Hp, Wp) return out
a2fc5ac502679b321b353438067c9e38d334835f
daedalus/misc
/rsa_conspicuous_check.py
2,055
3.640625
4
#!/usr/bin/env python # Author Dario Clavijo 2020 # GPLv3 import gmpy2 import math import sys def rsa_conspicuous_check(N, p, q, d, e): ret = 0 txt = "" nlen = int(math.log(N) / math.log(2)) if gmpy2.is_prime(p) == False: ret = -1 txt += "p IS NOT PROBABLE PRIME\n" if gmpy2.is_prime(q) == False: txt = "q IS NOT PROBABLE PRIME\n" if gmpy2.gcd(p, e) > 1: ret = -1 txt = "p and e ARE NOT RELATIVELY PRIME\n" if gmpy2.gcd(q, e) > 1: ret = -1 txt += "q and e ARE NOT RELATIVELY PRIME\n" if p * q != N: ret - 1 txt += "n IS NOT p * q\n" if not (abs(p - q) > (2 ** (nlen // 2 - 100))): ret - 1 txt += "|p - q| IS NOT > 2^(nlen/2 - 100)\n" if not (p > 2 ** (nlen // 2 - 1)): ret - 1 txt += "p IS NOT > 2^(nlen/2 - 1)\n" if not (q > 2 ** (nlen // 2 - 1)): ret - 1 txt += "q IS NOT > 2^(nlen/2 - 1)\n" if not (d > 2 ** (nlen // 2)): ret - 1 txt += "d IS NOT > 2^(nlen/2)\n" if not (d < gmpy2.lcm(p - 1, q - 1)): txt += "d IS NOT < lcm(p-1,q-1)\n" try: inv = gmpy2.invert(e, lcm(p - 1, q - 1)) except: inv = None ret = -1 txt += "e IS NOT INVERTIBLE mod lcm(p-1,q-1)\n" if d != inv: ret = -1 txt += "d IS NOT e^(-1) mod lcm(p-1,q-1)" return (ret, txt) N = 316261368912034372675763445966723947266774344998810856180818351533513143408311066715404168221570429244943608807202768750419814119768169538716460558822819 p = 58369550286914167474111748541510689816450004536626042802697414913369987394419 q = 5418259475316478646085475045771606831413402184064804926300497557405242083601 e = 65537 phi = (p - 1) * (q - 1) d = gmpy2.invert(e, phi) print("N:", N) print("p:", p) print("q:", q) print("e:", e) print("phi:", phi) print("d:", d) r, txt = rsa_conspicuous_check(N, p, q, d, e) if r == 0: print("RSA key has no conspicuousness") else: print("RSA key has Conspicuousness:") print(txt) sys.exit(-1)
d2ad5c4c7b41b746bfe8e82d634bb97062995fd8
DriesDries/shangri-la
/scripts/sample_codes/label_propagation.py
2,613
4.21875
4
# -*- coding: utf-8 -*- """ 半教師あり学習(Label Propagation Algorithm) ラベルなしデータに,周囲にあるデータのラベルの数などから,新たにラベルをつける. 実際に実装するときには,この後に改めてこのラベルを用いて教師あり学習(e.g. SVM)などで分類を行う. ============================================== Label Propagation learning a complex structure ============================================== Example of Label Propagation learning a complex internal structure to demonstrate "manifold learning". The outer circle should be labeled "red" and the inner circle "blue". Because both label groups lie inside their own distinct shape, we can see that the labels propagate correctly around the circle. """ import numpy as np import matplotlib.pyplot as plt from sklearn.semi_supervised import label_propagation from sklearn.datasets import make_circles # generate ring with inner box n_samples = 200 X, y = make_circles(n_samples=n_samples, shuffle=False) # label付け outer, inner = 0, 1 labels = -np.ones(n_samples) labels[0], labels[-1] = outer, inner '''Learn with LabelSpreading''' label_spread = label_propagation.LabelSpreading(kernel='knn', alpha=1.0) ## generate object label_spread.fit(X, labels) ## fitting output_labels = np.array(label_spread.transduction_) # 生成されたラベル ## Plot output labels plt.figure(figsize=(8.5, 4)) ## Origin plt.subplot(1, 2, 1) plot_outer_labeled, = plt.plot(X[labels == outer, 0], X[labels == outer, 1], 'rs') ## それぞれのデータを色を分けてplot plot_unlabeled, = plt.plot(X[labels == -1, 0], X[labels == -1, 1], 'g.') plot_inner_labeled, = plt.plot(X[labels == inner, 0], X[labels == inner, 1], 'bs') plt.legend((plot_outer_labeled, plot_inner_labeled, plot_unlabeled), ('Outer Labeled', 'Inner Labeled', 'Unlabeled'), loc='upper left', numpoints=1, shadow=False) ## データ名の表示 plt.title("Raw data (2 classes=red and blue)") ## Labeled plt.subplot(1, 2, 2) outer_numbers = np.where(output_labels == outer)[0] inner_numbers = np.where(output_labels == inner)[0] plot_outer, = plt.plot(X[outer_numbers, 0], X[outer_numbers, 1], 'rs') plot_inner, = plt.plot(X[inner_numbers, 0], X[inner_numbers, 1], 'bs') plt.legend((plot_outer, plot_inner), ('Outer Learned', 'Inner Learned'), loc='upper left', numpoints=1, shadow=False) plt.title("Labels learned with Label Spreading (KNN)") plt.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.92) plt.show()
d35316bd6c8ba4707f1637c7698f377341ab6f61
quizl/quizler
/quizler/models.py
4,255
3.5
4
"""OOP models for Quizlet terms abstractions.""" class Image: """Quizlet image abstraction.""" def __init__(self, url, width, height): self.url = url self.width = width self.height = height @staticmethod def from_dict(raw_data): """Create Image from raw dictionary data.""" url = None width = None height = None try: url = raw_data['url'] width = raw_data['width'] height = raw_data['height'] except KeyError: raise ValueError('Unexpected image json structure') except TypeError: # Happens when raw_data is None, i.e. when a term has no image: pass return Image(url, width, height) def to_dict(self): """Convert Image into raw dictionary data.""" if not self.url: return None return { 'url': self.url, 'width': self.width, 'height': self.height } def __eq__(self, other): if not isinstance(other, Image): raise ValueError return all(( self.url == other.url, self.width == other.width, self.height == other.height )) class Term: """Quizlet term abstraction.""" def __init__(self, definition, term_id, image, rank, term): self.definition = definition self.term_id = term_id self.image = image self.rank = rank self.term = term @staticmethod def from_dict(raw_data): """Create Term from raw dictionary data.""" try: definition = raw_data['definition'] term_id = raw_data['id'] image = Image.from_dict(raw_data['image']) rank = raw_data['rank'] term = raw_data['term'] return Term(definition, term_id, image, rank, term) except KeyError: raise ValueError('Unexpected term json structure') def to_dict(self): """Convert Term into raw dictionary data.""" return { 'definition': self.definition, 'id': self.term_id, 'image': self.image.to_dict(), 'rank': self.rank, 'term': self.term } def __eq__(self, other): if not isinstance(other, Term): raise ValueError return all(( self.definition == other.definition, self.term_id == other.term_id, self.image == other.image, self.rank == other.rank, self.term == other.term )) def __str__(self): return '{} = {}'.format(self.term, self.definition) class WordSet: """Quizlet set of terms and descriptions abstraction.""" def __init__(self, set_id, title, terms): self.set_id = set_id self.title = title self.terms = terms def has_common(self, other): """Return set of common words between two word sets.""" if not isinstance(other, WordSet): raise ValueError('Can compare only WordSets') return self.term_set & other.term_set @property def term_set(self): """Set of all terms in WordSet.""" return {term.term for term in self.terms} @staticmethod def from_dict(raw_data): """Create WordSet from raw dictionary data.""" try: set_id = raw_data['id'] title = raw_data['title'] terms = [Term.from_dict(term) for term in raw_data['terms']] return WordSet(set_id, title, terms) except KeyError: raise ValueError('Unexpected set json structure') def to_dict(self): """Convert WordSet into raw dictionary data.""" return { 'id': self.set_id, 'title': self.title, 'terms': [term.to_dict() for term in self.terms] } def __eq__(self, other): return all(( self.set_id == other.set_id, self.title == other.title, self.terms == other.terms )) def __str__(self): return '{}'.format(self.title) def __repr__(self): return 'WordSet(id={}, title={})'.format(self.set_id, self.title)
4b604d8adff4b0f376d4c6ee5262e2968fb8283f
seven613/PyQt5
/30个常用功能/09.输出某个路径下及其子目录下所有以html为后缀的文件.py
344
3.828125
4
''' 输出路径及其子目录下所有html为后缀的文件 ''' import os def print_dir(filepath): for i in os.listdir(filepath): path =os.path.join(filepath,i) if os.path.isdir(path): print_dir(path) if path.endswith(".html"): print(path) filepath ="e:\codes\python" print_dir(filepath)
60a99df7a20a1c01482a1c1e62e498645b280d60
moshegplay/net4u
/defim.py
480
3.6875
4
def summary(ILS,Euro,USD): count = ILS + (Euro*3.9) + (USD*3.4) print("I have " + str(count) + " ILS") return count def tax(a,b,c): ddddd=summary(a,b,c) print(ddddd*1.17) True False ######################main dev a = int(input("Enter how many shekels: ")) b = int(input("Enter how many EURO: ")) c = int(input("Enter how many USD: ")) choose=input("You want to pay tax free? y/n ") if choose == "y": summary(a,b,c) else: tax(a,b,c)
2cb40413d860c38dc8eb3ac413e4f7016868bfcc
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_34/806.py
979
3.59375
4
#!/usr/bin/env python fp = open('in.txt', 'rU') lines = (line.rstrip("\n") for line in fp.xreadlines()) L, D, N = [int(val) for val in lines.next().split(' ')] trie_root = {} for word_index in range(D): word = lines.next() node = trie_root for letter in word: node = node.setdefault(letter, {}) node[''] = True # leaf node marker for case_index in range(N): pattern = lines.next() nodes = [trie_root] multiple = False possible_nodes = [] for letter in pattern: if letter == '(': multiple = True elif letter == ')': multiple = False else: for test_node in nodes: if letter in test_node: possible_nodes.append(test_node[letter]) if not multiple: nodes = possible_nodes possible_nodes = [] possible_words = sum(1 for node in nodes if '' in node) print 'Case #%d: %d' % (case_index + 1 , possible_words)
d89eec5f31b56f6c4b5955fed09391ec38ec3e2b
Andyvn2/pythonfunctions
/randoms.py
547
3.8125
4
import random def scoresandgrades(x): x=10 y=0 while y<10: random_num = random.randint(60,100) if random_num<=100 and random_num>90: print "Score:", random_num,";", "Your grade is: A", if random_num<=90 and random_num>79: print "Score:", random_num,";", "Your grade is: B", if random_num<=79 and random_num>69: print "Score:", random_num,";", "Your grade is: C", if random_num<=69 and random_num>60: print "Score:", random_num,";", "Your grade is: D", y= y+1 print "end of the program. Bye!" scoresandgrades(1)
11d7e73aa7e34a950f5c6c7413ed15459bab9521
EfrainHSeg/semana6python
/problema(9).py
340
4.125
4
b = int ( input ( "Ingrese el numero del angulo: " )) if b == 0: print("nulo") elif 0<b<90: print("agudo") elif b==90: print("recto") elif 90<b<180: print("obtuso") elif b==90: print("llano") elif 180<b>360: print("concavo") elif b==360: print("completo") else: print("no encontrado")
f23d45058252b2b8cd2580727ce9a5c904a8a39b
Pitrified/snippet
/python/bresenham/bresenham_generator.py
2,600
3.625
4
import logging def bresenham_generator(x0, y0, x1, y1): """Yields the points in a Bresenham line from (x0,y0) to (x1,y1) """ # commented out for megafastperformance # logline = logging.getLogger(f"{__name__}.console.generator") # logline.setLevel("INFO") # logline.setLevel("DEBUG") # logline.debug(f"Generating ({x0}, {y0}) - ({x1}, {y1})") if abs(y1 - y0) < abs(x1 - x0): if x0 > x1: return add_line_low(x1, y1, x0, y0) else: return add_line_low(x0, y0, x1, y1) else: if y0 > y1: return add_line_high(x1, y1, x0, y0) else: return add_line_high(x0, y0, x1, y1) def add_line_low(x0, y0, x1, y1): """ """ # logline = logging.getLogger(f"{__name__}.console.linel") # logline.setLevel("DEBUG") # logline.setLevel("INFO") # logline.debug("LOW") dx = x1 - x0 dy = y1 - y0 yi = 1 if dy < 0: yi = -1 dy = -dy D = 2 * dy - dx y = y0 for x in range(x0, x1 + 1): # logline.log(5, f"Mapping {x} {y}") yield x, y if D > 0: y = y + yi D = D - 2 * dx D = D + 2 * dy def add_line_high(x0, y0, x1, y1): """ """ # logline = logging.getLogger(f"{__name__}.console.lineh") # logline.setLevel("INFO") # logline.setLevel('DEBUG') # logline.setLevel("TRACE") # logline.debug("HIGH") dx = x1 - x0 dy = y1 - y0 xi = 1 if dx < 0: xi = -1 dx = -dx D = 2 * dx - dy x = x0 for y in range(y0, y1 + 1): # logline.log(5, f"Mapping {x} {y}") yield x, y if D > 0: x = x + xi D = D - 2 * dy D = D + 2 * dx def setup_logger_generator(logLevel="DEBUG"): """Setup logger that outputs to console for the module """ logmoduleconsole = logging.getLogger(f"{__name__}.console") logmoduleconsole.propagate = False logmoduleconsole.setLevel(logLevel) module_console_handler = logging.StreamHandler() # log_format_module = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' log_format_module = "%(name)s - %(levelname)s: %(message)s" # log_format_module = '%(levelname)s: %(message)s' formatter = logging.Formatter(log_format_module) module_console_handler.setFormatter(formatter) logmoduleconsole.addHandler(module_console_handler) logging.addLevelName(5, "TRACE") # use it like this # logmoduleconsole.log(5, 'Exceedingly verbose debug') return logmoduleconsole
683ba92de1d6cfc8a4c9fd99df1442f59ec00e39
Lesikv/python_tasks
/python_practice/reach.py
681
3.984375
4
#!/usr/bin/env python #coding: utf-8 def reach(x, y): """ You are in an infinite 2D grid where you can move in any of the 8 directions You are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point. Input : [(0, 0), (1, 1), (1, 2)] Output : 2 """ steps = 0 n = len(x) if len(x) != len(y): return None for i in range(1,n): steps = max(abs(x[i] - x[i -1]), abs(y[i] - y[i-1])) return steps def test(): assert reach([0, 1, 1], [0, 1, 2]) == 2 if __name__ == '__main__': test()
aff88c7e712228fd0a10965b53c40748b2b624ea
patriciobaez/algoritmos1
/ejercicios/ejercicio12.py
1,183
4.15625
4
''' 1. Escribir una función que permita calcular la duración en segundos de un intervalo dado en horas, minutos y segundos. 2. Usando la función del ejercicio anterior, escribir un programa que pida al usuario dos intervalos expresados en horas, minutos y segundos, sume sus duraciones, y muestre por pantalla la duración total en horas, minutos y segundos. ''' def conversor(hora : int, minuto : int, segundo : int) -> int: segundos = hora * 60 * 60 + minuto * 60 + segundo return segundos def inputs() -> int: hora = int(input("Ingrese las horas: ")) minuto = int(input("Ingrese los minutos: ")) segundo = int(input("Ingrese los segundos: ")) return conversor(hora, minuto, segundo) def main() -> None: intervalo_1 = inputs() intervalo2 = inputs() suma = intervalo_1 + intervalo2 print("\n\nResultado: \n") horas = suma/60/60 print(f"Horas: {int(horas)}.") minutos = (horas % 1) * 60 print(f"Minutos: {int(minutos)}.") segundos = (minutos % 1) * 60 print(f"Segundos: {int(segundos)}.") print(f"La suma de los intervalos da como resultado: {int(horas)}:{int(minutos)}:{int(segundos)}.") main()
7009078ed0449ba6f081efa3ca38ad6175b69188
sultanhusnoo/small_programs
/game_number_geussing.py
2,601
4.125
4
# Number geussing Game. # User can choose a number and let computer try to geuss # Or computer can choose a number and user has to geuss # only bug to fix is if user inputs char for num import random def computer_geuss_number(x): # User has secret number. Computer tries to geuss lower = 1 upper = x while(True): geuss = random.randint(lower, upper) print(f"\nComputer geussed : {geuss}") feedback = input("Number is lower(l), higher(h) or correct(c)? ") if feedback.lower() == 'l': # Number needed lower. Maximum is too high upper = geuss - 1 elif feedback.lower() == 'h':# Number needed higher. Minimum too low lower = geuss + 1 elif feedback.lower() == 'c': break else: print("Input not recognised!") print("\n**************************") print("I WON!!So happy to have geussed your number correctly!!") print("Almost ready to take over the World!!") print("**************************") def user_geuss_number(x): # Computer has secret number. User has to geuss lower = 1 upper = x number_to_geuss = random.randint(lower,upper) while(True): user_geuss = int(input("Please input yout geuss : ")) if user_geuss > number_to_geuss: print("Your geuss is too HIGHT") elif user_geuss < number_to_geuss: print("Your geuss is too LOW") elif user_geuss == number_to_geuss: break print("\n**************************") print("You WIN!! You geussed my SECRET number!!") print("NOw I can't take over the World!!") print("**************************") def ask_user(): print("\nGeussed number is from 1 to a certain maximum positive integer.") while(True): user_num = int(input("Enter the maximum number : ")) if user_num <= 0: print("Maximum cannot be less than 1.") elif user_num > 1: break print("You have two options :") print("A. The computer has a secret number and you have to geuss it.") print("B. You choose a secret number and the computer has to guess it.") print("\nOr you can exit the game by typing 'E'") choice = str(input("Enter your choice (A/B/E): ")) return user_num,choice print("\nWelcome to the Number geussing game. Come play with me...") while(True): user_num,choice = ask_user() if choice.lower() == "a" : print("\nComputer has a secret number. Try to geuss it.") user_geuss_number(user_num) elif choice.lower() == "b" : print("\nThe computer will try to geuss a number in your mind.") computer_geuss_number(user_num) elif choice.lower() == "e": break else: print("Your choice is not recognised. Please Enter correct option.") print("\nGoodbye Buddy :( Come play with me again soon!")
6831327d71d97d717e4e771bd82fb6d7606d1483
eunice-pereira/DC-python-fundamentals
/python102/small_3.py
169
3.953125
4
my_list = [10, 20, 30, 40, 50] smallest = float("inf") for num in my_list: if num < smallest: smallest = num #easier built in method print(min(my_list))
376f81e857306aa81dc45c04f24ea79f1d4a8c1b
Purushotamprasai/Python
/Atul_MD/002.py
372
4.1875
4
#union operation a = {1,2,3,4} b = {3,4,5,6} print"******union operation**********" print a|b # {1,2,3,4,5,6} print a.__or__(b) # {1,2,3,4,5,6} print a.union(b) # update menethod ''' after union operation the result we can store that particular variable ''' print "a : ",a print "b : ",b a.update(b) # a = a|b print "a : ",a print "b : ",b
47193fe6c97eb7f37aa859b78f3b4adcfe17d068
awsserver/awsserver
/python/ex29.py
620
4.0625
4
#!/usr/bin/python people = int(raw_input("Enter The number of People:- ")) cats = int(raw_input("Enter The number of cats:- ")) dogs = int(raw_input("Enter The number of dogs:- ")) if int(people) < int(cats): print "Too Many cats! The world is doomed!" if int(people) > int(cats): print "Not many cats! The world is save!" if int(people) < int(dogs): print "The World is drooled on!" dogs += 5 if int(people) >= int(dogs): print "People are greater than or equal to dogs." if int(people) <= int(dogs): print "people are less than or equal to dogs." if int(people) == int(dogs): print "people are dogs."
b7bc8ea26c1bab83547b4802eb29a1bca6ef3c7b
Aitmambetov/2chapter-task17
/task17.py
2,403
4.3125
4
""" Write the code which will write excepted data to files below For example given offices of Google: 1)google_kazakstan.txt 2)google_paris.txt 3)google_uar.txt 4)google_kyrgystan.txt 5)google_san_francisco.txt 6)google_germany.txt 7)google_moscow.txt 8)google_sweden.txt When the user will say “Hello” Your code must communicate and give a choice from listed offices. After it has to receive a complain from user, and write it to file chosen by user. Hint: Use construction “with open” """ user = input() if user == "Hello": with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/List of countries.txt', 'r') as new: content = new.read() print(content) country_complaining = int(input('Please, choose the number of office you are complaining of: ' )) complain = input('Please, write what are you complaining of: ' ) if country_complaining == 1: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/1Kazakhstan.txt','a') as new1: kaz_complain = new1.write(' ' + complain) elif country_complaining == 2: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/2Paris.txt', 'a') as new2: paris_complain = new2.write(' ' + complain) elif country_complaining == 3: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/3UAR.txt', 'a') as new3: UAR_complain = new3.write(' ' + complain) elif country_complaining == 4: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/4Kyrgyzstan.txt', 'a') as new4: KG_complain = new4.write(' ' + complain) elif country_complaining == 5: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/5San Francisco.txt', 'a') as new5: SF_complain = new5.write(' ' + complain) elif country_complaining == 6: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/6Germany.txt', 'a') as new6: Germany_complain = new6.write(' ' + complain) elif country_complaining == 7: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/7Moscow.txt', 'a') as new7: Moscow_complain = new7.write(' ' + complain) elif country_complaining == 8: with open('/Users/maksataitmambetov/Desktop/makers/Tasks/chapter2/task2.17/8Sweden.txt', 'a') as new8: Sweden_complain = new8.write(' ' + complain)
8f43899b971ed1b50d7168ec2b3cd5fdc0513e2a
karanadapala/dsa_python_mit6.006
/lecture4.py
2,358
4.25
4
''' In this lecture version the concept of Heaps is covered. We will be implementing the following concepts: i. Max_heapify a.k.a Heapify the ds in descending Tree order. ii. Extract_max - maximun number from the heap is extract and the rest of the heap is Heapified. iii. Heap_Sort A Heap is an array representation of a binary tree, where if element 'x' of the heap 'S' is at 'i' (where i starts from 1 to n), then: i. x's parent is at the floor of i/2 (i.e x//2) ii. x's left child is at 2*i iii. x's right child is at 2*1+1 ''' class Heap(): def __init__(self, arr: list): self.arr = self.heapify(arr) def heapify(self, arr: list): def recursiv_swap(self, ind, arr, num): if ind == 1 or num < arr[(ind)//2-1]: temp = arr[ind-1] arr[ind-1] = num return temp else: temp = arr[ind-1] arr[ind-1] = recursiv_swap(self, ind//2, arr, num) return temp for i in range(2, len(arr)+1): if arr[(i//2)-1] < arr[i-1]: arr[i-1] = recursiv_swap(self, i//2, arr, arr[i-1]) return arr def insert(self, num: int or float): self.arr.append(num) self.arr = self.heapify(self.arr) return def extract_max(self): if len(self.arr) == 0: return 'nothing in heap :(' maxx = self.arr[0] if len(self.arr) > 2: if self.arr[1] > self.arr[2]: self.arr[0] = self.arr[1] self.arr.pop(1) else: self.arr[0] = self.arr[2] self.arr.pop(2) self.arr = self.heapify(self.arr) elif len(self.arr)==2: self.arr = self.arr[1:] return maxx def sort(self): lt = len(self.arr) init = 0 out_arr = [] while init < lt: out_arr.append(self.extract_max()) init += 1 self.arr = out_arr # Already in descending order --> no need to Heapify. return out_arr heap = Heap([1,2,3,4,5,6,7]) print(heap.arr) # [7, 4, 6, 1, 3, 2, 5] heap.insert(8) print(heap.arr) # [8, 7, 6, 4, 3, 2, 5, 1] print(heap.extract_max()) # 8 print(heap.arr) # [7, 6, 5, 3, 2, 4, 1] print(heap.sort()) # [7, 6, 5, 4, 3, 2, 1] print(heap.arr) # [7, 6, 5, 4, 3, 2, 1]
b863e75698d5f16c9b1690dc9d5de053707de296
lycantropos/Project-Euler
/14.py
642
3.75
4
from typing import Iterable from utils import odd memoized_collatz_sequences_lengths = {} def collatz_sequence_length(start: int) -> Iterable[int]: term = start length = 1 while term != 1: if not odd(term): term //= 2 else: term = 3 * term + 1 try: length += memoized_collatz_sequences_lengths[term] break except KeyError: length += 1 memoized_collatz_sequences_lengths[start] = length return length assert collatz_sequence_length(13) == 10 assert max(range(1, 1_000_000), key=collatz_sequence_length) == 837_799
d47247209a04ee2c5fdbdf801d6a803c959bb4f2
smehmood/advent-of-code
/2019/day4/solveB.py
878
3.53125
4
import sys def good_pw(pw_int): pw = str(pw_int) if len(pw) != 6: return False run_length = 1 double = False last = None for char in pw: if last is not None and last > char: return False if last == char: run_length += 1 else: if run_length == 2: double = True run_length = 1 # print(last, char, run_length) last = char if run_length == 2: double = True return double def main(): range_string = sys.stdin.readline() start, end = [int(x) for x in range_string.split("-")] num_valid = 0 for number in range(start, end): # puzzle is ambiguous on inclusive/exclusive if good_pw(number): num_valid += 1 print(number) print(num_valid) if __name__ == "__main__": main()
79f333db4bbddcf15eb15652b84d17cb15030ae3
anafplima/ALGORITMOS
/algHash.py
283
3.5625
4
import collections import string maiusculas=collections.deque(string.ascii_uppercase) minusculas=collections.deque(string.ascii_lowercase) mensagem=(input("Digite a mensagem: ")) total=0 for i in range (len(mensagem)): total+=ord(mensagem[i]) print("\nHASH: "+str(total%100))
ce2ef61159921e2d87aca000e5c59a8aed6e789d
anuranjanbose/Tic_Tac_Toe_py
/tictactoe.py
4,371
3.75
4
#from IPython.display import clear_output import os import random def display_board(board): print("\n"*100) print("\t | |") print("\t"+board[1] + " | " + board[2] + " | " + board[3]) print("\t | |") print("\t- - - - -") print("\t | |") print("\t"+board[4] + " | " + board[5] + " | " + board[6]) print("\t | |") print("\t- - - - -") print("\t | |") print("\t"+board[7] + " | " + board[8] + " | " + board[9]) print("\t | |") print("\n") def player_input(player1name): ''' OUTPUT: (player1,player2) ''' player1 = '' while player1 != 'X' and player1 != 'O': player1 = input("\n"+player1_name+" choose X or O: ").upper() if player1 == 'X': return ('X', 'O') else: return ('O', 'X') def place_marker(board, marker, position): board[position] = marker def win_check(board, mark): r1 = board[1] == board[2] == board[3] == mark r2 = board[4] == board[5] == board[6] == mark r3 = board[7] == board[8] == board[9] == mark c1 = board[1] == board[4] == board[7] == mark c2 = board[2] == board[5] == board[8] == mark c3 = board[3] == board[6] == board[9] == mark diag1 = board[1] == board[5] == board[9] == mark diag2 = board[3] == board[5] == board[7] == mark if r1 or r2 or r3 or c1 or c2 or c3 or diag1 or diag2: return True def choose_first(): choose = random.randint(1,2) if choose == 1 : return "Player1" else: return "Player2" def space_check(board, position): return board[position] == " " def full_board_check(board): #position = 0 for i in [1,2,3,4,5,6,7,8,9]: if space_check(board,i): return False # Return True if board is full return True def player_choice(board,player,move): position = 0 while((position not in range(1,10)) or (not space_check(board,position))): position = int(input("{} make your move no. {}:".format(player,move))) return position def replay(): ask = input("\n\nWant to play again(Y/N): ") return ask == 'Y' or ask == 'y' ##TIC TAC TOE print("\n\t\tWELCOME TO THE GAME TIC TAC TOE!\n") while True: # SETUP THE GAME my_board = [" "] * 10 player1_name = input("Player 1, Enter your name: ") player2_name = input("Player 2, Enter your name: ") player1, player2 = player_input(player1_name) chance = choose_first() if chance == "Player1": print("\n"+player1_name+" goes first!") else: print("\n"+player2_name+" goes first!") ask = input("\nReady to play the game? (y/n): ") if ask == 'y': game_on = True else: game_on = False move_2_no = 0 move_1_no = 0 while game_on: # Player 1 chance if chance == "Player1": # Display the board display_board(my_board) # Ask for position move_1_no += 1 pos = player_choice(my_board, player1_name,move_1_no) # Place the marker place_marker(my_board, player1, pos) # Check if player1 wins if win_check(my_board, player1): display_board(my_board) print("\n\t"+player1_name.upper()+" HAS WON!!") game_on = False else: if full_board_check(my_board): display_board(my_board) print("\n\tTIE GAME!") game_on = False else: chance = "Player2" else: # Display the board display_board(my_board) # Ask for position move_2_no += 1 pos = player_choice(my_board, player2_name,move_2_no) # Place the marker place_marker(my_board, player2, pos) # Check if player2 wins if win_check(my_board, player2): display_board(my_board) print("\n\t"+player2_name.upper()+" HAS WON!!") game_on = False else: if full_board_check(my_board): display_board(my_board) print("\n\tTIE GAME!") game_on = False else: chance = "Player1" if not replay(): break;
5c5aa07a122c350d52ab3d5d856064138e7896ee
abbas-sheikh-confiz/sql
/15_sql.py
569
3.984375
4
# Homework for SQL functions # Show car models and total number of orders import sqlite3 with sqlite3.connect('cars.db') as connection: c = connection.cursor() # Read data from inventory table c.execute("SELECT Make, Model, Quantity FROM inventory") cars = c.fetchall() for car in cars: print("Car Maker: {} - Car Model: {}".format(car[0], car[1])) print("In House Quantity:", car[2]) c.execute("SELECT count(order_date) FROM orders WHERE make = ? AND model = ?", (car[0], car[1])) orders_count = c.fetchone()[0] print("Total Orders:", orders_count)
da699fa380438bd6a677884a2f2c8d6a0c8e574d
CamilliCerutti/Python-exercicios
/Curso em Video/ex076.py
618
3.890625
4
# LISTA DE PREÇOS COM TUPLAS # Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular. print('~' * 40) titulo = 'LISTA DE PRECOS' print(titulo.center(30, ' ')) print('~' * 40) lista = ('arroz', 5.00, 'feijão', 2.50, 'óleo de cozinha', 1.50, 'farinha de trigo', 20.00, 'sal', 1.50, 'açúcar', 2.90, 'café', 2.00) for pos in range(0, len(lista)): if pos % 2 == 0: print(f'{lista[pos]:.<30}', end='') else: print(f'R${lista[pos]:>7.2f}') print('~' * 40)
d4878969d21a3c4ab62e66be81e41f2854d91ca7
cjineson/learning-python
/objects.py
439
3.921875
4
class Myclass(object): def __init__(self,name): self.name = name print('Constructor creating object - ', self.name) self.prefix = 'Hello' def sayhello(self,suffix): print(self.prefix + ' ' + suffix) def __del__(self): print('Destructor deleting object - ', self.name) myobject = Myclass("myobj") myobject.sayhello('World!') # note implicit call to destructor as program exits...
50f8c224b903253c523d06c1026d5dcedad6ca5c
MrHamdulay/csc3-capstone
/examples/data/Assignment_1/crrlen001/question3.py
992
3.96875
4
firstname = input('Enter first name:\n') lastname = input('Enter last name:\n') money = eval(input('Enter sum of money in USD:\n') ) country = input('Enter country name:\n') money30 = money*0.3 print('\nDearest', end=' ') print(firstname, end='') print('\nIt is with a heavy heart that I inform you of the death of my father,\nGeneral Fayk', end=' ') print(lastname, end='') print(', your long lost relative from Mapsfostol.\nMy father left the sum of', end=' ') print(money, end='') print('USD for us, your distant cousins.\nUnfortunately, we cannot access the money as it is in a bank in', end=' ') print(country, end='') print('.\nI desperately need your assistance to access this money.\nI will even pay you generously, 30% of the amount -', end=' ') print(money30, end='') print('USD,\nfor your help. Please get in touch with me at this email address asap.') print('Yours sincerely\nFrank', end=' ' ) print(lastname, end='') #Author: Lenard Carroll #Student_Number: CRRLEN001
1cc69f2ea48049368048bb29224c149edb8f9e95
yuki9965/PAT-1
/PAT_B_TEST/1004_Tree_Traversals_Again.py
2,274
3.75
4
# -*- coding: utf-8 -*- __author__ = 'Yaicky' import sys rlt = [] class Node(object): def __init__(self, data=-1, lchild=None, rchild=None, parent=None): self.data = data self.lchild = lchild self.rchild = rchild self.parent = parent self.count = 0 class BinaryTree(object): def __init__(self): self.root = Node() def add(self, data): cur_node = self.root # count = 0 for n in data: while cur_node.count == 2: cur_node = cur_node.parent if n==0: # count += 1 cur_node.count += 1 else: node = Node(data=n, parent=cur_node) cur_node.count += 1 if self.isEmpty(): self.root = node self.root.parent = Node(data=-1, parent=-1) cur_node = self.root else: if cur_node.count == 1: cur_node.lchild = node cur_node = node else: cur_node.rchild = node cur_node = node if cur_node.count == 2: if cur_node.parent != -1: cur_node = cur_node.parent # print(cur_node.parent.data, cur_node.data) def post_order(self, start): node = start if node == None: return self.post_order(node.lchild) self.post_order(node.rchild) rlt.append(str(node.data)) def isEmpty(self): return True if self.root.data == -1 else False all, cur = 0, 0 bTree = BinaryTree() nums = [] # nums1 = [1,2,3,0,0,4,0,0,5,6,0,0] # bTree.add(nums1) # bTree.post_order(bTree.root) for line in sys.stdin: if cur == 0: all = int(line) cur += 1 continue else: op = line.split() if "Push" in op: nums.append(int(op[1])) else: nums.append(0) if cur == all*2: cur = 0 bTree.add(nums) # print(nums) bTree.post_order(bTree.root) print(' '.join(rlt)) cur += 1 ''' 6 Push 1 Push 2 Push 3 Pop Pop Push 4 Pop Pop Push 5 Push 6 Pop Pop '''
925331ad9553b6c4c87cb79dba0b776825ce23f4
xiaoxiae/Advent-of-Code-2018
/03/03-1.py
649
3.546875
4
from re import compile input = open("03.in", "r") data = input.read().splitlines() total = 0 board = [[0] * 1000 for _x in range(1000)] # put all of the pieces of fabric on the board for line in data: s = compile(" @ |: ").split(line) start = tuple(map(int, s[1].split(","))) size = tuple(map(int, s[2].split("x"))) # create the fabric rectangle for x in range(start[0], start[0] + size[0]): for y in range(start[1], start[1] + size[1]): board[x][y] += 1 # if they overlap, increment the total if board[x][y] == 2: total += 1 print(total)
619580f3805ec431379ef1f07ef24654f35fa609
diri-daniel/C.I.D.S_projects_ibinabo_daniel
/wk2/wk2_ex2.py
399
3.5
4
""" Question 2 doesnt have an example but here's my interpretation: input a = 4 process is 4+44+444+4444 output 4936.""" def digit_multp(t, v): b = 1 v = str(v) p = v while b < t: p += v b += 1 return int(p) def incr_n(n): n_n = 0 for x in range(1, n+1): n_n += digit_multp(x, n) return n_n a = int(input()) print(incr_n(a))
be7291cf330aa1d583f9904f2671f36d9fc3759f
seamkh/codetest_2021
/python/DataStructureWithPython/3-2 nodestack/nodestack.py
962
4
4
class Node: def __init__(self,item,link): self.item = item self.next = link def push(item): global top global size top = Node(item, top) size +=1 def peek(): if size != 0: return top.item def pop(): global top global size if size != 0: top_item = top.item top = top.next size -= 1 return top_item def print_stack(): print('top => \t', end = '') p = top while p: if p.next != None: print(p.item, '-> ', end = '') else: print(p.item, end = '') p = p.next print() top = None size = 0 push('apple') push('orange') push('cherry') print('사과, 오렌지, 체리 push 후 : \t', end = '') print_stack() print('top 항목: ' , end = '') print(peek()) push('pear') print('배 push 후 : \t\t', end = '') print_stack() pop() push('grape') print('pop(), 포도 push 후 :\t', end = '') print_stack()
b0d4ddee2143642fee23659331031ba05dae05db
Aasthaengg/IBMdataset
/Python_codes/p02795/s146411544.py
104
3.8125
4
l=[int(input()) for i in range(3)] x=l[0] y=l[1] z=l[2] if x<y: print(-(-z//y)) else: print(-(-z//x))
32d83c75c7c6a6c0d63b7f4ef68668b19fe2ebca
rogersineb/python_developer
/Ciencia_da_Computacao_USP_2/submissao_6_semana/fibonacci_recursivo.py
453
3.734375
4
def fibonacci(numero): if numero < 2: # base da recursão return numero else: return fibonacci(numero-1) + fibonacci(numero-2) #chamada recursiva import pytest @pytest.mark.parametrize("entrada, esperado", [ (0 , 0), (1 , 1), (2 , 1), (3 , 2), (4 , 3), (5 , 5), (6 , 8), (7 , 13) ]) def test_fibonacci(entrada, esperado): assert fibonacci(entrada) == esperado
6cc2fad20de15747225db199155e1c9cb238c863
lsaruwat/address_book
/addressBook.py
6,193
4.125
4
#Assignment 3 Address Book #CS310 Python #By: Logan Saruwatari #Date: 3/30/2016 #Copyright MIT license import sqlite3 from os import system from os import name as osName class Interface(object): enumColumn = ('fName', 'lName', 'phone', 'email') def __init__(self): # Pretty much don't do anything. It feels wrong to connect the db automatically print("Welcome to the Address Book") self.running = True def connect(self): # Connect to the db. Want to make singleton pattern if time permits self.connection = sqlite3.connect("contact.db") self.cur = self.connection.cursor() def close(self): # close db connection. Not sure how what will happen if I don't do this self.connection.close() def insertContact(self, contact): # create a new entry based on the contact object. sql = "INSERT INTO contact VALUES (?,?,?,?)" self.cur.execute(sql, (contact.fName, contact.lName, contact.phone, contact.email)) self.connection.commit() def getAllContacts(self): # return everyone in the address book sql = "SELECT ROWID, fName, lName, phone, email FROM contact" self.cur.execute(sql) return self.cur.fetchall() def removeByName(self, _fName, _lName): #remove a contact by full name. Potential for this not being a unique entry...dangerous sql = "DELETE FROM contact WHERE fName=? AND lName=?" self.cur.execute(sql, (_fName, _lName)) self.connection.commit() def removeById(self, _id): #remove a contact by id. Using built in ROWID which seems to be a unique identifier sql = "DELETE FROM contact WHERE ROWID=?" self.cur.execute(sql, (_id)) self.connection.commit() def removeByPhone(self, _phone): # remove by phone number. sql = "DELETE FROM contact WHERE phone=?" self.cur.execute(sql, (_phone)) self.connection.commit() def prettyPrint(self, fetchAllQuery): for i in fetchAllQuery: print("{} {} {} {} {}".format(i[0], i[1],i[2], i[3], i[4])) def createContact(self): fname = input("Enter First Name: ") lname = input("Enter Last Name: ") phone = input("Enter Phone Number: ") email = input("Enter Email Address: ") self.insertContact(Contact(fname, lname, phone, email)) def searchByName(self, searchPrompt="Enter a Name to search for: "): search = input(searchPrompt) sql = "SELECT ROWID, fName, lName, phone, email FROM contact WHERE fName LIKE ? OR lName LIKE ? OR email LIKE ?" self.cur.execute(sql, ("%"+search+"%", "%"+search+"%", "%"+search+"%")) # % is the wildcard that sqlite3 uses return self.cur.fetchall() def updateById(self, rowId): fname = input("Enter New First Name: ") lname = input("Enter New Last Name: ") phone = input("Enter New Phone Number: ") email = input("Enter New Email Address: ") sql="UPDATE contact SET fName=?, lName=?, phone=?, email=? WHERE ROWID=?" self.cur.execute(sql, (fname, lname, phone, email, rowId)) self.connection.commit() def selectThisThing(self, thing): sql = "SELECT ? FROM contact" self.cur.execute( sql, (thing,) ) return self.cur.fetchall() def sortByColumn(self): self.clearScreen() print("How would you like your contacts sorted?\n") print("1. First Name 2. Last Name") print("3. Phone Number 4. Email") columnToSort = input("Please select a Number: ") if columnToSort.isdigit() and int(columnToSort) > 0 and int(columnToSort) < 5:# input is a valid int sql = "SELECT ROWID, fName, lName, phone, email FROM contact ORDER BY {} ASC".format(self.enumColumn[int(columnToSort)-1]) # the question mark escape doesn't work for strings in program memory. Idk why self.cur.execute(sql) self.prettyPrint(self.cur.fetchall()) input("Press any key to continue") else: self.sortByColumn() def routeInput(self, intInput): #wow I just realized there is no switch/case in python. #Although that makes this harder I understand why they left it out. if intInput == 1: self.clearScreen() self.createContact() elif intInput == 2: self.clearScreen() self.prettyPrint(self.getAllContacts()) input("press any key to continue") elif intInput == 3: self.clearScreen() self.prettyPrint(self.searchByName()) input("press any key to continue") elif intInput == 4: self.clearScreen() self.prettyPrint(self.searchByName("Enter a Name to Update: ")) idToUpdate = input("Enter the id you wish to update or letter to cancel: ") if idToUpdate.isdigit(): self.updateById(int(idToUpdate)) elif intInput == 5: self.clearScreen() self.prettyPrint(self.searchByName("Enter a Name to Delete: ")) idToUpdate = input("Enter the id you wish to Delete or letter to cancel: ") if idToUpdate.isdigit(): self.removeById(int(idToUpdate)) elif intInput == 6: self.sortByColumn() elif intInput == 7: self.running = False print("KTHXBAI") else: print("Edge case occurred! This is why unit testing exists Logan... I think... I'll know ten years from now") def clearScreen(self): system('cls' if osName == 'nt' else 'clear') # cross platform clearing of terminal. clear and cls are system calls def showOptions(self, message="Please select a number: "): # Show the user what they can do to the address book. self.clearScreen() print("-------------Address Book-------------") print("-"*40) print("\n") print("1. Create Contact 2. List Contacts") print("3. Search Contact 4. Update Contact") print("5. Delete Contact 6. Sort Contacts") print("7. Quit Address Book") print("\n") userChoice = input(message) if userChoice.isdigit() and int(userChoice) > 0 and int(userChoice) < 8: # input is between 1 and 6 print(userChoice, " is valid") running = self.routeInput(int(userChoice)) else: # if the users input is nonsense recurse with error message self.showOptions("Invalid Selection!\nPlease select a number") def run(self): while self.running: self.showOptions() class Contact(object): def __init__(self, _fName, _lName, _phone, _email): self.fName = _fName self.lName = _lName self.phone = _phone self.email = _email addressBook = Interface() addressBook.connect() print(addressBook.getAllContacts()) addressBook.run() addressBook.close()
5584842fd704aeb58dbe254cd51324249fd17651
zhaoxinnZ/HeadFirstPythonPractice
/12-3.py
126
3.890625
4
num = float(input()) if num > 0: print(num, '是正數') elif num == 0: print('零') else: print(num, '是負數')