blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
2f84dc3635b64b59f3c19cf036069a34aa2c5e7d
therikshak/FantasyFootball
/DraftYear.py
346
3.65625
4
class DraftYear: teamName = '' year = '' picks = [] def __init__(self, name, year): self.teamName = name self.year = year self.picks = [] # add pick def add_pick(self, pick_num, pick_round, position, player): temp = [pick_num, pick_round, position, player] self.picks.append(temp)
b9bb7deb73be996ec847225a3c10f9f8c063b7c8
jglantonio/learning_python
/curso001/03_strings.py
562
4.375
4
#!/usr/bin/env python3 # Strings y funciones para trabajar con ellos variable = "Tengo un conejo "; print(variable); variable2 = "llamado POL"; print(variable2); print(variable + variable2); print(variable*2); # function len length_variable = len(variable); print("La variable "+variable+", tiene ",length_variable); # primera letra del string print(variable[0]); # Poner todas las letras en capital. variable3 = variable+variable2; print(variable3.title()); # islower(); son todo minusculas print(variable3.islower()); print((variable3.lower()).islower());
4d2c074afe66f9a13380994d59b80c83c29c6ed3
fivepandas/panda-python
/full_name.py
347
3.578125
4
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(full_name) full_name = f"Hell0, {full_name.title()}!" print(full_name)#f 字符串是是python 3.6 引入的,之前的版本需要使用format full_name = "{} {}".format(first_name, last_name) print("Python") print("\tPython") print("Languages:\nPython\nC")
888fd9bf8e6d7215ca56886186a6629a63050f13
glossywhite/Project_Baczyk_Bury
/Baczyk_bury_projekt.py
3,010
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 23 11:26:26 2021 @author: szymo """ from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer ps = PorterStemmer() def process_word(word): word = ps.stem(word) word = word.lower() word = word.strip() return word if __name__ == '__main__': categories = {} with open('categories_list_txt.txt', 'r') as params: for line in params.readlines(): cat = line[:line.find('; ')] words = line[line.find('; ') + 2:] words = words.split(', ') dict_words = {} for word in words: w = word.split(':') w[1] = w[1].replace('\n', '') dict_words[w[0]] = w[1] categories[cat] = dict_words with open('test_text_input.txt', 'r') as input_text: in_txt = input_text.read() in_txt_tokens_words = word_tokenize(in_txt) all_positive = 0 all_negative = 0 cat_occurence = {} param_occurence = {} for cat in categories.keys(): cat_occurence[cat] = 0 cat_positive = 0 cat_negative = 0 print(f'=== {cat.upper()} ===') for param in categories[cat].keys(): param_occurence[param] = 0 processed_word_params = process_word(param) for token in in_txt_tokens_words: processed_word_input = process_word(token) if processed_word_params == processed_word_input: cat_occurence[cat] += 1 param_occurence[param] += 1 if categories[cat][param] == 'positive': all_positive += 1 cat_positive += 1 else: all_negative += 1 cat_negative += 1 print(f'"{param}" occurence: {param_occurence[param]}') print(f' >> {cat.upper()} occurence: {cat_occurence[cat]}') print(f' >> {cat.upper()} positives: {cat_positive}, negatives: {cat_negative}') cat_pos_neg = cat_positive + cat_negative if cat_positive != 0: print(f' >> {cat_positive / cat_pos_neg * 100}% of positives') if cat_negative != 0: print(f' >> {cat_negative / cat_pos_neg * 100}% of negatives') print('===============\n') print('\n\n') print('=== FINAL RESULTS ===') numbers = [cat_occurence[cat] for cat in cat_occurence] max = max(numbers) most_occured_cat = [cat for cat in cat_occurence if cat_occurence[cat] == max] print('Mostly occuring:') for moc in most_occured_cat: print(f'{moc} occured {max} times') all_pos_neg = all_positive + all_negative print(f'{all_positive / all_pos_neg * 100}% of positives') print(f'{all_negative / all_pos_neg * 100}% of negatives')
767c20e0de12d9682365786062e7edb414fb893b
GurenMK/Read-Write-File
/ReadWrite.py
1,244
3.859375
4
""" Alexander Urbanyak CS4720(01) Created: 01-25-2019 Python 3.6 """ # The program reads a text file "in.txt", converts all letters to uppercase, # and writes all contents of the read file to "out.txt" # reads and writes multiple lines # "out.txt" will be created if it doesn't exist, # otherwise all its contents will be erased and re-written # numbers and special characters are unaffected def read_file(file_name): assert file_name is not None file = open(file_name, "r") result = file.readlines() file.close() return result def to_upper_case(lines): for line in lines: lines[lines.index(line)] = line.upper() # assumes something must be written to a file def write_file(file_name, lines): assert file_name is not None if len(lines) < 1: raise ValueError("No text is provided to write to " + file_name) file = open(file_name, "w") file.writelines(lines) file.close() if __name__ == '__main__': input_file = "in.txt" output_file = "out.txt" # read file content = read_file(input_file) # convert all characters to upper case to_upper_case(content) # write to a file write_file(output_file, content)
ed5276467a97a1f9b3af74eee83f615b4aea6789
RaginiD/Warm-up-Challenges
/sock_merchant_hashing.py
596
3.765625
4
#!/bin/python import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): # dict to store socks color and number of pairs socks_data = {} for item in ar: old_count = socks_data.get(item,0) socks_data[item] = old_count+1 # counter count = 0 for value in socks_data.values(): count += value//2 return count if __name__ == '__main__': n = int(raw_input()) ar = map(int, raw_input().rstrip().split()) result = sockMerchant(n, ar) print(str(result) + '\n')
2b20099429be59aa4bcca71df556eb4806aca1f3
Noor9920/PythonAssignment
/Assignment4.py
100
3.9375
4
n=int(input("The value of n")) fact=1 for each in range(1,n+1): fact=fact*each print(fact)
78cfdf23395424fbcad9e4f5248929013f3a2ac7
Noor9920/PythonAssignment
/Assignment6.py
90
3.8125
4
a=int(input("Enter a No")) fact=1 for i in range(1,a+1): fact=fact*i print(fact)
026526ddd9c38e990d966a0e3259edcb2c438807
arlionn/readit
/readit/utilities/filelist.py
1,003
4.21875
4
import glob from itertools import chain def filelist(root: str, recursive: bool = True) -> [str]: """ Defines a function used to retrieve all of the file paths matching a directory string expression. :param root: The root directory/file to begin looking for files that will be read. :param recursive: Indicates whether or not glob should search for the file name string recursively :return: Returns a list of strings containing fully specified file paths that will be consumed and combined. """ listoffiles = [ glob.glob(filenm, recursive=recursive) for filenm in root ] return unfold(listoffiles) def unfold(filepaths: [str]) -> [str]: """ Defines a function that is used to convert a list of lists into a single flattened list. :param filepaths: An object containing a list of lists of file paths that should be flattened into a single list. :return: A single list containing all of the file paths. """ return list(chain(*filepaths))
e8a3eb0c3ec81c3d341740c6982fbfa39112f4ca
ramesh-anandan/learn-python
/dictionaries.py
210
3.640625
4
my_stuff = {'firstName': 'Ramesh', 'lastName': 'Anandhan', 'address': {'city': 'Bangalore', 'pin': 560043}} print(my_stuff['lastName']) print(my_stuff['address']['pin']) my_stuff['age'] = 35 print(my_stuff)
af9a36eaf88bc49ccbdf85a869506b9d3d5c587e
ramesh-anandan/learn-python
/decorators.py
387
3.6875
4
def new_decorator(func): def wrap(): print('before') func() print('after') return wrap @new_decorator def func_need_decorator(): print('i need decorator') func_need_decorator() # global/locals: Accessing global/local variables from dictionary def localFunction(): varLocal = 10; print(locals()) print(globals()) localFunction();
f81259cfbd65e766de3bf29218a7154d4e2fc7e0
Daoi/SumOfIntervals
/sum_of_intervals.py
393
3.609375
4
def sum_of_intervals(intervals): from collections import Counter interval = [] length = 0 for i in range(len(intervals)): for j in range(len(intervals[i])): for x in range(intervals[i][j], intervals[i][j+1]): interval.append(x) break numbers = Counter(interval) for k in numbers: length += 1 return length
8350835189b46c5e88273d3145749b1b8d89c7ed
qinxinWu/turtle
/绘制分形树和分形正方形的代码及运行结果/DrawTree.py
1,790
3.53125
4
# !/usr/bin/env python # coding:utf-8 # Author: Qingxin Wu import turtle #绘制分形树的递归方法 #length是指每个树干的长度 def drawFractalTree(length): #限定递归函数终止的条件为:当传入的树干的长度小于等于10时递归终止即只有大于10才能执行 if length > 10: #先是画主树干:方向为竖直向上 turtle.forward(length) #其次,把画笔的方向向右旋转33度,为了接下来画右子树 turtle.right(33) #由于要和实际的树相符,所以一般来说子树干会比主树干长度小,所以我这里设置子树干的长度仅为主树干的0.8倍长 #且这里开始调用自身函数,即递归开始绘制右子树 drawFractalTree(0.8 * length) #接下来准备画左子树 #由于此时画笔已经是与竖直方向相比向右偏移了33度,所以为了左右子树对称,此时要将画笔方向向左旋转33度*2,即66度 turtle.left(66) #同理,左子树的树干长度也是主树干的0.8倍,开始递归绘制左子树 drawFractalTree(0.8 * length) # 左子树绘制完成后要返回到原来的竖直方向的主树干上,所以要先向右旋转33度,然后沿袭竖直向下方向返回同样长度 turtle.right(33) turtle.backward(length) # 由于初始画笔的方向是水平向右的,所以要画竖直向上的树,要先把方向向左方向旋转90度 turtle.left(90) #设置画笔的粗细大小为3 turtle.pensize(3) #设置画笔的颜色为蓝色 turtle.color('blue') #开始递归绘制,并给出初始树干长度为50 drawFractalTree(50) #使得绘制完成不直接退出,而是点击一下才退出 turtle.exitonclick()
0d012a23dfd3e68024f560287226171040c2ca67
EthanReeceBarrett/CP1404Practicals
/prac_03/password_check.py
941
4.4375
4
"""Password check Program checks user input length and and print * password if valid, BUT with functions""" minimum_length = 3 def main(): password = get_password(minimum_length) convert_password(password) def convert_password(password): """converts password input to an equal length "*" output""" for char in password: print("*", end="") def get_password(minimum_length): """takes a users input and checks that it is greater than the minimum length if not, repeats till valid then returns the password""" valid = False while not valid: password = input("Please enter password greater than 3 characters long: ") password_count = 0 for char in password: password_count += 1 if password_count <= minimum_length: print("invalid password") else: print("valid password") valid = True return password main()
262d7b72a9b8c8715c1169b9385dd1017cb2632b
EthanReeceBarrett/CP1404Practicals
/prac_06/programming_language.py
800
4.25
4
"""Intermediate Exercise 1, making a simple class.""" class ProgrammingLanguage: """class to store the information of a programing language.""" def __init__(self, field="", typing="", reflection="", year=""): """initialise a programming language instance.""" self.field = field self.typing = typing self.reflection = reflection self.year = year def __str__(self): """returns output for printing""" return "{}, {} typing, reflection = {}, First appeared in 1991".format(self.field, self.typing, self.reflection, self.year) def is_dynamic(self): if self.typing == "Dynamic": return True else: return False
4b9e2e7be91d9ed0b3627cfb2ac93b1cc25ed53e
mei1797/tarea-2
/ejercicio 6.py
120
3.953125
4
n = int(input("Introduce la altura del triangulo (entero postitivo): ")) for i in range(n): print("*"*(i+1))
028e52236ff8d4765bcfabcaf25457cc78901835
Sourav-1234/Blockchain-Programming
/Module-1/Blockchain.py
3,279
3.640625
4
# Module 1 Create A Blockchain #Importing necessary libaries import datetime import hashlib # Libary use to generate the hash code of secure hash algorithm i.e 256 import json from flask import Flask ,jsonify #Building a Blockchain class Blockchain: def __init__(self): self.chain = [] self.create_block(proof =1, previous_hash ='0') def create_block(self,proof, previous_hash): block={'index':len(self.chain)+1 , 'timestamp': str(datetime.datetime.now()), 'proof': proof, 'previous_hash': previous_hash} self.chain.append(block) return block def get_previous_block(self): return self.chain[-1] def proof_of_work(self,previous_proof): new_proof=1 check_proof= False while check_proof is False : hash_operation=hashlib.sha256(str(new_proof **2 -previous_proof**2).encode()).hexdigest() if hash_operation[:4]=='0000': check_proof= True else: new_proof+=1 return new_proof def hash(self,block): encoded_block= json.dumps(block, sort_keys =True).encode() return hashlib.sha256(encoded_block).hexdigest() def is_chain_valid(self,chain) : block_index=1 previous_block =chain[0] while block_index<len(chain): block= chain[block_index] if block['previous_hash']!= self.hash(previous_block): return False previous_proof=previous_block['proof'] proof=block['proof'] hash_operation=hashlib.sha256(str(proof **2 -previous_proof**2).encode()).hexdigest() if hash_operation[:4] !='0000': return False previous_block=block block_index+=1 return True #Creating a Webpage app = Flask(__name__) #Creating a Blockchain blockchain = Blockchain() # Mining the Blockchain @app.route('/mine_block', methods=['GET']) def mine_block(): previous_block =blockchain.get_previous_block() previous_proof= previous_block['proof'] proof = blockchain.proof_of_work(previous_proof) previous_hash = blockchain.hash(previous_block) block = blockchain.create_block(proof,previous_hash) response ={'message':'Congratulation, you have mined a block', 'timestamp':block['timestamp'], 'proof': block['proof'],'previous_hash': block['previous_hash']} return jsonify(response) ,200 @app.route('/get_chain', methods=['GET']) #Getting the full BlockChain def get_chain(): response= {'chain':blockchain.chain , 'length':len(blockchain.chain)} return jsonify(response) ,200 @app.route('/is_valid', methods=['GET']) def is_valid(): is_v=blockchain.is_chain_valid(blockchain.chain) if is_v: response ={'message':'You have valid blockchain'} else: response ={'message':'Dont have a valid blockchain'} return jsonify(response) ,200 #Running the app app.run( host = '0.0.0.0' , port = 5000)
8aa1cf81834abd2a7cb368ffdb9510ae7f0039e4
nobleoxford/Simulation1
/testbubblesort.py
1,315
4.46875
4
# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr1 = [64, 34, 25, 12, 22, 11, 90] arr2 = [64, 34, 25, 12, 22, 11] arr3 = [-64, 34, 25] arr4 = [] bubbleSort(arr1) bubbleSort(arr2) bubbleSort(arr3) bubbleSort(arr4) print ("Sorted array1 is:") print(arr1) print ("Sorted array2 is:") print(arr2) print ("Sorted array3 is:") print(arr3) print ("Sorted array4 is:") print(arr4) cards = ['5♣', '8♠', '4♠', '9♣', 'K♣', '6♣', '5♥', '3♣', '8♥', 'A♥', 'K♥', 'K♦', '10♣', 'Q♣', '7♦', 'Q♦', 'K♠', 'Q♠', 'J♣', '5♦', '9♥', '6♦', '2♣', '7♠', '10♠', '5♠', '4♣', '8♣', '9♠', '6♥', '9♦', '3♥', '3♠', '6♠', '2♥', '10♦', '10♥', 'A♠', 'A♣', 'J♥', '7♣', '4♥', '2♦', '3♦', '2♠', 'Q♥', 'A♦', '7♥', '8♦', 'J♠', 'J♦', '4♦'] bubbleSort(cards) print("Sorted cards:" ) print(cards)
3ec9603781aa7c06da5eda3af61af8f0244e697e
juanda2222/playground
/arrays/find_missing_and_repeating.py
1,630
3.921875
4
""" Given an unsorted array of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers. Note: If you find multiple answers then print the Smallest number found. Also, expected solution is O(n) time and constant extra space. Input: The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. Output: Print B, the repeating number followed by A which is missing in a single line. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 106 1 ≤ A[i] ≤ N Example: Input: 2 2 2 2 3 1 3 3 Output: 2 1 3 2 Explanation: Testcase 1: Repeating number is 2 and smallest positive missing number is 1. Testcase 2: Repeating number is 3 and smallest positive missing number is 2. """ def repeated_and_missing(arr:list = [2,1,3,1])-> int: n = len(arr) #goes from 1 to n+1 seeker_list = [1] * n for i, num in enumerate(arr): # repeated found if seeker_list[num - 1] == -1: repeated = num seeker_list[num - 1] = -1 missing = seeker_list.index(1) + 1 # this might give a o(2n) complexity return (repeated, missing) if __name__ == '__main__': a = [1,2,3,14,13,12,4,5,12,11,7,8,9,10] (repeated, missing) = repeated_and_missing(a) print("the repeated is: "+str(repeated)+" and the missing is: "+str(missing))
58e80763a40ced56a528694905d2b45729becd17
juanda2222/playground
/interview_questions/24_game copy 2.py
1,052
3.546875
4
# Property always holds: root.val = min(root.left.val, root.right.val) from itertools import product, permutations parenthesis = ["(", "(", ")", ")"]+[" "]*6 parenthesis_combinations = set(list(permutations(parenthesis, 6))) # 6 possible positions for the parenthesis # for each parenthesis combination try each operation combination: for parenthesis_list in parenthesis_combinations: # create the operation using eval: operation = "".join( [ parenthesis_list[0], str(2), "*", parenthesis_list[1], str(2), parenthesis_list[2], "*", parenthesis_list[3], str(3), parenthesis_list[4], "*", str(4), parenthesis_list[5] ]) # if the operation is valid process it try: #if operation_list[0] is "*" and operation_list[1] is "*" and operation_list[2] is "*": result = eval(operation) #print("Operation: ", operation) #print("Result: ", result) print(parenthesis_list) except Exception: #print("Discarted: ", operation) pass
c1f82edf11f08b802d69e41ddc27344f15feef7e
juanda2222/playground
/python_stackoverflow/next_bigger_number.py
3,024
3.90625
4
# https://stackoverflow.com/questions/61719835/increasing-itertools-permutations-performance import itertools def next_bigger2(n): num = str(n) num1 = set(int(x) for x in str(num)) if num == num[0] *len(num): return -1 #full_set = set(num) lis = set(int(''.join(nums)) for nums in itertools.permutations(num, len(num))) lis = sorted(lis) try: return int(lis[lis.index(n)+1]) except Exception: return -1 # this is a basic bubble sort algorithm (Which is kind of a simple but efficent sorting algorithm) def sort_ascendant( arr:list = [4,8,3,6,23,90,2] ): if len(arr)<=0 : raise ValueError("Array too small") keep_looping = True ret_arr = list(arr) while keep_looping: keep_looping = False # start false to exit by default for i, item in enumerate(ret_arr): if i >= len(ret_arr) - 1: # we r already on the last item so no need to sort break elif item <= ret_arr[i+1]: #do nothing pass elif item > ret_arr[i+1]: #reverse the order aux = ret_arr[i] ret_arr[i] = ret_arr[i+1] ret_arr[i+1] = aux keep_looping = True # if at least one item if sorted check again return ret_arr def next_bigger(n): num_string = list(str(n)) for i in range(1, len(num_string)): if i == len(num_string): return -1 #find two the two numbers one bigger than the other with the minimun order if num_string[-i] > num_string[-i-1]: compare_reference = num_string[-i] index_reference = -i #check if the current number is smaller than any of the tail for k, current in enumerate(num_string[-i:]): if num_string[-i-1] < current and current < compare_reference: compare_reference = current index_reference = -i+k print("index num: " + str(index_reference)) print("next bigger num: " + compare_reference) print("pivot: " + num_string[-i-1]) #interchange the locations: num_string[index_reference] = num_string[-i-1] num_string[-i-1] = compare_reference #check if the tail is larger than one digit if i > 1: #order the rest of the vector to create the smaller number (ordering it). lower_part_ordered = sort_ascendant(num_string[-i:]) else: lower_part_ordered = [num_string[-i]] # create a string from the list return int("".join(num_string[:-i] + lower_part_ordered)) # no match found means a number like 65311 return -1 print(next_bigger(35421)) print(next_bigger(454321)) print(next_bigger(76422211)) print(next_bigger(12)) print(next_bigger(513342342342342342234))
4156cf132cddb60d49ec6208315a0e206053ec45
hannahtuttle/Sorting
/src/recursive_sorting/recursive_sorting.py
3,287
4.09375
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): # Create an array arr3[] of size n1 + n2. elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO for i in range(0, len(merged_arr)): if not arrA: merged_arr[i] = arrB[0] del arrB[0] elif not arrB: merged_arr[i] = arrA[0] del arrA[0] elif arrA[0] > arrB[0]: merged_arr[i] = arrB[0] del arrB[0] else: merged_arr[i] = arrA[0] del arrA[0] # i=0 # # Simultaneously traverse arrA and arrB. # for item in arrA[:]: # for it in arrB[:]: # # Pick smaller of current elements in arrA and arrB, copy this smaller element to next position in merged_arr and move ahead in merged_arr and the array whose element is picked. # if it < item: # # if it already exists in merged_ then skip it and go to the next value # if (it in merged_arr): # pass # else: # merged_arr[i] = it # i += 1 # elif item < it: # if (item in merged_arr): # pass # else: # merged_arr[i] = item # i += 1 # # If there are remaining elements in arrA or arrB, copy them also in merged_arr. # if (arrA[-1] in merged_arr): # pass # else: # instert_here = merged_arr.index(arrB[-1]) +1 # for item in arrA: # if(item in merged_arr): # pass # else: # print('last inserted value', instert_here) # merged_arr[instert_here] = item # instert_here +=1 # if (arrB[-1] in merged_arr): # pass # else: # for item in arrB: # if(item in merged_arr): # pass # else: # merged_arr[i] = item # i+=1 # print('index of merge after loop', i) return merged_arr sampleA = [1, 3, 5, 6, 9, 10] sampleB = [2, 4, 7, 8, 11, 12] print(merge(sampleA, sampleB)) # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO if len(arr) <= 1: return arr # this finds the index of the widdle of hthe array rounded to an int. middle = round(len(arr)/2) # this splits the arr into two new smaller arr first_half = arr[:middle] second_half= arr[middle:] # print('first half', first_half) # print('second half', second_half) x = merge_sort(first_half) y = merge_sort(second_half) # split_arr = [merge_sort(first_half)] # print(split_arr) return merge(x, y) sampleC = [12, 1, 10, 8, 4, 2, 7, 5, 6] # print(merge_sort(sampleC)) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
fa3e3540c5bf171c1f1fd2b69b16d495883f4995
hiroto-kazama/cs-362_Unit_Testing
/avg_elem.py
161
3.5625
4
def cal_average(a): avg = sum(a)/len(a) return avg """ userInt = list(map(int, input("Enter elements: ").split())) print(cal_average(userInt)) """
f5690a2f35bb5e7aac15fa49553217ea3efb11a1
zaleskasylwia/Converter
/zad1.1.1.py
1,667
4
4
#done def converter_binary(number): #z dziesietnego na binarny a = [] #print(number) while number > 0: a.append(number % 2) number = int(number / 2) print_backward(a) print (" 2") def converter_decimal(number): # z binarnego na dziesietny decimal = 0 for digit in str(number): decimal = decimal*2 + int(digit) print (decimal, "10") def print_backward(table): #funkcja aby napisać wynik od tylu length = len(table) - 1 while length >= 0: print(table[length], end='') length -= 1 def main(): while True: type_nr = print (""" ***Hello in binary and decimal converter*** \n First number which you'll write is a number to convert, after that the sesond number is responsible for the system '2' is for decimal, '10' is for binary """) input_read = input() try: try: input_read = input_read.split() number = int(input_read[0]) system = int(input_read[1]) if system == 10: converter_binary(number) elif system == 2: converter_decimal(number) except ValueError: print("Error: Use just numbers") except IndexError: print("Error: Try again, remember about space place ") ask = "" while not (ask == 'YES' or ask== 'NO'): #ask about game again ask = input("Do you want to try again? (YES/NO) ").upper() if ask == 'NO': break main()
5c01f26f3660c86e732bfb63c7f5210e745a6181
Vanya-Rusin/labs
/Завдання 1.py
163
3.96875
4
from math import sqrt d=float(input("введіть довжину сторони d: ")) S=d**2/2 P=2 * sqrt(2)*d print("S=" + str(S)) print("P=" + str(P))
9ba1770e3585a53d3a22b801034192427bb124e3
berglaura/pythonCourse
/ehtoarkkitehti.py
250
3.5
4
luku = int(input("Anna kokonaisluku: ")) if luku > 1000: print("Luku on suurempi kuin 1000") elif luku > 100: print("Luku on suurempi kuin 100") elif luku > 10: print("Luku on suurempi kuin 10") else: print("Luku on 10 tai pienempi")
f08082886a4bbc9ccef1c4fe92f5923d79ac3b2d
Kingdageek/Learn_Python
/Box_Display.py
524
4.09375
4
# Collect sentence to display in centre of the box sentence = input("Enter a Sentence: ") screen_width = 80 text_width = len(sentence) box_width = text_width + 6 margin = (screen_width - box_width)// 2 #Designing our box print() print(' ' * margin + '+' + '-' * (box_width - 2) + '+') print(' '* margin + '|' + ' ' * (box_width - 2) + '|') print(' ' * margin + '|' + ' ' * 2 + sentence + ' ' * 2 + '|') print(' '* margin + '|' + ' ' * (box_width - 2) + '|') print(' ' * margin + '+' + '-' * (box_width - 2) + '+') print()
5beac375837694d0f0357bd1d2d19289fdb9c9b9
Kingdageek/Learn_Python
/dark_room.py
3,347
3.8125
4
#dark_room.py from Guess_game import enter_cmd def help(): print("There are 4 rooms, Just flow with the game") print("type 'play' to play 'a dark room'") print("type 'quit' to quit playing") print("type 'help' to see this message again") def play(): while True: print("You enter a dark room with four doors. Do you go through door #1, door #2, door #3 or door #4") door = input("> ") if door == "quit": return elif door == "help": help() return elif door == "1": print("You see a giant Python curling itself around a man. What do you do?") print("1. Run out\n2. Try to save the man") python = input("> ") if python == "1": print("You're a bloody coward!!!. We'll see how you fare soon.") continue elif python == "2": print("The Python gets angry and squeezes life out of you... Good Job!") return else: print("doing %s is probably better" % python) return elif door == "2": print("You see people partying and drinking booze. What do you do?") print("1. join them to party\n2. Try another room") party = input("> ") if party == "1": print("As soon as you enter, you discover they're vampires and they suck all of your blood. Good job!") return elif party == "2": print("You HOPPER!!!! we'll soon see how you fare SUCKER!!!") continue else: print("doing %s is probably better" % party) return elif door == "3": print("You see a bear eating cake. What do you do?") print("1. take the cake from the bear\n2. Scream at the bear") bear = input("> ") if bear == "1": print("The bear eats your face. Good Job!") return elif bear == "2": print("The bear eats your balls if you're a guy or your boobs for the other gender. Good job!") return else: print("Doing %s is probably better." % bear) elif door == "4": print("You stare into an abyss of lost souls. What do you do?") print("1. piss into the abyss\n2.run out in fear") abyss = input("> ") if abyss == "1": print("While pissing, you slip and fall into the abyss. Good Job!") return elif abyss == "2": print("Scaredy Cat!!! You fall on a knife and die!") return else: print("I guess doing %s is probably better" % abyss) return else: print("You fall on a knife and DIE!!!!!") return def main(): print("WELCOME TO A DARK ROOM. DARK THE KEYWORDD\n") while True: print("THIS IS A DARK ROOM OPTIONS MENU...\n") cmd = enter_cmd() if cmd == "play": play() elif cmd == "help": help() elif cmd == "quit": return else: print("INVALID COMMAND | ENTER 'help' for help") if __name__ == "__main__": main()
b6d570d9942e4cad129c3cf3252f3a2c79630c29
Kingdageek/Learn_Python
/gen_primes.py
237
3.546875
4
# gen_primes.py import pprint import math def gen_primes(n): primes = [2] for i in range(3,n): for k in range(2,int(math.sqrt(i)) + 1): if i % k == 0: break else: primes.append(i) return primes pprint.pprint(gen_primes(1000))
ff54f51ac7d2eecf0faa3a0145462f07e9a2095c
Kingdageek/Learn_Python
/shelve_database.py
1,872
3.921875
4
import shelve def store_person(db): """Query user for details to store in database""" pid = input("Enter your unique ID: ") person = {} person["name"] = input("Enter your name: ") person["age"] = input("Enter your age: ") person["phone"] = input("Enter your phone: ") db[pid] = person def lookup_person(db): """Query user for the ID and desired field and returns the value appropriate to field""" pid = input("Enter your ID: ") field = input("Enter the info you'd like to know? (name, age, phone): ").strip().lower() print(field.capitalize()+ ": " + db[pid][field]) #field with first letter capitalized def print_help(): print("The commands are: ") print("Enter 'store' to store details in database") print("Enter 'look' to lookup details already in database") print("Enter 'quit' to close and exit") print("Enter '?' for help; essentially reprinting this message") def enter_command(): cmd = input("Enter command (press '?' for help): ").strip().lower() return cmd def main(): database = shelve.open("example.dat") # shelve database object... extension '.dat' try: while True: cmd = enter_command() if cmd == "store": store_person(database) print("Congratulations! Person now stored in database") elif cmd == "look": lookup_person(database) elif cmd == "?": print_help() elif cmd == "quit": return else: print("This command is not available, Enter '?' for help") finally: database.close() # Close shelve object if __name__ == "__main__": main() #if it's run as a script on its own. It can also be im # ported as a module
703312ee6d095e5e3990811d98bf6690c1e29f37
Kingdageek/Learn_Python
/PredatoryCreditCard.py
1,385
3.515625
4
#PredatoryCreditCard.py from CreditCard import CreditCard class PredatoryCreditCard(CreditCard): OVERLIMIT_FEE = 5 SURCHARGE = 1 def __init__(self, customer, bank, account, limit, apr): super().__init__(customer, bank, account, limit) self._apr = apr # Annual Percentage Rate self._count = 0 def charge(self, price): """ Specialize the charge method in the CreditCard superclass. If the superclass's charge() returns True, return True. if it returns False, add $5 to balance/debt """ self._count += 1 success = super().charge(price) if not success: self._balance += PredatoryCreditCard.OVERLIMIT_FEE return success def process_month(self): """ Interest to be charged on balance/debt monthly. Using compound interest. Amount = principal(1 + R(in 1 yr))**time(in years) 1/12 implies a month. If the charge method was called more than 10 times that month, charge a $1 fee according to the number of times more that 10. set count back to zero. """ self._balance = self._balance * ((1 + self._apr) ** (1/12)) if self._count > 10: temp = self._count - 10 self._balance += PredatoryCreditCard.SURCHARGE * temp self._count = 0
7d2d55966b1b93149efdec02330bcd4cb17a7fbe
michaelsmirnoff/SF_DAT_15_WORK
/hw/hw1.py
4,927
3.828125
4
''' Move this code into your OWN SF_DAT_15_WORK repo Please complete each question using 100% python code If you have any questions, ask a peer or one of the instructors! When you are done, add, commit, and push up to your repo This is due 7/1/2015 ''' #Author:Nick Smirnov import pandas as pd import matplotlib.pyplot as plt # pd.set_option('max_colwidth', 50) # set this if you need to pk_file = 'C:\Users\Nick\Desktop\GA\SF_DAT_15\hw\data\police-killings.csv' killings = pd.read_csv(pk_file) killings.head() killings.columns # 1. Make the following changed to column names: # lawenforcementagency -> agency # raceethnicity -> race killings.rename(columns={'lawenforcementagency':'agency', 'raceethnicity':'race'}, inplace=True) # 2. Show the count of missing values in each column killings.isnull().sum() # 3. replace each null value in the dataframe with the string "Unknown" killings.fillna(value='Unknown', inplace=True) # 4. How many killings were there so far in 2015? killings[killings.year==2015].year.count() # 5. Of all killings, how many were male and how many female? killings.groupby('gender').gender.count() # 6. How many killings were of unarmed people? killings[killings.armed == 'No'].armed.count() # 7. What percentage of all killings were unarmed? unarmed = killings[killings.armed == 'No'].armed.count() total = killings.armed.count() percentage = float(unarmed) / float(total) * 100 # 8. What are the 5 states with the most killings? killings.groupby('state').state.count().nlargest(5) # 9. Show a value counts of deaths for each race killings.groupby('race').race.count() # 10. Display a histogram of ages of all killings killings.groupby('age').age.plot(kind='hist', stacked=True) # 11. Show 6 histograms of ages by race byrace = killings.groupby('race').age #plot(kind='hist', stacked=False) ''' fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(20, 10)) fig.subplots_adjust(hspace=1.0) ## Create space between plots byrace['FL'].plot(ax=axes[0,0]) byrace['GA'].plot(ax=axes[0,1]) byrace['GA'].plot(ax=axes[0,1]) byrace['TX'].plot(ax=axes[1,0]) byrace['NY'].plot(ax=axes[1,1]) byrace['GA'].plot(ax=axes[0,1]) # Add titles axes[0,0].set_title('Florida') axes[0,1].set_title('Georgia') axes[0,1].set_title('Georgia') axes[1,0].set_title('Texas') axes[1,1].set_title('North East'); axes[0,1].set_title('Georgia') byrace.hist(figsize=(6, 4)) ''' # 12. What is the average age of death by race? killings.groupby('race').age.mean() # 13. Show a bar chart with counts of deaths every month killings.groupby('month').month.count().plot(kind='bar') ################### ### Less Morbid ### ################### m_file = 'C:\Users\Nick\Desktop\GA\SF_DAT_15\hw\data\college-majors.csv' majors = pd.read_csv(m_file) majors.head() majors.columns # 1. Delete the columns (employed_full_time_year_round, major_code) del majors['Major_code'] del majors['Employed_full_time_year_round'] # 2. Show the cout of missing values in each column majors.isnull().sum() # 3. What are the top 10 highest paying majors? majors.sort_index(by='P75th', ascending=False).Major.head(10) # 4. Plot the data from the last question in a bar chart, include proper title, and labels! #import matplotlib.pyplot as plt top10 = majors.sort_index(by='P75th', ascending=False).head(10) top10.plot(x='Major', y='P75th', kind='bar') '''plt.xlabel("Major") # set the x axis label plt.ylabel("Salary") # set the y axis label plt.title("Top 10 Highest Paying majors") # set the title plt.plot(top10.Major, top10.P75th) ''' # 5. What is the average median salary for each major category? majors.groupby('Major_category').Median.mean() # 6. Show only the top 5 paying major categories majors.groupby('Major_category').Median.mean().nlargest(5) # 7. Plot a histogram of the distribution of median salaries majors.groupby('Major').Median.mean().plot(kind='hist') # 8. Plot a histogram of the distribution of median salaries by major category majors.groupby('Major_category').Median.mean().plot(kind='hist') # 9. What are the top 10 most UNemployed majors? # What are the unemployment rates? majors.columns majors.sort_index(by='Unemployed', ascending=False).head(5) # 10. What are the top 10 most UNemployed majors CATEGORIES? Use the mean for each category # What are the unemployment rates? majors.groupby('Major_category').Unemployed.mean().nlargest(10) # 11. the total and employed column refer to the people that were surveyed. # Create a new column showing the emlpoyment rate of the people surveyed for each major # call it "sample_employment_rate" # Example the first row has total: 128148 and employed: 90245. it's # sample_employment_rate should be 90245.0 / 128148.0 = .7042 majors['sample_employment_rate'] = [(m.Unemployed / m.Employed) for m in majors] # 12. Create a "sample_unemployment_rate" colun # this column should be 1 - "sample_employment_rate"
f6b938632305063a193494ad8b3eb0be06791802
Likkrid/cryptography-summer-2014
/lista7/ec.py
3,573
3.609375
4
from finite_fields.finitefield import FiniteField import random class Point(object): def __init__(self, curve, x, y): self.curve = curve self.x = x self.y = y if not curve.contains(x, y): raise Exception("%s does not contains (%s, %s)" % (self.curve, self.x, self.y)) def __eq__(self, other): return self.x == other.x and self.y == other.y def __neg__(self): return Point(self.curve, self.x, -self.y) def __repr__(self): return "(%r, %r)" % (self.x, self.y) def __add__(self, Q): if isinstance(Q, O): return self if (self.x, self.y) == (Q.x, Q.y): if self.y == 0: return O(self.curve) # slope of the tangent line m = (3 * self.x * self.x + self.curve.a) / (2 * self.y) else: if self.x == Q.x: return O(self.curve) # slope of the secant line m = (Q.y - self.y) / (Q.x - self.x) x_3 = m*m - Q.x - self.x y_3 = m*(x_3 - self.x) + self.y return Point(self.curve, x_3, -y_3) def __sub__(self, Q): return self + (-Q) def __mul__(self, n): if not (isinstance(n, int) or isinstance(n, long)): print n.__class__.__name__ raise Exception("We don't scale a point by a non-int") else: if n < 0: return -self * -n if n == 0: return O(self.curve) else: Q = self R = self if n & 1 == 1 else O(self.curve) i = 2 while i <= n: Q = Q + Q if n & i == i: R = Q + R i = i << 1 return R def __rmul__(self, n): return self * n #Point at Infinity class O(Point): def __init__(self, curve): self.curve = curve def __neg__(self): return self def __add__(self, Q): return Q def __sub__(self, Q): return -Q def __mul__(self, n): if not isinstance(n, int): raise Exception("We don't scale a point by a non-int") else: return self def __repr__(self): return "Infinity" class EllipticCurve(object): #y^2 = x^3 + ax + b def __init__(self, a, b): self.a = a self.b = b self.det = 4*(a*a*a) + 27*b*b if not self.is_nonsingular(): raise ValueError("%s is not nonsingular" % self) def is_nonsingular(self): return self.det != 0 def contains(self, x, y): return y*y == x**3 + self.a * x + self.b def __str__(self): return 'y^2 = x^3 + %sx + %s' % (self.a, self.b) def __eq__(self): return (self.a, self.b) == (other.a, other.b) class PublicKey(object): def __init__(self, curve, P, Q, order): self.curve = curve self.P = P self.Q = Q self.order = order class SecretKey(object): def __init__(self, order): self.a = random.randint(2, order) if __name__ == '__main__': p = int("fffffffffffffffffffffffffffffffeffffffffffffffff", 16) print "p = ", p a = p - 3 print "a = ", a b = int("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16) print "b = ", b x_G = int("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16) print "x_G = ", x_G y_G = int("07192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16) print "y_G = ", y_G #order - rzad G order = int("ffffffffffffffffffffffff99def836146bc9b1b4d22831", 16) print "order = ", order F = FiniteField(p, 1) curve = EllipticCurve(a=F(a), b=F(b)) P = Point(curve, F(x_G), F(y_G)) r = random.randint(2, order) priv_key = SecretKey(r) P = r * P Q = priv_key.a * P pub_key = PublicKey(curve, P, Q, order) #STEP1 send R k = random.randint(1, order) R = k * P print "k = ", k #STEP2 send challenge e = random.randint(1, order) print "e = ", e #STEP3 compute s s = (k + priv_key.a * e) % order print "s = ", s #Verficiation print s * P print R + e * Q print s * P == R + e * Q
f4b9071820ebb88f2b00a01942b3b9f253400d35
Lyrics2000/lecture2
/solutions/Strings/AssignVariableToString.py
237
4
4
# assign single variable to string a = "Hello" print(a) #Assign multiple variable to string a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a)
be2b0b5b397c557001a7636943186c9c2bebd0d4
finn79426/Algorithm
/Selection Sort/SelectionSort.py
627
3.75
4
import random def random_list(ran, elements): return random.sample(range(ran), elements) def selection_sort(list): # from small to large for i in range(0, len(list)-1): min = 1 for j in range(i+1, len(list)): if(list[min] > list[j]): min = j if(min != i): list[min], list[i] = list[i], list[min] print("Round ", i+1, ":", list) return list if __name__ == '__main__': data = random_list(100, 10) print("\nUnsorted data: \n{}\n".format(data)) sorted_data = selection_sort(data) print("\nResult: \n{}".format(sorted_data))
c367b6aff58bbf529e96b53cea5a122188cef7fe
cursosbit/solucionador_automatico_CT
/var/variable.py
2,885
3.921875
4
''' Clase para definir ls variable mediante sus atributos''' class Unidad(): '''Clase para definir las unidades mediante sus atributos''' def __init__(self, simbolo, nombre, lstunidades): '''simbolo, símbolo asigndo a la unidad nombre, identificador de la unidad lstunidades, unidades posibles ''' self.simbolo = simbolo self.nombre = nombre self.lstunidades = lstunidades def print_unid(self): ''' Imprime la variable ''' print(self.simbolo + ', ' + str(self.nombre) + ', ' + self.lstunidades) class Variable(): '''Clase para definir las variable mediante sus atributos''' def __init__(self, simbolo, nombre, valor, unidad): '''simbolo, símbolo asigndo a la variable nombre, identificador de la variable valor, valor asignado a la variable unidad, unidad de medida de la variable ''' self.simbolo = simbolo self.nombre = nombre self.valor = valor self.unidad = unidad def print_var(self): ''' Imprime la variable ''' print(self.simbolo + ' = ' + str(self.valor) + ' [' + self.unidad + ']') class Enunciado(): '''Clase para definir las variable mediante sus atributos''' def __init__(self, enunciado, modelo, lstvarindep, lstvardep, ref, pag, nro): '''simbolo, símbolo asigndo a la variable nombre, identificador de la variable valor, valor asignado a la variable unidad, unidad de medida de la variable ''' self.enunciado = enunciado self.modelo = modelo self.lstvarindep = lstvarindep self.lstvardep = lstvardep self.ref = ref self.pag = pag self.nro = nro def print_enunc(self): ''' Imprime la variable ''' print(self.enunciado + ', ' + str(self.modelo) + ', ' + self.lstvarindep + ', ' + ', ' + self.lstvardep + ', ' + str(self.ref) + ', ' + str(self.pag) + ', ' + str(self.nro)) if __name__ == '__main__': simb = 'vi' nomb = 'Velocidad Inicial' val = 20 unid = 'm/s' vi = Variable(simb, nomb, val, unid) vi.print_var() simb = 'd' nomb = 'distancia' unid = '[m, pie, pulg, km, milla, yarda]' un = Unidad(simb, nomb, unid) un.print_unid() enunciado = 'Un automóvil mantiene una aceleración constante de 8 m/s2. Si su velocidad inicial era de 20 m/s al norte, cuál será su velocidad después de 6 s?' modelo = 'distancia' varindep = '[m, pie, pulg, km, milla, yarda]' vardep = '[m, pie, pulg, km, milla, yarda]' ref = 1 pag = 1 nro = 1 enunc = Enunciado(enunciado, modelo, varindep, vardep, ref, pag, nro) enunc.print_enunc()
ae3f8bfde79ae460511901e3f0153f455afeaf3d
Johnny112F/currency_calculator
/currency.py
857
3.703125
4
"""Functions handling currency.""" from forex_python.converter import CurrencyCodes, CurrencyRates, RatesNotAvailableError rates = CurrencyRates() codes = CurrencyCodes() def check_currency_code(code): """Is currency code valid? >>> check_currency_code("USD") True >>> check_currency_code("FOOBAR") False """ return codes.get_currency_name(code) is not None def convert_to_pretty(code_from, code_to, amt): """Convert amt between currencies & return pretty result. >>> convert_to_pretty('USD', 'USD', 1) '$ 1.0' >>> convert_to_pretty('USD', 'USD', 1.22) '$ 1.22' """ try: amt = f"{rates.convert(code_from, code_to, amt):.2f}" except RatesNotAvailableError: return None symbol = codes.get_symbol(code_to) return f"{symbol} {amt}"
b4d3eefb5b74f789a3ae7d99bfd52dff64efb996
iamkarantalwar/tkinter
/mysqlwithpython(insert)/insertwithmysql(var).py
759
3.78125
4
#insert data with variables name = input("Enter the name") email = input("Enter the Email") password = input("Enter the password") dob = input("Enter the D.O.B.") #import the MySql Api import mysql.connector #create a bridge between mysql and python #create the connection mydb = mysql.connector.connect( user="root", passwd = "", host = "localhost", database = "first_database", ) #make a cursor cursor = mydb.cursor() cursor.execute("""INSERT INTO `users`(`name`, `email`, `password`, `dob`) VALUES (%s,%s,%s,%s)""",(name,email,password,dob)) #if you use insert query then it's important to commit the command #if you send the data from python to mysql you will use commit mydb.commit()
b29b3de7434393fca62ea01898df1015e7a8871f
iamkarantalwar/tkinter
/GUI Sixth/canvas.py
1,080
4.21875
4
#tkinter program to make screen a the center of window from tkinter import * class Main: def __init__(self): self.tk = Tk() #these are the window height and width height = self.tk.winfo_screenheight() width = self.tk.winfo_screenwidth() #we find out the center co ordinates y = (height - 600)//2 x = (width - 600)//2 #place the window at the center co ordinate self.tk.geometry('600x600+'+str(x)+'+'+str(y)+'') #these lines of code are for placing picture as background self.can = Canvas(self.tk,height=600,width=600,bg="red") self.can.pack() self.img = PhotoImage(file='./images/obama.gif') self.can.create_image(0,0,image=self.img,anchor=NW) self.fr = Frame(self.tk,height=200,width=200) #we make resizable false to restrict user from resizing the window self.fr.place(x=200,y=200) self.tk.resizable(height=False,width=False) self.tk.mainloop() d = Main()
443c3d560be29b11764ec609751c86d8fa9eb130
ValenVictorious/Slot-Saving-Test
/main.py
1,061
3.609375
4
import stuff import trace_goto loop = 1 name = input("Name? ") content = input("content? ") place = input("place? ") while(loop < 2): Next = input("next? ") if Next == "commands": print("""commands: New Save: Create a new save Veiw Save: Veiw saves end: end the program""") if name != "" and content != "" and place != "": stuff.assignStuff(name, content, place) Next = input("next? ") if Next == "veiw save": veiwplace = input("which file? ") stuff.getStuff(veiwplace) Next = input("next? ") if Next == "new save": name = input("name? ") content = input("content? ") place = input("place? ") if name != "" and content != "" and place != "": stuff.assignStuff(name,content,place) Next = input("next? ") if Next == "end": loop = 2 print("""ended to continue type "continue" to end type "terminate" """) Next = input("next? ") if Next == "continue" and loop == 2: loop = 1 trace_goto.goto(7) if Next == "terminate" and loop == 2: print("termenated", end="-" )
55abeaf992065b49348262fd31cc660a1f68c3ea
Blaine-Rob5000/STECH-Capstone
/whiteboard.py
7,617
4.34375
4
"""Whiteboard projects Potential whiteboard project questions created by: R. G. Blaine on: April, 9, 2018 """ # imports import random ################################################################################ def listFibs(n): '''Creates and prints a list of the first n fibonacci numbers. arguments: n : integer 2 or greater returns: none ''' # variables fibNums = [] # list to hold the fibonacci numbers fibNums.append(0) # the 1st fibonacci number fibNums.append(1) # the 2nd fibonacci number # error handling if (n < 2) or (n != int(n)): print("\n\n\n !!! Argument must be an integer 2 or greater !!! \n\n\n") return # adds the next (n - 2) fibonacci numbers to the list for i in range(n - 2): fibNums.append(fibNums[i] + fibNums[i + 1]) # formats and prints the list printIntList(fibNums) # spacer print() return ################################################################################ def listPrimes(n): '''Creates and prints a list of the first n prime numbers. arguments: n : integer 1 or greater returns: none ''' # variables primeNums = [] # list to hold the prime numbers primeNums.append(2) # the 1st prime number num = 3 # the 2nd prime number # error handling if (n < 1) or (n != int(n)): print("\n\n\n !!! Argument must be an integer 1 or greater !!! \n\n\n") return # add prime numbers to the list until it of length n while len(primeNums) < n: isPrime = True # flag to see if the number is prime # loop through all possible divisors up to num/2 for i in range(2, num // 2 + 1): # if the number divides evenly flag it as not prime if (num/i) == int(num/i): isPrime = False # if the number is prime, append it to the list if isPrime: primeNums.append(num) # increment the number to check num += 1 # format and print the list printIntList(primeNums) # spacer print() return ################################################################################ def makeDeck(): '''Create and return an unsorted deck of cards and return it as a list. arguments: none returns: unsorted list of cards (strings) ''' # variables columnWidth = 20 # width of the columns numColumns = 4 # number of columns deck = [] # list to hold the deck # creat deck for suit in ('Clubs', 'Diamonds', 'Hearts', 'Spades'): for faceValue in ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'): deck.append(faceValue + ' of ' + suit) # print deck printDeck(deck) # spacer print() # return deck return deck ################################################################################ def shuffleDeck(deck): '''Shuffle and print a deck of cards. arguments: deck : an unsorted list of cards (strings) returns: none ''' # variables columnWidth = 19 # width of the coloumns numColumns = 4 # number of columns shuffledDeck = [] # list to hold the deck # shuffle deck for i in range(52): shuffledDeck.append(deck.pop(random.randint(0, 51 - i))) # print deck printDeck(shuffledDeck) # spacer print() return ################################################################################ def printDeck(deck): '''Prints the submitted list representing a deck cards arguments: deck : a list of strings representing a deck of 52 cards returns: none ''' # error handling if len(deck) != 52: print("\n\n\n !!! Illegal deck! Must be 52 elements !!!\n\n\n") return # print the deck for faceIndex in range(13): for suitIndex in range(4): cardIndex = faceIndex + suitIndex * 13 print(" " * (19 - len(deck[cardIndex])), end = "") print(deck[cardIndex], end = "") print() return ################################################################################ def bubbleSort(listSize): '''Creates a list of random integers then sorts, reverses, and re-sorts it. arguments: listSize: integer (2 or greater) returns: none ''' # define variables numList = [] # the list # error handling if (listSize < 2) or (listSize != int(listSize)): print("\n\n\n !!! Argument must be integer of value 2+ !!!\n\n\n") # create the random list for n in range(listSize): numList.append(random.randint(100, 999)) print("Random list:", numList) # bubble sort n = len(numList) - 1 # maximum number of passes for p in range(n): # pass counter exchange = False # exchange flag for i in range(n - p): # list index # exchange elements if the 1st one is larger if numList[i] > numList[i + 1]: numList[i], numList[i + 1] = numList[i + 1], numList[i] exchange = True # flag that an exchange was made print(" Pass #" + str(p + 1) + ":", numList) # end sort if no exchanges were made if not exchange: break # built-in Python sort numList.sort(reverse = True) print(" Reversed:", numList) numList.sort() print(" Re-sorted:", numList) print("2nd largest:", numList[-2]) return ################################################################################ def printIntList(intList): '''Formats and prints a list of integers. arguments: intList : a list of integers ''' # variables columnWidth = len(("{:,}".format(intList[-1]))) + 2 # column width screenWidth = 80 # screen width numColumns = screenWidth // columnWidth # number of columns # ensure that the number of columns is at least 1 if numColumns < 1: numColumns = 1 # print list count = 1 # counter to track when to end a line # go through the list for n in intList: # error checking if n != int(n): print("\n\n\n !!! List must contain only integers !!! \n\n\n") return # print column x = ("{:,}".format(n)) print(" " * (columnWidth - len(x)), end = "") print(x, end = "") # go to next line once the appropriate number of columns have printed if (count % numColumns) == 0: print() # increment the count count += 1 return ################################################################################ # run the functions print("Fibonacci numbers:") listFibs(50) print("\nPrime numbers:") listPrimes(330) print("\n\nNew deck:") newDeck = makeDeck() print("\nShuffled deck:") shuffleDeck(newDeck) print("\nBubble sort:") bubbleSort(10)
a8dadea942a0cc4859355eca917b86fe3d253e54
calanoue/GFIN_Data_Work
/formatting_forecasting_for_new_student_version.py
9,567
3.625
4
""" Formatting and forecasting script for new and final Python student version """ import numpy as np from scipy import stats from clean_data import CleanData, ExpSmooth from sqlite3 import dbapi2 as sqlite # Global variables VALUE_COLUMN = 5 # First column that holds values START_YEAR = 1961 # First year in the database END_YEAR = 2030 # Last year in the database NUM_FORECASTS = 7 # Number of forecast methods ID_SLICE = slice(0, VALUE_COLUMN) # Slice for where id columns are located X = np.arange(START_YEAR, END_YEAR + 1) # Valid years for database TABLE = "Datum" # Table to update in the database exp_smooth = ExpSmooth() # Exponential smoothing class # Connect to the database and create a cursor DB = r"C:\Users\calanoue\Dropbox\Dont Want to Lose\GFIN Random Python Work\demoGFIN\sqlite_student_db.db3" connection = sqlite.connect(DB) cursor = connection.cursor() # Get data from student database for formatting and forecasting - minus id column Q = "SELECT * FROM Datum WHERE element_id NOT BETWEEN 511 AND 703" datum_xs = np.ma.masked_equal(cursor.execute(Q).fetchall(), -1)[:, 1:] def forecast_from_trend_line(xs, yrs, forecast_yrs, forecast_periods, trend_function): """ Forecast data by using the specified trend function. Trend functions are the same functions offered in Excel for adding trend lines to a plot. """ if trend_function == 1: # Linear trend (y = ax + B) slope, intercept, _, _, _ = stats.linregress(yrs, xs) y = slope * forecast_yrs + intercept elif trend_function == 2: # 2nd degree Polynomial trend (p(x) = p[0] * x**2 + p[2]) z = np.polyfit(yrs, xs, 2) y = np.polyval(z, forecast_yrs) elif trend_function == 3: # 3rd degree Polynomial trend (p(x) = p[0] * x**3 + x**2 + p[3]) z = np.polyfit(yrs, xs, 3) y = np.polyval(z, forecast_yrs) elif trend_function == 4: # Logarithmic trend (y = A + B log x) slope, intercept, _, _, _ = stats.linregress(np.log(yrs), xs) y = intercept + slope * np.log(forecast_yrs) elif trend_function == 5: # Exponential trend (y = Ae^(Bx)) slope, intercept, _, _, _ = stats.linregress(yrs, np.log(xs)) y = np.exp(intercept) * np.exp(slope * forecast_yrs) elif trend_function == 6: # Power function trend (y = Ax^B) slope, intercept, _, _, _ = stats.linregress(np.log(yrs), np.log(xs)) y = np.exp(intercept) * np.power(forecast_yrs, slope) elif trend_function == 7: # Exponential smoothing with a dampened trend xs_fit_opt = exp_smooth.calc_variable_arrays(.98, xs, forecast_periods) y = exp_smooth.exp_smooth_forecast(xs_fit_opt, True)[-forecast_periods:] else: # Consumption forecasting with elasticity and income y = 8 # Mask any negative, zero, infinity, or n/a values before returning y = np.ma.masked_less_equal(y, 0) y = np.ma.fix_invalid(y) return y # Format all rows new_datum_xs = np.ma.masked_all(datum_xs.shape, np.float) count = 0 for row in datum_xs: try: start, stop = np.ma.flatnotmasked_edges(row[VALUE_COLUMN:][np.newaxis, :]) values = CleanData(row[VALUE_COLUMN:stop + VALUE_COLUMN + 1][np.newaxis, :], X) xs = np.ma.hstack((values.get_return_values().flatten(), np.ma.masked_all(X.shape[0] - stop - 1))) except TypeError: # Some GDP rows do not have any values, therefore remove them xs = np.ma.array([0]) if np.ma.sum(xs): new_datum_xs[count] = np.ma.hstack((row[ID_SLICE], xs)) count += 1 # Resize the array to remove blank rows of data new_datum_xs = np.ma.resize(new_datum_xs, (count, new_datum_xs.shape[1])) # Append population and population net change arrays to the formatted and forecasted datum table count = 0 Q = "SELECT * FROM Datum WHERE element_id BETWEEN 511 AND 703" pop_xs = np.ma.masked_equal(cursor.execute(Q).fetchall(), -1)[:, 1:] pop_xs = np.ma.filled(np.ma.column_stack( (np.ma.arange( count, pop_xs.shape[0] ), pop_xs[:, ID_SLICE], np.ma.masked_all((pop_xs.shape[0], 1)), pop_xs[:, VALUE_COLUMN:]) ), -1) count += pop_xs.shape[0] # Add new column in the datum table for forecasting method values when adding the new trend data Q = """ DROP TABLE Datum; CREATE TABLE %s (id INTEGER PRIMARY KEY AUTOINCREMENT,country_id INTEGER REFERENCES Country, item_id INTEGER REFERENCES Item,element_id INTEGER REFERENCES Element,unit_id INTEGER REFERENCES Unit, source_id INTEGER REFERENCES Source,forecast_id INTEGER REFERENCES Forecast, yr1961 FLOAT,yr1962 FLOAT,yr1963 FLOAT, yr1964 FLOAT,yr1965 FLOAT,yr1966 FLOAT,yr1967 FLOAT,yr1968 FLOAT,yr1969 FLOAT,yr1970 FLOAT,yr1971 FLOAT,yr1972 FLOAT, yr1973 FLOAT,yr1974 FLOAT,yr1975 FLOAT,yr1976 FLOAT,yr1977 FLOAT,yr1978 FLOAT,yr1979 FLOAT,yr1980 FLOAT,yr1981 FLOAT, yr1982 FLOAT,yr1983 FLOAT,yr1984 FLOAT,yr1985 FLOAT,yr1986 FLOAT,yr1987 FLOAT,yr1988 FLOAT,yr1989 FLOAT,yr1990 FLOAT, yr1991 FLOAT,yr1992 FLOAT,yr1993 FLOAT,yr1994 FLOAT,yr1995 FLOAT,yr1996 FLOAT,yr1997 FLOAT,yr1998 FLOAT,yr1999 FLOAT, yr2000 FLOAT,yr2001 FLOAT,yr2002 FLOAT,yr2003 FLOAT,yr2004 FLOAT,yr2005 FLOAT,yr2006 FLOAT,yr2007 FLOAT,yr2008 FLOAT, yr2009 FLOAT,yr2010 FLOAT,yr2011 FLOAT,yr2012 FLOAT,yr2013 FLOAT,yr2014 FLOAT,yr2015 FLOAT,yr2016 FLOAT,yr2017 FLOAT, yr2018 FLOAT,yr2019 FLOAT,yr2020 FLOAT,yr2021 FLOAT,yr2022 FLOAT,yr2023 FLOAT,yr2024 FLOAT,yr2025 FLOAT,yr2026 FLOAT, yr2027 FLOAT,yr2028 FLOAT,yr2029 FLOAT,yr2030 FLOAT); """%TABLE cursor.executescript(Q) # Insert population data into Datum table cursor.executemany( "INSERT INTO %s VALUES(%s)"%(TABLE, ','.join('?' for _ in xrange(pop_xs.shape[1]))), pop_xs ) connection.commit() # Extract the value and the id data from the returned query values = new_datum_xs[:, VALUE_COLUMN:] ids = new_datum_xs[:, ID_SLICE] # Go through each row of remaining data - except population - and forecast using trend line methods above # Add a new column at the end of ids to keep track of the forecasting trend method N = new_datum_xs.shape[0] for forecast_method in xrange(1, NUM_FORECASTS + 1): trend_datum_xs = np.ma.masked_all((N, new_datum_xs.shape[1] + 1), np.float) for enum, value_row in enumerate(values): xs = value_row[~value_row.mask] yrs = X[~value_row.mask] forecast_yrs = np.arange(np.max(yrs) + 1, END_YEAR + 1) forecast_periods = forecast_yrs.shape[0] # Forecast one method at a time trend_xs = forecast_from_trend_line(xs, yrs, forecast_yrs, forecast_periods, forecast_method) # Add masked values to the start if minimum starting year is greater than the first year trend_datum_xs[enum] = np.ma.hstack( (ids[enum], forecast_method, np.ma.masked_all(np.min(yrs) - START_YEAR), xs, trend_xs) ) # Sort on index columns - forecast, element, item, country dtype = ",".join('<f8' for _ in xrange(trend_datum_xs.shape[1])) trend_datum_xs = np.ma.sort(trend_datum_xs.view(dtype), order=['f5', 'f2', 'f1', 'f0'], axis=0).view(np.float) # Add in a primary key field trend_datum_xs = np.ma.column_stack((np.ma.arange(count, count + N), trend_datum_xs)) # Change missing values to -1 for storage in database trend_datum_xs = np.ma.filled(trend_datum_xs, -1) # Insert forecasted data into Datum table cursor.executemany( "INSERT INTO %s VALUES(%s)"%(TABLE, ','.join('?' for _ in xrange(trend_datum_xs.shape[1]))), trend_datum_xs ) connection.commit() # Increase count of records for primary key index count += N # Add index to Datum table cursor.execute("CREATE INDEX %s_index ON %s (forecast_id, element_id, item_id, country_id)"%(TABLE, TABLE)) connection.commit() def forecast_xs_consumption(formatted_xs, id_xs, country_id_index): """ Forecast consumption values from income and elasticity. """ xs = formatted_xs if not np.any(self.income_xs): # Get unique country ids from consumption values for income country_ids = np.unique(id_xs[:, country_id_index]) # Retrieve and format income data self.income_xs = np.ma.masked_equal( self.cursor[self.c_cycle.next()].execute(self.sql.left_query_income(country_ids)).fetchall(), -1 ) income_x, income_x_formats = self.format_xs(self.income_xs[:, 6:]) # Forecast income data using a linear regression # TODO - change to exp smooth forecast here income_edges = np.transpose(np.ma.notmasked_edges(income_x, axis=1)) for i, row in enumerate(income_x): start, stop = income_edges[i, 1, :] slope, intercept, r_value, p_value, std_err = stats.linregress(X[:stop + 1], row[:stop + 1]) forecasts = intercept + X[stop + 1:] * slope self.income_xs[i, 6:] = np.hstack((row[:stop + 1], forecasts)) # Forecast consumption values using forecasted income and elasticity values consumption_edges = np.transpose(np.ma.notmasked_edges(xs, axis=1)) for i, idx in enumerate(consumption_edges[:, 0, 0]): start, stop = consumption_edges[i, 1, :] country_id = id_xs[idx, country_id_index] # Attempt to find the income that goes with the specified and if not found return the original masked xs try: income_row = self.income_xs[np.where(self.income_xs[:, 1] == country_id)[0]].flatten()[6:] xs[idx] = self.misc_forecast.cons_forecast(xs[idx], income_row, TMP_ELASTICITY, stop) except IndexError: pass return xs # Close the cursor and the connection cursor.close() connection.close()
e4680806f90440a2ad2474ae38e3c2d683e47379
calanoue/GFIN_Data_Work
/merge_countries.py
1,418
3.703125
4
""" Merge a country that has two separate former entities, i.e. Russia and the 'Slavias. """ import numpy as np import sqlite_io import numpy.lib.recfunctions as nprf #Global variables DB = r".\FBS_ProdSTAT_PriceSTAT_TradeSTAT.db3" TABLE_NAME = "Commodity_Raw_Data" #Countries to merge with country one being the country to stay in the database country_one = 185 country_two = 228 country_name = "Russian_Federation" #table_name #Query to merge the rows of the two countries query = """ SELECT country_id, item_id, element_id, unit_id, source_id, %s FROM %%s WHERE country_id=%s OR country_id=%s GROUP BY item_id||element_id||source_id """%(",".join("SUM(yr%s) AS yr%s"%(x, x) for x in xrange(1961, 2011)), country_one, country_two) #Run query through sqlite_io file, creating a temporary table and then dropping when complete xs = sqlite_io.fromsqlite(DB, query%TABLE_NAME, "tmp") print xs[xs['item_id']==1012] exit() #Extract out merged data for country remaining in the database xs_merged = xs[xs['country_id']==country_one] #Create a new table in the database for this new merged country count = 0 foreign_keys = {'country_id':'Country', 'element_id':'Element', 'unit_id':'Unit', 'source_id':'Source'} index = ['source_id', 'element_id', 'item_id', 'country_id'] #index in order sqlite_io.tosqlite(xs_merged, count, DB, country_name, autoid=True, foreign_keys=foreign_keys, index=index)
6b0c82e66ebe574a537a970c217c73c26583fa15
RohinPoloju/HackerRank
/InterviewPrep/strings/sherlock-and-valid-string.py
1,315
3.890625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'isValid' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def isValid(s): # Write your code here char_dict = {} for char in s: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 min_count = char_dict[char] max_count = char_dict[char] count_dict = {} for char, value in char_dict.items(): if value in count_dict: count_dict[value] += 1 else: count_dict[value] = 1 #also update max and min count if value < min_count: min_count = value if value > max_count: max_count = value print(min_count, max_count) if len(count_dict) == 1: return 'YES' elif len(count_dict) == 2: if count_dict[max_count] == 1 and max_count - min_count == 1: return 'YES' elif count_dict[min_count] == 1 and min_count == 1: return 'YES' return 'NO' if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = isValid(s) fptr.write(result + '\n') fptr.close()
481bd030ef8e07991471f21de973ad7e9d237579
kevinam99/ML-internship-training
/ML-internship-training-earnestek/python/02-lists.py
554
3.984375
4
list1 = [2,4,5,6,72,17,54,1,3,2,2,44] print(list1[2]) print(list1[1:3]) print(list1[:3]) print(list1[3:]) print(list1[-1]) print(len(list1)) list1.append(69) print (list1) list1.extend([3,4]) ''' list1.extend('yes')#stores as 'y', 'e', 's' print (list1) list1.extend(['yes'])#stores as 'yes' print (list1) list1.extend(["yes"]) print (list1) ''' list1.insert(1,55)#(index, element) print(list1) print(list1.index(72))#value to be located, value MUST EXIST in the list print(list1.index(2)) del (list1[5]) print(list1) list1.sort() print(list1)
46ce3a2346198c0fca61a05d6c0dfe821f336170
niha-p/Natural-Language-Processing
/Basic NLTK (Word Similarity)/A.py
431
3.75
4
import nltk import sys greeting=sys.stdin.read() print greeting token_list = nltk.word_tokenize(greeting) print "The tokens in the greeting are" for token in token_list: print token squirrel=0 girl=0 for token in token_list: str=token.lower() if (str=='squirrel'): squirrel+=1 if (str=='girl'): girl+=1 print "There were %d instances of the word 'squirrel' and %d instances of the word 'girl.'"% (squirrel, girl)
901330d060d7f2b458b05e04ee1eb4ee979146f9
jaybenaim/python-intro-pt5
/test.py
266
3.921875
4
def pizza_maker(): print('How many pizzas do you want to order?') quantity_pizza = int(input()) # order_num = toppings.pizza_order_num() # toppings.pizza_order_num ind_pizza = range(1,(quantity_pizza+1)) print(ind_pizza) print(pizza_maker())
4f3a617844b5bce95b1a37c10c86b20fa75c4e1e
yangzhao5566/go_study
/cookbook/第八章/8.4.py
696
4.0625
4
""" 创建大量对象时节省内存方法 """ class Date: __slots__ = ["year", "month", "day"] def __init__(self, year, month, day): self.year = year self.month = month self.day = day """ 当你定义__slots__ 后,Python就会为实例使用一种更加紧凑的内部表示。 实例通过一个很小 的固定大小的数组来构建,而不是为每个实例定义一个字典,这跟元组或列表很类似。 在 __slots__ 中列出的属性名在内部被映射到这个数组的指定小标上。 使用slots一个不好的地方就是我们不能再给 实例添加新的属性了,只能使用在 __slots__ 中定义的那些属性名。 """
f687a3b60aade360831f0a559bac2fc622194ba0
yangzhao5566/go_study
/cookbook/第八章/8.5.py
2,930
3.609375
4
""" 关于类的私有方法和私有属性 """ """ _xx 以单下划线开头的表示的是proected类型的变量。 即保护类型只能允许其本身和子类进行访问 __xx双下划线表示的是私有类型的变量,只能允许这个类本身进行访问,子类也不可以用于命名一个 类属性(类变量),调用时名字被改变(在类FooBar内部,__boo变成_FooBar__boo,如self._FooBar__boo) """ import math class Pub(object): _name = "protected 类型的变量" __info = "私有类型的变量" def _func(self): print("这是一个protected类型的方法") def __func2(self): print("这是一个私有类型的方法") def get(self): return self.__info ##################创建可管理的属性################## class Person(object): def __init__(self, first_name): self._first_name = first_name @property def first_name(self): return self._first_name @first_name.setter def first_name(self, value): if not isinstance(value, str): raise TypeError("Expected a string") self._first_name = value @first_name.deleter def first_name(self): raise AttributeError("Can't delete attribute") """ 不要写下边这种没有做任何其他额外操作的property """ class Persons: def __init__(self, first_name): self.first_name = first_name @property def first_name(self): return self._first_name @first_name.setter def first_name(self, value): self._first_name = value class Circle(object): def __init__(self, radius): self.radius = radius @property def area(self): return math.pi * self.radius ** 2 @property def diameter(self): return self.radius * 2 @property def perimeter(self): return 2 * math.pi * self.radius class A(object): def spam(self): print("A.spam") class B(A): def spam(self): print("B.spam") super().spam() class Proxy(object): def __init__(self, obj): self._obj = obj def __getattr__(self, name): return getattr(self._obj, name) def __setattr__(self, name, value): if name.startswith("_"): super().__setattr__(name, value) else: setattr(self._obj, name, value) ############## 对于继承的property 的修改如下################ class SubPerson(Person): @Person.first_name.getter def first_name(self): print('Getting name') return super().first_name """ 在子类中扩展一个property可能会引起很多不易察觉的问题, 因为一个property其实是 getter、 setter 和 deleter 方法的集合,而不是单个方法。 因此,当你扩展一个property的时候, 你需要先确定你是否要重新定义所有的方法还是说只修改其中某一个。 """
15a9da7261655dd9e4c5a64aa19467f0a3cba3c7
JagritiG/Data-Visualization-vol2
/matplotlib/scatter/scatter.py
2,821
3.609375
4
# Scatter plot using Iris dataset import pandas as pd import matplotlib.pyplot as plt font_param = {'size': 12, 'fontweight': 'semibold', 'family': 'serif', 'style': 'normal'} # Prepare data for plotting # load iris dataset from file in Pandas Dataframe col_names = ['Sepal_length', 'Sepal_width', 'Petal_length', 'Petal_width', 'Species'] iris = pd.read_csv('iris.csv', names=col_names) # Print first 5 and last 5 rows from DataFrame to check if data is correctly loaded print(iris.head()) print(iris.tail()) # Find out unique class of iris flower print(iris['Species'].unique()) # Find out no of rows for each Species print(iris.groupby('Species').size()) # Create 3 DataFrame for each Species setosa = iris[iris['Species'] == 'Iris-setosa'] versicolor = iris[iris['Species'] == 'Iris-versicolor'] virginica = iris[iris['Species'] == 'Iris-virginica'] print(setosa.describe()) print(versicolor.describe()) print(virginica.describe()) print(iris.describe()) # Plotting Petal length vs Petal width and Sepal length vs Sepal width fig, ax = plt.subplots(1, 2, figsize=(10, 5)) iris.plot(x="Sepal_length", y="Sepal_width", kind="scatter",ax=ax[0], label="Sepal", color='b') iris.plot(x="Petal_length", y="Petal_width", kind="scatter",ax=ax[1], label="Petal", color='g',) ax[0].set_title('Sepal Comparison', font_param) ax[1].set_title('Petal Comparison', font_param) ax[0].legend() ax[1].legend() plt.tight_layout() plt.savefig('scatter_plot.pdf') # For each Species ,let's check what is petal and sepal distribution fig, ax = plt.subplots(1,2,figsize=(10, 5)) setosa.plot(x="Sepal_length", y="Sepal_width", kind="scatter", ax=ax[0], label='setosa', color='r') versicolor.plot(x="Sepal_length", y="Sepal_width", kind="scatter",ax=ax[0], label='versicolor', color='b') virginica.plot(x="Sepal_length", y="Sepal_width", kind="scatter", ax=ax[0], label='virginica', color='g') setosa.plot(x="Petal_length", y="Petal_width", kind="scatter",ax=ax[1], label='setosa',color='r') versicolor.plot(x="Petal_length", y="Petal_width", kind="scatter", ax=ax[1], label='versicolor', color='b') virginica.plot(x="Petal_length", y="Petal_width", kind="scatter", ax=ax[1], label='virginica', color='g') ax[0].set_title('Sepal Comparison', font_param) ax[1].set_title('Petal Comparison', font_param) ax[0].legend() ax[1].legend() plt.tight_layout() plt.savefig('petal_and_sepal_distibutuon_for_each_species.pdf') plt.show() # Observation: # Satosa - satosa Petal are relatively smaller than rest of species. # satosa petal < versicolor petal < virginica petal # Satosa sepal are smallest in length and largest in Width than other species
9fbb5b1f048534d10c2175b8033216fe457133fe
spitis/stable-baselines
/stable_baselines/common/math_util.py
5,382
3.625
4
import numpy as np import scipy.signal def discount(vector, gamma): """ computes discounted sums along 0th dimension of vector x. y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k], where k = len(x) - t - 1 :param vector: (np.ndarray) the input vector :param gamma: (float) the discount value :return: (np.ndarray) the output vector """ assert vector.ndim >= 1 return scipy.signal.lfilter([1], [1, -gamma], vector[::-1], axis=0)[::-1] def explained_variance(y_pred, y_true): """ Computes fraction of variance that ypred explains about y. Returns 1 - Var[y-ypred] / Var[y] interpretation: ev=0 => might as well have predicted zero ev=1 => perfect prediction ev<0 => worse than just predicting zero :param y_pred: (np.ndarray) the prediction :param y_true: (np.ndarray) the expected value :return: (float) explained variance of ypred and y """ assert y_true.ndim == 1 and y_pred.ndim == 1 var_y = np.var(y_true) return np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y def explained_variance_2d(y_pred, y_true): """ Computes fraction of variance that ypred explains about y, for 2D arrays. Returns 1 - Var[y-ypred] / Var[y] interpretation: ev=0 => might as well have predicted zero ev=1 => perfect prediction ev<0 => worse than just predicting zero :param y_pred: (np.ndarray) the prediction :param y_true: (np.ndarray) the expected value :return: (float) explained variance of ypred and y """ assert y_true.ndim == 2 and y_pred.ndim == 2 var_y = np.var(y_true, axis=0) explained_var = 1 - np.var(y_true - y_pred) / var_y explained_var[var_y < 1e-10] = 0 return explained_var def flatten_arrays(arrs): """ flattens a list of arrays down to 1D :param arrs: ([np.ndarray]) arrays :return: (np.ndarray) 1D flattend array """ return np.concatenate([arr.flat for arr in arrs]) def unflatten_vector(vec, shapes): """ reshape a flattened array :param vec: (np.ndarray) 1D arrays :param shapes: (tuple) :return: ([np.ndarray]) reshaped array """ i = 0 arrs = [] for shape in shapes: size = np.prod(shape) arr = vec[i:i + size].reshape(shape) arrs.append(arr) i += size return arrs def discount_with_boundaries(rewards, episode_starts, gamma): """ computes discounted sums along 0th dimension of x (reward), while taking into account the start of each episode. y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k], where k = len(x) - t - 1 :param rewards: (np.ndarray) the input vector (rewards) :param episode_starts: (np.ndarray) 2d array of bools, indicating when a new episode has started :param gamma: (float) the discount factor :return: (np.ndarray) the output vector (discounted rewards) """ discounted_rewards = np.zeros_like(rewards) n_samples = rewards.shape[0] discounted_rewards[n_samples - 1] = rewards[n_samples - 1] for step in range(n_samples - 2, -1, -1): discounted_rewards[step] = rewards[step] + gamma * discounted_rewards[step + 1] * (1 - episode_starts[step + 1]) return discounted_rewards def conjugate_gradient(f_ax, b_vec, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10): """ conjugate gradient calculation (Ax = b), bases on https://epubs.siam.org/doi/book/10.1137/1.9781611971446 Demmel p 312 :param f_ax: (function) The function describing the Matrix A dot the vector x (x being the input parameter of the function) :param b_vec: (numpy float) vector b, where Ax = b :param cg_iters: (int) the maximum number of iterations for converging :param callback: (function) callback the values of x while converging :param verbose: (bool) print extra information :param residual_tol: (float) the break point if the residual is below this value :return: (numpy float) vector x, where Ax = b """ first_basis_vect = b_vec.copy() # the first basis vector residual = b_vec.copy() # the residual x_var = np.zeros_like(b_vec) # vector x, where Ax = b residual_dot_residual = residual.dot(residual) # L2 norm of the residual fmt_str = "%10i %10.3g %10.3g" title_str = "%10s %10s %10s" if verbose: print(title_str % ("iter", "residual norm", "soln norm")) for i in range(cg_iters): if callback is not None: callback(x_var) if verbose: print(fmt_str % (i, residual_dot_residual, np.linalg.norm(x_var))) z_var = f_ax(first_basis_vect) v_var = residual_dot_residual / first_basis_vect.dot(z_var) x_var += v_var * first_basis_vect residual -= v_var * z_var new_residual_dot_residual = residual.dot(residual) mu_val = new_residual_dot_residual / residual_dot_residual first_basis_vect = residual + mu_val * first_basis_vect residual_dot_residual = new_residual_dot_residual if residual_dot_residual < residual_tol: break if callback is not None: callback(x_var) if verbose: print(fmt_str % (i + 1, residual_dot_residual, np.linalg.norm(x_var))) return x_var
db208265703bbdec3e4ed14b2987ae0ba068561d
jcuartas/MITx-6.00.1x
/Week2/polysum.py
464
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 11 12:18:09 2017 @author: jcuartas - Juan Manuel Cuartas Bernal Inputs n integer s integer Output polysum float """ from math import * def polysum(n, s): # Calculate area of the polygon area = (0.25*n*s**2)/(tan(pi/n)) # Calculate perimeter perimeter = n * s # Polysum is the sum of the area plus squared perimeter return round(area + perimeter**2, 4)
be32419b60e322bf07b7fae724bf67aedddf2610
jcuartas/MITx-6.00.1x
/Midterm Exam/largestOddTimes.py
840
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 2 04:02:34 2017 @author: jcuartas """ def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ # Your code here LCount = {} largestKey = None count = 0 for i in L: count = L.count(i) if count%2 == 1: LCount[i] = count for key, value in LCount.items(): if largestKey == None or largestKey < key: largestKey = key return largestKey print(largest_odd_times([3,9,5,3,5,3])) print(largest_odd_times([2, 2])) print(largest_odd_times([2, 2, 4, 4])) print(largest_odd_times([2, 4, 5, 4, 5, 4, 2, 2])) print(largest_odd_times([3, 2]))
931eb4a2c91cee8b70a4319af766dc7ce17b6ece
royakash2203/Python_Learning
/Day 1-10/sotc1 calculator.py
242
4.09375
4
n1=int(input("enter the 1st number:")) n2=int(input("enter the 2nd number:")) sign=input("enter the operation [+,-,*,/]:") if sign == "+":print(n1 + n2) elif sign == "-":print(n1-n2) elif sign == "*":print(n1*n2) elif sign == "/":print(n1/n2)
ffcb969a86f1bfde63159f3fe6913ebc50a4abcb
Kbman99/Python-FAU
/Assignment2/p2.py
1,002
3.75
4
def find_dup_str(s, n): for index in range(len(s)-n+1): temp_string = s[index:index+n] updated_string = s[index+n:] if updated_string.find(temp_string) != -1 and len(updated_string) != 0: return temp_string return "" program Find_Duplicate_String(s, n): for i from 0 to len(s) - 1: temp_s = s substring of length n starting at index i updated_s = s substring of length n starting at index n + i if updated_s contains any substring which matches temp_s: return temp def find_max_dups(s): if len(s) > 1: for i in range(len(s)): if find_dup_str(s, i) != "": longest_dup = find_dup_str(s, i) return longest_dup else: return "" while True: base_string = input("Enter a string to search through: ") substring_length = int(input("Enter a substring length: ")) print(find_dup_str(base_string, substring_length)) print(find_max_dups(base_string))
fc7297411e304306ef379e18475ad8353436e889
Kbman99/Python-FAU
/Assignment2/p3.py
1,351
3.5625
4
import pylab import math def compute_interval(min, max, number_of_samples): while max > min: sample_points = [] interval_separation = float((max - min)/number_of_samples) for i in range(number_of_samples): sample_points.append(round(max - i*interval_separation, 4)) return sample_points print("The maximum value must be larger than the minimum value!") def evaluate_func(sample_points, function): while sample_points: func_values = [] for x in sample_points: y = eval(function) func_values.append(round(y, 4)) return func_values def setup_table_and_graph(): print(" x y") print("-----------------------------") for i in range(ns): print(" {: 9.4f} {: 9.4f}".format(xs[i], ys[i])) pylab.xlabel("x") pylab.ylabel("y") pylab.title(fun_str) pylab.plot(xs, ys, '-bo') pylab.grid() pylab.show() while True: fun_str = input("Pleas enter a function using x as the variable: ") x_min = float(input("Enter a Minimum value for x: ")) x_max = float(input("Enter a Maximum value for x: ")) ns = int(input("How many samples would you like to use: ")) xs = compute_interval(x_min, x_max, ns) ys = evaluate_func(xs, fun_str) setup_table_and_graph()
3acf680e3f9d80cd772d0e401d95e6a830d5123b
mishaZ-Lab/ooop
/Зверушка.Py
937
3.546875
4
class Critter: total = 0 @staticmethod def status(): print('Общее число зверюшек', Critter.total) def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom Critter.total += 1 def talk(self): print("Меня зовут",self.name ) def __str__(self): ans = 'Объект класа Critter\n' ans += 'имя:'+ self.name +'\n' return ans def main(): print('Доступ к атрибуту класа Critter.total:', end="") print(Critter.total) print("Создание зверюшек.") crit1 = Critter('Зверюшка 1') crit2 = Critter('Зверюшка 2') crit3 = Critter('Зверюшка 3') Critter.status() print("Доступ к атрибуту класа через объект:", end=" ") print(crit1.total) main()
e5f23cd93a4665b2ea3b9b67f472bb6793ab6959
ggconstante/ggconstante.github.io
/mrPython/hw5.py
5,828
4
4
# Name: Gingrefel G. Constante # Date: 02/28/2016 # Class: ISTA 350, Hw5 class Binary: ''' init has one string parameter with a default argument of '0'. This string can be the empty string (treat the same as '0'). Otherwise, it should consist only of 0’s and 1’s and should be 16 or less characters long. If the argument does not meet these requirements, raise a RuntimeError. Each Binary object has one instance variable, a list called num_list. num_list has integers 0 or 1 in the same order as the corresponding characters in the argument. If the string is less than 16 characters long, num_list should be padded by repeating the leftmost digit until the list has 16 elements. This is to be done by calling the next method. ''' def __init__(self, string_zero = '0'): # string_zero is a string of zeroes and ones if string_zero == '': # if string is empty string_zero = '0' # return a string of zeroes and ones self.num_list = list(string_zero) # lets turn a string_zero into a list since a list is mutable if string_zero: for number in string_zero: if number not in ['0','1', 0 , 1]: # if the user put in not one of these raise RuntimeError() # raise this if len(string_zero) > 16: # if the len which is an int is greater than 16 raise RuntimeError() # raise this for i in range(len(self.num_list)): # iterate through self.num_list self.num_list[i] = int(self.num_list[i]) # this is converting self.num_list into int if len(string_zero) < 16: # if length is less than 16 self.pad() # call the function pad() and 0's to the left ''' Pad num_list by repeating the leftmost digit until the list has 16 elements ''' def pad(self): while len(self.num_list) < 16: self.num_list.insert(0, self.num_list[0]) ''' repr: Return a 16-character string representing the fixed-width binary number, such as: '00000000000000000'. ''' def __repr__(self): return "".join(str(item) for item in self.num_list) ''' eq: Takes a Binary object as an argument. Return True if self == the argument, False otherwise. ''' def __eq__(self, other): if self.num_list == other.num_list: return True else: return False ''' add: Takes a Binary object as an argument. Return a new Binary instance that represents the sum of self and the argument. If the sum requires more than 16 digits, raise a RuntimeError. ''' def __add__(self, other_binary): result = [] carry = 0 for i in range(15, -1, -1): bit_sum = self.num_list[i] + other_binary.num_list[i] + carry result.insert(0, bit_sum % 2) carry = int(bit_sum > 1) if self.num_list[0] == other_binary.num_list[0] != result[0]: raise RuntimeError() return Binary(result) ''' neg: Return a new Binary instance that equals -self. ''' def __neg__(self): new_list = [] # make an empty list counter = '' for i in range(len(self.num_list)): # if self.num_list[i] == 1: # if the index [i] is an integer 1 new_list.append('0') # then we flip that 1 and append 0 to it or change 1 to 0. this is a string 0 else: new_list.append(str(1)) # append str 1 counter = ''.join(new_list) return Binary(counter) + Binary('01') # Binary() = 0, we do this to not change the Binary(counter) ''' sub: Takes a Binary object as an argument. Return a new Binary instance that represents self – the argument. ''' def __sub__(self, other): return self + (-other) ''' int: Return the decimal value of the Binary object. This method should never raise a RuntimeError due to overflow. Do not use int on Binary objects in any other method. You may use it to convert strings to integers, but not on Binary objects. ''' def __int__(self): dec_total = 0 # this is an int starting fresh cola at 0 subscript = 0 if self.num_list == [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]: # 2^15 = -32768, now we put negative because the leading binary digit is 1 return (-32768) if self.num_list[0] == 1: foobar = (-self) # this is like calling the neg() function for pos in foobar.num_list[::-1]: # let's go reverse fellas if pos == 1: # in this location is a string dec_total += 2** subscript subscript += 1 # incrementing subscript return (-dec_total) for pos in self.num_list[::-1]: # let's go reverse fellas if pos == 1: # in this location is a string dec_total += 2** subscript subscript += 1 return dec_total ''' lt: Takes a Binary object as an argument. Return True if self < the argument, False otherwise. This method should never raise a RuntimeError due to overflow. ''' def __lt__(self, other): if self.num_list[0] == 0 and other.num_list[0] == 1: return False elif self.num_list[0] == 1 and other.num_list[0] == 0: return True else: winnie = self + (-other) if winnie.num_list[0] == 1: # you are checking if it is negative means self is smaller 10-100 = -90 return True else: return False ''' abs: Return a new instance that is the absolute value of self. ''' def __abs__(self): if self.num_list[0] == 1: return (-self) else: return self + Binary()
cb3a8cdc35714d708f5e11c0b8fdeb45c8544e47
Rodrigocabral144/Projeto_Controle_tv
/aula7_televisao.py
1,371
4.03125
4
class Televisao: def __init__(self): self.ligada = False self.canal = 1 self.volume = 10 def power(self): if self.ligada: self.ligada = False else: self.ligada = True def aumenta_canal(self): if self.ligada: self.canal +=1 def diminui_canal(self): if self.ligada: self.canal -=1 def aumenta_volume(self): if self.ligada: self.volume += 1 def diminui_volume(self): if self.ligada: self.volume -= 5 if __name__ == '__main__': televiasao = Televisao() print("televisão está ligada = {}".format(televiasao.ligada)) televiasao.power() print("televisão está ligada = {}".format(televiasao.ligada)) televiasao.power() print("televisão está ligada = {}".format(televiasao.ligada)) print('canal :{}'.format(televiasao.canal)) televiasao.power() print("televisão está ligada = {}".format(televiasao.ligada)) televiasao.aumenta_canal() print("canal :{}".format(televiasao.canal)) televiasao.diminui_canal() print("canal :{}".format(televiasao.volume)) print("volume aumentado :{}" .format(televiasao.volume)) televiasao.aumenta_volume() televiasao.aumenta_volume() print("volume aumentado :{}" .format(televiasao.volume))
bd36a8a99fd2d3eae86da3fa0b115bd553f9a618
eidanjacob/advent-of-code
/2020/6.py
476
3.53125
4
s = 0 with open("./input.txt") as f: group = set() first = True for line in f: if line != "\n" and line != "": if first: first = False [group.add(c) for c in line if c != "\n"] else: newgroup = set([c for c in group if c in line]) group = newgroup else: first = True s += len(group) group = set() print(s + len(group))
fd9435912655021c274f70ae9220d7e55f750794
eidanjacob/advent-of-code
/2020/12.py
1,430
3.6875
4
actions = open("input.txt").readlines() turn = {"E" : { "L" : "N", "R" : "S"}, "N" : { "L" : "W", "R" : "E"}, "W" : { "L" : "S", "R" : "N"}, "S" : { "L" : "E", "R" : "W"}} current_direction = "E" current_x = 0 current_y = 0 for action in actions: a = action[0] m = int(action[1:]) if a == "F": a = current_direction if a == "E": current_x += m elif a == "W": current_x -= m elif a == "S": current_y -= m elif a == "N": current_y += m else: while m > 0: current_direction = turn[current_direction][a] m -= 90 print(abs(current_x)+abs(current_y)) def rotate_left(waypt): return -1 * waypt[1], waypt[0] def rotate_right(waypt): return waypt[1], -1 * waypt[0] ship_x = 0 ship_y = 0 waypt_x = 10 waypt_y = 1 for action in actions: a = action[0] m = int(action[1:]) if a == "N": waypt_y += m elif a == "S": waypt_y -= m elif a == "W": waypt_x -= m elif a == "E": waypt_x += m elif a == "L": while m > 0: waypt_x, waypt_y = rotate_left([waypt_x, waypt_y]) m -= 90 elif a == "R": while m > 0: waypt_x, waypt_y = rotate_right([waypt_x, waypt_y]) m -= 90 elif a == "F": ship_x += m * waypt_x ship_y += m * waypt_y print(abs(ship_x) + abs(ship_y))
7db499e4e39bb0f7545f1cd01d983b3790a1207d
andzajan/Adeept_Ultimate_Starter_Kit_Python_Code_for_RPi
/service.py
1,398
3.953125
4
#!/usr/bin/env python #----------------------------------------------------------- # File name : 01_blinkingLed_1.py # Description : make an led blinking. # Author : Jason # E-mail : [email protected] # Website : www.adeept.com # Date : 2015/06/12 #----------------------------------------------------------- import RPi.GPIO as GPIO import time import random import os LedPin = [11, 13, 15, 29, 31, 33, 35, 37] # pin11 count = 0 length = [0.1, 0.2, 0.5, 1] lnum = [1,2,3,4] GPIO.setmode(GPIO.BOARD) # Numbers pins by physical location GPIO.setup(LedPin, GPIO.OUT) # Set pin mode as output GPIO.output(LedPin, GPIO.LOW) # Set pin to high(+3.3V) to off the led GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) try: while True: new_lnum = random.sample (lnum,1)[0] #print new_lnum new_pin = random.sample (LedPin, new_lnum) new_length = random.sample (length, 1)[0] #print new_length #print '...led on' GPIO.output(new_pin, GPIO.HIGH) # led on time.sleep(new_length) #print 'led off...' GPIO.output(new_pin, GPIO.LOW) # led off time.sleep(new_length) count = count + 1 if GPIO.input(10) == GPIO.HIGH: print("Button was pushed!") GPIO.output (LedPin, GPIO.LOW) GPIO.cleanup() os.system ("shutdown -h now") except KeyboardInterrupt: #except if GPIO.input(10) == GPIO.HIGH: GPIO.cleanup() print "\n Blink cycles:", count
5765384a784ac51407757564c0cbafa06cedb83b
divyaprabha123/programming
/arrays/set matrix zeroes.py
1,059
4.125
4
'''Set Matrix Zeroes 1. Time complexity O(m * n) 2. Inplace ''' def setZeroes(matrix): """ Do not return anything, modify matrix in-place instead. """ #go through all the rows alone then is_col = False nrows = len(matrix) ncols = len(matrix[0]) for r in range(nrows): if matrix[r][0] == 0: is_col = True for c in range(1,ncols): if matrix[r][c] == 0: matrix[0][c] = 0 matrix[r][0] = 0 for r in range(1, nrows): for c in range(1, ncols): if not matrix[r][0] or not matrix[0][c]: matrix[r][c] = 0 if matrix[0][0] == 0: for c in range(ncols): matrix[0][c] = 0 if is_col: for r in range(nrows): matrix[r][0] = 0 return matrix
04c2c908a8c25385efd32b14220e9939c94bb010
divyaprabha123/programming
/arrays/sort_k_arrays.py
683
3.796875
4
import heapq '''Sorting k arrays 1. Use heap time O(n) space O(n) ''' def merge_arrays(arrays): heap = [(lst[0], i,0) for i, lst in enumerate(arrays) if lst] heapq.heapify(heap) merge = [] while heap: min_num, lst_index, ele_index = heapq.heappop(heap) merge.append(min_num) if len(arrays[lst_index]) > ele_index+1: heapq.heappush(heap, (arrays[lst_index][ele_index+1], lst_index,\ ele_index + 1)) return merge print(merge_arrays([[1,2,4], [3,6,5]])) '''keys 1. Ordinary sort O(nlog n) 2. Learn index out of error when using two pointers approach '''
8d6ae66c36e6bef05464f78e93979a89c279d0b6
jcurnutt14/FBFriendData
/friendcount.py
2,100
3.875
4
#Program Name: Friendship Paradox #Author: Jon Curnutt #Date: 10/15/19 import networkx as nx G = nx.read_graphml('FrankMcCown-Facebook.graphml') #Determine number of friends my_friends = len(G.nodes) print(f'Total Friends: {my_friends}') #Determine the average number of friends each friend has friends_of_friends_total = 0 for friend in G.nodes: # Make sure node has friend_count attribute if ('friend_count' in G.node[friend]): friends_of_friends_total += G.node[friend]['friend_count'] #Calculate average friends_of_friends_avg = friends_of_friends_total / my_friends print('Average friend count: ' + "{:.1f}".format(friends_of_friends_avg)) #Determine how many friends have more friends than Dr. McCown more_friends = 0 for friend in G.nodes: if ('friend_count' in G.node[friend]): if G.node[friend]['friend_count'] > my_friends: more_friends += 1 #Determine percentage more_friends_percentage = (more_friends / my_friends) * 100 print(f'How many have more friends: {more_friends} ({"{:.1f}".format(more_friends_percentage)}%)') #Determine which friend has the most friends most_friends_name = " " most_friends = 0 for friend in G.nodes: if ('friend_count' in G.node[friend]): if G.node[friend]['friend_count'] > most_friends: most_friends = G.node[friend]['friend_count'] most_friends_name = G.node[friend]['name'] print(f'Most friends: {most_friends_name} ({most_friends})') #Determine the friend with the greatest number of mutual friends friend_name = " " friend_mutual_friends = 0 for friend in G.nodes: if ('friend_count' in G.node[friend]): if len(G.edges(friend)) > friend_mutual_friends: friend_name = G.node[friend]['name'] friend_mutual_friends = len(G.edges(friend)) print(f'Most friends in common: {friend_name} ({friend_mutual_friends})') #Determine if friendship paradox is true or false if friends_of_friends_avg > my_friends: print('Friendship paradox: YES') else: print('Friendship paradox: NO')
c3c6955259b4691b202c3c456461362f079c5119
falcoco/pythonstudy
/ex23.py
245
3.65625
4
L = range(100) ''' print L[:10] print L[20:30] print L[-5:] ''' print L[:10:2] #pcik one every two numbers print L[::5] #pick one every five numbers print L[:] #copy the list print range(1000)[-5:] print 'ABCDEFG'[-2:] #see string as list
47040df315ac09b44047e645f8f988b5a1142342
falcoco/pythonstudy
/ex7.py
299
4.25
4
age = 7 if age >= 18: print 'your age is ',age print 'adult' #else: # print 'your age is ',age # print 'teenager' elif age >= 6: print 'your age is ',age print 'teenager' else: print 'kid' #age = 20 #if age >= 6: # print 'teenager' #elif age >= 18: # print 'adult' #else: # print 'kid'
962d932bddbabc462877308cce22e97594590a0a
falcoco/pythonstudy
/ex9.py
119
3.796875
4
# -*- coding: utf-8 -*- birth = int(raw_input('Your birth:')) if birth < 2000: print '00before' else: print '00after'
5d9305bf6007fa9278894e29bcca9c8b8c0dbae5
Leejeunghun/Capstan
/11-14/test.py
2,101
3.625
4
from tkinter import * from tkinter import ttk import subprocess # 바로 python 실행하기 위해서 사용 def button_pressed(value): number_entry.insert("end",value) print(value,"pressed") def insertNum_on(): txt.insert(100, "On") subprocess.call('gpio -g write 21 1',shell=True) def insertNum_off(): txt.insert(100, "Off") subprocess.call('gpio -g write 21 0',shell=True) subprocess.call('gpio -g mode 21 out',shell=True) #GPIo 21 번을 출력으르로 사용 root = Tk() root.title("Calculator") root.geometry("250x200") # 버튼폭에 맞춰서 확장. entry_value = StringVar(root, value='') number_entry = ttk.Entry(root, textvariable = entry_value, width=20) number_entry.grid(row=0, columnspan=4) #columnspan 은 여러칸에 걸쳐서 표시함. # button 12개 추가 button1 = ttk.Button(root, text="ON", command = insertNum_on) button1.grid(row=4, column=0) button2 = ttk.Button(root, text="OFF", command = insertNum_off) button2.grid(row=4, column=1) button3 = ttk.Button(root, text="Check", command = lambda:button_pressed('3')) button3.grid(row=4, column=2) button7 = ttk.Button(root, text="7", command = lambda:button_pressed('7')) button7.grid(row=1, column=0) button8 = ttk.Button(root, text="8", command = lambda:button_pressed('8')) button8.grid(row=1, column=1) button9 = ttk.Button(root, text="9", command = lambda:button_pressed('9')) button9.grid(row=1, column=2) button4 = ttk.Button(root, text="4", command = lambda:button_pressed('4')) button4.grid(row=2, column=0) button5 = ttk.Button(root, text="5", command = lambda:button_pressed('5')) button5.grid(row=2, column=1) button6 = ttk.Button(root, text="6", command = lambda:button_pressed('6')) button6.grid(row=2, column=2) button1 = ttk.Button(root, text="1", command = lambda:button_pressed('1')) button1.grid(row=3, column=0) button2 = ttk.Button(root, text="2", command = lambda:button_pressed('2')) button2.grid(row=3, column=1) button3 = ttk.Button(root, text="3", command = lambda:button_pressed('3')) button3.grid(row=3, column=2) root.mainloop() # Connection 닫기
7e91ef8f4bce914f08e73ba994e325aaa6cca056
lisaschubeka/CS50x-Solutions
/Problem Set 7/Houses/import.py
743
3.625
4
from cs50 import SQL import csv import sys def main(): if len(sys.argv)!= 2: print("Usage: python import.py characters.csv") sys.exit() db = SQL("sqlite:///students.db") with open("characters.csv", "r") as students: reader = csv.DictReader(students, delimiter=",") for row in reader: tmp_lst = [] tmp_lst.append(row['name']) tmp_lst = tmp_lst[0].split() if len(tmp_lst) == 2: tmp_lst.insert(1, None) db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", tmp_lst[0], tmp_lst[1], tmp_lst[2], row["house"], row["birth"]) main()
b1f9edecef0578ea8b6ec91147e36ed1e28f2621
madacoo/aoc
/2017/05/solve.py
1,148
3.625
4
from time import clock def puzzle_input(): with open("input.txt", "r") as f: return [int(i) for i in f.read().strip().split()] def solve(instructions): "Return the number of steps required to 'escape' the instructions." i = 0 steps = 0 length = len(instructions) while (i >= 0): try: offset = instructions[i] except IndexError: return steps instructions[i] += 1 i += offset steps += 1 return steps def solve2(instructions): "Return the number of steps required to 'escape' the instructions." i = 0 steps = 0 while (i >= 0): try: offset = instructions[i] except IndexError: return steps increment = 1 if offset >= 3: increment = -1 instructions[i] += increment i += offset steps += 1 return steps def timer(f, *args): t0 = clock() result = f(*args) t1 = clock() return t1-t0, result print(timer(solve, puzzle_input())) print(timer(solve2, puzzle_input()))
926c7141c1f6ad007ba57652c1de5c30913d1bbb
chetan1327/Engineering-Practical-Experiments
/Semester 4/Analysis of Algorithm/KMP.py
1,245
3.828125
4
# for proper examples refer https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/ # https://www.youtube.com/watch?v=V5-7GzOfADQ # uncomment print statements to see how the table is updated def prefixTable(pattern): prefix_table = [0] for i in range(1, len(pattern)): j = prefix_table[i-1] # print(f"(i,j): {i, j}") while(j > 0 and pattern[j] != pattern[i]): # print(f"In while j values: {j}, table[{j}]: {prefix_table[j-1]}, Pattern[{j}]: {pattern[j]}, Pattern[{i}]: {pattern[i]}") j = prefix_table[j-1] # print(f"J: {j}, Pattern[{j}]: {pattern[j]}, Pattern[{i}]: {pattern[i]}") prefix_table.append(j+1 if pattern[j] == pattern[i] else j) # print(f"Table: {prefix_table}") # print() return prefix_table print(prefixTable("abadab")) def kmp(text, pattern): table, ret, j = prefixTable(pattern), [], 0 print(table) for i in range(len(text)): while j > 0 and text[i] != pattern[j]: j = table[j - 1] if text[i] == pattern[j]: j += 1 if j == len(pattern): ret.append(i - j + 2) j = table[j - 1] return ret print(kmp("badbabababadaa", "ababada"))
a20cb3c954513dc21d65ab569264c38d1ec07dbc
antuniooh/http-api-without-lib
/databaseUser/ObjectUser.py
2,223
3.875
4
import datetime class UserObj: def __init__(self, name: str, phone: str, pokemon: str, image: str) -> None: """ Create an object of type UserObj, besides that will be create an ID based on the date of the creation time :param name: Contact name :param phone: Contact phone :param pokemon: Contact's favorite Pokémon :param image: Contact DataURL """ self.name = name self.phone = phone self.pokemon = pokemon self.image = image self.id = "" self.setId(str(hash(( self.name, self.phone, self.pokemon, self.image, datetime.datetime.now().strftime("%d %b %Y %H:%M:%S GMT") )))) def setId(self, newID) -> None: """ Set the object ID :param newID: New object ID """ self.id = newID def __hash__(self) -> str: """ Get the UserObj hash :returns: Object hash """ return hash(( self.name, self.phone, self.pokemon, self.image, datetime.datetime.now().strftime("%d %b %Y %H:%M:%S GMT") )) def __dict__(self) -> dict: """ Make a cast from UserObj to dictionary :returns: A dictionary based on the UserObj object """ return { "name": self.name, "phone": self.phone, "pokemon": self.pokemon, "image": self.image } def __str__(self) -> str: """ Add the object's parameters in a String :returns: A String containing the object's attributes """ return f"{{'{self.id}': {{" \ f"name: '{self.name}'," \ f" phone: '{self.phone}'," \ f" pokemon: '{self.pokemon}'," \ f" image: '{self.image}' " \ f"}} " \ f"}}" @staticmethod def fromDict(data: dict): """ Make a cast from dictionary to UserObj :returns: The dictionary based on UserObj object """ return UserObj(data['name'], data['phone'], data['pokemon'], data['image'])
9a3b9864abada3b264eeed335f6977e61b934cd2
willzhang100/learn-python-the-hard-way
/ex32.py
572
4.25
4
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #first for loop goes through a list for number in the_count: print "This is count %d" % number #same for fruit in fruits: print "A fruit of type: %s" % fruit #mixed list use %r for i in change: print "I got %r" % i #built lists, start with empty elements = [] """ for i in range(0,6): print "Adding %d to the list." % i #append elements.append(i) """ elements = range(0,6) #print for i in elements: print "Element was: %d." % i
ffe68ef6fd0c1e21356795a2dc42dc0f26bb3c1c
ananabh/Graph_Algorithm
/Graph_Algorithm/Depth_First.py
236
3.828125
4
def search(graph, visited, current=0): if visited[current] == 1: return visited[current] = 1 print("Visit :", current) for vertex in graph.get_adjacent_vertices(current): search(graph, visited, vertex)
1bf6bde7716587e3767c5b3f2d8a771c31109019
ananabh/Graph_Algorithm
/Graph_Algorithm/Dijkstra_Algorithm.py
1,466
3.859375
4
import Graph_Algorithm.priority_dict as priority_dict def build_distance_table(graph,source): distance_table = {} for i in range(graph.numVertices): distance_table[i] = (None,None) distance_table[source] = (0, source) priority_queue = priority_dict.priority_dict() priority_queue[source] = 0 while len(priority_queue.keys()) > 0: current_vertex=priority_queue.pop_smallest() current_distance=distance_table[current_vertex][0] for neighbour in graph.get_adjacent_vertices(current_vertex): distance = current_distance + graph.get_edge_weight(current_vertex,neighbour) neighbour_distance=distance_table[neighbour][0] if neighbour_distance is None or neighbour_distance > distance: distance_table[neighbour]=(distance,current_vertex) priority_queue[neighbour]=distance return distance_table def shortest_path(graph, source, destination): distance_table = build_distance_table(graph, source) path = [destination] previous_vertex = distance_table[destination][1] while previous_vertex is not None and previous_vertex is not source: path = [previous_vertex] + path previous_vertex = distance_table[previous_vertex][1] if previous_vertex is None: print("There is no path from %d to %d" % (source, destination)) else: path = [source] + path print("Shortest path is : ", path)
f4d5665b4ae72f01abdd3a22863b35102dc45bd3
VP-Soup/Python-Secure-Parallel-and-Distributed-Computing
/SecretCode.py
1,182
4.09375
4
""" Name: Vicente James Perez Date: 1/09/2020 Assignment: Module 1: Secret Code Due Date: 1/10/2020 About this project: Using a dict structure, take user input and translate to "coded" version Assumptions:NA All work below was performed by Vicente James Perez """ import string # create reverse alphabet for populating secret code dict alphabet_reversed = string.ascii_uppercase[::-1] # declare blank dict secret_code = {} # populate dict with alphabet mapped to reverse alphabet for key in string.ascii_uppercase: for value in alphabet_reversed: secret_code[key] = value alphabet_reversed = alphabet_reversed[1:] break # user prompt input_string = input("Please input a string (alphabet characters only): ") # validation while input_string.isspace() or (input_string == ""): input_string = input("Error: invalid string, please enter a new string: ") # declare new coded string bucket coded_string = "" # iterate through each char in input and concatenate val into coded_sgring for char in input_string: if char.isalpha(): coded_string += secret_code[char.upper()] else: coded_string += char print(coded_string)
a53b9ce0419476bc740adb64ba498d84201a2bbd
helen229/AI_Project_Python
/Mini_max.py
3,374
3.53125
4
import Game_Tree # from TreeDriver import Node # from TreeDriver import Tree class MiniMax: def __init__(self, game_tree, curChoice): self.game_tree = game_tree # GameTree self.root = game_tree.root # GameNode self.currentNode = None # GameNode self.successors = [] # List of GameNodes self.curChoice = curChoice self.countH = 0 return def minimax(self, node): # first, find the max value if self.curChoice == "Choice.COLOR": best_val = self.max_value(node) else: best_val = self.min_value(node) successors = self.getSuccessors(node) # find the node with our best move best_move = None for elem in successors: if elem.val == best_val: best_move = elem break return best_move def max_value(self, node): if self.isTerminal(node): return self.getUtility(node) infinity = float('inf') max_value = -infinity successors_states = self.getSuccessors(node) for state in successors_states: min_val = self.min_value(state) max_value = max(max_value, min_val) state.val = min_val return max_value def min_value(self, node): if self.isTerminal(node): return self.getUtility(node) infinity = float('inf') min_value = infinity successor_states = self.getSuccessors(node) for state in successor_states: max_val = self.max_value(state) min_value = min(min_value, max_val) state.val =max_val return min_value # successor states in a game tree are the child nodes... def getSuccessors(self, node): return node.children # return true if the node has NO children (successor states) # return false if the node has children (successor states) def isTerminal(self, node): return len(node.children) == 0 def getUtility(self, node): # return node.val self.countH += 1 return node.get_Heuristic() # def main(): # root = Node(3) # node11 = Node(3) # node12 = Node(9) # node13 = Node(0) # node14 = Node(7) # node15 = Node(12) # node16 = Node(6) # # node11.addChildren(Node(2)) # node11.addChildren(Node(3)) # # node12.addChildren(Node(5)) # node12.addChildren(Node(9)) # # node13.addChildren(Node(0)) # node13.addChildren(Node(-1)) # # node14.addChildren(Node(7)) # node14.addChildren(Node(4)) # # node15.addChildren(Node(2)) # node15.addChildren(Node(1)) # # node16.addChildren(Node(5)) # node16.addChildren(Node(6)) # # node21 = Node(21) # node22 = Node(22) # node23 = Node(23) # # node21.addChildren(node11) # node21.addChildren(node12) # # node22.addChildren(node13) # node22.addChildren(node14) # # node23.addChildren(node15) # node23.addChildren(node16) # # # root.addChildren(node21) # root.addChildren(node22) # root.addChildren(node23) # # tree=Tree(root) # tree.printTree(root,1) # cur = "Choice.DOT" # alpha = MiniMax(tree, cur) # best = alpha.minimax(root) # tree.printTree(root, 1) # print(best.val) # # if __name__ == '__main__': # main()
5a34d77e683868d8c9949401771d0bcea5054c69
bilha-analytics/skoot
/skoot/utils/dataframe.py
524
3.859375
4
# -*- coding: utf-8 -*- from __future__ import absolute_import import pandas as pd import numpy as np __all__ = [ 'get_numeric_columns' ] def get_numeric_columns(X): """Get all numeric columns from a pandas DataFrame. This function selects all numeric columns from a pandas DataFrame. A numeric column is defined as a column whose ``dtype`` is a ``np.number``. Parameters ---------- X : pd.DataFrame The input dataframe. """ return X.select_dtypes(include=[np.number])
6d284c79a505fcc61f317a33ee6265a52b64bf6d
ZaytsevDmitriy/netology_Iterators.Generators.Yield
/main.py
1,318
3.53125
4
nested_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'] ] # class FlatIterator: # # def __init__(self, my_list): # self.my_list = my_list # self.position = 0 # self.position2 = -1 # # def __iter__(self): # return self # # def __next__(self): # if self.position < len(self.my_list): # if self.position2 < len(self.my_list[self.position]) - 1: # self.position2 += 1 # return self.my_list[self.position][self.position2] # else: # self.position2 = -1 # self.position += 1 # return # else: # raise StopIteration class FlatIterator: def __init__(self, my_list): self.my_list = my_list self.position = -1 def __iter__(self): return self def __next__(self): new_list = sum(self.my_list, []) if len(new_list) - 1 == self.position: raise StopIteration else: self.position += 1 return new_list[self.position] def flat_generator(my_list): for i in my_list: for j in i: yield j def flat_generator_rec(my_list): for i in my_list: if isinstance(i, list): yield from flat_generator(i) else: yield i if __name__ == '__main__': for item in FlatIterator(nested_list): print(item) print('\n') for item in flat_generator(nested_list): print(item) print('\n') for item in flat_generator_rec(nested_list): print(item)
9d90bbd139731a568a40c106aa7c10261ab46d2e
subodhsondkar/vadict_machine_learning
/session.py
9,139
3.609375
4
''' What is this? This is a python program for predicting heat generated in some machine according to sensor data provided in the file main.csv. main.csv contains: 1. Time 2. Day_Of_Year 3. TT_16: temperature sensor 4. PYNM_02: temperature sensor 5. TT_11: temperature sensor 6. FT_02: flow rate sensor 7. Wind_Velocity 8. HG_ARRAY_02: heat generated in machine. We have to predict HG_ARRAY_02, with all other columns as inputs. We have used four machine learning methods to achieve this: 1. KNN: K-Nearest Neighbours 2. LR: Linear Regression 3. QR: Quadratic Regression 4. NN: Neural Networks Steps followed: 1. Importing the data 2. Making plots for analysis 3. Removing unneeded data 4. Filling in missing data 5. Making the same plots again for analysis 6. Predicting HG_ARRAY_02 using KNN 7. Predicting HG_ARRAY_02 using LR 8. Predicting HG_ARRAY_02 using QR 9. Predicting HG_ARRAY_02 using NN ''' import pandas as pd # for handling databases import numpy as np # standard mathematical library import time # time calculation import seaborn as sns # for plotting import matplotlib.pyplot as plt # for plotting ### Importing data ### # Loading data df = pd.read_csv('./main.csv') df.head() df['Time'] = pd.to_datetime(df['Time']) # conversion of datatype of a row print('Shape:', df.shape) # number of rows and columns of the database print() print(df.describe()) # mathematical information of int and float columns ### Plots with raw data ### df.loc[:, 'TT_16':].plot(kind = 'box', subplots = True, figsize = (20, 8)) # for a sub-dataframe, plotting a box plot # Pairplot sns.set_style("darkgrid") sns.pairplot(df, hue = None, kind = "scatter") plt.show() ### Data cleaning ### dft = df.copy() # Removing phaaltu rows and columns dft.drop(dft[dft.isnull().sum(axis = 1) > 3].index, axis = 0, inplace = True) # all rows with more than three columns missing dft.drop(dft[dft['HG_ARRAY_02'].isnull()].index, axis = 0, inplace = True) # output missing dft.drop(dft[dft['HG_ARRAY_02'] < 500].index, axis = 0, inplace = True) # outlying outputs dft.drop(dft[dft['Wind_Velocity'] > 10].index, axis = 0, inplace = True) # outlying inputs dft.drop([17], axis = 0, inplace = True) print() print(dft.describe()) # Filling missing values by using current database metrics for index, row in dft[dft['Wind_Velocity'].isnull()].iterrows(): dft.loc[index, 'Wind_Velocity'] = np.random.normal(dft['Wind_Velocity'].mean(), dft['Wind_Velocity'].std()) for index, row in dft[dft['TT_16'].isnull()].iterrows(): dft.loc[index, 'TT_16'] = dft.loc[index, 'TT_11'] + np.random.normal((dft['TT_16'] - dft['TT_11']).mean(), (dft['TT_16'] - dft['TT_11']).std()) for index, row in dft[dft['PYNM_02'].isnull()].iterrows(): dft.loc[index, 'PYNM_02'] = np.random.normal(dft['PYNM_02'].mean(), dft['PYNM_02'].std()) print() print(dft.describe()) ### Data Analysis ### # Scatter plot of inputs vs output for i in range(5): sns.set_style("darkgrid") sns.FacetGrid(dft, hue = None, height = 5)\ .map(plt.scatter, df.columns[i + 2], "HG_ARRAY_02")\ .add_legend() plt.show() # New box plots dft.loc[:, 'TT_16':].plot(kind = 'box', subplots = True, figsize = (20, 8)) ### KNN ### print("\n\nKNN\n") ds = dft.values traindata, trainanswers, testdata, testanswers = ds[:200, 2:7], ds[:200, 7], ds[200:, 2:7], ds[200:, 7] # Euclidean distance function def distance(d1, d2): dist = 0 for i in range(len(d1)): dist += np.square(d1[i] - d2[i]) return dist print('Root Mean Square Error (Testing):') for k in range(1, 16): testpredictions = [] # stores the average values for metrics for i in range(len(testdata)): # for each test datapoint distances = [] # stores distances from each data point for j in range(len(traindata)): distances += [[j, distance(traindata[j], testdata[i])]] sorteddistances = sorted(distances, key = lambda l: l[1]) # sorting distances answer = 0 for j in range(k): answer += trainanswers[sorteddistances[j][0]] # adding top k values testpredictions += [answer / k] # storing mean rmse = 0 for i in range(len(testanswers)): rmse += np.square(testanswers[i] - testpredictions[i]) rmse /= len(testanswers) rmse = np.sqrt(rmse) print('\tfor K =', k, ':', rmse) ### Linear Regression ### print("\nLR\n") from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split traindata, testdata, trainanswers, testanswers = train_test_split( dft.iloc[:, 2:7], dft.iloc[:, 7], test_size = 0.3) # splitting model = LinearRegression() # base model model.fit(traindata, trainanswers) # fitting train data trainpredictions = model.predict(traindata) # predictions on train data for metrics y = 0 trainmse, trainr2 = mean_squared_error(trainanswers, trainpredictions), r2_score(trainanswers, trainpredictions) # metrics print('TRAINING') print('--------') print('Root Mean Square Error (Training):', np.sqrt(trainmse)) print('R-square Score (Training):', trainr2) plt.scatter(trainpredictions, trainanswers - trainpredictions, s = 8) plt.plot([0, 4500], [0, 0]) plt.show() print('x-axis: Predicted value, y-axis: Actual value - Predicted value') testpredictions = model.predict(testdata) # predictions on test data testmse, testr2 = mean_squared_error(testanswers, testpredictions), r2_score(testanswers, testpredictions) # metrics print('\nTESTING') print('-------') print('Root Mean Square Error (Testing):', np.sqrt(testmse)) print('R-square Score (Testing):', testr2) plt.scatter(testpredictions, testanswers - testpredictions, s = 8) plt.plot([0, 4500], [0, 0]) plt.show() print('x-axis: Predicted value, y-axis: Actual value - Predicted value') ### Quadratic Regression ### print("\n\nQR\n") from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score from sklearn.preprocessing import PolynomialFeatures from sklearn.model_selection import train_test_split # same as linear traindata, testdata, trainanswers, testanswers = train_test_split( dft.iloc[:, 2:7], dft.iloc[:, 7], test_size = 0.2) # only difference is the next line, setting coeffecients for given degree polytraindata, polytestdata = PolynomialFeatures(degree = 2).fit_transform(traindata), PolynomialFeatures(degree = 2).fit_transform(testdata) model = LinearRegression() model.fit(polytraindata, trainanswers) polypredictions = model.predict(polytraindata) trainrmse, trainr2 = np.sqrt(mean_squared_error(polypredictions, trainanswers)), r2_score(polypredictions, trainanswers) print('TRAINING') print('--------') print('Root Mean Square Error (Training):', trainrmse) print('R-square Score (Training):', trainr2) plt.scatter(polypredictions, trainanswers - polypredictions, s = 8) plt.plot([0, 4500], [0, 0]) plt.show() polypredictions = model.predict(polytestdata) testrmse, testr2 = np.sqrt(mean_squared_error(polypredictions, testanswers)), r2_score(polypredictions, testanswers) print('\nTESTING') print('-------') print('Root Mean Square Error (Training):', testrmse) print('R-square Score (Training):', testr2) plt.scatter(polypredictions, testanswers - polypredictions, s = 8) plt.plot([0, 4500], [0, 0]) plt.show() ### Neural Network ### print("\n\nNN\n") import random from sklearn.neural_network import MLPRegressor from sklearn.metrics import r2_score from sklearn.model_selection import train_test_split traindata, testdata, trainanswers, testanswers = train_test_split( dft.iloc[:, 2:7], dft.iloc[:, 7], test_size = 0.4) i = 0 while i < 1: n1, n2 = random.randint(3, 20), random.randint(3, 20) lr = 'constant' if random.randint(0, 1) == 0 else 'adaptive' maxiter, iternochange = random.randint(20000, 60000), random.randint(4000, 12000) model = MLPRegressor(hidden_layer_sizes = (n1, n2,), learning_rate = lr, max_iter = maxiter, verbose = False, early_stopping = True, validation_fraction = 0.2, n_iter_no_change = iternochange) st = time.time() model.fit(traindata, trainanswers) et = time.time() trainpredictions = model.predict(traindata) trainr2 = r2_score(trainanswers, trainpredictions) testpredictions = model.predict(testdata) testr2 = r2_score(testanswers, testpredictions) print('Iteration', i, '\nSize of hidden layers:', n1, '|', n2, '\nLearning:', lr) print('r2 value for training:', trainr2, '\nr2 value for testing:', testr2) print('Time:', et - st, 'seconds\nNumber of steps:', model.n_iter_) i += 1 plt.scatter(trainpredictions, trainanswers - trainpredictions, s = 8) plt.scatter(testpredictions, testanswers - testpredictions, s = 8) plt.plot([0, 4500], [0, 0]) plt.plot([0, 4500], [1000, 1000]) plt.plot([0, 4500], [-1000, -1000]) plt.show()
749186c75529d26678b30736069c7babb7aa8bd3
dgilros/TuringNDTMSimulator
/NDTM.py
5,831
3.546875
4
#### # NDTM.py: a nondeterministic Turing Machine Simulator # Author: David Gil del Rosal ([email protected]) #### from collections import defaultdict, deque class Tape: # Constructor. Sets the blank symbol, the # string to load and the position of the tape head def __init__(self, blank, string ='', head = 0): self.blank = blank self.loadString(string, head) # Loads a new string and sets the tape head def loadString(self, string, head): self.symbols = list(string) self.head = head # Returns the symbol on the current cell, or the blank # if the head is on the start of the infinite blanks def readSymbol(self): if self.head < len(self.symbols): return self.symbols[self.head] else: return self.blank # Writes a symbol in the current cell, extending # the list if necessary def writeSymbol(self, symbol): if self.head < len(self.symbols): self.symbols[self.head] = symbol else: self.symbols.append(symbol) # Moves the head left (-1), stay (0) or right (1) def moveHead(self, direction): if direction == 'L': inc = -1 elif direction == 'R': inc = 1 else: inc = 0 self.head+= inc # Creates a new tape with the same attributes than this def clone(self): return Tape(self.blank, self.symbols, self.head) # String representation of the tape def __str__(self): return str(self.symbols[:self.head]) + \ str(self.symbols[self.head:]) class NDTM: # Constructor. Sets the start and final states and # inits the TM tapes def __init__(self, start, final, blank ='#', ntapes = 1): self.start = self.state = start self.final = final self.tapes = [Tape(blank) for _ in range(ntapes)] self.trans = defaultdict(list) # Puts the TM in the start state and loads an input # string into the first tape def restart(self, string): self.state = self.start self.tapes[0].loadString(string, 0) for tape in self.tapes[1:]: tape.loadString('', 0) # Returns a tuple with the current symbols read def readSymbols(self): return tuple(tape.readSymbol() for tape in self.tapes) # Add an entry to the transaction table def addTrans(self, state, read_sym, new_state, moves): self.trans[(state, read_sym)].append((new_state, moves)) # Returns the transaction that corresponds to the # current state & read symbols, or None if there is not def getTrans(self): key = (self.state, self.readSymbols()) return self.trans[key] if key in self.trans else None # Executes a transaction updating the state and the # tapes. Returns the TM object to allow chaining def execTrans(self, trans): self.state, moves = trans for tape, move in zip(self.tapes, moves): symbol, direction = move tape.writeSymbol(symbol) tape.moveHead(direction) return self # Returns a copy of the current TM def clone(self): tm = NDTM(self.start, self.final) tm.state = self.state tm.tapes = [tape.clone() for tape in self.tapes] tm.trans = self.trans # shallow copy return tm # Simulates the TM computation. Returns the TM that # accepted the input string if any, or None. def accepts(self, string): self.restart(string) queue = deque([self]) while len(queue) > 0: tm = queue.popleft() transitions = tm.getTrans() if transitions is None: # there are not transactions. Exit # if the TM is in the final state if tm.state == tm.final: return tm else: # If the transaction is not deterministic # add replicas of the TM to the queue for trans in transitions[1:]: queue.append(tm.clone().execTrans(trans)) # execute the current transition queue.append(tm.execTrans(transitions[0])) return None def __str__(self): out = '' for tape in self.tapes: out+= self.state + ': ' + str(tape) + '\n' return out # Simple parser that builds a TM from a text file @staticmethod def parse(filename): tm = None with open(filename) as file: for line in file: spec = line.strip() if len(spec) == 0 or spec[0] == '%': continue if tm is None: start, final, blank, ntapes = spec.split() ntapes = int(ntapes) tm = NDTM(start, final, blank, ntapes) else: fields = line.split() state = fields[0] symbols = tuple(fields[1].split(', ')) new_st = fields[2] moves = tuple(tuple(m.split(', ')) for m in fields[3:]) tm.addTrans(state, symbols, new_st, moves) return tm if __name__ == '__main__': # Example TM that performs unary complement tm = NDTM('q0', 'q1', '#') tm.addTrans('q0', ('0', ), 'q0', (('1', 'R'), )) tm.addTrans('q0', ('1', ), 'q0', (('0', 'R'), )) tm.addTrans('q0', ('#', ), 'q1', (('#', 'S'), )) acc_tm = tm.accepts('11011101') if acc_tm: print(acc_tm) else: print('NOT ACCEPTED')
da77c952ce085dc401d65edd7b0bdec7d4899504
HellLive/Lista-Zumbi
/questao9.py
458
4.03125
4
'''Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usuário, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km rodado.''' x=int(input("Qual a quantidade de KM percorrido com o carro:")) y=int(input("Quantidade de dias utilizado pelo carro:")) pagar = (y*60)+(x*0.15) print("Valor a ser pago é de R$%5.2f"%pagar)
065ef683f3667f0da058f83fe29fe8a671c918f9
yash9168/codeforces-problems
/PY/1stOct_shalin24999.py
172
3.53125
4
n = int(input()) for i in range(n): str = input() length = len(str) if length <= 10: print(st) else: print(st[0], l - 2, st[l - 1], sep="")
5d0dc760875c2d5c703c164881a904ed19716979
wojiushilr/PRML_SVM_ADABOOST_RF
/face_recog/temp3.py
436
3.8125
4
''' import csv with open("XXX.csv","w",newline="") as datacsv: #dialect为打开csv文件的方式,默认是excel,delimiter="\t"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv,dialect = ("excel")) #csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow(["A","B","C","D"])''' print(list(zip([1, 3, 5], [2, 4, 6])))
8244cceeb3f483b05b666a6a268c432426101809
rapferrer/entry-drawer
/src/random_selector/winning_entry_selector.py
2,349
3.625
4
#!/usr/bin/env python """Takes in a list of entrants from a .csv and finds the winner or winners.""" from argparse import Namespace import logging import random from typing import List from models.entrants_collection import EntrantsCollection logger = logging.getLogger(__name__) def find_winning_entries(entrants_collection: EntrantsCollection, args: Namespace) -> List: without_removal = args.without_removal if without_removal: return _find_winning_entries_without_removal(entrants_collection, args.number_of_winners) else: return _find_winning_entries_with_removal(entrants_collection, args.number_of_winners) def _find_winning_entry(entrants_collection: EntrantsCollection) -> str: """Take in a list of Entrant objects, then find a random entry in the list and selects it as\ the winner.""" winning_entrant = "" winning_entry_number = random.randint(0, entrants_collection.max_entries) logger.info(f'Time to select a random entry for our winner! Selecting entry number {winning_entry_number}') for entrant_name, entrant_entry_range in entrants_collection.entrant_entries.items(): if entrant_entry_range[0] < winning_entry_number <= entrant_entry_range[1]: winning_entrant = entrant_name break return winning_entrant def _find_winning_entries_with_removal(entrants_collection: EntrantsCollection, numberOfWinners: int) -> List: """Find x winning entries from the list of entrants(x being the second arg passed in).""" winners_list = [] for _ in range(numberOfWinners): winner_name = _find_winning_entry(entrants_collection) entrants_collection.remove_entrant(winner_name) winners_list.append(winner_name) return winners_list def _find_winning_entries_without_removal(entrants_collection: EntrantsCollection, number_of_winners: int) -> List: """Find winners in the entrants list without removing them from the list as they are\ selected.""" winners_list = [] while len(winners_list) < number_of_winners: winner_name = _find_winning_entry(entrants_collection) if winner_name not in winners_list: winners_list.append(winner_name) else: logger.info(f'Oops. We already selected {winner_name} before! Drawing again!') return winners_list
d6c2b9f271797e580226702c6ec843e00eea3508
SMinTexas/work_or_sleep
/work_or_sleep_in.py
428
4.34375
4
#The user will enter a number between 0 and 6 inclusive and given #this number, will make a decision as to whether to sleep in or #go to work depending on the day of the week. Day = 0 - 4 go to work #Day = 5-6 sleep in day = int(input('Day (0-6)? ')) if day >= 5 and day < 7: print('Sleep in') elif day >= 0 and day <= 4: print('Go to work') else: print('You are outside the range of available days of the week!')
c62a59b69b55dfb757de7342bba9b9a46a899367
khaloodi/Graphs
/projects/social/social.py
5,617
3.96875
4
import random class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) class User: def __init__(self, name): self.name = name def __repr__(self): return self.name class SocialGraph: def __init__(self): self.last_id = 0 self.users = {} self.friendships = {} def add_friendship(self, user_id, friend_id): """ Creates a bi-directional friendship """ if user_id == friend_id: print("WARNING: You cannot be friends with yourself") return(False) elif friend_id in self.friendships[user_id] or user_id in self.friendships[friend_id]: print("WARNING: Friendship already exists") return(False) else: self.friendships[user_id].add(friend_id) self.friendships[friend_id].add(user_id) return(True) def add_user(self, name): """ Create a new user with a sequential integer ID """ self.last_id += 1 # automatically increment the ID to assign the new user self.users[self.last_id] = User(name) self.friendships[self.last_id] = set() def populate_graph(self, num_users, avg_friendships): """ Takes a number of users and an average number of friendships as arguments Creates that number of users and a randomly distributed friendships between those users. The number of users must be greater than the average number of friendships. """ # Reset graph self.last_id = 0 self.users = {} self.friendships = {} # !!!! IMPLEMENT ME # 100 users, avg 10 friendships each? # ex: avg_friendships = total_friendships / num_users # 2 = total_friendships / 10 # so total_friendships = 20 # therefore, 10 = total_friendships / 100 ... = 1000 # total_friendships = avg_friendships * num_users # BUT have to divide by 2 b/c every time we call add friendships, it adds 2 friendships !!! # Add users for i in range(num_users): self.add_user(f" User {i + 1}") # Create friendships # total_friendships = avg_friendships * num_users # create a list with all possible friendship combinations possible_friendships = [] for user_id in self.users: for friend_id in range(user_id + 1, self.last_id + 1): possible_friendships.append((user_id, friend_id)) # print('POSSIBLE FRIENDSHIPS:') # print(possible_friendships) # print('TOTAL POSSIBLE FRIENDSHIPS:') # print(len(possible_friendships)) # shuffle the list, random.shuffle(possible_friendships) print(possible_friendships) # then grab the first N elements from the list. You will need to import random to get shuffle. # nuber of times to call add_friendship = avg_friendships * num_users for i in range(num_users * avg_friendships // 2): friendship = possible_friendships[i] self.add_friendship(friendship[0], friendship[1]) # O(N) solution: # total_friendships = avg_friendships * numUsers # friendshipsCreated = 0 # while friendshipsCreated < totalFriendships: # pick a random number 1-n, pick another random number 1-n # userID = random.randint(1, self.lastID) # friendID = random.randint(1, self.lastID) # create friendship between those 2 ids # if self.addFriendship(userID, friendID): # friendshipsCreated += 2 # until you have friendship count == totalFriendships # totalFriendships = avg def get_all_social_paths(self, user_id): """ Takes a user's user_id as an argument Returns a dictionary containing every user in that user's extended network with the shortest friendship path between them. The key is the friend's ID and the value is the path. """ # do a BFT, store the paths as we go # BFT steps: # create an empty queue q = Queue() visited = {} # Note that this is a dictionary, not a set # add a PATH from the starting node to the queue q.enqueue([user_id]) # while the queue is not empty... while q.size() > 0: # dequeue FIRST PATH from the queue path = q.dequeue() v = path[-1] # check if it's been visited if v not in visited: # when we reach an unvisited node, add the path to visited dictionary visited[v] = path # add a path to each neighbor to the back of the queue for friend in self.friendships[v]: path_copy = path.copy() # or can do list of path path_copy.append(friend) q.enqueue(path_copy) # return visited dictionary return visited if __name__ == '__main__': sg = SocialGraph() sg.populate_graph(11, 3) print("----------") print('USERS:') print(sg.users) print("----------") print('FRIENDSHIPS:') print(sg.friendships) print('\nSocial Paths:') connections = sg.get_all_social_paths(1) print(connections)
a7cc600378806c5afab02b2bee30a1fc5ebaa3cd
jhfengyun/Evo-Comp
/timer.py
871
3.578125
4
import logging from time import time class Timer: """ A class to investigate code runtime. """ def __init__(self, seed): """ Timer Initialisation :param seed: The seed of the world being timed """ self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.INFO) path = r'log/%s.log' % seed open(path, 'w').close() handler = logging.FileHandler(path) handler.setLevel(logging.INFO) self.logger.addHandler(handler) self.previous_time = time() def take_time(self, msg='', *args): current_time = time() self.logger.info('%s: %f', msg, current_time - self.previous_time) self.previous_time = current_time if args: self.logger.info('----------------%s----------------' % ', '.join(map(str, args)))
7fa7ce262340b1761172fef53f7ea8690a4ce166
yujmo/python
/yield/yield.py
233
3.59375
4
def gen(): yield from subgen() def subgen(): while True: x = yield yield x + 1 def main(): g = gen() next(g) retval = g.send(1) print(retval) g.throw(StopIteration) main()
4abf0f0bd2d6170360ac72b0815fdcba40233dfd
yujmo/python
/python练习题/11/11.py
358
3.6875
4
#!/usr/bin/python2 import re def words(): file_cache = open("filter_word") file_read = file_cache.readlines() file_cache.close() cache = raw_input("Please input a word:") if cache and cache !="q": for i in file_read: if cache == i[:-1]: print "freedom" words() else: exit() words()
16a79229599922fa4fa255d73e9dd46517e86485
sahilohe/Even_or_ODD
/even_or_odd.py
175
3.765625
4
def showNumbers(limit): for i in range(1 ,limit + 1): if i % 2 == 0: print(f'{i} EVEN') else: print(f'{i} ODD') showNumbers(10)
713be8caaafcd510a7ab9abe8ae3d9ff59f7e037
denissden/joystick-mouse
/utils.py
267
3.703125
4
def interpolate(val, low, high): if val <= low: return 0 if val >= high: return 1 return (val - low) / (high - low) def interpolate_power(val, power): sign = 1 if val > 0 else -1 after = abs(val ** power) return sign * after
d0db003c65b5b4bb5d08db8d23f49b29d15a2d9b
mariaKozlovtseva/Algorithms
/monotonic_check.py
798
4.3125
4
def monotonic(arr, if_true_false=False): """ Check whether array is monotonic or not :param arr: array of different numbers :return: string "Monotonic" / "Not monotonic" or if True / False """ decreasing = False increasing = False idx = 0 while not increasing and idx < len(arr)-1: # use abs() as we may have negative values if abs(arr[idx]) > abs(arr[idx+1]): increasing = True else: decreasing = True idx += 1 if if_true_false: return True if (decreasing and not increasing) else False return "Monotonic" if (decreasing and not increasing) else "Not monotonic" if __name__ == '__main__': print(monotonic([1,-2,-4,-10,-100])) print(monotonic([0,-1,-2,1,4], if_true_false=True))
753f1d9d63eab52182e562bfecc9bd42f7acb0c3
mariaKozlovtseva/Algorithms
/leet_code/longest_incr_subseq.py
899
3.875
4
def lengthOfLIS(nums: 'List[int]') -> int: """ https://leetcode.com/problems/longest-increasing-subsequence/submissions/ Given an integer array nums, return the length of the longest strictly increasing subsequence. """ n = len(nums) ends_arr = [None] * (n) ends_arr[0] = 0 length = 1 prev = [None] * n for i in range(1, n): left, right = 0, length if nums[ends_arr[right - 1]] < nums[i]: j = right else: while right - left > 1: mid = (right + left) // 2 if nums[ends_arr[mid - 1]] < nums[i]: left = mid else: right = mid j = left prev[i] = ends_arr[j - 1] if j == length or nums[i] < nums[ends_arr[j]]: ends_arr[j] = i length = max(length, j + 1) return length
5841f6e9177fd876d1831a4c1b6c7f492db7f299
mariaKozlovtseva/Algorithms
/stepik_algo/quicksort_bisearch.py
1,305
3.65625
4
def partition(arr): pivot = (arr[0] + arr[len(arr)//2] + arr[-1]) // 3 ls, gr, eq = [], [], [] for x in arr: if x > pivot: gr.append(x) elif x < pivot: ls.append(x) else: eq.append(x) return ls, eq, gr def quicksort(arr): while len(arr) > 1: ls, eq, gr = partition(arr) if len(ls) < len(gr): ls = quicksort(ls) return ls + eq + quicksort(gr) elif len(ls) > len(gr): gr = quicksort(gr) return quicksort(ls) + eq + gr else: return quicksort(ls) + eq + quicksort(gr) return arr def bi_search(arr, point, i): l, r = 0, len(arr) - 1 while l <= r: mid = l + (r-l) // 2 if arr[mid] <= point - i: l = mid + 1 elif arr[mid] > point - i: r = mid - 1 return l def main(): n, m = tuple(map(int,input().split())) left, right = [], [] for _ in range(n): l_r_point = tuple(map(int,input().split())) left.append(l_r_point[0]) right.append(l_r_point[1]) points = tuple(map(int, input().split())) left, right = quicksort(left), quicksort(right) for p in points: print(bi_search(left, p, 0) - bi_search(right, p, 1), end=' ') if __name__ == '__main__': main()
d8f7bbe7d88f807fab605333df84486b74e2cb88
mariaKozlovtseva/Algorithms
/DoubleLL.py
2,319
3.796875
4
class Node: size = 0 def __init__(self, value): self.value = value self.prev = None self.next = None class DoubleLinkedList: def __init__(self): self.head = None self.tail = None def setHead(self, node): if not self.head: self.head = node self.tail = node return self.insertBefore(self.head, node) def setTail(self, node): if not self.tail: self.setHead(node) self.insertAfter(self.tail, node) def insertBefore(self, node, nodeToInsert): if nodeToInsert == self.head and nodeToInsert == self.tail: return nodeToInsert.prev = node.prev nodeToInsert.next = node if not node.prev: self.head = nodeToInsert else: node.prev.next = nodeToInsert node.prev = nodeToInsert def insertAfter(self, node, nodeToInsert): if nodeToInsert == self.head and nodeToInsert == self.tail: return nodeToInsert.prev = node nodeToInsert.next = node.next if not node.next: self.tail = nodeToInsert else: node.next.prev = nodeToInsert node.next = nodeToInsert def insertAtPosition(self, position, nodeToInsert): """ :param position: count starts at 0 :param nodeToInsert: object of class Node """ if position == 0: self.setHead(nodeToInsert) node = self.head count = 0 while count != position: node = node.next count += 1 if not node: self.setTail(nodeToInsert) else: self.insertBefore(node,nodeToInsert) def removeNodesWithValue(self, value): node = self.head val = node.value while val != value: node = self.head.next val = node.value self.remove(node) def remove(self, node): if node == self.head: self.head = self.head.next if node == self.tail: self.tail = self.tail.prev if node.prev is not None: node.prev.next = node.next if node.next is not None: node.next.prev = node.prev node.prev = None node.next = None
1f1a00fbb0a7d9b21bfd159b0ae4665af39370d6
mariaKozlovtseva/Algorithms
/stack_prefix_postfix_notation.py
2,996
3.765625
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) def postfix_string(s): s = s.split() priority = {'(': 0, '-':1, '+':1, '*':2, '/':2} stack = Stack() result = [] for elem in s: if elem in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or elem in "0123456789": result.append(elem) elif elem == '(': stack.push(elem) elif elem == ')': top_el = stack.pop() while top_el != '(': result.append(top_el) top_el = stack.pop() else: while not stack.isEmpty() and priority[stack.peek()] > priority[elem]: result.append(stack.pop()) stack.push(elem) while not stack.isEmpty(): result.append(stack.pop()) return ' '.join(result) def eval_postfix(postfix_s): postfix_s = postfix_s.split() stack = Stack() for elem in postfix_s: if elem in "0123456789": stack.push(int(elem)) else: oper2 = stack.pop() oper1 = stack.pop() result = calculate(elem, oper1, oper2) stack.push(result) return stack.pop() def calculate(op, op1, op2): if op == "*": return op1 * op2 elif op == "/": return op1 / op2 elif op == "+": return op1 + op2 else: return op1 - op2 def prefix_string(s): s = s.split() priority = {')': 0, '-': 1, '+': 1, '*': 2, '/': 2} result = [] stack = Stack() for elem in s[::-1]: if elem in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or elem in "0123456789": result.insert(0, elem) elif elem == ')': stack.push(elem) elif elem == '(': top_el = stack.pop() while top_el != ')': result.insert(0, top_el) top_el = stack.pop() else: if not stack.isEmpty() and priority[stack.peek()] > priority[elem]: result.insert(0, stack.pop()) stack.push(elem) while not stack.isEmpty(): result.insert(0,stack.pop()) return ' '.join(result) def eval_prefix(prefix_s): prefix_s = prefix_s.split() stack = Stack() for elem in prefix_s[::-1]: if elem in "0123456789": stack.push(int(elem)) else: oper1 = stack.pop() oper2 = stack.pop() result = calculate(elem, oper1, oper2) stack.push(result) return stack.pop() if __name__ == '__main__': print(postfix_string("( A + B ) * C - ( D - E ) * ( F + G )")) print(prefix_string("( A + B ) * C - ( D - E ) * ( F + G )")) print(eval_postfix('7 8 + 3 2 + /')) print(eval_prefix('+ 5 * 4 3'))
09896d5ccf05e5b341ad50e28fe2ad3f4d248c75
bets42/42bets
/scripts/send_cmd.py
2,082
3.59375
4
#!/usr/bin/env python -u """Send a single command to a 42bets server Connects to the command port of a server and sends a command, outputting whatever message is received in response""" import optparse import os import socket import sys class TCPCommandSender: """Wrapper around TCP client for sending commands""" def __init__(self, host, port): """Setup connection to host:port""" self.__host = host self.__port = port self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__socket.connect((host, port)) def __enter__(self): """Return self""" return self def __exit__(self, type, value, traceback): """Tear down connection if connected""" if self.__socket: self.__socket.close() def send(self, cmd): """Send admin command to server and return received message""" try: self.__socket.sendall(cmd) data = self.__socket.recv(4096) return data except EnvironmentError, msg: return "ERROR" def main(): #define command line arguments parser = optparse.OptionParser("Usage: %prog [options]") parser.add_option('--host', dest='host', help='Server to send commands to', type='string') parser.add_option('--port', dest='port', help='Server admin port to send commands to', type='int') parser.add_option('--command', dest='command', help='Command to send to server', type='string') (options, args) = parser.parse_args() #check we have all required command line arguments if options.host and options.port and options.command: try: with TCPCommandSender(options.host, options.port) as cmd_sender: sys.stdout.write(cmd_sender.send(options.command + '\n')) except EnvironmentError, msg: sys.stderr.write("Failed to connect to %s:%s; reason=%s" % (options.host, options.port, msg)) sys.exit(1) else: sys.stderr.write(str(parser.print_help())) if __name__ == "__main__": main()
e9696c152599ed1337c59ebace30cf8275ca3876
suleyman-kutukoglu/guessing-game
/guess-game.py
1,865
3.984375
4
import random def randomWordFromTxt(): allWords = list() with open("word_list.txt", "r", encoding="utf-8") as file: for line in file: line = line.split() allWords.append(line[0]) randomWord = allWords[random.randint(0, len(allWords) - 1)] return randomWord secretWord = randomWordFromTxt() secretWordWithStars = "*" * len(secretWord) currentStatus = str() guessLetterList = list() howManyTry = int() for letter in secretWordWithStars: guessLetterList.append(letter) print("The word contains {} letters.".format(len(secretWord))) while secretWord.upper() != currentStatus: indexOfArray = 0 letterCounter = 0 howManyTry += 1 anyLetter = input("Please enter one letter or a {}-letter word:".format(len(secretWord))) if len(anyLetter) is 1: for e in secretWord: if e.upper() == anyLetter.upper(): guessLetterList[indexOfArray] = anyLetter.upper() letterCounter += 1 indexOfArray += 1 currentStatus = str() for e in guessLetterList: currentStatus += e if letterCounter is 1: print("Yes! The word contains the letter '{}'\n{}".format(anyLetter, currentStatus)) elif letterCounter is 0: print("The letter {} is not found.\n{}".format(anyLetter, currentStatus)) else: print("Yes the word contains '{}'s.\n{}".format(anyLetter, currentStatus)) else: currentStatus = str() tempList = list() for e in anyLetter: tempList.append(e) for e in [x.upper() for x in tempList]: currentStatus += e if secretWord.upper() != currentStatus: print("Wrong guess.") print("Yes, the word is {}! You got it {} tries.".format(secretWord, howManyTry)) input()