blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
733e38312e73bd0ec4cc2c27f571dcbdbd94197f
kyledgls/pdxcodeguild_assignments
/Python/week4/lab28-socks.py
549
3.765625
4
""" sock sorter original version by Kyle Douglas """ import random sock_types = ['ankle', 'crew', 'calf', 'thigh'] i = 0 laundry = [] while i < 100: laundry.append(random.choice(sock_types)) i += 1 print(laundry) sorted_laundry = {} lone_rangers = {} for sock in laundry: if sock not in sorted_laundry: sorted_laundry[sock] = 1 else: sorted_laundry[sock] += 1 for sock_type in sorted_laundry: if sorted_laundry[sock_type]%2 == 1: lone_rangers[sock_type] = 1 print(sorted_laundry) print(lone_rangers)
d56d83109a66b60b73160c4a45d770d01ef76274
Stuff7/stuff7
/stuff7/utils/collections/collections.py
1,021
4.1875
4
class SafeDict(dict): """ For any missing key it will return {key} Useful for the str.format_map function when working with arbitrary string and you don't know if all the values will be present. """ def __missing__(self, key): return f"{{{key}}}" class PluralDict(dict): """ Parses keys with the form "key(singular, plural)" and also "key(plural)". If the value in the key is 1 it returns singular for everything else it returns plural """ def __missing__(self, key): if "(" in key and key.endswith(")"): key, rest = key.split("(", 1) value = super().__getitem__(key) suffix = rest.rstrip(")").split(",") if len(suffix) == 1: suffix.insert(0, "") return suffix[0].strip() if value == 1 else suffix[1].strip() return f"{{{key}}}" def safeformat(string, **options): """ Formatting and ignoring missing keys in strings. """ try: return string.format_map(SafeDict(options)) except ValueError as e: return f"There was a parsing error: {e}"
8678b04cd9e28847b30d4b8ec7fe3f9aaddc1708
rohan8594/DS-Algos
/leetcode/medium/Arrays and Strings/ReverseWordsInAString.py
1,076
4.3125
4
# Given an input string, reverse the string word by word. # Example 1: # Input: "the sky is blue" # Output: "blue is sky the" # Example 2: # Input: " hello world! " # Output: "world! hello" # Example 3: # Input: "a good example" # Output: "example good a" # Note: # A word is defined as a sequence of non-space characters. # Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. # You need to reduce multiple spaces between two words to a single space in the reversed string. class Solution: def reverseWords(self, s: str) -> str: strArr = [] curWord, res = "", "" # strArr = s.split(" ") for char in s: if char == " ": strArr.append(curWord) curWord = "" continue curWord += char strArr.append(curWord) for i in range(len(strArr) - 1, -1, -1): if strArr[i] == "": continue res += strArr[i] + " " return res[:-1]
40ff7f550216205131dcf6131c150505925fbfce
BlackBloodLT/URI_Answers
/Python3/1_INICIANTE/uri1021.py
4,341
4.03125
4
""" Notas e Moedas Leia um valor de ponto flutuante com duas casas decimais. Este valor representa um valor monetário. A seguir, calcule o menor número de notas e moedas possíveis no qual o valor pode ser decomposto. As notas consideradas são de 100, 50, 20, 10, 5, 2. As moedas possíveis são de 1, 0.50, 0.25, 0.10, 0.05 e 0.01. A seguir mostre a relação de notas necessárias. Entrada O arquivo de entrada contém um valor de ponto flutuante N (0 ≤ N ≤ 1000000.00). Saída Imprima a quantidade mínima de notas e moedas necessárias para trocar o valor inicial, conforme exemplo fornecido. Obs: Utilize ponto (.) para separar a parte decimal. """ # Está com erro, verificar e corrigir!!! valor = float(input()) numeroNotas100 = valor // 100 valor = valor - numeroNotas100*100 numeroNotas50 = valor // 50 valor = valor - numeroNotas50*50 numeroNotas20 = valor // 20 valor = valor - numeroNotas20*20 numeroNotas10 = valor // 10 valor = valor - numeroNotas10*10 numeroNotas5 = valor // 5 valor = valor - numeroNotas5*5 numeroNotas2 = valor // 2 valor = valor - numeroNotas2*2 numeroMoedas100 = valor // 1 valor = valor - numeroMoedas100*1 numeroMoedas100 = float('%.2f' %numeroMoedas100) valor = float('%.2f' %valor) numeroMoedas50 = valor // 0.5 valor = valor - numeroMoedas50*0.5 numeroMoedas50 = float('%.2f' %numeroMoedas50) valor = float('%.2f' %valor) numeroMoedas25 = valor // 0.25 valor = valor - numeroMoedas25*0.25 numeroMoedas25 = float('%.2f' %numeroMoedas25) valor = float('%.2f' %valor) numeroMoedas10 = valor // 0.10 valor = valor - numeroMoedas10*0.10 numeroMoedas10 = float('%.2f' %numeroMoedas10) valor = float('%.2f' %valor) numeroMoedas5 = valor // 0.05 valor = valor - numeroMoedas5*0.05 numeroMoedas5 = float('%.2f' %numeroMoedas5) valor = float('%.2f' %valor) numeroMoedas1 = valor * 100 numeroMoedas1 = float('%.2f' %numeroMoedas1) valor = float('%.2f' %valor) print('NOTAS:') print('{} nota(s) de R$ 100.00'.format(int(numeroNotas100))) print('{} nota(s) de R$ 50.00'.format(int(numeroNotas50))) print('{} nota(s) de R$ 20.00'.format(int(numeroNotas20))) print('{} nota(s) de R$ 10.00'.format(int(numeroNotas10))) print('{} nota(s) de R$ 5.00'.format(int(numeroNotas5))) print('{} nota(s) de R$ 2.00'.format(int(numeroNotas2))) print('MOEDAS:') print('{} moeda(s) de R$ 1.00'.format(int(numeroMoedas100))) print('{} moeda(s) de R$ 0.50'.format(int(numeroMoedas50))) print('{} moeda(s) de R$ 0.25'.format(int(numeroMoedas25))) print('{} moeda(s) de R$ 0.10'.format(int(numeroMoedas10))) print('{} moeda(s) de R$ 0.05'.format(int(numeroMoedas5))) print('{} moeda(s) de R$ 0.01'.format(int(numeroMoedas1))) """ entrada = float(input()) valor = int(entrada*100) numeroNotas100 = 0 numeroNotas50 = 0 numeroNotas20 = 0 numeroNotas10 = 0 numeroNotas5 = 0 numeroNotas2 = 0 numeroNotas1 = 0 numeroMoedas100 = 0 numeroMoedas50 = 0 numeroMoedas25 = 0 numeroMoedas10 = 0 numeroMoedas5 = 0 numeroMoedas1 = 0 while(valor>9999): numeroNotas100 += 1 valor -= 10000 while(valor>4999): numeroNotas50 += 1 valor -= 5000 while(valor>1999): numeroNotas20 += 1 valor -= 2000 while(valor>999): numeroNotas10 += 1 valor -= 1000 while(valor>499): numeroNotas5 += 1 valor -= 500 while(valor>199): numeroNotas2 += 1 valor -= 200 while(valor>99): numeroMoedas100 += 1 valor -= 100 while(valor>49): numeroMoedas50 += 1 valor -= 50 while(valor>24): numeroMoedas25 += 1 valor -= 25 while(valor>9): numeroMoedas10 += 1 valor -= 10 while(valor>4): numeroMoedas5 += 1 valor -= 5 while(valor>0): numeroMoedas1 += 1 valor -= 1 print("NOTAS:") print("{} nota(s) de R$ 100.00".format(numeroNotas100)) print("{} nota(s) de R$ 50.00".format(numeroNotas50)) print("{} nota(s) de R$ 20.00".format(numeroNotas20)) print("{} nota(s) de R$ 10.00".format(numeroNotas10)) print("{} nota(s) de R$ 5.00".format(numeroNotas5)) print("{} nota(s) de R$ 2.00".format(numeroNotas2)) print("MOEDAS:") print("{} moeda(s) de R$ 1.00".format(numeroMoedas100)) print("{} moeda(s) de R$ 0.50".format(numeroMoedas50)) print("{} moeda(s) de R$ 0.25".format(numeroMoedas25)) print("{} moeda(s) de R$ 0.10".format(numeroMoedas10)) print("{} moeda(s) de R$ 0.05".format(numeroMoedas5)) print("{} moeda(s) de R$ 0.01".format(numeroMoedas1)) """
bdea8daa6a256f3a3253063a841b6c0f2f8e51ca
Jucindra/minimundo-eletrodomesticos-apgsi
/appliances_store.py
1,148
3.765625
4
from datetime import date class Customer(): def __init__(self, my_id, name, address): self.id = my_id self.name = name self.address = address class Product(): def __init__(self, my_id, mark, model, serial_number): self.id = my_id self.mark = mark self.model = model self.serial_number = serial_number # self.warranty = { # 'id':my_id, # 'mark':mark, # 'model':model, # 'serial_number':serial_number, # } class Purchase(): def __init__(self, my_id, customer, date): self.id = my_id self.customer = customer self.date = date self.products = [] def add_product(self, product): self.products.append(product) def is_my_purchase_in_the_warranty(self, purchase_id): warranty_year = date.today().year - 1 warranty_date = date(warranty_year, date.today().month, date.today().day) if date(2010, 1, 17) <= warranty_date: return True else: return False
24ff6652d849d61879c95a0b778157f79031071c
RyanCrowleyCode/StudentExercises
/reports.py
2,006
4.25
4
# sqlite3 allows python to access the database import sqlite3 from student import Student class StudentExerciseReports(): '''Methods for reports on the Student Exercises Database''' def __init__(self): # creating a variable to hold the exact path on my computer to the database self.db_path = '/Users/ryancrowley/workspace/backend/StudentExercises/studentexercises.db' # Method that returns Student instances def create_student(self, cursor, row): return Student(row[1],row[2], row[3], row[5]) def all_students(self): '''Retrieve all students with the cohort name''' # Opens and closes connection because we use 'with' with sqlite3.connect(self.db_path) as conn: # re-define what row factory does to create Student instances using anonymous function conn.row_factory = lambda cursor, row: Student(row[1],row[2], row[3], row[5]) # creating a variable to hold the cursor (translator between Python and SQL) db_cursor = conn.cursor() # SQL Query that creates a property on cursor db_cursor.execute(""" select s.student_id, s.first_name, s.last_name, s.slack_handle, s.cohort_id, c.name FROM Students s JOIN Cohorts c on s.Cohort_Id = c.Cohort_Id ORDER BY s.Cohort_Id; """) # retrieve data after executing select statement to get a list of the matching rows all_students = db_cursor.fetchall() # loop through each tuple in all_students and print out information # for student in all_students: # print(student) # as a comprehension: [print(s) for s in all_students] # create an object instance of StudentExerciseReports reports = StudentExerciseReports() # call the all_students method reports.all_students()
d4763ee0ca83d71576c8fb5641804b019051f15b
caiquemarinho/python-course
/Exercises/Module 04/exercise_31.py
185
4.1875
4
""" Read a number and prints the number that comes before it and the one that comes after it. """ print('Please, insert a number') num = int(input()) print(f'{num-1} and {num+1}') 4
7337154c0f16690df6ead64ff37212285897cc20
vdloo/dotfiles
/code/scripts/fun/quicksort_functional.py
409
3.84375
4
#!/usr/bin/env python import random, string random_digits = map(lambda _ : random.randint(0, 10), range(0, 10)) def quicksort(seq): if len(seq) > 1: left = filter(lambda x: x < seq[0], seq[1:]) middle = seq[:1] right = filter(lambda x: x >= seq[0], seq[1:]) return quicksort(left) + middle + quicksort(right) else: return seq print quicksort(random_digits)
19189414320d7e176d50725f259ba25fa44d65ba
alonzo-olum/py-algo
/anagram.py
368
4.03125
4
#!/bin/env python3 from collections import Counter import cProfile def anagram(first_string, second_string): if Counter(first_string) == Counter(second_string): return True # Main Program Block first_string = "algorithm" second_string = "logarithm" print(anagram(first_string, second_string)) #print(cProfile.run('anagram(first_string, second_string))')
3e2c76d4a779d3559f3b800c5fd083ebfb5d4ca2
crileiton/curso_python
/5 Entradas y salidas de datos/tabla.py
522
3.8125
4
# Ejercicio No. 2 import sys if len(sys.argv) == 3: filas = int(sys.argv[1]) columnas = int(sys.argv[2]) if ( (filas > 0 and filas < 10) and (columnas > 0 and columnas < 10) ): for fila in range(filas): print("") for columna in range(columnas): print("*", end='') else: print("Filas o columnas incorrectas.") print("Ejemplo: tabla.py [1-9] [1-9 ]") else: print("Error argumentos incorrectos.") print("Ejemplo: tabla.py [1-9] [1-9 ]")
a912c8189096a069ef1684385f55191d3a160fdd
mani5348/Python
/Day3/Third_Largest_No.py
213
4.5
4
#write a program to Find the 3rd Largest Number in a List list=[1,2,4,32,5,8,4,9,10,15] list.sort() print("sorted list is :",list) len1=len(list) print("Third largest element in the list is :",list[len1-3])
b6a6b915b2ade7f035d4ddebc105f1476256347a
DavidSchmidtSBU/DavidSchmidtSBU.github.io
/Bible.py
788
4.1875
4
# First find a bible in text form inFile = open('KJV12.TXT', 'r') longWord = " " #Initialize longWord inLine = inFile.readline() #Read in a line of text while (inLine != ''): #While more lines to read lineList = inLine.split(' ') #Split words into a list # Look through the list. If a longer word is found, # assign it to be the new longWord for i in range (0, len(lineList)): if (len(lineList[i]) > len(longWord)): longWord = lineList[i] # Go get another doughnu…line of text inLine = inFile.readline() # Done—just read the entire Bible. Superpower? Not quite.. print('Your longest word: ', longWord)# …but still… print('End of processing!') inFile.close() # Done!
2878c3f8a5b9180bc5d2eea6399fba16ab06922f
MarkisDev/python-fun
/Competitive Programming/binary-triangle.py
772
4.125
4
""" Binary Triangle This script prints a Binary Triangle with inputted number of lines. @author : MarkisDev @copyright : https://markis.dev @source : https://www.geeksforgeeks.org/program-to-print-modified-binary-triangle-pattern/ """ # Taking input from user for number of lines number = int(input("Enter the number of lines: ")) # First loop to print number of lines for i in range(1 , (number+1)): # Second loop to print either 0 or 1 depending on the value of i for j in range (1 , (i+1)): if (j == 1 or j == i): # Print 1 or 0 in the same line print(1 , end = '') else: print(0, end = '') # Print new line after a part of the triangle is done print(end="\n")
b34c39f1f5be55530badcbf5254deeb24a3c2ae5
thaismr/pythonAdvanced
/Collections/05_ordered_dict.py
452
3.71875
4
from collections import OrderedDict def main(): scores = [ ("Name", (18, 12)), ("Name 2", (10, 8)), ("Name 3", (15, 9)) ] sorted_scores = sorted(scores, key=lambda t: t[1][0], reverse=True) print(sorted_scores) scores = OrderedDict(sorted_scores) print(scores) name, stats = scores.popitem(False) print('Highest score:', name, stats) print(scores) if __name__ == "__main__": main()
cb9cd760d9d1f6857fdaf91c34b7af869c8c55b0
alanjvano/pi_hexa
/math_hw.py
95
3.75
4
x = True a = 0 while x < 100: x = x+1 print('{}: {}, {}'.format(x, 6*x-1, 6*x+1))
e46b24d0ae1ff6a8e843f4ff1813b751c6744641
lozaeric/icpc_undav
/Kattis/oddities.py
104
4.125
4
n = int(input()) for i in range(n): m = int(input()) print(m, "is even" if m%2==0 else "is odd")
326979a28d81b329c96585bdc46a83e47f0c3000
DAltier/Math_Dojo_TDD
/math_dojo_tdd.py
732
3.578125
4
class MathDojo: def __init__(self): self.result = 0 def add(self, num, *nums) : self.result += num for var in nums : self.result += var return self def subtract(self, num, *nums) : self.result -= num for var in nums : self.result -= var return self import unittest class mathTests(unittest.TestCase) : def setUp(self): self.md = MathDojo() #creating MathDojo object def testAdd(self) : self.assertEqual(self.md.add(2,5,1,7).result, 15) def testSubtract(self) : self.assertEqual(self.md.subtract(7,2,5).result, -14) def tearDown(self): pass if __name__ == '__main__': unittest.main()
71412657c69f3f63454dd8a2e3510fcea6d06114
atveretinov/tests
/HuckerRankProblems/src/min_distance.py
823
4.03125
4
# Consider an array of n integers, A = [a0,a1,...,an-1] . The distance between two indices,i and j, is denoted by # di,j =|i-j| . Given A , find the minimum di,j such that ai=aj and i!=j . In other words, find the minimum distance # between any pair of equal elements in the array. If no such value exists, print -1 . # Note: denotes the absolute value of a. import sys def minimumDistances(a): distances = list() for i in range(0,len(a)+1): for j in range(i+1,len(a)): if a[i] == a[j]: distances.append(abs(i-j)) if len(distances) == 0: return "-1" minDist = min(distances) return minDist if __name__ == "__main__": n = int(input().strip()) a = list(map(int, input().strip().split(' '))) result = minimumDistances(a) print(result)
80e17154c4f7ecb7c16fea243913a4ca5728f1a1
ack8006/EulerProjects
/prob9-specialPythag.py
710
4.3125
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def main(): afterDerivationByHand() def afterDerivationByHand(): b = 1 while b <= 999: a = (500000-(1000*b))/(1000-b) c = 1000 - a - b if (a+b+c == 1000 and isPythagorean(a,b,c) and a >0 and b >0 and c>0): print "a = " + str(a) print "b = " + str(b) print "c = " + str(c) print "product = " + str(a*b*c) b += 1 def isPythagorean(a, b, c): if ((a**2 + b**2) == c**2): return True else: return False if __name__ == "__main__": main()
e704be964d02e7a6cfc9adf16b2932f82d417427
amogchandrashekar/Leetcode
/Medium/Merge Intervals.py
789
3.875
4
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key=lambda x: (x[0], x[1])) merged_intervals = [] start, stop = intervals[0] for strt_i, stop_i in intervals[1:]: # merge the intervals if start <= strt_i <= stop: start = min(start, strt_i) stop = max(stop, stop_i) else: # create a new interval merged_intervals.append([start, stop]) start, stop = strt_i, stop_i merged_intervals.append([start, stop]) return merged_intervals if __name__ == '__main__': intervals = [[1, 3], [2, 6], [8, 10], [15, 18]] print(Solution().merge(intervals))
1ce42a3233096c9ed90d2709e517665b054094f0
lyineee/NN_regression
/plot.py
336
3.59375
4
import matplotlib.pyplot as plt from random import random import numpy as np #y = x**2 + 1*random(0,1) - 25 def graph(): x=np.linspace(-5,5,50) y=np.ones((50,)) for i,data in enumerate(x): y[i]=data**2 + 1*random() - 25 plt.figure() plt.plot(x, y) plt.show() if __name__ == "__main__": graph()
be72c62328561a2ae507e2838314cbf77818f4cc
108krohan/codor
/hackerrank-python/algorithm/strings/alternatingCharacters - number of deletrions.py
1,047
4.0625
4
# -*- coding: utf-8 -*- """alternating characters at hackerrank.com """ """ Shashank likes strings in which consecutive characters are different. For example, he likes ABABA, while he doesn't like ABAA. Given a string containing characters A and B only, he wants to change it into a string he likes. To do this, he is allowed to delete the characters in the string. Your task is to find the minimum number of required deletions. Input Format The first line contains an integer T, i.e. the number of test cases. The next T lines contain a string each. Output Format For each test case, print the minimum number of deletions required. Constraints 1≤T≤10 1≤ length of string ≤105 Sample Input 5 AAAA BBBBB ABABABAB BABABA AAABBB Sample Output 3 4 0 0 4 """ testCases = int(raw_input()) for _ in range(testCases) : string = raw_input() delete = 0 for i in range(len(string)-1) : if string[i] == string[i+1] : delete += 1 print delete
b1dccb6a269c09b4cf894ad37c27fb9469fc3622
2470370075/all
/剥皮.py
226
3.75
4
l=[1,2,[2,3,[4]]] def func(x): l2 = [] def func2(x): for i in x: if isinstance(i,list): func2(i) else: l2.append(i) func2(x) print(l2) func(l)
687f38ce0faeddabba0ea5b28cc568413f941812
Kraszu/mojGitHub
/Python/task2/task2.py
1,168
3.875
4
"""Assignment 2 TASK2 Maciej Kubiniec R00144142""" """ function checks if number given by user is odd or even. if number is even then is devided by 2. if number is odd then is multiplay by 3 and 1 is added""" def reducer(number): if number % 2 == 0: print("(",number ,"/ 2 )") print() return int(number / 2) else: print("(",number ,"* 3 + 1 )") print() return number * 3 + 1 """main function that takes number as parameter and until number will reach 1 will be devided or multiple depending on its value equal to even or odd number""" def main(): number = 0 print("Please enter a number") number = int(input()) if number % 2 == 0: print("you enetered an even number so first operation is division" ) else: print("you enetered an odd number so first operation is multiplication" ) while number != 1: print(number) number = reducer(number) print(number) main() ### CORRECT SOLUTION BUT OUTPUTTING INSIDE THE REDUCER FUNCTION IS WRONG. THOSE CODE SHOULD HAVE BEEN REMOVED. ### SCORE = 6.5 MARKS
155521d62436f87f2c405656cccd37d12ddd3ed6
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/palindromePermutation.py
2,550
3.828125
4
""" Palindrome Permutation Given a string, determine if a permutation of the string could form a palindrome. Example 1: Input: "code" Output: false Example 2: Input: "aab" Output: true Example 3: Input: "carerac" Output: true """ """ HashMap Time: O(N) Space: O(N) """ class Solution(object): def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ counts = collections.Counter(s) odd_used = False for ch in counts.keys(): if counts[ch]%2: if len(s)%2 == 0 or odd_used: return False odd_used = True return True class Solution: def canPermutePalindrome(self, s: str) -> bool: counts = dict() for c in s: counts[c] = counts.get(c, 0) + 1 n = len(s) if len(counts) > (n//2)+1: return False if n%2: two_odds = False for c in counts: if counts[c]%2: if two_odds: return False two_odds = True break return True else: for c in counts: if counts[c]%2: return False return True class Solution: def canPermutePalindrome(self, s: str) -> bool: counts = dict() for c in s: counts[c] = counts.get(c, 0) + 1 res = 0 for c in counts: res += counts[c]%2 return res <= 1 """ Use Set to keep track of odd elements and remove when necessary Time: O(n) Space: O(n) """ public class Solution { public boolean canPermutePalindrome(String s) { Set < Character > set = new HashSet < > (); for (int i = 0; i < s.length(); i++) { if (!set.add(s.charAt(i))) set.remove(s.charAt(i)); } return set.size() <= 1; } } class Solution: def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ # Only at most one character can appear odd number of times. charmap = dict() for c in s: if c not in charmap: charmap[c] = 1 else: charmap[c] += 1 oddcount = 0 for c in charmap: if charmap[c]%2: oddcount += 1 if oddcount >= 2: return False return True
f036744066ab5df34625447d36a1743af5b9fb72
kalkins/plab-bbr
/color_sensob.py
1,993
3.703125
4
from math import floor from sensob import Sensob from sensors.camera import Camera class ColorSensob(Sensob): """A sensob that detects the amount of a given color in an image.""" expensive = True def __init__(self, color, threshold=0.3, cut_ratio=(0.5, 0.25, 0, 0.25)): """ Initialize the sensob. Arguments: color -- A RGB tuple of the color to look for threshold -- The amount of leeway for the color cut_ratio -- The amount of the image to crop before analysing. This is a tuple of ratios of the image, beginning at the top and going clockwise. For example, passing (0.1, 0.2, 0.3, 0.4) will cut 10% off the top, 20% off the right side, 30% off the bottom and 40% of the left. """ super().__init__() self.color = color self.threshold = threshold self.cut_ratio = cut_ratio self.camera = Camera() def update(self): """Take a picture with the camera, and analyse its color values.""" image = self.camera.update() width, height = image.size start_y = floor(height * self.cut_ratio[0]) stop_y = floor(height * (1-self.cut_ratio[2])) start_x = floor(width * self.cut_ratio[3]) stop_x = floor(width * (1-self.cut_ratio[1])) lower = [self.color[i] - 255*self.threshold for i in range(3)] upper = [self.color[i] + 255*self.threshold for i in range(3)] num_color_pixels = 0 num_pixels = (stop_x - start_x) * (stop_y - start_y) for x in range(start_x, stop_x): for y in range(start_y, stop_y): pixel = image.getpixel((x, y)) for i in range(3): if not lower[i] <= pixel[i] <= upper[i]: break else: num_color_pixels += 1 self.value = num_color_pixels / num_pixels
20d8c6f23ce7d9d66b06c0ad66cbd0eeef72e106
dbsgh9932/TIL
/list/06_list_append_insert.py
1,441
3.96875
4
# append() - 리스트의 끝에 새로운 요소 추가 / 리스트.append(새로 추가할 요소) a=[1,2,3,4] a.append(5) # a print(a) a.append([6,7]) print(a) # a.append(8,9) # 2개 이상 원소 불가 # print(a) # TypeError: list.append() takes exactly one argument (2 given) # 빈 리스트를 생성하고 요소 나중에 추가 values=[] values.append(10) values.append(20) values.append(30) print(values) # 사용자에게 5개의 값을 입력받아서 리스트에 저장하는 코드 scores=[] for i in range(5): num=int(input('값을 입력하세요 : ')) scores.append(num) print(i+1,'번째 결과',scores) print(scores) # 위 코드에서 입력받은 값을 각 요소로 출력하는 코드를 작성하시오. # 리스트 요소 출력 for j in range(len(scores)): print(scores[j]) # insert(위치,값) : 리스트 특정 위치에 요소 삽입 nums=[1,2,3,4,5] nums.insert(1,200) # 1은 1번 인덱스(2번째) 자리를 의미 print(nums) # 2번째 자리에 200이 들어가고 나머지는 뒤로 밀림 -> [1,200,2,3,4,5] nums.insert(-1,"홍길동") # 마지막 원소에 들어갔는데 마지막 자리의 5가 뒤로 밀려서 print(nums) # [1,200,2,3,4,홍길동,5] 라는 결과가 나옴 # insert로 맨 뒤에 삽입 nums.insert(len(nums),12.3) # 맨 뒤에 삽입은 길이를 선언 후 사용 -> 일반적으로 append()씀 print(nums) nums.insert(len(nums)-1,[10,20]) print(nums)
170907ad0f92f4ee2906b25b287d0136ccf5e452
gergo091/CodewarChallenge
/first.py
671
3.921875
4
import re def title_case(title, minor_words=None): if not minor_words: return title.title() else: splited_title = re.split("\\s", title.title()) splited_minor_words = re.split("\\s",minor_words.lower()) new_title = splited_title[0] for s in splited_title[1:]: if (s.lower() in splited_minor_words): new_title+=str(' '+s.lower()) else: new_title+=str(' '+s) return new_title if __name__ == "__main__": print title_case('a clash of KINGS','a an the of') print title_case('THE WIND IN THE WILLOWS', 'The In') print title_case('the quick brown fox')
d5029b798d9528d60577e197ca5dcf460379b6e0
Netmistro/Py-Practical-Problems
/Chapter 2/2.5.6.py
131
4.21875
4
# 6. Write a program that uses a for loop to print the numbers 100, 98, 96, . . . , 4, 2. for i in range(100, 0, -2): print(i)
66db4de1548f187d131f4e227182bf542a34a39f
wudongdong1000/Liaopractice
/practice_6.py
301
3.828125
4
#没搞太懂 def move(n, a, b, c): if n == 1: print('move', a, '-->', c) else: move(n-1, a, c, b) move(1, a, b, c) move(n-1, b, a, c) #计算移动了多少步 move(4, 'A', 'B', 'C') def f(n): if n==2: return 3 return f(n-1)*2+1 print(f(4))
8330dd686199cc1515e5595364a6d6fc22e245f6
ishan793/EE239-Big-Data-Analysis
/Project1_804587205_204617837_004589213_204587029/polynomial/plot_underfitting_overfitting.py
3,557
4.40625
4
""" ============================ Underfitting vs. Overfitting ============================ This example demonstrates the problems of underfitting and overfitting and how we can use linear regression with polynomial features to approximate nonlinear functions. The plot shows the function that we want to approximate, which is a part of the cosine function. In addition, the samples from the real function and the approximations of different models are displayed. The models have polynomial features of different degrees. We can see that a linear function (polynomial with degree 1) is not sufficient to fit the training samples. This is called **underfitting**. A polynomial of degree 4 approximates the true function almost perfectly. However, for higher degrees the model will **overfit** the training data, i.e. it learns the noise of the training data. We evaluate quantitatively **overfitting** / **underfitting** by using cross-validation. We calculate the mean squared error (MSE) on the validation set, the higher, the less likely the model generalizes correctly from the training data. """ #print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn import cross_validation import pickle from sklearn.metrics import mean_squared_error np.random.seed(0) #data = pickle.load( open( "housing_data.pickle", "rb" ) ) data=pickle.load(open('network.pickle','rb')) X=np.array(data['x'],dtype='float') y=np.array(data['y'],dtype='float') print X.shape n_samples=X.shape[0] y=np.reshape(y,(n_samples,1)) print y.shape degrees = [1] avg_score=[] fixed_score=[] X_test=X[0:50,:] y_test=y[0:50,:] X_train=X[51:,:] y_train=y[51:,:] #plt.figure(figsize=(14, 5)) '''for i in range(len(degrees)): #ax = plt.subplot(1, len(degrees), i + 1) #plt.setp(ax, xticks=(), yticks=()) polynomial_features = PolynomialFeatures(degree=degrees[i],interaction_only=True, include_bias=False) linear_regression = LinearRegression() pipeline = Pipeline([("polynomial_features", polynomial_features), ("linear_regression", linear_regression)]) #pipeline.fit(X,y) # Evaluate the models using crossvalidation scores = cross_validation.cross_val_score(pipeline, X, y, scoring="mean_squared_error", cv=10) scores=np.average((abs(scores)**0.5)) avg_score.append(scores) #plt.plot(X_test, true_fun(X_test), label="True function") #plt.scatter(X, y, label="Samples") #plt.xlabel("x") #plt.ylabel("y") #plt.xlim((0, 1)) #plt.ylim((-2, 2)) #plt.legend(loc="best") #plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( #degrees[i], -scores.mean(), scores.std())) #plt.show()''' '''print avg_score plt.scatter(degrees,avg_score) plt.show()''' plt.figure(figsize=(14,5)) for i in range(len(degrees)): ax=plt.subplot(1,len(degrees),i+1) plt.setp(ax,xticks=(),yticks=()) poly=PolynomialFeatures(degree=degrees[i]) X_train_trans = poly.fit_transform(X_train) X_test_trans = poly.fit_transform(X_test) regr =LinearRegression() regr.fit(X_train_trans,y_train) y_pred = regr.predict(X_test_trans) fixed_score.append((mean_squared_error(y_test,y_pred)**0.5)) #plt.plot(range(len(y_test)),(y_test-pipeline.predict(X_test)),range(len(y_test)),[0]*len(y_test)) print fixed_score plt.scatter(degrees,fixed_score) plt.show()
00feccb1bf7b8c15b0cc4b4c0e8f9d38d9065ed3
programming-practices/python
/src/main/python/Lista.py
6,907
4.28125
4
# Tanto las Tumpla como las listas son conjuntos ordenados de elementos, no asi los diccionarios. # Que son las listas: # Estructura de datos que nos permite almacenar grand cantidad de valores(equivalente a los array en todos lenguajes # de programacion. # En Python las listas pueden guardar diferentes tipos de valores(en otros lenguajes no ocurre esto con los array) # Se pueden expandir dinamicamente anadiendo nuevos elementos (otra novedad respecto a los arrays en otros lenguajes) # En la lista se puede guardar diferentes tipos # Una lista es similar a una tupla con la diferencia fundamental de que permite modificar los datos una ves creados. # Las listas se encierren entre corchetes []. lista_A = [4, 'Hola', 6.0, 99] # print('lista_A = ', lista_A) # print('Tupe de lista_A = ', type(lista_A)) # print('1--------------------------------------------') tupla_A = (4, 'Hola', 6.0, 99) # print('tupla_A = ', tupla_A) # print('Tupe de tupla_A = ', type(tupla_A)) # print('2--------------------------------------------') # print('tupla_A == lista_A ->',tupla_A == lista_A) # print('tupla_A[0] == lista_A[0] ->',tupla_A[0] == lista_A[0]) # print('3--------------------------------------------') miLista = ['Maria', 'Pepe', 'Marta', 'Antonio'] # Para aceder a todos elementos de la lista # print(miLista[:]) # Da una ERROR, este indice no existe # print(miLista[7]) # IndexError: list index out of range # print(miLista[0:10]) # Asi no le da IndexError #---------------------------------------------------- Una matriz ------------------------------------------------------- listaMatriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # print(listaMatriz) #------------------------------------------------ Modificacion de lista ------------------------------------------------ # Mientras que una tupla no permite modificar sus elementos, una lista si # print('Antes ',lista_A) lista_A[0] = 0.0 # print('Despues ',lista_A) # print('Antes ', listaMatriz) # listaMatriz[1] = 2 # listaMatriz[1] = None listaMatriz[1] = ['A', 'B', 'C'] # print('Despuse ', listaMatriz) # print('Antes ', listaMatriz) listaMatriz[1][0] = 'A' listaMatriz[1][0] = ['A', 'Z'] # print('Despuse ', listaMatriz) #------------ Acceso a los elementos de la secuencias ---------- # Los elementos de las secuencias pueden ser accedidos(indexados) mediante el uso de corchetes: lista[<index>] # En Python, la indexacion se empieze por 0, es decir, el primer elemento tiene indice cero. # print(lista_ordenada[0]) # Podemos indexar las secuencias utilisando la sintaxis: lista[<inicio>:<final>:<salto>] lista_ordenada = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # print(lista_ordenada[1:4]) # print(lista_ordenada[1:5:2]) # print(lista_ordenada[1:6:2]) # v ciomy exemplo 2 oznacae.... wchob zrozymitu treba duvutus exemplos # VNIMANIE Nety vuxoda za razmer lista # print(len(lista_ordenada)) # print(lista_ordenada[1:8]) # print(lista_ordenada[1:9]) # print(lista_ordenada[1:10]) # print(lista_ordenada[1:100]) # Asi no le da IndexError # Desde el primero hasta el 3 # print(lista_ordenada[:3]) # Desde el primero hasta el ultimo, saltando de 2 en 2: # print(lista_ordenada[::2]) # Desde el primero hasta el 4, saltando de 2 en 2: # print(lista_ordenada[:4:2]) # Desde el 2 hasta el ultimo, saltando de 2 en 2: # print(lista_ordenada[2::2]) # Forma inversa de acceso a una secuencia (de atras hacia adelante): Se usa una indice negativo. # print(lista_ordenada[-1]) # print(lista_ordenada[-2]) # print(lista_ordenada[-3]) # print(lista_ordenada[-3:-1]) # Los elementos de una lista o tupla pueden ser de cualquier tipo, incluyendo otra lista o tupla datosL = [['1', '2', '3'], 'Hola', 4] # print(datosL) sL = datosL[0][1] # print(sL) # print(type(sL)) #----------------------------------------------- Operaciones sobre listas ---------------------------------------------- # Crear una lista a partir de una tupla tupla_q = (2,3,1) lista_T = list(tupla_q) # print(lista_T) # Anadir un elemento, al final de la lista, con append() lista_Sem = ['lunes', 'jueves'] # print(lista_Sem) lista_Sem.append('viernes') # print(lista_Sem) # Anadir un elemento, en una determinada position, con insert() lista_Sem.insert(1, 'martes') # print(lista_Sem) # Funcion extend muy parasida a concatenacion, agrega todos elementos indicados en parametros al final de la lista lista_Sem.extend([1, 2, 3, 4, 5]) # print(lista_Sem) # Eliminar el elemento de la lista de un determinado posicion con pop(): e = lista_Sem.pop(3) # print(lista_Sem) # print(e) # e vale 'viernes' y lista vale ['lunes', 'martes', 'jueves'] # Si usar funcion pop sin parametros, ella va eliminar ultimo elemento en la lista # print(lista_Sem) lista_Sem.pop() # print(lista_Sem) # Elimina un elemento a partir de su valor con remove(). Methodo remove() borra primera occurencia # print(lista_Sem) # lista_Sem.remove('lunes') # functio remove nose puede usar sin argumentos # lista_Sem.remove() #TypeError:F remove() takes exactly one argument (0 given) # print(lista_Sem) # Funcion index nos auyda saber en que indice se encuentra value que buscamos # print(lista_Sem.index("jueves")) # print(lista_Sem.index(5)) # print(lista_Sem.index("Cara")) # ValueError: 'Cara' is not in list # Si se repiten los values en la lista, la funcion index devuelve primer indice que encuentre lista_Sem.insert(7, 'martes') # print(lista_Sem) # print(lista_Sem.index('martes')) # Para comprobar si existe value en la lista se usa in # print(5 in lista_Sem) # print('martes' in lista_Sem) # print('R' in lista_Sem) # Metodo count permite buscar la cantidad de mizmos elementos, es decir cuantos elementos(que se pasan como parametro) # iguales existen en la lista myLista = ['q', 'e', 't', 'q', 'c', 'q'] # print(myLista.count('q')) # Method len() le dice la longitud de lista # print(len(myLista)) # Ordenar una lista con funccion sort(). No es necesario crear una lista nueva. listaS = [8, 34, 56, 1, 9, 78, 78.5, 3, 18, 23, 21, 12, 10, 2, 3] # print(max(listaS)) # print(listaS) listaS.sort() # print(listaS) # Generar listas con range. range() solo admite enteros # inicio,fin,paso # print(list(range(11))) # print(list(range(0,11))) # print(list(range(0,11,2))) #----------------------------------- Concatenacion de listas con + -------------------------------------------- # Estas operaciones no modifican las secuencias originales. lista_1 = [1,2,3,4,5] lista_2 = [11,22,33,44,55] lista_result = lista_1 + lista_2 # print(lista_result) lista_result2 = [1, 2, 3] + [4, 5, 6] # print(lista_result2) #--------------------------------------------- Replication (*) de secuencias ------------------------------------------- # Estas operaciones no modifican las secuencias originales. l = lista_1 * 4 # print(l) #--------------------------------------------------- Help -------------------------------------------------------------- # help(list.remove) # help(list)
3680bb1c5c4f941e709cd7bca19c16b67366d30c
ahsankhan530/python-practice
/Assignment-5.10.py
244
3.640625
4
current_users=['Ahsan','KASHIF','jawad','abbas','daim'] new_users=[str(input())] for new_user in new_users : if new_user in current_users : print(new_user,"is available") else: print(new_user,"is not available")
66e4913262b9bdb6df83bd4ba34a1169e107ba85
panditdandgule/DataScience
/Other/Projects/Dictonary/DictfromkeysAndUpdate.py
621
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 24 15:54:08 2019 @author: pandit """ #fromkeys() and update() #Intializing dictionary 1 dic1={'Name':'Nandini','Age':19} #Initializing dictionary 2 dic2={'ID':2541997} #Initizlizing sequance sequ=('Name','Age','ID') #Using update to add dic2 values in dic 1 dic1.update(dic2) #printing the updated dictionary values print("The updated dictionary is: ") print(str(dic1)) #using fromkeys() to transform sequence into dictionary dict=dict.fromkeys(sequ,5) #printing new dictionary values print("The new dictionary values are: ") print(str(dict))
c8e485c0acc87b563df03e2a54d0f8f82246220e
duy2001x1/nguyenquangduy-fundamentals-c4e14
/session3/homework/sheep.py
1,027
3.859375
4
sheep = [5, 7, 300, 90, 24, 50, 75] print("Hello, my name is Duy and these are my flook: ") print(sheep, sep = ', ') print() sheep_boss = max(sheep) print("Now my biggest sheep has size",sheep_boss,"!", "Let's shear it!") ind = sheep.index(max(sheep)) default = 8 sheep[ind] = default print("After shearing, here is my flock: ") print(sheep, sep = ', ') print() months = int(input("How many months? ")) for a in range(months): print("MONTH", a + 1, ":") for i in range(len(sheep)): growth = sheep[i] + 50 sheep[i] = growth print("One month has passed, now here is my flock: ") print(sheep, sep = ', ') sheep_boss = max(sheep) print("Now my biggest sheep has size",sheep_boss,"!", "Let's shear it!") ind = sheep.index(max(sheep)) default = 8 sheep[ind] = default print("After shearing, here is my flock: ") print(sheep, sep = ', ') print() print("My flock has size in total: ", sum(sheep)) print("I would get ", sum(sheep), "* 2$ =", sum(sheep) * 2, "$")
e065555c5f291f462cfccbc461106026f6c0aa9f
snlab/odl-summit-2016-tutorial-vm
/utils/Maple_Topo_Scripts/exampletopo.py
1,676
3.640625
4
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo from mininet.util import quietRun class MyTopo( Topo ): "Simple topology example." def __init__( self ): "Create custom topo." # Initialize topology Topo.__init__( self ) # Add hosts and switches Host1 = self.addHost( 'h1' ) Host2 = self.addHost( 'h2' ) Host3 = self.addHost( 'h3' ) Host4 = self.addHost( 'h4' ) Host6 = self.addHost( 'h6' ) Switch1 = self.addSwitch( 's1' ) Switch2 = self.addSwitch( 's2' ) Switch3 = self.addSwitch( 's3' ) Switch4 = self.addSwitch( 's4' ) # Add links self.addLink( Host1, Switch1 ) self.addLink( Host3, Switch1 ) self.addLink( Host2, Switch4 ) self.addLink( Host4, Switch4 ) self.addLink( Host6, Switch4 ) self.addLink( Switch1, Switch2 ) self.addLink( Switch1, Switch3 ) self.addLink( Switch2, Switch4 ) self.addLink( Switch3, Switch4 ) # h1 = nt.get('h1') # h1.cmd( 'ifconfig h1-eth0 192.168.1.10' ) # Host2.cmd( 'ifconfig h2-eth0 192.168.1.20' ) # Host3.cmd( 'ifconfig h3-eth0 10.0.0.2' ) # Host4.cmd( 'ifconfig h4-eth0 10.0.0.3' ) # leftSwitch.cmd( 'ifconfig s1-eth2 192.168.1.1' ) # rightSwitch.cmd( 'ifconfig s2-eth2 192.168.1.2' ) topos = { 'mytopo': ( lambda: MyTopo() ) }
e63e4d6a4b4272a44249d7224f64b6377ba30d2b
sahansera/algo-src
/problems/common_elements_sorted_arrays/run-no-ds.py
936
3.984375
4
# No DS and onnly using pointers def common_elements(list1, list2): result = [] p1 = 0 p2 = 0 # we can't rely on the array length. hence, while while p1 < len(list1) and p2 < len(list2): if list1[p1] == list2[p2]: result.append(list1[p1]) p1 += 1 p2 += 1 elif list1[p1] > list2[p2]: p2 += 1 else: p1 += 1 return result # NOTE: The following input values will be used for testing your solution. list_a1 = [1, 3, 4, 6, 7, 9] list_a2 = [1, 2, 4, 5, 9, 10] #print common_elements(list_a1, list_a2) should return [1, 4, 9] (a list). list_b1 = [1, 2, 9, 10, 11, 12] list_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15] print common_elements(list_b1, list_b2) #should return [1, 2, 9, 10, 12] (a list). list_c1 = [0, 1, 2, 3, 4, 5] list_c2 = [6, 7, 8, 9, 10, 11] # common_elements(list_b1, list_b2) should return [] (an empty list).
54963f02efb2c3d9712229d20664fca2fb38e406
SereDim/Trash
/36.py
537
4.03125
4
''' Знайти суму додатніх елементів лінійного масиву цілих чисел. Розмірність масиву - 10. Заповнення масиву здійснити з клавіатури. Серебренніков Дмитро ''' c=0# for a in range(10):#диапазон b=int(input())#ввод if b>=0:#условие при котором будут сумироватся только положительные числа c=c+b#сумма print(c)# ####################################
6cbafa6915d044d467fe62a06c1f41a4bd26fc64
oakoak/5_lang_frequency
/lang_frequency.py
1,287
3.609375
4
import string from collections import Counter import sys import argparse def load_data(filepath): with open(filepath, "r") as file: return file.read() def get_most_frequent_words(text, number_of_words): all_words = filter(None, [word.strip(string.punctuation) for word in text.lower().split()]) most_frequent_words = Counter(all_words).most_common(number_of_words) return most_frequent_words def pprint_words(most_frequent_words): for word, count in most_frequent_words: print(word, ":", count) def get_parser_args(): parser = argparse.ArgumentParser(description="Most frequent words in text") parser.add_argument( "path", help="path for .txt file", ) parser.add_argument( "number", type=int, nargs="?", default=10, help="count of encountered words in text" ) arguments = parser.parse_args() return arguments if __name__ == "__main__": arguments = get_parser_args() try: text = load_data(arguments.path) except FileNotFoundError: exit("ERROR : file '{}' not found\n".format(arguments.path)) most_frequent_words = get_most_frequent_words(text, arguments.number) pprint_words(most_frequent_words)
9ccd30bb1c2f91c954f35cbe9f6af6c75c0b96ec
xcsp3team/pycsp3
/problems/csp/single/Dinner.py
679
3.734375
4
""" My son came to me the other day and said, "Dad, I need help with a math problem." The problem went like this: - We're going out to dinner taking 1-6 grandparents, 1-10 parents and/or 1-40 children - Grandparents cost $3 for dinner, parents $2 and children $0.50 - There must be 20 total people at dinner and it must cost $20 How many grandparents, parents and children are going to dinner? Execution: python3 Dinner.py """ from pycsp3 import * # g is the number of grandparents g = Var(range(1, 7)) # p is the number of parents p = Var(range(1, 11)) # c is the number of children c = Var(range(1, 41)) satisfy( g * 6 + p * 2 + c * 1 == 40, g + p + c == 20 )
e8682307d0780ac047907e6f9f11ed73ae4ef743
AnjalBam/IWassign-data-types-functions-python
/data_types/5_add_ing_or_ly.py
621
4.5625
5
""" 5. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Sample String : 'abc' Expected Result : 'abcing' Sample String : 'string' Expected Result : 'stringly' """ sample_str = 'string' # input can be varied def add_ing_or_ly(word): if len(word) < 3: return word else: if word[-3:] == 'ing': return word + 'ly' else: return word + 'ing' print(add_ing_or_ly(sample_str))
9d9c25d7efbee35e1cd76b14ab9fea79301c096f
pedr0diniz/cevpython
/PythonExercícios/ex095 - Aprimorando os Dicionários.py
2,236
3.984375
4
# DESAFIO 095 - Aprimore o DESAFIO 093 para que ele funcione com VÁRIOS JOGADORES, incluindo um sistema de visuali- #zação de DETALHES DO APROVEITAMENTO de cada jogador. dicio = {} partidas = idjog = 1 gols = [] controle = 'S' jogadores = [] while controle == 'S': dicio['nome'] = str(input('Nome do Jogador: ')) partidas = int(input(f'Quantas partidas {dicio["nome"]} jogou? ')) for i in range(0, partidas): gols.append(int(input(f'Quantos gols na partida {i+1}? '))) dicio['gols'] = gols.copy() dicio['total'] = sum(gols) jogadores.append(dicio.copy()) gols.clear() #se eu não der um clear nos gols, eles irão se acumulando nos termos seguintes dicio.clear() controle = str(input('Quer continuar? [S/N] ')).strip().upper()[0] while controle not in 'SN': controle = str(input('Opção inválida! \nDigite S ou N: ')).strip().upper()[0] print('-=' * 40) print(jogadores) print('Nº Nome Gols Total') print('-----------------------------------------------') for i, jogador in enumerate(jogadores): print(f'{i+1:<3} ',end='') for v in jogador.values(): #não preciso das keys, posso usar .values() ao invés de .items() print(f'{str(v):<18}',end =' ') #precisei converter tudo pra string pra mostrar #tava dando erro ao tentar espaçar s impressão da lista de gols print() print('-----------------------------------------------') while 0 < idjog <= len(jogadores) or idjog == 999: idjog = int(input('Mostrar dados de qual jogador [999 para parar]? ')) while idjog < 1 or (idjog > len(jogadores) and idjog != 999): print('Jogador não encontrado!') idjog = int(input('Mostrar dados de qual jogador [999 para parar]? ')) if idjog == 999: break print(f' -- Levantamento do jogador {jogadores[idjog-1]["nome"]}: ') for i, gols in enumerate(jogadores[idjog - 1]['gols']): # ACESSANDO A LISTA DE GOLS DO jogador [idjog-1] print(f' No jogo {i + 1} fez {gols} gols.') # IMPRIMINDO CADA GOL DENTRO print('-----------------------------------------------') # DA CÉLULA "GOLS" DO JOGADOR NA print('<< ENCERRADO >>') # CÉLULA[idjog-1] DA LISTA jogadores[]
c56d4b94b95e82c801bfc1ee556a5a83f413073a
WinrichSy/HackerRank-Solutions
/Python/Collections.OrderedDict.py
511
3.96875
4
#Collections.OrderedDict() #https://www.hackerrank.com/challenges/py-collections-ordereddict/problem from collections import OrderedDict items = int(input()) ordered_dict = OrderedDict() for i in range(items): item_price = input().split() item = ' '.join(item_price[0:-1]) price = int(item_price[-1]) if item not in ordered_dict.keys(): ordered_dict[item] = price else: ordered_dict[item] += price for key, val in ordered_dict.items(): print('{} {}'.format(key, val))
6a6716391aae23c09e74170692f8bd6debe4339a
Visheshjha09/project_sorting_visualization_using_python_gui
/quickSort.py
2,403
4.125
4
#Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and #partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. #Always pick first element as pivot. #Always pick last element as pivot (implemented below) #Pick a random element as pivot. #Pick median as pivot. #The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) #before x, and put all greater elements (greater than x) after x. All this should be done in linear time. import time def partition(data, head, tail, drawData, timeTick): border = head pivot = data[tail] drawData(data, getColorArray(len(data), head, tail, border, border)) time.sleep(timeTick) for j in range(head, tail): if data[j] < pivot: drawData(data, getColorArray(len(data), head, tail, border, j, True)) time.sleep(timeTick) data[border], data[j] = data[j], data[border] border += 1 drawData(data, getColorArray(len(data), head, tail, border, j)) time.sleep(timeTick) #swap pivot with border value drawData(data, getColorArray(len(data), head, tail, border, tail, True)) time.sleep(timeTick) data[border], data[tail] = data[tail], data[border] return border def quick_sort(data, head, tail, drawData, timeTick): if head < tail: partitionIdx = partition(data, head, tail, drawData, timeTick) #LEFT PARTITION quick_sort(data, head, partitionIdx-1, drawData, timeTick) #RIGHT PARTITION quick_sort(data, partitionIdx+1, tail, drawData, timeTick) def getColorArray(dataLen, head, tail, border, currIdx, isSwaping = False): colorArray = [] for i in range(dataLen): #base coloring if i >= head and i <= tail: colorArray.append('gray') else: colorArray.append('white') if i == tail: colorArray[i] = 'blue' elif i == border: colorArray[i] = 'red' elif i == currIdx: colorArray[i] = 'yellow' if isSwaping: if i == border or i == currIdx: colorArray[i] = 'grey2' return colorArray
631080fdd12a02c3f77d9a9a4dba5535604c8045
ParulProgrammingHub/assignment-1-bansiundhad
/q7.py
307
4.4375
4
# program to calculate third angle using function angle1=input("enter the 1st angle :") angle2=input("enter the 2nd angle :") def thirdangle(angle1,angle2): angle=180-(angle1+angle2) return angle print "the third angle is :%s" %thirdangle(angle1,angle2) r=raw_input("press any key to exit")
4e7b68984abf439ec9237b9a0c9f3e0aeb8bbe47
Hoon94/Algorithm
/Programmers/단속카메라.py
400
3.53125
4
def solution(routes): routes = sorted(routes, key=lambda x: x[1]) last_camera = -30000 answer = 0 for route in routes: if last_camera < route[0]: answer += 1 last_camera = route[1] return answer if __name__ == "__main__": # Test case 1 routes = [[-20, 15], [-14, -5], [-18, -13], [-5, -3]] # result 2 print(solution(routes))
039da223b1fe70e997d677b225ab46453a9d5b82
used-for-me/ProjectName
/windows下的编程/SystemChangeManager/findfile.py
620
3.59375
4
import os import os.path # os.chdir('/') # # print([filename for filename in os.listdir('./')]) my_path = [] def list_dir_depth(directory): for filename in os.listdir(directory): path = os.path.join(directory, filename) if os.path.isfile(path): my_path.append('f_'+path) elif os.path.isdir(path): my_path.append('d_'+path) try: list_dir_depth(path) except PermissionError: break finally: print(path) if __name__ == '__main__': list_dir_depth('/') print(my_path)
af6da1dfb4a369e98ea0d896afaa1a2766a16d93
saipavans/programming_winter
/winter_lab_4/ATask1.py
832
4.125
4
def capitalize_all(t): res = [] for s in t: res.append(s.capitalize()) return res def check_nested_list(input_list): for element in input_list: if isinstance(element, list): return True return False def capitalize_nested(nested_string_list): res = [] if isinstance(nested_string_list, list): if check_nested_list(nested_string_list): for element in nested_string_list: if isinstance(element, list): res = res + (capitalize_nested(element)) else: res.append(element.capitalize()) else: ## List, but not nested res = res + (capitalize_all(nested_string_list)) return res input = ["python", "course", ["dalhousie", "inwk"]] print(capitalize_nested(input))
864928c047602e58e6091b5ca0350ac198187cb6
akshaykumar34/Email-slicer
/EMAIL SLICER.py
230
4
4
email=input("What is the email address:").strip() user = email[:email.index("@")] domain = email[email.index("@")+1:] output = "Your email is {} and your username is {} and domain is {}".format(email,user,domain) print(output)
149ee84b0a9fca234751783908dd1e92b84ae856
BobcatsII/pyscript
/test2.py
681
3.78125
4
import random times = 0 total = 0 while True: choise = input('1.begin,2.close\n') if choise == 1: total += 1 num = random.randint(1,50) while True: gue = int(input("please guess my input:")) times += 1 if gue > num: print "too big" elif gue < num: print "too small" else: print "good , u guess right" break print "total guess number of %s round, you guess number of %s times, you guess right %s " %(total, times, float(total)/times) elif choise == 2: break else: print "please input right num"
8ff10312196ea5bd89c6b036f094aa707dfb149d
manas1410/Spectrum-Internship_2020
/Write a python program to print all the prime number in a given interval and also check is a given input number is prime or not..py
1,049
4.3125
4
#Write a python program to print all the prime number in a given interval and also check is a given input number is prime or not. def prime(x):#function to check a number is prime or not c=0#counter value for i in range(1,x+1): if(x%i==0): c=c+1 if(c==2): return (True) else: return (False) if __name__=="__main__":#main function n=int(input("Enter the starting Number:"))#stores the starting number m=int(input("Enter the ending Number:"))#stores the ending number v=int(input("Enter Number which you want to check:"))#stores the number which you want to check print("Prime Numbers from {} to {} are:".format(n,m),end='') for i in range(n,m+1): if(prime(i)==True): print(i,end=',')#print the prime number in the interval if(prime(v)==True): print("\n{} is a prime number".format(v))#print if it is a prime number else: print("\n{} is not a prime number".format(v))#print it is not a prime number
b2d7299f532847b901829b17f18c20e8d34708d2
jcspencer/s1_algs
/recursion/binary_search.py
757
4.15625
4
def recursive_binary_search(a_list, target, low, high): # make sure the list is sorted a_list = sorted(a_list) def recursion(first, last): # find the middle index of the segment # we're searching in mid = (first + last) // 2 if first > last: # not allowed return None elif (a_list[mid] < target): # item is greater than the middle, # so we only need to look at the right # half of the current list return recursion(mid + 1, last) elif (a_list[mid] > target): # item is less than the middle, # so we only need to look at the left # half of the current list return recursion(first, mid - 1) else: # found it! return mid return recursion(low, high)
b858f57d2728a06e3608081fd9bded30392d62d1
imlifeilong/MyAlgorithm
/leetcode/动态规划/279. 完全平方数.py
821
3.671875
4
''' 输入:n = 12 输出:3 解释:12 = 4 + 4 + 4 ''' class Solution: def numSquares(self, n: int) -> int: res = self.process(1, n) print(res) def process(self, index, n): # 目标值为0时,已经被分配完 if n == 0: return 0 # 当前值平方大于目标值时,需要舍弃这个分支,返回无穷大(因为要取最小值) if index * index > n: return float('inf') # 选择当前值,选择后可以继续选择当前值, 目标值减去当前值 p1 = self.process(index, n - index * index) + 1 # 不选当前值,去下个位置 p2 = self.process(index + 1, n) return min(p1, p2) if __name__ == '__main__': s = Solution() n = 12 n = 17 s.numSquares(n)
abc9e63c63e8e6da3ab6f7fb4edf5dc53604a11a
MRS88/python_basics
/week_4_functions/triangle_perimeter.py
965
4.375
4
''' Напишите функцию, вычисляющую длину отрезка по координатам его концов. С помощью этой функции напишите программу, вычисляющую периметр треугольника по координатам трех его вершин. Формат ввода На вход программе подается 6 целых чисел — координат x₁, y₁, x₂, y₂, x₃, y₃ вершин треугольника. Все числа по модулю не превосходят 30 000.''' from math import sqrt def perimeter(ax, ay, bx, by, cx, cy): ab = sqrt((bx-ax)**2 + (by-ay)**2) ac = sqrt((cx-ax)**2 + (cy-ay)**2) bc = sqrt((cx-bx)**2 + (cy-by)**2) return ab + ac + bc ax, ay = int(input()), int(input()) bx, by = int(input()), int(input()) cx, cy = int(input()), int(input()) print(perimeter(ax, ay, bx, by, cx, cy))
69aeb8c0fd889063fa2bd55d5b071ffb17b8def3
manisha54/TestProject1
/functionality/six.py
160
4.125
4
''' Q.No.6 Write a Python program to reverse a string. ''' ''' a=input("enter a string: ") print(a[::-1]) ''' str=input("enter a sentence: ") print(str[::-1])
076f67bd4b747d7e418764cbc97bb605397d01d0
2Clutch/briefcase
/src/briefcase/console.py
1,586
4.5
4
import operator def select_option(options, input=input, prompt='> ', error="Invalid selection"): """ Prompt the user for a choice from a list of options. The options are provided as a dictionary; the values are the human-readable options, and the keys are the values that will be returned as the selection. The human readable options will be sorted before display to the user. This method does *not* print a question or any leading text; it only prints the list of options, and prompts the user for their choice. If the user chooses an invalid selection (either provides non-integer input, or an invalid integer), it prints an error message and prompts the user again. :param options: A dictionary of options to present to the user. :param input: The function to use to retrieve the user's input. This exists so that the user's input can be easily mocked during testing. :param prompt: The prompt to display to the user. :param error: The error message to display when the user provides invalid input. :returns: The key corresponding to the user's chosen option. """ ordered = list( sorted( options.items(), key=operator.itemgetter(1) ) ) for i, (key, value) in enumerate(ordered, start=1): print(' {i}) {label}'.format(i=i, label=value)) print() while True: try: selection = int(input(prompt)) return ordered[selection - 1][0] except (ValueError, IndexError): print(error)
1b7becbda936221e6cd6b66c6e9c42f0fa53ad76
kilala-mega/coding-pattern
/rotation-count.py
553
3.890625
4
def count_rotations(nums: List[int]) -> int: if not nums: return 0 start, end = 0, len(nums)-1 if nums[start] <= nums[end]: return 0 while start + 1 < end: mid = (start + end)//2 if nums[mid] >= nums[start]: start = mid else: end = mid if nums[start] < nums[end]: return start else: return end def main(): print(count_rotations([10, 15, 1, 3, 8])) print(count_rotations([4, 5, 7, 9, 10, -1, 2])) print(count_rotations([1, 3, 8, 10])) main()
f889df8bc101874db1d53fc49382ece5e6d43a3b
KoralK5/ScienceFair2021
/NeuralNetwork/Games/Snake/snakeNNgame.py
3,873
3.71875
4
import random import snakeNN import time import os import keyboard from copy import deepcopy def show(arr): for row in arr: print(''.join(row)) def putApple(arr): x, y = [], [] for row in range(len(arr)): for col in range(len(arr[row])): if arr[row][col] == '⬛': x += [row] y += [col] elif arr[row][col] == '🍎': arr[row][col] = '⬛' point = random.randint(0, len(x)-1) arr[x[point]][y[point]] = '🍎' return arr def go(arr, head, tail): if head[2] == 'W': try: if arr[head[0]-1%10][head[1]] == '🍎': arr[head[0]-1%10][head[1]] = '🟩' head[0] -= 1 return putApple(arr), tail elif arr[head[0]-1%10][head[1]] == '🟩': return 0, 0 else: arr[head[0]-1%10][head[1]] = '🟩' arr[tail[0][0]][tail[0][1]] = '⬛' tail = tail[1:] head[0] -= 1 return arr, tail except: return 0, 0 elif head[2] == 'S': try: if arr[(head[0]+1)%10][head[1]] == '🍎': arr[(head[0]+1)%10][head[1]] = '🟩' head[0] += 1 return putApple(arr), tail elif arr[(head[0]+1)%10][head[1]] == '🟩': return 0, 0 else: arr[(head[0]+1)%10][head[1]] = '🟩' arr[tail[0][0]][tail[0][1]] = '⬛' tail = tail[1:] head[0] += 1 return arr, tail except: return 0, 0 elif head[2] == 'A': try: if arr[head[0]][(head[1]-1)%10] == '🍎': arr[head[0]][(head[1]-1)%10] = '🟩' head[1] -= 1 return putApple(arr), tail elif arr[head[0]][(head[1]-1)%10] == '🟩': return 0, 0 else: arr[head[0]][(head[1]-1)%10] = '🟩' arr[tail[0][0]][tail[0][1]] = '⬛' tail = tail[1:] head[1] -= 1 return arr, tail except: return 0, 0 elif head[2] == 'D': try: if arr[head[0]][(head[1]+1)%10] == '🍎': arr[head[0]][(head[1]+1)%10] = '🟩' head[1] += 1 return putApple(arr), tail elif arr[head[0]][(head[1]+1)%10] == '🟩': return 0, 0 else: arr[head[0]][(head[1]+1)%10] = '🟩' arr[tail[0][0]][tail[0][1]] = '⬛' tail = tail[1:] head[1] += 1 return arr, tail except: return 0, 0 def binarize(arr, head, tail): inputs = [] for row in range(len(arr)): for col in range(len(arr[row])): if arr[row][col] == '⬛': inputs += [0] elif arr[row][col] == '🟩': inputs += [0.5] elif arr[row][col] == '🍎': inputs += [10] apple = [row, col] elif [row, col] == [head[0], head[1]]: inputs += [2] elif [row, col] == [tail[0][0], tail[0][1]]: inputs += [1] inputs += [abs(head[0]%10 - apple[0]) + abs(head[1]%10 - apple[1])] return inputs def points(arr, head): for row in range(len(arr)): for col in range(len(arr[row])): if arr[row][col] == '🍎': return (10 - abs(head[0]%10-row) + 10 - abs(head[1]%10-col))/20 def play(weights, inp, net, t, costBatch, disp): arr = [['⬛']*10 for row in range(10)] arr[4][4] = '🟩' arr[4][5] = '🟩' arr[4][6] = '🟩' arr[4][7] = '🟩' arr = putApple(arr) head, tail = [4,7,'D'], [[4,4],[4,5],[4,6],[4,7]] ite, wait, score, prevScore, speed = 0, 0, 0, 0, 0 while arr != 0 and wait < (len(tail)-3)*10: score = len(tail)-4 + points(arr, head) if disp: print('Generation:', inp) print('Network:', net) print(f'Time: {t}s') print('\nBest:', max(costBatch)) print('Score:', score) show(arr) if keyboard.is_pressed('s'): speed = abs(speed-1) time.sleep(speed) os.system('cls') if score == prevScore: wait += 1 else: wait = 0 ite += 1 tail += [[head[0], head[1]]] head[2] = snakeNN.neuralNetwork(binarize(arr, head, tail), weights) arr, tail = go(arr, head, tail) prevScore = score return score
95e89d793c1bbc9cafc028cd205ca0db6740020e
OishinSmith/Python-exercises
/2017-02-10/ca117/smitho25/beststudent_v1_22.py
496
3.5625
4
import sys try: with open(sys.argv[1], "r") as f: highest_mark = 0 lines = f.readlines() for sentence in lines: sentence = sentence.strip().split(" ") if int(sentence[0]) > int(highest_mark): highest_mark = sentence[0] best_student = " ".join(sentence[1:]) print("Best student: " + best_student) print("Best mark: " + str(highest_mark)) except FileNotFoundError: print('The file {:s} does not exist.'.format(sys.argv[1]))
699b65b08e547f990563db87c79e6534b238f200
domoramas/code_guild_projects
/python labs/lab19_2.py
785
3.84375
4
#black jack advice def blackjack_adv(x,y,z): card_dict = { "A" : 1, "2": 2, "3" : 3, "4": 4, "5": 5, "6" : 6, "7": 7, "8": 8, "9" : 9, "10" : 10, "J": 10, "Q": 10, "K": 10 } total = (card_dict[x] + card_dict[y] + card_dict[z]) if total < 12 and "A" in (x,y,z): total = total + 10 if total < 17: print(f"{total} Hit") elif total >= 17 and total <21: print(f"{total} Stay") elif total == 21: print(f"{total} Blackjack!") elif total > 21: print(f"{total} Already Busted") first_card = input("What's your first card?: ").upper() second_card = input("What's your second card?: ").upper() third_card = input("What's your third card?: ").upper() blackjack_adv(first_card,second_card,third_card)
e088abbe422968c52de87f173ae5a055cfc52e8b
zhd785576549/py-utils
/py_utils/validator/phone/cn.py
1,012
3.515625
4
""" This is validate for phone in China Author: Winter History: Version Author Email Date Message 1.0.0 Winter 785576549@qq.com 2019-10-10 Create """ import re def mobile_valid(mobile): """ Mobile phone number validator :param mobile: [str] Mobile phone number :return: """ r = re.match(r"^1[345789]\d{9}$", mobile) if r: return True else: return False def telephone_valid(telephone): """ Whole station telephone number validator :param telephone: [str] Telephone number :return: """ r = re.match(r"0\d{2,3}-\d{7,8}", telephone) if r: return True else: return False def tj_telephone_valid(telephone): """ TianJin telephone number validator :param telephone: [str] Telephone number :return: """ r = re.match(r"^022-\d{7,8}$", telephone) if r: return True else: return False
4085c413e1fe017f149ae36ee236b914c4752801
Aasthaengg/IBMdataset
/Python_codes/p03555/s167958170.py
277
3.8125
4
# 文字列を取得 C1 = str(input()) C2 = str(input()) # 文字列の結合 ori_str = C1 + C2 # 末尾から1文字ずつ取得して逆さま文字を生成 rev_str = ori_str[-1::-1] # 比較結果を出力 if ori_str == rev_str: print("YES") else: print("NO")
f886751d183fd3f7f477728e1e031df9c8b76c62
decadevs/use-cases-python-lere01
/instance_methods.py
1,611
4.5
4
# Document at least 3 use cases of instance methods """ Instance methods are methods that are which are called on the object (instance) of a class. Through the 'self' parameter, they have access to all attributes and other methods on the same object. Hence, class methods can modify the said attributes. The instance methods are used most of the time. Note: Like 'cls', 'self' is a convention. You might as well use 'jackass' as long as it is the first parameter/argument of the method """ import math # a class of Vehicles class Vehicle: def __init__(self, maker, model, year, color): self.maker = maker self.model = model self.year = year self.color = color def display_details(self): return 'Make: {}, Model: {}, Year: {}, Colour: {}'.format(self.maker, self.model, self.year, self.color) # A class of circles class Cirlce: def __init__(self, radius, circumference = 0, area = 0): self.radius = radius self.area = area self.circumference = circumference def calculate_area(self): self.area = (2 * math.pi) * (self.radius ** 2) return self.area def calculate_circumference(self): self.circumference = (2 * math.pi) * (2 * self.radius) return self.circumference # A class of trousers class Trousers: def __init__(self, waist_size, length, color): self.waist_size = waist_size self.length = length self.color = color def details(self): return "Waist Size: {}, Length: {}, Colour: {}".format(self.waist_size, self.length, self.color)
d0cee4073f5e7054da8edaf68798d89b6fad9a0c
fxmike/bootcamp
/github challenge/#17.py
728
3.78125
4
# Question: # Write a program that computes the net amount of a bank account based a transaction # log from console input. The transaction log format is shown as following: # D 100 # W 200 # # D means deposit while W means withdrawal. # Suppose the following input is supplied to the program: # D 300 # D 300 # W 200 # D 100 # Then, the output should be: # 500 account = 0 while True: q = input("D or W: ") q2 = input("How much: ") if q.lower() == "d" and q2.isdigit(): account += int(q2) elif q.lower() == "w" and q2.isdigit(): account -= int(q2) elif q == "" and q2 == "": break else: print("Nie podałeś właściwej danej") continue print(account) #DONE!
5b70c992903e842a2067c2beac039cc064d41207
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/kindergarten-garden/30aafd1f62114511acff8d7b05c32bce.py
796
3.5625
4
class Garden(): def __init__(self, diagram, students=None): self.diagram = diagram.split('\n') if students: self.students = students self.students.sort() else: self.students = ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry'] self.plantnames = {'V':'Violets', 'R':'Radishes', 'C':'Clover', 'G':'Grass'} def plants(self, student): snum = self.students.index(student) plants = [] for row in self.diagram: for i in range(2): plants.append(self.plantnames[row[2*snum+i]]) return plants
014875c654d4ed3b125fab06b92979a9b5d6620c
Madara701/Python_OO
/Python_OO/NumeroComParametrodeVariavel.py
308
3.796875
4
def Funcao(*args): print(args) Funcao(1,2,3, 'fabio') ''' a utilização do args serve para poder passa mais de um parametro cqunado declaramos a função ou uma classe sempre utilizamos * ou ** para transformar em tupla ou dicionario ''' def F1(**Kwargs): print(Kwargs) F1(nome ='Fabio',idade=25)
57b7de2b232d702d472aac32bf8795a3646c95d2
yashwinder/Geo-Visualizer_and_Analysis_Tool
/clipmosaic.py
8,665
3.6875
4
'''Function to perform clipping on the mosaic file. The input mosaic is provided in .tif file. Clipping is basically cropping the input image according to the given dimensions. These dimesions are specified as 'xmax', 'xmin', 'ymax' and 'ymin'. Main libraries used are tkinter, rasterio, shapely, geopandas, earthpy, cartopy, osgeo and matplotlib''' import tkinter as tk from tkinter import ttk import rasterio import os import numpy as np import rasterio as rio from rasterio.plot import show from rasterio.mask import mask from shapely.geometry import mapping import matplotlib.pyplot as plt import geopandas as gpd import earthpy as et import earthpy.plot as ep import earthpy.spatial as es import cartopy as cp from tkinter import filedialog from osgeo import gdal from matplotlib.backends.backend_tkagg import (NavigationToolbar2Tk) from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas from rasterio.windows import Window import warnings warnings.filterwarnings('ignore') #out_tif = "clipped_mosaic.tif" class clipping(ttk.Frame): def __init__(self,master): super().__init__(master) self.master = master self.msfile='' #mosaic file self.display=ttk.Frame(self) self.createWidgets() def show_image(self): # Display the original image if self.display.winfo_exists(): self.display.grid_forget() self.display.destroy() self.display = ttk.Frame(self) self.display.grid(row = 0, column = 2, columnspan = 4, rowspan=3, sticky = 'nsew') frame=self.display fp = self.msfile self.fig = plt.Figure(figsize = (8,4), dpi =100) self.ax = self.fig.add_subplot(111) self.canvas_preview = FigureCanvas(self.fig, frame) self.dataset = gdal.Open(fp) self.band = self.dataset.GetRasterBand(1) self.geotransform = self.dataset.GetGeoTransform() self.arr = self.band.ReadAsArray() self.ax.imshow(self.arr, cmap='terrain') self.ax.axis('equal') self.ax.set(title="",xticks=[], yticks=[]) self.ax.spines["top"].set_visible(False) self.ax.spines["right"].set_visible(False) self.ax.spines["left"].set_visible(False) self.ax.spines["bottom"].set_visible(False) self.canvas_preview.draw() self.fig.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0) #self.canvas_preview.get_tk_widget().pack(side='top', fill='both', expand = 1) self.toolbar = NavigationToolbar2Tk(self.canvas_preview, frame) self.toolbar.update() self.canvas_preview.get_tk_widget().pack(side='top', fill='both', expand = 1) def show_clipped_image(self): # Display the clipped image if self.display.winfo_exists(): self.display.grid_forget() self.display.destroy() self.display = ttk.Frame(self) self.display.grid(row = 0, column = 2, columnspan = 4, rowspan=3, sticky = 'nsew') frame=self.display fp = self.msfile self.fig = plt.Figure(figsize = (8,4), dpi =100) self.ax = self.fig.add_subplot(111) self.canvas_preview = FigureCanvas(self.fig, frame) fp = 'OutputImages/'+self.outname.get()+'.tif' self.dataset = gdal.Open(fp) self.band = self.dataset.GetRasterBand(1) self.geotransform = self.dataset.GetGeoTransform() self.arr = self.band.ReadAsArray() self.ax.imshow(self.arr, cmap='terrain') self.ax.axis('equal') self.ax.set(title="",xticks=[], yticks=[]) self.ax.spines["top"].set_visible(False) self.ax.spines["right"].set_visible(False) self.ax.spines["left"].set_visible(False) self.ax.spines["bottom"].set_visible(False) self.canvas_preview.draw() self.fig.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0) #self.canvas_preview.get_tk_widget().pack(side='top', fill='both', expand = 1) self.toolbar = NavigationToolbar2Tk(self.canvas_preview, frame) self.toolbar.update() self.canvas_preview.get_tk_widget().pack(side='top', fill='both', expand = 1) def createWidgets(self): # create widgets self.grid_columnconfigure(0,weight = 0) self.grid_columnconfigure(1,weight = 1) self.grid_rowconfigure(0,weight = 0) self.grid_rowconfigure(1,weight = 1) self.panel = ttk.Frame(self) self.panel.grid(row=1, column=0, sticky='nsew') #mosaicfile selection button self.msbtn = ttk.Button(self.panel, text='Select Mosaicfile', command=self.mosaicfile) self.msbtn.grid(row=0, column=0, sticky='nsew', padx=10, pady=10) #show image self.showimage = ttk.Button(self.panel, text='Show Image', command = self.show_image) self.showimage.grid(row=1, column=0, sticky = 'nsew', pady = 10,padx = 10) #xmin self.InputLabe1 = ttk.Label(self.panel, text = "x min") self.InputLabe1.grid(row=2, column=0, sticky = 'nsew', padx = 10, pady = 10) self.InputXmin= ttk.Entry(self.panel) self.InputXmin.grid(row=3, column=0, sticky = 'nsew', padx = 10, pady = 10) #ymin self.InputLabe2 = ttk.Label(self.panel, text = "y min") self.InputLabe2.grid(row=4, column=0, sticky = 'nsew', padx = 10, pady = 10) self.InputYmin = ttk.Entry(self.panel) self.InputYmin.grid(row=5, column=0, sticky = 'nsew', padx = 10, pady = 10) #xmax self.InputLabe3 = ttk.Label(self.panel, text = "x max") self.InputLabe3.grid(row=6, column=0, sticky = 'nsew', padx = 10, pady = 10) self.InputXmax = ttk.Entry(self.panel) self.InputXmax.grid(row=7, column=0, sticky = 'nsew', padx = 10, pady = 10) #ymax self.InputLabe4 = ttk.Label(self.panel, text = "y max") self.InputLabe4.grid(row=8, column=0, sticky = 'nsew', padx = 10, pady = 10) self.InputYmax = ttk.Entry(self.panel) self.InputYmax.grid(row=9, column=0, sticky = 'nsew', padx = 10, pady = 10) #name of clipped image self.InputLabel5 = ttk.Label(self.panel, text = "Output Image Name") self.InputLabel5.grid(row=10, column=0, sticky = 'nsew', padx = 10, pady = 10) self.outname= ttk.Entry(self.panel) self.outname.grid(row=11, column=0, sticky = 'nsew', padx = 10, pady = 10) #clipping button #self.cpbtn = ttk.Button(self.panel, text='clip mosaic', command=(lambda e=ents: self.ClipImage(e))) self.cpbtn = ttk.Button(self.panel, text='Clip Mosaic', command=self.ClipImage) self.cpbtn.grid(row=12, column=0, sticky='nsew', padx=10, pady=10) self.showimage1 = ttk.Button(self.panel, text='Show Clipped Image', command = self.show_clipped_image) self.showimage1.grid(row=13, column=0, sticky = 'nsew', pady = 10,padx = 10) def mosaicfile(self, event=None): # Event Handler to choose mosaic file self.msfile = filedialog.askopenfilename() if(self.msfile!=() and self.msfile!=''): ind= self.msfile.rfind('/') self.msbtn["text"]='shape: '+self.msfile[ind+1:] #self.window.grid(row=1, column=0, columnspan=4, sticky='nsew') else: self.msfile='' def ClipImage(self): # Main clipping function if self.display.winfo_exists(): self.display.grid_forget() self.display.destroy() #self.display = ttk.Frame(self) #self.display.grid(row = 0, column = 1,rowspan=2, sticky = 'nwes') x_min = float(self.InputXmin.get()) y_min = float(self.InputYmin.get()) x_max = float(self.InputXmax.get()) y_max = float(self.InputYmax.get()) #out_path = 'OutputImages/'+self.entry.get()+'.tif' cfile = 'OutputImages/'+self.outname.get()+'.tif' with rasterio.open(self.msfile) as src: #window = Window(padding, padding, src.width - 2 * padding, src.height - 2 * padding) window = Window(x_min, y_min, x_max, y_max) kwargs = src.meta.copy() kwargs.update({'height': window.height, 'width': window.width, 'transform': rasterio.windows.transform(window, src.transform)}) with rasterio.open(cfile, 'w', **kwargs) as dst: dst.write(src.read(window=window))
81bcda5134eee69f105daf20765da1960b0c41d2
joekimga/python-challenge
/PyPoll/test.py
167
3.734375
4
mydictionary = {'d': 34, 'a': 4, 'b': 18, 'c': 1} print(mydictionary['d'], end = '') print(mydictionary.get('d')) print(max(mydictionary, key = mydictionary.get))
8b5da1de7d343b3a4a674a7510e5ec227323a87d
galoryzen/AdventOfCodeChallenge
/2020/06/code.py
811
3.5625
4
def readFile(): with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: return [line.split() for line in f.read().strip().split("\n\n")] def part1(groups): i = 0 for group in groups: s = "" for answer in group: s += answer new_str = "".join(set(s)) i += len(new_str) return i def part2(groups): result = 0 for group in groups: letters = dict([(chr(i),0) for i in range(97,123)]) for answer in group: for letter in answer: letters[letter] += 1 result += sum([1 for letter in letters if letters[letter] == len(group)]) return result def main(): groups = readFile() print(part1(groups)) print(part2(groups)) if __name__ == "__main__": main()
7567c0a7ff956992d73cb75d5c53e4b94d5e5544
xgenOsama/python_learning
/test_Regex.py
437
3.75
4
import re # \s space charcter * any number of them () group them print (re.split(r'(\s*)','here is some words')) # \s space \S not space \d digest \D not digest # print (re.split(r'([a-f]','adfadfadfbafjkgbjndalsjfadb')) print (re.findall(r'\w{1,60}\@\w{1,20}\.\w{1,6}','osama@gmail.com')) pat = re.findall(r'\w{1,60}\@\w{1,20}\.\w{1,6}','osama@@gmail.com') if pat: print 'this is a true email' else: print 'this is a fake email'
e96ad6f3f2ead231676185d515d619732ac4908d
durban24k/cell_trilateration
/draw.py
1,556
3.640625
4
import turtle from random import randint def drawCellTowers(): myPen = turtle.Turtle() myPen.hideturtle() turtle.tracer(0) myPen.speed(0) window = turtle.Screen() window.bgcolor("#F0F0F0") x1 = randint(-150,-80) y1 = randint(-150,150) x2 = randint(80,150) y2 = randint(20,150) x3 = randint(80,150) y3 = randint(-150,-20) x = randint(-60,60) y = randint(-60,60) r1 = ((x-x1)**2 + (y-y1)**2)**0.5 r2 = ((x-x2)**2 + (y-y2)**2)**0.5 r3 = ((x-x3)**2 + (y-y3)**2)**0.5 myPen.color("#ff5744") myPen.penup() myPen.goto(x1-5,y1) myPen.pendown() myPen.goto(x1+5,y1) myPen.penup() myPen.goto(x1,y1-5) myPen.pendown() myPen.goto(x1,y1+5) myPen.penup() myPen.goto(x1,y1-r1) myPen.pendown() myPen.circle(r1) myPen.color("#41befc") myPen.penup() myPen.goto(x2-5,y2) myPen.pendown() myPen.goto(x2+5,y2) myPen.penup() myPen.goto(x2,y2-5) myPen.pendown() myPen.goto(x2,y2+5) myPen.penup() myPen.goto(x2,y2-r2) myPen.pendown() myPen.circle(r2) myPen.penup() myPen.color("#52bf54") myPen.goto(x3-5,y3) myPen.pendown() myPen.goto(x3+5,y3) myPen.penup() myPen.goto(x3,y3-5) myPen.pendown() myPen.goto(x3,y3+5) myPen.penup() myPen.goto(x3,y3-r3) myPen.pendown() myPen.circle(r3) myPen.getscreen().update() return x1,y1,r1,x2,y2,r2,x3,y3,r3
148cf1ab0d4f152660491994a08c27b11a57489a
loushingba/loushingbaPyRepo
/strfuns.py
766
3.8125
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 13:36:05 2020 @author: sanathoi """ line=input("Enter a line of text: ") upcount=lowcount=alphacount=digitcount=specialcount=0 for a in line: if a.isalpha(): alphacount+=1 if a.isupper(): upcount+=1 else: lowcount+=1 elif a.isdigit(): digitcount+=1 else: specialcount+=1 else: print("Counting complete:",len(line)) print("The no. of alpha: ",alphacount) print("The no. of digit: ",digitcount) print("The no. of upper: ",upcount) print("The no. of low: ",lowcount) print("The no. of special: ",specialcount) print("Total characters:",alphacount+digitcount+specialcount)
0a021f9ff3d5680facff657eb4cdc475b154eb3b
763272955/python
/practice/大小.py
320
3.5625
4
#-*- coding: utf-8 -*- import random import time input('请输入下注金额'), c a= random.randrange(1,6) b = random.randrange(1,6) if a > b: print '最大值a为 \n',a time.sleep(10) print '最大值a为 \n', a else: print '最大值b为 \n', b time.sleep(10) print '最大值b为 \n', b
e4758b3951d3c9fa0ac533cc37cae523742f1778
vsdrun/lc_public
/depth-first-search/426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.py
4,354
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/ Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Let's take the following BST as an example, it may help you understand the problem better: fig_1 We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. The figure below shows the circular doubly linked list for the BST above. The "head" symbol means the node it points to is the smallest element of the linked list. fig_2 Specifically, we want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. We should return the pointer to the first element of the linked list. The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. fig_3 """ # Definition for a Node. class Node(object): def __init__(self, val, left, right): self.val = val self.left = left self.right = right class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """ if not root: return def traverse(node): """ ret: node's min, max 左 assign 左邊的largest, 右 assign 右邊的smallest """ lmin = lmax = rmin = rmax = None if node.left: lmin, lmax = traverse(node.left) if node.right: rmin, rmax = traverse(node.right) node.right = rmin node.left = lmax if not rmax: rmax = node if not lmin: lmin = node if lmax: lmax.right = node if rmin: rmin.left = node return lmin, rmax mmin, mmax = traverse(root) mmin.left = mmax mmax.right = mmin return mmin def rewrite(self, root): """ :type root: Node :rtype: Node SMART. """ stack = [] while root: stack.append(root) root = root.left prev = head = Node(None, None, None) while stack: cur = stack.pop() prev.right = cur cur.left= prev prev = cur if cur.right: root = cur.right while root: stack.append(root) root = root.left head.right.left = prev prev.right = head.right return head.right def rewrite4(self, root): """ :type root: Node :rtype: Node """ # use stack to the rescue if not root: return dummy = prev = Node(None, None, None) stack = [] while root: stack.append(root) root = root.left while stack: curr = stack.pop() prev.right = curr curr.left = prev prev = curr tnode = curr.right while tnode: stack.append(tnode) tnode = tnode.left prev.right = dummy.right dummy.right.left = prev return dummy.right def build(): n1 = Node(1, None, None) n3 = Node(3, None, None) n5 = Node(5, None, None) n2 = Node(2, n1, n3) n4 = Node(4, n2, n5) return n4 def pp(node, reverse=False): result = [] headnode = node while node: result.append(node.val) node = node.right if not reverse else node.left if node == headnode: break print(result) if __name__ == "__main__": s = Solution() r = s.treeToDoublyList(build()) pp(r) pp(r, True) print("---") r = s.rewrite(build()) pp(r) pp(r, True)
6a764fd49bb0b8173adf004d9b5177b6145c5653
liukai234/python_course_record
/函数和lambda表达式/lambda表达式.py
1,494
4.28125
4
''' lambda表达式:lambda [parameter_list] : 表达式 语法格式要点:1、必须要lambda关键字来定义 2、lambda之后、冒号左边是参数列表,可以没有参数或者多个参数,右边是表达式的返回值 3、只能是单行表达式,本质上是匿名的、单行函数体 ''' # lambda表达式代替局部函数 def get_math_func(type): ''' def square(n): # 求平方 return n*n def cube(n): # 求立方 return n * n * n def sum(n): # 求1+2+3+...+n return (1 + n) * n / 2 ''' if type == 'square': return lambda n: n * n # return square if type == 'cube': return lambda n: n * n * n # return cube if type == 'sum': return lambda n: (1 + n) * n / 2 # return sum def test(): # 返回一个嵌套函数 math_func=get_math_func('cube') print(math_func(5)) # lambda 表达式调用内置函数map() x = map (lambda x: x * x if x % 2 == 0 else 0 , range(10)) print([y for y in x]) # [注] # 刘润凤 19:36:14 # map() 会根据提供的函数对指定序列做映射 # 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表 # 刘润凤 19:39:03 # lambda写的单行函数:后边的表达式用了三目运算,如果是偶数,返回值就是 x*x,是奇数返回值为0
7c15abb43b81e29e26f5b7011b8c00de217e2e77
founek2/python
/docs/_assignments/lesson5/assignment/calc_normal.py
2,145
4.21875
4
operator_list = ["+", "-", "/", "*", "q"] print("Byl spuštěn program Kalkulačka, který umožnuje sčítaní, odečítání, násobení a dělení") print("Program Vás nejprve vyzve pro zadání čísla, následně Vás vyzve pro zadání matematického operátoru (+,-,*,/), poté k dalšímu číslu") print("Pokud zadáte matematický operátor jako první operand se bude brát předešlý výsledek, pokud číslo tak program Vás postupně vyzve pro zadání operátoru a poté čísla, pokud zadáte q program se ukončí. Pokud zadáte operátor a číslo a ještě žádný předešlý výsledek neexistuje, tak se vezme jako výchozí hodnota 0.") def is_float(str): try: float(str) return True except ValueError: return False while True: vstup = input("Zadejte vstup: ") while not (vstup in operator_list or is_float(vstup)): print("Nezadali jste žádný podporovaný oparátor nebo číslo") vstup = input( "Zadejte vstup: ") if vstup in operator_list: operator = vstup # TODO nekontroluje se, zda bylo zadáno číslo operand_2 = float(input("Zadejte číslo: ")) else: operand_1 = float(vstup) operator = input( "Zadejte matematický operátor, Kalkulačka umožňuje +,-,*,/ : ") while operator not in operator_list: operator = input( "Nezadali jste žádný podporovaný oparátor, zadejte ho znovu: ") # TODO tady se číslo kontroluje operand_2 = input("Zadejte číslo: ") while not is_float(operand_2): operand_2 = input("Zadejte číslo: ") operand_2 = float(operand_2) if operator == "+": vysledek = operand_1 + operand_2 elif operator == "-": vysledek = operand_1 - operand_2 elif operator == "*": vysledek = operand_1 * operand_2 elif operator == "/": vysledek = operand_1 / operand_2 operand_1 = vysledek print(f"Výsledek je: {vysledek}") # TODO program nikdy nedojde sem na konec - nelze ukončit pomocí "q" print("Program byl ukončen")
134b39d21692c18fbd2046c2f371f105ab1bc086
AndiLi99/gan
/src/deconv_layer.py
5,840
3.5625
4
from kernel import Kernel import numpy as np from activation_functions import LeakyRELU from activation_functions import Sigmoid # leaky relu function def func (z): return LeakyRELU.func(z) def func_deriv(z): return LeakyRELU.func_deriv(z) # Pads an image with zeros given a mapping # Args: # image (3D np array) - a list of images # padded_image_shape (tuple) - the desired padded image shape (depth, height, length) # input_to_padded (dictionary) - a mapping from a 2D coordinate (input) to a 2D coordinate on the padded image def pad(image, padded_image_shape, input_to_padded): padded_image = np.zeros(padded_image_shape) for i, img in enumerate(image): for incoord, outcoord in input_to_padded.items(): padded_image[i][outcoord[0]][outcoord[1]] = img[incoord[0]][incoord[1]] return padded_image # Unpads an image using the same operation as the padding method, but with opposite parameters # Args: # padded_image (3D np array) - the image to be unpadded # input_image_shape (tuple) - the desired new image shape # padded_to_input (dictionary) - a mapping from a 2D coordinate on the padded image onto a # 2D coordinate on the input image def unpad(padded_image, input_image_shape, padded_to_input): return pad(padded_image, input_image_shape, padded_to_input) class DeconvLayer: # Args: # input_shape (3 tuple (ints)) - (image depth, image height, image length) # output_shape (3 tuple (ints)) - the expected output image shape (same format as image_shape) # kernel_shape (4 tuple (ints)) - (num kernels, kernel depth, kernel height, kernel length) def __init__(self, input_shape, output_shape, kernel_shape, kernels=None): self.input_shape = input_shape self.kernel_shape = kernel_shape self.output_shape = output_shape # Size of the zero padded image self.padded_image_shape = (input_shape[0], output_shape[1]+kernel_shape[2]-1, output_shape[2]+kernel_shape[3]-1) # Maps a 2D coordinate from the input to a 2D coordinate on the zero padded input self.input_to_padded = {} # Maps a 2D coordinate from the zero padded input onto a 2D coordinate onto the input image self.padded_to_input = {} # Calculate how much blank space should be left between horizontal and vertical # adjacent pixels for evenly spaced padding # # Math: # number of white spaces total = (len/height of padded image) - (len/height of input image) # number of seperations = (len/height of input image) + 1 # length of evenly distributed blank spaces (approx) = (total white spaces) / (number of seperations) space_y = (self.padded_image_shape[1]-self.input_shape[1]+0.0)/(self.input_shape[1]+1.0) space_x = (self.padded_image_shape[2]-self.input_shape[2]+0.0)/(self.input_shape[2]+1.0) for y in range(input_shape[1]): for x in range(input_shape[2]): new_x = int(np.floor(space_x*(x+1))) + x new_y = int(np.floor(space_y*(y+1))) + y new_coord = (new_y, new_x) old_coord = (y, x) # Append to dictionaries self.input_to_padded[old_coord] = new_coord self.padded_to_input[new_coord] = old_coord if kernels is not None: self.kernels = kernels else: self.kernels = [] for x in range(kernel_shape[0]): self.kernels.append(Kernel(kernel_shape[1:])) def get_kernels(self, index=-1): if index == -1: return self.kernels return self.kernels[index] # Similar to feedforward, but without squashing # Args: image - 3D np array of the image def get_activations(self, image): image = pad(image, self.padded_image_shape, self.input_to_padded) new_img = [] for k in self.kernels: new_img.append(k.use_kernel(image)) return np.array(new_img) # Returns the new image created using padding and the current layers kernels squashed by an activation function # Args: image - 3D np array of the image def feed_forward(self, image): new_img = self.get_activations(image) return func(new_img) # Returns the kernel errors (weights and biases) and the previous image error (3D np arr) # Args: # z-activations (3D np arr) - activations for the previous layer # deltas (3D np arr) - errors in the forward layer def backprop(self, z_activations, deltas): prevDeltas = np.zeros(self.padded_image_shape) kernelWeightDeltas = [] kernelBiasDeltas = [] for k, d in zip(self.kernels, deltas): z_activations = pad(z_activations, self.padded_image_shape, self.input_to_padded) wd, bd, pd = k.get_errors(input_image_shape=self.padded_image_shape, output_image_shape=self.output_shape, z_activations=z_activations, deltas=d) kernelWeightDeltas.append(wd) kernelBiasDeltas.append(bd) prevDeltas += pd prevDeltas = unpad(prevDeltas, self.input_shape, self.padded_to_input) return np.array(kernelWeightDeltas), np.array(kernelBiasDeltas), prevDeltas # Update the kernels # Args: # d_weights - 4d np array to change kernel weights # d_bias - 1d np array to change kernel bias def update(self, d_weights, d_bias): for i, k in enumerate(self.kernels): k.update(d_weights[i], d_bias[i]) def get_output_shape(self): return self.output_shape
955c30593b5c8952a9edef6555ccefd769723532
DaZhiZi/chest
/problem/pro1.py
837
3.609375
4
def func1(): from itertools import permutations import json l = [0, 1, 2, 3] r = ['{}{}{}'.format(a, b, c) for a, b, c in permutations(l, 3)] print(json.dumps(r, indent=4)) def func2(length=6): import random a = [chr(i) for i in range(97, 97 + 26)] b = [chr(i) for i in range(65, 65 + 26)] c = [chr(i) for i in range(48, 48 + 10)] d = [chr(i) for i in range(33, 33 + 15)] e = [a, b, c, d] f = list(map(random.choice, e)) while len(f) < length: f.append(random.choice(random.choice(e))) random.shuffle(f) f = ''.join(f) print(f) def func3(): import random s = ' '.join([str(random.randint(0, 9)) for i in range(100)]) print(s) with open('test.txt', 'w+') as f: f.write(s) if __name__ == '__main__': func1() func2(10) func3()
57942b23653373961a941aa0f1f186139e92887b
Ant-Ross/Programming-for-Social-Sciences
/Python_exercise/18.09.18_notes.py
1,931
3.84375
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 18 10:46:18 2018 @author: ts16larp """ #TUESDAY 18/09/18 a = "Hey" #Retrievinig the last element of the string a[len(a)-1] a[-1] #Strings are immutable, i.e. I can't change a single value in it. #i.e, a[1] = 'a' is not allowed #Concatenate strings by... a = "Hey" b = "You" print(a+b) # Tuples # Tuples are indexed in the same way as strings q = (1,2,3,4) len(q) q[1] #Lists g = [5,6,7,8] print(len(g),g[1],g[-2]) # Lists are mutable g[2] = 33 print(g) # but you need to be careful a = [1,2,3] b = a # Now labels a nad b are both attached to the same list b[0] = 100 #That list has its first element changed # and both a and b lables are still attached, so print(a) # a has also changed # Slices a = [1,2,3,4,5,6,7,8,9] a[2:6] # slicing 4 elements: position 2 up to 5 (last position is not included) a[:6] # From the first position to 5 a[2:] # From the second to the last a[:]# Slice of the whole list. An entirely separate object from the original # Ranges range(4,17,2) # the range function makes an *iterable* (more later), here starting # at 4, ending one number before 17, in steps of 2. # Functions def squared(x): x_squared = x**2 return x_squared # x is only defined within the function and not outside. def pythagoras(a,b): c_squared = a**2+b**2 return c_squared**0.5,c_squared # Classes class Rational: def __init__(self,a,b): self.__n = a self.__d = b def getNumerator(self): return self.__n def getDenominator(self): return self.__d def __mul__(self,rhs): a = self.__n * rhs.getNumerator() b = self.__d * rhs.getDenominator() return Rational(a,b) def __repr__(self): str = '%d' % self.__n str = str + '/' str = str + '%d' % self.__d return str
f3ca96526b0f432a896bbc8e2e20085a110697b3
LinnikPolina/Compiler
/tokenizer.py
4,866
3.53125
4
PRINT, BEGIN, END, IF, THEN, ELSE, \ WHILE, OR, AND, NOT, READ, PROGRAM, \ VAR, INT, BOOLEAN, \ TRUE, FALSE, \ FUNCTION = ('print', 'begin', 'end', 'if', 'then', 'else', 'while', 'or', 'and', 'not', 'read', 'program', 'var', 'int', 'boolean', 'true', 'false', 'function') ALPHABET = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '(', ')', ':', '=', ';', '<', '>', '!', '.', ','] KEYWORDS = [PRINT, BEGIN, END, IF, THEN, ELSE, WHILE, OR, AND, NOT, READ, PROGRAM, VAR, INT, BOOLEAN, TRUE, FALSE, FUNCTION] TYPES = [INT, BOOLEAN] BOOL = [TRUE, FALSE] class Tokenizer(): def __init__(self, origin): self.origin = origin self.position = 0 self.actual = None self.alphabet = ALPHABET def selectNext(self): # Final do arquivo if self.position >= len(self.origin): self.actual = None return None char = self.origin[self.position] # Comentarios if char == '{': while char != '}': self.position += 1 if self.position == len(self.origin): return None char = self.origin[self.position] self.position += 1 char = self.origin[self.position] # Espacos,enter e tabs while char.isspace() and self.position: self.position += 1 if self.position == len(self.origin): return None char = self.origin[self.position] # Identificador if char.isalpha(): identifier = char while True: self.position += 1 if (self.position >= len(self.origin)): break char = self.origin[self.position] if not char.isalpha() and not char.isdigit() and char != '_': break else: identifier += char if identifier in TYPES: self.actual = Token('TYPE', identifier) elif identifier in BOOL: self.actual = Token('boolean', identifier) elif identifier in KEYWORDS: self.actual = Token(identifier, None) else: self.actual = Token('IDE', identifier) # Caracter invalido elif char not in self.alphabet: raise ValueError("Invalid Char") # Digitos elif char.isdigit(): number = char while True: self.position += 1 if (self.position >= len(self.origin)): break char = self.origin[self.position] if not char.isdigit(): break else: number += char self.actual = Token('int', int(number)) # Operacoes e parenteses else: if (char == '+'): self.actual = Token('PLUS', None) elif (char == '-'): self.actual = Token('MINUS', None) elif (char == '*'): self.actual = Token('MULT', None) elif (char == '/'): self.actual = Token('DIV', None) elif (char == '('): self.actual = Token('OPEN_PAR', None) elif (char == ')'): self.actual = Token('CLOSE_PAR', None) elif (char == ';'): self.actual = Token('SEMI_COLON', None) elif (char == ':'): if (self.position + 1 < len(self.origin)): char = self.origin[self.position + 1] if (char == '='): self.actual = Token('ATRIBUTE', None) self.position += 1 else: self.actual = Token('VAR_DECLARATION', None) elif (char == '>'): self.actual = Token('COMP', ">") elif (char == '<'): self.actual = Token('COMP', "<") elif (char == '='): self.actual = Token('COMP', "=") elif (char == '!'): self.position += 1 char = self.origin[self.position] if (char == '='): self.actual = Token('COMP', "!=") else: raise ValueError("Invalid Char") elif (char == '.'): self.actual = Token('END_PROGRAM', None) elif (char == ','): self.actual = Token('COMMA', None) self.position += 1 return self.actual class Token(): def __init__(self, token_type, value): self.type = token_type self.value = value
e50b83b55d5f3e602cf6ffaef14215925c67ad99
abmish/pyprograms
/euler/e4.py
428
4.03125
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99 Find the largest palindrome made from the product of two 3-digit numbers """ num = 0 for a in xrange(999, 100, -1): for b in xrange(a, 100, -1): prod = a * b if prod > num: pal = str(prod) if pal == pal[::-1]: num = prod print num
3c4a3dc515cd2b4520c10c95e12a07e5d42ee119
ddc899/cmpt145
/Tanner's Docs/A5/a5q2_scoring.py
8,508
3.53125
4
# CMPT 145: Assignment 5 Question 2 # test script # try to import the student's solutions imported = False try: import a5q2 as student_a5q2 imported = True except: print('a5q2 not found') # if a5q1 isn't there, try A5Q2 if not imported: try: import A5Q2 as student_a5q2 print('found A5Q2') imported = True except: print('No A5Q2 either') # if A5Q2 isn't there, try A5q2 if not imported: try: import A5q2 as student_a5q2 print('found A5q2') imported = True except: print('No A5q2 either') # if A5q2 isn't there, try a5Q2 if not imported: try: import a5Q2 as student_a5q2 print('found A5q2') imported = True except: print('No a5Q2 either') if not imported: # made a reasonable attempt, bail! print('Not continuing') exit(1) import node as node ############################################################################################### # A little tool to help with the reporting of errors and counting, etc. # It's an ADT defined within this file, with the following operations: # - createCounter(reason, lim) # create a counter data structure labelled with a reason (string) and an error limit (lim) # - expecting(counter, flag, errstring) # counts and reports, based on the outcome of a test (flag) # - set_limit(counter, lim) # cause the counter to stop the script after a given number of errors (lim) # - final_report(counter) # displays the final results def createCounter(reason, lim=0, quiet=True): """ Create a counter to counter tests. The counter will collect statistics based on calls to function expecting(). :param reason: a string to describe what's being tested. :param lim: how many errors to detect before halting the tests :return: None """ return {'successes': 0, 'tests': 0, 'reason': reason, 'limit': lim, 'silent' : quiet} def expecting(counter, flag, errstring='null'): """ Do the work of counting and reporting. If flag is true, the condition being tested is true, meaning no error. Report the progress at all times, but give more detail when flag is False. The value of this for debugging depends on useful errstring! :param counter: the counter to use :param flag: A Boolean, the result of a test for an expected correct result :param errstring: a string that describes what should have happened :return: None """ counter['tests'] += 1 if flag: counter['successes'] += 1 if not counter['silent']: print("***", counter['successes'], 'of', counter['tests'], 'tests passed', end=' ') if not flag: print('**FAILURE**', counter['reason'] + errstring) else: print() assert counter['limit'] == 0 or counter['tests'] - counter['successes'] < counter[ 'limit'], "Halting because of too many errors" def set_limit(counter, errors): """ Set the counter to terminate testing after a number of errors. If errors is 0, there is no limit. :param counter: a counter :param errors: an integer :return: None """ counter['limit'] = errors def final_report(counter): """ Display the final count for the number of successful tests. :param counter: a counter. :return: None """ print(counter['reason']+'\t', counter['successes'], 'of', counter['tests'], 'tests passed') # end of the counter ADT ############################################################################################### def to_string_correct(node_chain): """ Purpose: Create a string representation of the node chain. E.g., [ 1 | *-]-->[ 2 | *-]-->[ 3 | / ] Pre-conditions: :param node_chain: A node-chain, possibly empty Post_conditions: None Return: A string representation of the nodes. """ # special case: empty node chain if node_chain is None: result = 'EMPTY' else: # walk along the chain walker = node_chain value = node.get_data(walker) # print the data result = '[ ' + str(value) + ' |' while node.get_next(walker) is not None: walker = node.get_next(walker) value = node.get_data(walker) # represent the next with an arrow-like figure result += ' *-]-->[ '+str(value)+' |' # at the end of the chain, use '/' result += ' / ]' return result test_count_chain = [ {'inputs' : None, 'outputs': 0, 'reason' : 'Empty node chain'}, {'inputs' : node.create(1), 'outputs': 1, 'reason' : 'node chain with one node'}, {'inputs' : node.create(1, node.create('two')), 'outputs': 2, 'reason' : 'node chain with two nodes'}, {'inputs' : node.create(1, node.create('two', node.create(3))), 'outputs': 3, 'reason' : 'node chain with three nodes'}, ] count_chain_counter = createCounter('A5Q2 count_chain()') for t in test_count_chain: args_in = t['inputs'] expected = t['outputs'] result = student_a5q2.count_chain(args_in) expecting(count_chain_counter, result == expected, 'count_chain(): got '\ +str(result)+' expected '+str(expected)+' -- ' +t['reason']) test_copy_chain = [ {'inputs' : None, 'outputs': None, 'reason' : 'Empty node chain'}, {'inputs' : node.create(1), 'outputs': None, 'reason' : 'node chain with one node'}, {'inputs' : node.create(1, node.create('two')), 'outputs': None, 'reason' : 'node chain with two nodes'}, {'inputs' : node.create(1, node.create('two', node.create(3))), 'outputs': None, 'reason' : 'node chain with three nodes'}, ] final_report(count_chain_counter) copy_chain_counter = createCounter('A5Q2 copy_chain()') for t in test_copy_chain: args_in = t['inputs'] result = student_a5q2.copy_chain(args_in) expecting(copy_chain_counter, (args_in is None and result is None) or (args_in is not result), 'copy_chain(): original chain returned -- '+t['reason']) expecting(copy_chain_counter, args_in == result, 'copy_chain(): chains not equal -- '+t['reason']) final_report(copy_chain_counter) replace_counter = createCounter('A5Q2 replace()\t') test_replace = [ {'inputs' : [None, 1, 1], 'outputs': "EMPTY", 'reason' : 'Empty node chain'}, {'inputs' : [node.create(1), 1, 2], 'outputs': "[ 2 | / ]", 'reason' : 'node chain with one node, target in'}, {'inputs' : [node.create(1), 5, 2], 'outputs': "[ 1 | / ]", 'reason' : 'node chain with one node, target not in'}, {'inputs' : [node.create(1, node.create('two')), 1, 'one'], 'outputs': "[ one | *-]-->[ two | / ]", 'reason' : 'node chain with two nodes, target first'}, {'inputs' : [node.create(1, node.create('two')), 5, 'five'], 'outputs': "[ 1 | *-]-->[ two | / ]", 'reason' : 'node chain with two nodes, target not in'}, {'inputs' : [node.create(1, node.create('two')), 'two', 2], 'outputs': "[ 1 | *-]-->[ 2 | / ]", 'reason' : 'node chain with two nodes, target last'}, {'inputs' : [node.create(1, node.create('two', node.create(3))), 'two', 2], 'outputs': "[ 1 | *-]-->[ 2 | *-]-->[ 3 | / ]", 'reason' : 'node chain with three nodes, target middle'}, {'inputs' : [node.create(1, node.create(3, node.create(3))), 3, 2], 'outputs': "[ 1 | *-]-->[ 2 | *-]-->[ 2 | / ]", 'reason' : 'node chain with three nodes, target repeated middle last'}, {'inputs' : [node.create(3, node.create(1, node.create(3))), 3, 2], 'outputs': "[ 2 | *-]-->[ 1 | *-]-->[ 2 | / ]", 'reason' : 'node chain with three nodes, target repeated first last'}, {'inputs' : [node.create(1, node.create(1, node.create(3))), 1, 2], 'outputs': "[ 2 | *-]-->[ 2 | *-]-->[ 3 | / ]", 'reason' : 'node chain with three nodes, target repeated first middle'}, ] for t in test_replace: args_in = t['inputs'] expected = t['outputs'] student_a5q2.replace(args_in[0], args_in[1], args_in[2]) result = to_string_correct(args_in[0]) expecting(replace_counter, result == expected, 'replace(): got "'+result+'" expected "'+expected+'" -- '+t['reason']) final_report(replace_counter) print('*** testing complete ***')
5a43969531621b3dd525ec892bb43e70387d34e5
nbenkler/CS110_Intro_CS
/Lab 2/strings3.py
1,927
4.78125
5
'''strings3.py Blake Howald 9/19/17, modified from original by Jeff Ondich, 2 April 2009 This sample program will introduce you to some standard string operations. See http://docs.python.org/library/stdtypes.html#id4 for documentation on these operations and many more. ''' # Using the "replace" method. # # -- Go to the link shown above, and scroll down to the paragraph # about "str.replace". Does the description of "replace" in # this documentation describe what you observe when you run the # the code below? (It should, but you never know...) # -- Do the replace operations below modify the string s, or just t? # Why does one change, but not the other? # -- In the second replace operation, what would happen if we did # t = s.replace('cranky', 'content') instead of what's there? s = 'The apple and the banana are cranky.' t = s.replace('apple', 'peach') t = t.replace('cranky', 'rotten') print('Original:', s) print('Modified:', t) print() # Using the "find" method. # # -- Read about str.find in the Python string documentation (same # link as above). Try to predict what the following code will # print before you run it. s = 'The apple and the other apple are rotten.' print(s.find('apple')) print(s.find('rotten')) print(s.rfind('apple')) if s.find('apple') >= 0: print('There is a apple here.') else: print('No apple.') if s.find('rotten') >= 0: print('There is something rotten here.') else: print('There is nothing rotten here.') print() # Exploring other methods. # # -- Take a look at the documentation for str.lower, str.upper, # str.strip, str.isdigit, and str.isalpha. Create some # little tests for these operations to see whether they # work as you expect them to. For example... s = '12345' if s.isdigit(): print(s, 'is entirely composed of digits') else: print(s, 'contains something that is not a digit') print()
bf15be1134f9a189240999810bcc7cd9a717138e
emmas0507/leetcode
/rotate_list.py
745
4.0625
4
class Node(object): def __init__(self, value, next=None): self.value = value self.next = next def rotate_list(list, K): length = 0 head = list while head is not None: length = length + 1 head = head.next K = K % length start = list end = list for i in range(K): end = end.next while end.next is not None: start = start.next end = end.next new_head = start.next start.next = None end.next = list return new_head def print_list(list): while list is not None: print(list.value) list = list.next n5 = Node(5) n4 = Node(4, n5) n3 = Node(3, n4) n2 = Node(2, n3) n1 = Node(1, n2) print(print_list(rotate_list(n1, 2+5)))
5237f812f3f5a863b3b2cd9b421c42a48c8796b0
nlscng/ubiquitous-octo-robot
/p000/problem-50/BinaryTreeArithmetic.py
1,761
4.21875
4
# Good morning! Here's your coding interview problem for today. # # This problem was asked by Microsoft. # # Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one # of '+', '−', '∗', or '/'. # # Given the root to such a tree, write a function to evaluate it. # # For example, given the following tree: # # * # / \ # + + # / \ / \ # 3 2 4 5 # You should return 45, as it is (3 + 2) * (4 + 5). from common.treenode.MyBST import StrNode ''' * / \ + + / \ / \ 3 2 4 5 ''' def bst_arithmetic(root: StrNode) -> int: if not root or not isinstance(root, StrNode): return 0 # this looks like a post order processing def post_traverse(node: StrNode) -> int: if node.left is None or node.right is None: return int(node.val) left_res = post_traverse(node.left) right_res = post_traverse(node.right) my_ops = { '+': left_res + right_res, '-': left_res - right_res, '*': left_res * right_res, '/': left_res // right_res } return my_ops[node.val] return post_traverse(root) test_a = StrNode('3') assert bst_arithmetic(test_a) == 3 test_b = StrNode('+') b_1 = StrNode('2') b_2 = StrNode('3') test_b.left = b_1 test_b.right = b_2 assert bst_arithmetic(test_b) == 5 test_c = StrNode('*') c_left = StrNode('+') c_right = StrNode('+') c_left_left = StrNode('3') c_left_right = StrNode('2') c_right_left = StrNode('4') c_right_right = StrNode('5') test_c.left = c_left test_c.right = c_right c_left.left = c_left_left c_left.right = c_left_right c_right.left = c_right_left c_right.right = c_right_right assert bst_arithmetic(test_c) == 45
091726856e4d4166dbfdb0056da20c7170ddc529
Dreamh4ck/Projects_2020
/4.py
524
3.953125
4
def string2ascii(s): ascii = [ord(c) for c in s] ascii = int("".join(map(str, ascii))) return ascii def checkPrime(number): if number > 1: for i in range (2, number//2): if (number % i) == 0: print("", number, "is not a prime number") break else: print("", number, "is a prime number") else: print("", number, "is not a prime number") print() s = str(input(" Enter a string: ")) ascii = string2ascii(s) print() print("", "Ascii code: ", ascii) print() checkPrime(ascii)
d9401522c65f04972b580897eb3c78c8a5fe637c
csw279/new
/dailywork/020502.py
279
3.65625
4
db={'username':'123','password':'1234'} x=[] for i in db:#(for循环取值时虽然是取得元素,但是字典的键值段时分别取出来的,所以直接取得 键 key 当然db.keys()用这个方法也是可以的) x.append(i) x.append(db[i]) print(x)
94452e87dbcbe59438f56bd162af66d0b21c10fa
gaspard-quenard/artificial_intelligence
/reinforcement_learning/Puzzle/puzzle.py
11,617
3.5625
4
import numpy as np import matplotlib.pyplot as plt import itertools from p5 import * class Board(): def __init__(self, width, height, width_square): self.width = width self.height = height self.width_square = width_square self.ending_point = (3, 1) self.counter = 0 self.initialize() self.initialize_array() def initialize(self): self.pieces = [] self.pieces.append(Piece(0, 1, self.width_square, 2, 2)) self.pieces.append(Piece(0, 0, self.width_square, 1, 2)) self.pieces.append(Piece(0, 3, self.width_square, 1, 2)) #self.pieces.append(Piece(0, 0, self.width_square, 1, 2)) #self.pieces.append(Piece(0, 3, self.width_square, 1, 2)) self.pieces.append(Piece(2, 1, self.width_square, 2, 1)) #self.pieces.append(Piece(3, 1, self.width_square, 1, 1)) self.pieces.append(Piece(3, 2, self.width_square, 1, 1)) self.pieces.append(Piece(4, 1, self.width_square, 1, 1)) self.pieces.append(Piece(4, 2, self.width_square, 1, 1)) def initialize_array(self): self.all_pos_pieces1 = [] self.all_pos_pieces3 = [] for i in range(self.height - self.pieces[0].height + 1): for j in range(self.width - self.pieces[0].width + 1): self.all_pos_pieces1.append((i, j)) print(len(self.all_pos_pieces1)) self.all_pos_pieces2 = self.get_all_pos_piece2(self.pieces[2]) print(len(self.all_pos_pieces2)) for i in range(self.height - self.pieces[3].height + 1): for j in range(self.width - self.pieces[3].width + 1): self.all_pos_pieces3.append((i, j)) print(len(self.all_pos_pieces3)) self.all_pos_pieces4 = self.get_all_pos_piece4(self.pieces[4]) print(len(self.all_pos_pieces4)) def get_all_pos_piece2(self, piece): pos = [] pos_1_piece = [] for i in range(self.height - piece.height + 1): for j in range(self.width - piece.width + 1): pos_1_piece.append((i, j)) for piece1 in pos_1_piece: controlled_squares_piece1 = [(piece1[0] + h, piece1[1] + w) for h in range(piece.height) for w in range(piece.width)] for piece2 in pos_1_piece: controlled_squares_piece2 = [(piece2[0] + h, piece2[1] + w) for h in range(piece.height) for w in range(piece.width)] if (len(set(controlled_squares_piece1) & set(controlled_squares_piece2)) == 0 and (piece2 + piece1) not in pos): pos.append(piece1 + piece2) return pos def get_all_pos_piece4(self, piece): pos = list(itertools.combinations_with_replacement(range(20), 3)) pos_2 = [] for elemt in pos: # remove state with elements if same position if (elemt[0] in elemt[1:] or elemt[1] == elemt[2]): pass else: pos_2.append(elemt) pos_3 = [(val1 // self.width, val1 % self.width) + (val2 // self.width, val2 % self.width) + (val3 // self.width, val3 % self.width) for val1, val2, val3 in pos_2] return pos_3 def get_state(self): state1 = self.all_pos_pieces1.index(self.pieces[0].get_pos()) # piece with width = 2 and height = 2 a = sorted((self.pieces[1].get_pos(), self.pieces[2].get_pos()), key=lambda tup: (tup[0], tup[1])) state2 = self.all_pos_pieces2.index(a[0] + a[1]) # piece with width = 1 and height = 2 state3 = self.all_pos_pieces3.index(self.pieces[3].get_pos()) b = sorted((self.pieces[4].get_pos(), self.pieces[5].get_pos(), self.pieces[6].get_pos()), key=lambda tup: (tup[0], tup[1])) #state4 = self.all_pos_pieces4.index(b[0] + b[1] + b[2] + b[3]) state4 = self.all_pos_pieces4.index(b[0] + b[1] + b[2]) state = (state1,) + (state2,) + (state3,) + (state4,) return state def step(self, action): reward = -1 episode_finsished = False piece_choosen_index = action[0] new_state = tuple([self.pieces[piece_choosen_index].pos_y + action[1], self.pieces[piece_choosen_index].pos_x + action[2]]) # First manage the boundaries if (new_state[0] < 0 or \ new_state[1] < 0 or \ new_state[0] + self.pieces[piece_choosen_index].height > self.height or \ new_state[1] + self.pieces[piece_choosen_index].width > self.width): return self.get_state(), reward, episode_finsished controlled_squares = [(self.pieces[piece_choosen_index].pos_y + action[1] + h, self.pieces[piece_choosen_index].pos_x + action[2] + w) for h in range(self.pieces[piece_choosen_index].height) for w in range(self.pieces[piece_choosen_index].width)] #print(controlled_squares) for index, piece in enumerate(self.pieces): if (index != piece_choosen_index): if (len(set(controlled_squares) & set(piece.controlled_squares)) > 0): return self.get_state(), reward, episode_finsished self.pieces[piece_choosen_index].move_to((action[1], action[2])) if (piece_choosen_index == 0 and new_state == self.ending_point): #print("BRAVO") reward = 80 episode_finsished = True return self.get_state(), reward, episode_finsished def draw(self): fill(100, 0, 0); rect((0, 0), self.width*self.width_square, self.height*self.width_square, mode='CORNER') for i in range(self.height): line((0, i*self.width_square), (self.width_square*self.height, i*self.width_square)) for i in range(self.width): line((i*self.width_square, 0), (i*self.width_square, self.width_square*self.height)) for piece in self.pieces: piece.draw() class Piece(): def __init__(self, pos_y, pos_x, width_square, width, height): self.width = width self.height = height self.pos_x = pos_x self.pos_y = pos_y self.controlled_squares = [(self.pos_y + h, self.pos_x + w) for h in range(self.height) for w in range(self.width)] self.width_square = width_square if (width * height == 1): self.color = Color(255, 0, 0) elif (width * height == 2): self.color = Color(0, 0, 255) else: self.color = Color(0, 255, 0) def move_to(self, new_pos): self.pos_y += new_pos[0] self.pos_x += new_pos[1] self.controlled_squares = [(self.pos_y + h, self.pos_x + w) for h in range(self.height) for w in range(self.width)] def draw(self): fill(0, 100, 0) stroke(0); rect((self.pos_x*self.width_square, self.pos_y*self.width_square), self.width*self.width_square, self.height*self.width_square, mode='CORNER') fill(self.color); circle(((self.pos_x + self.width/2 ) * self.width_square, (self.pos_y + self.height/2 ) * self.width_square), self.width_square/2); def get_pos(self): return (self.pos_y, self.pos_x) class Agent(): def __init__(self, number_pieces): self.actions = [] for i in range(number_pieces): # left, right, down, up for each pieces self.actions.append((i, 0, 1)) self.actions.append((i, 0, -1)) self.actions.append((i, 1, 0)) self.actions.append((i, -1, 0)) self.Q = np.zeros((12, 108, 15, 1140, len(self.actions))) self.policy = np.zeros((12, 108, 15, 1140), dtype=np.int32) # e greedy policy self.initial_epsilon = 0.2 self.epsilon = self.initial_epsilon self.alpha = 0.5 self.discount_factor = 1 def choose_action(self, state): if (np.random.random() < self.epsilon): return self.actions[np.random.randint(len(self.actions))] else: return self.actions[self.policy[state]] def update_policy(self, state): self.policy[state] = np.argmax(self.Q[state]) def setup(): size(width_board*width_square, height_board*width_square) background(0) def draw(): board.draw() def key_pressed(event): state = board.get_state() agent.update_policy(state) action = agent.choose_action(state) new_state, reward, episode_finsished = board.step(action) # Take action, observe R, S' index = state + (agent.actions.index(action), ) #print("State: {}, action: {}, new state: {}, reward: {}".format(state, action, new_state, reward)) agent.Q[index] = agent.Q[index] + agent.alpha * (reward + agent.discount_factor * np.max(agent.Q[new_state]) - agent.Q[index]) save('frames_8_pieces/Frame_.jpg'); board.counter += 1 def generate_episode_Q_learning(board, agent): episode = [] safe_counter = 0 episode_finsished = False board.initialize() while (safe_counter < 50000 and not episode_finsished): safe_counter += 1 state = board.get_state() agent.update_policy(state) action = agent.choose_action(state) new_state, reward, episode_finsished = board.step(action) # Take action, observe R, S' #print("Step: {}\nState: {}\nAction: {}\nNew state: {}\nReward: {}\n".format(safe_counter, state, action, new_state, reward)) index = state + (agent.actions.index(action), ) agent.Q[index] = agent.Q[index] + agent.alpha * (reward + agent.discount_factor * np.max(agent.Q[new_state]) - agent.Q[index]) return safe_counter def generate_episode_sarsa(board, agent): episode = [] safe_counter = 0 episode_finsished = False state = board.get_state() action = agent.choose_action(state) board.initialize() while (safe_counter < 50000 and not episode_finsished): safe_counter += 1 state = board.get_state() agent.update_policy(state) new_state, reward, episode_finsished = board.step(action) # Take action, observe R, S' new_action = agent.choose_action(new_state) #print("Step: {}\nState: {}\nAction: {}\nNew state: {}\nReward: {}\n".format(safe_counter, state, action, new_state, reward)) index = state + (agent.actions.index(action), ) new_index = new_state + (agent.actions.index(new_action),) agent.Q[index] = agent.Q[index] + agent.alpha * (reward + agent.discount_factor * agent.Q[new_index] - agent.Q[index]) agent.update_policy(state) action = new_action return safe_counter if __name__ == '__main__': width_board = 4 height_board = 5 width_square = 50 board = Board(width_board, height_board, width_square) agent = Agent(len(board.pieces)) #agent.Q = np.load("Q array_7_pieces.npy") counter_mean = [] number_episodes = 30000 for episode in range(number_episodes): print("{} / {}".format(episode, number_episodes)) print(generate_episode_Q_learning(board, agent)) if (episode % 10 == 0): agent.epsilon = 0 mean = 0 for i in range(10): mean += generate_episode_Q_learning(board, agent) counter_mean.append(mean) print("Episode: {} / {}, mean: {}".format(episode, number_episodes, mean / 10)) agent.epsilon = agent.initial_epsilon - (agent.initial_epsilon / (number_episodes * 2)) * episode plt.plot([10 * index for index in range(len(counter_mean))], counter_mean) plt.ylabel("Number of step by episode") plt.xlabel("Episode") plt.show() np.save("Q array_7_pieces", agent.Q) board.initialize() agent.epsilon = 0 run()
1230865a40b0736f0385ad8d31fe23b578d196e6
SophieWilson/Snakegame
/snakeclass.py
8,421
3.609375
4
import pygame, sys, random from pygame.locals import * pygame.init() random.seed() pygame.display.init() # size = width, height = 600, 600 #nothing changes if you remove this screen = pygame.display.set_mode((1280, 700) ,0) class Megasnakes (pygame.sprite.Sprite): """ snakes?? """ def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("sophie.png").convert_alpha() self.image.set_colorkey((255, 255, 255)) self.image = pygame.transform.scale(self.image, (50, 100)) self.rect = self.image.get_rect() self.rect.centery = y self.rect.centerx = x self.speed = 15 def key_move(self): dist = 1 key = pygame.key.get_pressed() if key[pygame.K_UP]: self.rect.move_ip([0, -self.speed]) if key[pygame.K_LEFT]: self.rect.move_ip([-self.speed, 0]) if key[pygame.K_RIGHT]: self.rect.move_ip([self.speed, 0]) if key[pygame.K_DOWN]: self.rect.move_ip([0, self.speed]) # making background change colour when you hit the edge of the screen self.rect.clamp_ip(screen.get_rect()) class Minisnakes (pygame.sprite.Sprite): """the snakes that follow the biggo snake (mega snake)""" def __init__(self, speed, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("cutesnake.jpg").convert_alpha() self.image.set_colorkey((255, 255, 255)) self.image = pygame.transform.scale(self.image, (20, 50)) self.rect = self.image.get_rect() self.rect.centerx = x self.rect.centery = y self.speed = speed def follow(self, snakerect): if self.rect.centerx < snakerect.centerx: self.rect.move_ip([self.speed, 0]) if self.rect.centerx > snakerect.centerx: self.rect.move_ip([-self.speed, 0]) if self.rect.centery < snakerect.centery: self.rect.move_ip([0, self.speed]) if self.rect.centery > snakerect.centery: self.rect.move_ip([0, -self.speed]) self.rect.clamp_ip(screen.get_rect()) def avoid(self, snakerect): if self.rect.centerx < snakerect.centerx: self.rect.move_ip([-self.speed, 0]) if self.rect.centerx > snakerect.centerx: self.rect.move_ip([self.speed, 0]) if self.rect.centery < snakerect.centery: self.rect.move_ip([0, -self.speed]) if self.rect.centery > snakerect.centery: self.rect.move_ip([0, self.speed]) self.rect.clamp_ip(screen.get_rect()) def killyou(self): """when they hit you""" self.kill() hitsound = pygame.mixer.Sound("splat.wav") pygame.mixer.Sound.play(hitsound) def hide(self): self.kill() hitsound = pygame.mixer.Sound("hit.wav") pygame.mixer.Sound.play(hitsound) # print(self.visible) def runaway(self): self.rect.move_ip([1000,1000]) def die(self): self.kill() class Boomerangs (pygame.sprite.Sprite): """the object that will kill the minisnakes""" def __init__(self, speed, maxdist, x, y, dir): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("boomerang2.png").convert_alpha() self.image.set_colorkey((255, 255, 255)) self.image = pygame.transform.scale(self.image, (50, 30)) self.rect = self.image.get_rect() self.speed = speed self.distance = 0 self.maxdistance = maxdist self.direction = dir self.rect.centerx = x self.rect.centery = y self.done = False def update(self, snake): if (self.distance < self.maxdistance): # print("yes down") if self.direction == 0: self.rect.move_ip([0,-self.speed]) if self.direction == 1: self.rect.move_ip([self.speed,0]) if self.direction == 2: self.rect.move_ip([0,self.speed]) if self.direction == 3: self.rect.move_ip([-self.speed,0]) self.distance = self.distance + 1 elif pygame.sprite.collide_rect(self,snake): self.done = True self.distance = 0 else: # print("no down") self.follow(snake.rect) def follow(self, snakerect): if self.rect.centerx < snakerect.centerx: self.rect.move_ip([self.speed, 0]) if self.rect.centerx > snakerect.centerx: self.rect.move_ip([-self.speed, 0]) if self.rect.centery < snakerect.centery: self.rect.move_ip([0, self.speed]) if self.rect.centery > snakerect.centery: self.rect.move_ip([0, -self.speed]) self.rect.clamp_ip(screen.get_rect()) # class Lives (pygame.sprite.Sprite): # """the counter thats on the thingy""" # def __init__(self, x, y): # pygame.sprite.Sprite.__init__(self) # self.image = pygame.image.load("one.png").convert_alpha() # self.image.set_colorkey((255, 255, 255)) # self.image = pygame.transform.scale(self.image, (100, 50)) # self.rect = self.image.get_rect() # self.rect.centerx = x # self.rect.centery = y class Endscreen (pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("gameover.jpg").convert_alpha() self.image.set_colorkey((255, 255, 255)) self.image = pygame.transform.scale(self.image, (x, y)) self.rect = self.image.get_rect() def stopgame(self): # pygame.mixer.Sound.stop() pygame.mixer.stop() class Randoctopus (pygame.sprite.Sprite): def __init__(self, speed, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("6.png").convert_alpha() self.image.set_colorkey((255, 255, 255)) self.image = pygame.transform.scale(self.image, (60, 60)) self.rect = self.image.get_rect() self.rect.centerx = x self.rect.centery = y self.speed = speed self.move = 0 self.hit = False self.saved_boomerang = -1 def movement(self): distance = 1 if self.move < 30: self.rect.move_ip([self.speed, -self.speed]) self.move += 1 if self.move >= 30 and self.move < 60: self.move += 1 self.rect.move_ip([self.speed, self.speed]) if self.move == 60: self.move = 0 if (self.rect.right >= pygame.display.get_surface().get_width() or self.rect.left <= 0): self.speed = -self.speed self.rect.clamp_ip(screen.get_rect()) def avoid(self, octorect): if self.rect.centerx < octorect.centerx: self.rect.move_ip([-self.speed, 0]) if self.rect.centerx > octorect.centerx: self.rect.move_ip([self.speed, 0]) if self.rect.centery < octorect.centery: self.rect.move_ip([0, -self.speed]) if self.rect.centery > octorect.centery: self.rect.move_ip([0, self.speed]) self.rect.clamp_ip(screen.get_rect()) def saveboomerang(self, boomerang_id): if self.hit == False: self.saved_boomerang = boomerang_id self.hit = True return True return False def hide(self): '''when you hit them''' self.kill() hitsound = pygame.mixer.Sound("angrychipmunk.wav") pygame.mixer.Sound.play(hitsound) def killyou(self): """when they hit you""" self.kill() hitsound = pygame.mixer.Sound("splat.wav") pygame.mixer.Sound.play(hitsound) def die(self): self.kill() class Heart (pygame.sprite.Sprite): '''they give you more lives''' def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("heart.png").convert_alpha() self.image.set_colorkey((255, 255, 255)) self.image = pygame.transform.scale(self.image, (40, 50)) self.rect = self.image.get_rect() self.rect.centerx = x self.rect.centery = y def hide(self): '''when you get them''' self.kill() hitsound = pygame.mixer.Sound("bob.wav") pygame.mixer.Sound.play(hitsound)
34f027457836acbfef92f92032b0f0697f788f52
IlhamLamp/uas-program1
/program1/model/daftar_nilai.py
3,274
3.609375
4
from view.input_nilai import * mahasiswa = {} #menambah daftar mehasiswa def tambah_data(): global mahasiswa print("Masukkan data mahasiswa . . .") nama = input_nama() nim = input_nim() n_tugas= input_ntugas() n_uts = input_nuts() n_uas = input_nuas() n_akhir= nakhir() mahasiswa[nama] = [nama, nim, n_tugas, n_uts, n_uas, n_akhir] print("-> Data berhasil di tambah!") #menghapus daftar mahasiswa def hapus_data(): nama = input("Masukkan nama untuk menghapus : ") if nama in mahasiswa.keys(): del mahasiswa[nama] print("-> Daftar Mahasiswa {} telah di hapus".format(nama)) else: print("-> Mahasiswa {} tidak ditemukan".format(nama)) #mengubah daftar mahasiswa def ubah_data(): nama = input("Masukkan nama mahasiswa untuk merubah data : ") if nama in mahasiswa.keys(): print("-> Mau merubah apa ?") tanya = input("-> (semua), (nim), (tugas), (uts), (uas) : ") if tanya.lower() == "semua": print("+++ Mulai mengubah data {} +++".format(nama)) mahasiswa[nama][1] = input("Ubah NIM : ") mahasiswa[nama][2] = input("Ubah nilai tugas : ") mahasiswa[nama][3] = input("Ubah nilai uts : ") mahasiswa[nama][4] = input("Ubah nilai uas : ") mahasiswa[nama][5] = int(mahasiswa[nama][2])*30/100 + int(mahasiswa[nama][3])*35/100 + int(mahasiswa[nama][4])*35/100 print("-> Data berhasil diubah!") elif tanya.lower() == "nim": mahasiswa[nama][1] = input("Ubah NIM : ") print("-> NIM berhasil diubah!") elif tanya.lower() == "tugas": mahasiswa[nama][2] = input("Ubah nilai tugas : ") mahasiswa[nama][5] = int(mahasiswa[nama][2])*30/100 + int(mahasiswa[nama][3])*35/100 + int(mahasiswa[nama][4])*35/100 print("-> Nilai tugas berhasil diubah!") elif tanya.lower() == "uts": mahasiswa[nama][3] = input("Ubah nilai uts :") mahasiswa[nama][5] = int(mahasiswa[nama][2])*30/100 + int(mahasiswa[nama][3])*35/100 + int(mahasiswa[nama][4])*35/100 print("-> Nilai UTS berhasil diubah!") elif tanya.lower() == "uas": mahasiswa[nama][4] = input("Ubah nilai uas : ") mahasiswa[nama][5] = int(mahasiswa[nama][2])*30/100 + int(mahasiswa[nama][3])*35/100 + int(mahasiswa[nama][4])*35/100 print("-> Nilai UAS berhasil diubah!") else: print("-> Keyword yang anda masukkan salah ...") else: print("-> Mahasiswa {} tidak ditemukan".format(nama)) # Mencari data mahasiswa def cari_data(): print("Mencari data: ") print("=================================================") nama = input("Masukan nama untuk mencari data: ") if nama in mahasiswa.keys(): print('\nHasil') print("Nama: {0}\nNIM : {1}\nNilai Tugas: {2}\nUTS: {3}\nUAS: {4}\nNilai akhir: {5:.2f}" .format(nama, mahasiswa[nama][1], mahasiswa[nama][2], mahasiswa[nama][3], mahasiswa[nama][4], mahasiswa[nama][5])) else: print("'{}' tidak ditemukan.".format(nama))
2c74acae8a43f870b39a0614a88f8a548ef65b67
echase6/network_poker
/client.py
2,641
3.9375
4
"""Client main and modules for communicating with server and displaying table. Run this module on the client computers (i.e., computers for each player) Hard-coded to work with a fixed address, entered at startup. This can be changed in the connect_to_server() module. Valid ports are 8000 and 8001. It is more stable if they are the order of the connecting clients, although not 100% necessary. connect_to_server() connects the client to the server message_from_server() displays a message from the server answer_to_server() inquires the user and sends the response to the server render_table() unpacks the shipped JSON version of the table and displays it process_server_message() interprets the incoming info and acts appropriately """ from PIL import Image, ImageTk, ImageFont, ImageDraw from card import SUITS, RANKS from chip import calc_chips, DENOMINATIONS, DENOM_COLORS from client_gui import update_table, display_window, display_image import socket import jsonpickle PORTS = [8000, 8001] def connect_to_server(): """Module to connect the client to the server. Returns individual serversocket for communication. """ host = input('Host address: ') if host == '': host = '127.0.0.1' port = int(input('Port number: ')) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((host, port)) return server, port def message_from_server(s): """Get (wait for) message from server.""" return s.recv(2048).decode() def answer_to_server(msg_string, server): """Sends answer to server.""" msg_string += ' ' # make sure something goes across server.send(msg_string.encode()) def process_server_message(msg, server, canvas, table_img, port): """Analyzes and acts on the content of a message from the server. Valid actions are: rendering a table (Table JSON was sent, starts with a {) asking a question and sending response to server (msg contains a ?) displaying a message (if above not true) """ if msg[0] == '{': table = jsonpickle.decode(msg) update_table(table, canvas, table_img, port) elif '?' in msg: answer = input(msg) answer_to_server(answer, server) else: print(msg) def main(): skt, port = connect_to_server() table_img = Image.open('./images/poker-table-felt.jpg') canvas = display_window() display_image(canvas, table_img) while True: message = message_from_server(skt) if len(message) > 0: process_server_message(message, skt, canvas, table_img, port) if __name__ == '__main__': main()
83d372efff8124802bc558a1bb0aab15e0b6a409
ArnaVin/Python-Games
/Connect4/Connect4_v1.py
2,123
3.515625
4
# Terminal based Connect-4 import numpy as np ROW_COUNT = 6 COLUMN_COUNT = 7 def create_board(): board = np.zeros((ROW_COUNT, COLUMN_COUNT)) return board def drop_piece(board, row, col, piece): board[row][col] = piece def is_valid_loc(board, col): return board[ROW_COUNT-1][col] == 0 def get_next_open_row(board, col): for r in range(ROW_COUNT): if board[r][col] == 0: return r def show_board(board): print(np.flip(board, 0), "\n 0 1 2 3 4 5 6 \n") def winning_move(board, piece): # Horizontal wins for c in range(COLUMN_COUNT-3): for r in range(ROW_COUNT): if board[r][c]==piece and board[r][c+1]==piece and board[r][c+2]==piece and board[r][c+3]==piece: return True # Verical wins for c in range(COLUMN_COUNT): for r in range(ROW_COUNT-3): if board[r][c]==piece and board[r+1][c]==piece and board[r+2][c]==piece and board[r+3][c]==piece: return True # Positve slope diagonal wins for c in range(COLUMN_COUNT-3): for r in range(ROW_COUNT-3): if board[r][c]==piece and board[r+1][c+1]==piece and board[r+2][c+2]==piece and board[r+3][c+3]==piece: return True # Negative slope diagonal wins for c in range(COLUMN_COUNT-3): for r in range(3, ROW_COUNT): if board[r][c]==piece and board[r-1][c+1]==piece and board[r-2][c+2]==piece and board[r-3][c+3]==piece: return True board = create_board() gameover = False turn = 0 print("\n-------CONNECT 4!-------\n") show_board(board) while not gameover: if turn == 0: col = int(input(f"Player 1 turn (0-{COLUMN_COUNT-1}): ")) piece = 1 else: col = int(input(F"Player 2 turn (0-{COLUMN_COUNT-1}): ")) piece = 2 if is_valid_loc(board, col): row = get_next_open_row(board, col) drop_piece(board, row, col, piece) show_board(board) if winning_move(board, piece): print(f"PLAYER {piece} WINS!!!") gameover = True turn += 1 turn = turn % 2
53cd61636b7676bcdcb6f8f353fe1b6f134a0cb9
Floozutter/silly
/python/fizzbuzzfunctional.py
1,446
3.828125
4
""" An extensible solution to the FizzBuzz problem, in a functional style. https://en.wikipedia.org/wiki/Fizz_buzz Updated using Maciej Piróg's "FizzBuzz in Haskell by Embedding a Domain-Specific Language"! https://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf """ from functools import reduce from typing import NamedTuple, Callable, Iterable class Rule(NamedTuple): subname: str predicate: Callable[[int], bool] def make_namer(rules: Iterable[Rule]) -> Callable[[int], str]: """ Returns a namer constructed from the given rules. The namer will name an integer as a concatenation of every valid subname it fulfills from the rules. The order of the subnames corresponds to the order of the rules in the Iterable. However, if no subnames were fulfilled, the namer will default to naming the integer by its string value instead. """ def namer(z: int) -> str: """Names the integer argument using the bound rules.""" def test(rule: Rule, f: Callable[[str], str]) -> Callable[[str], str]: if rule.predicate(z): return lambda _: rule.subname + f("") else: return f return reduce( lambda f, g: lambda x: f(g(x)), map( lambda rule: lambda f: test(rule, f), rules ) )(lambda s: s)(str(z)) return namer if __name__ == "__main__": fizzbuzz = make_namer(( Rule("Fizz", lambda z: z % 3 == 0), Rule("Buzz", lambda z: z % 5 == 0) )) for name in map(fizzbuzz, range(0, 100)): print(name)
8fabcc035d501d122253075038f400382ced8b02
AshimaSEthi/Tkinter_Programs
/Buttons.py
382
3.671875
4
import tkinter as tk def addition(): a=40 b=50 add_num = a+b label.configure(text=str(add_num)) root = tk.Tk() root.title("Buttons in Tkinter") root.geometry("500x400") button = tk.Button(root,text="Add Button",command=addition) button.pack(padx=20,pady=20) label = tk.Label(root,text="Hi ! I am a label") label.pack(padx=20,pady=20) root.mainloop()
43c8e84326c18d4e902dce3b62b4d24d3674db14
rinleit/hackerrank-solutions
/problem-solving/Implementation/The Time in Words/solutions.py
1,530
3.546875
4
#!/bin/python3 import math import os import random import re import sys # Complete the timeInWords function below. def timeInWords(h, m): hours = ("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve") minutes = ("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen","fifteen", "sixteen", "seventeen", "eighteen", "ninteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine") formats = { 0: "%s o' clock", 15: "quarter past %s", 30: "half past %s", 45: "quarter to %s", } if m % 15 == 0: time = formats[m] % hours[h + int(m > 30)] else: h, m, is_past = (h + 1, 60 - m, 'to') if m > 30 else (h, m, 'past') minutes_txt = 'minutes' if m > 1 else 'minute' time = "{} {} {} {}".format(minutes[m], minutes_txt, is_past, hours[h]) return time if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') h = int(input()) m = int(input()) result = timeInWords(h, m) fptr.write(result + '\n') fptr.close()
a8cd6106047b1bb15bf22351dce5c01c1ed7aec7
Thomas-Rudge/facebook-birthday-bot
/fb_bday_bot.py
7,103
3.65625
4
#! python3 #------------------------------------------------------------------------------- # Name: facebook-birthday-bot # Purpose: Automatically checks your facebook notifications for # friends birthdays, and writes a message on their wall. # Author: Thomas Rudge # # Created: 5th July 2016 # Modified: 9th July 2016 # Copyright: (c) Thomas Rudge # Licence: MIT #------------------------------------------------------------------------------- from robobrowser import RoboBrowser as robo import logging, re, datetime, sys, random, traceback class facebookBirthdayBot: def __init__(self, email, password, **kwargs): self.email = email self.password = password self.messages = None self.log = False self.logfile = False self.browser = None self.fb_url_login = 'https://www.facebook.com/login' self.fb_url_notifs = 'https://m.facebook.com/notifications' self.date = datetime.datetime.today() # Handle keyword arguments for logging and messages if 'log' in kwargs: self.log = kwargs['log'] if 'logfile' in kwargs: self.logfile = kwargs['logfile'] if 'messages' in kwargs: self.messages = kwargs['messages'] else: self.messages = ('Happy birthday!', 'Hope you have a great birthday!', 'Happy birthday \u263A', 'Happy birthday, have a great day!', '\U0001F382 Happy Birthday \U0001F382 ', 'Happy birthday, have a good one', '\U0001F389 \U0001F38A \U0001F389 Happy Birthday \U0001F389 \U0001F38A \U0001F389', '\U0001F381 Happy Birthday \U0001F381 ') # Set the logging settings based on the log flags if self.logfile: logging.basicConfig(filename='%s_fbBdayBot_logfile.txt' % str(self.date.date()), level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') else: logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') if not self.log: logging.disable(logging.CRITICAL) def start(self): logging.debug('Start triggered.') self.open_page() self.login() notifications = self.get_birthday_notifications() if notifications: self.send_greetings(notifications) logging.debug('Start ends.') def open_page(self): logging.debug('Initating browser and opening main page.') try: self.browser = robo(history=True, parser="lxml") self.browser.open(self.fb_url_login) except: logging.error(traceback.format_exc()) def login(self): ''' Logs into facebook ''' logging.debug('Logging into Facebook.') form_id = 'login_form' try: form = self.browser.get_form(form_id) if not form: raise Exception("Form with id '%s' not found." % form_id) form['email'] = self.email form['pass'] = self.password self.browser.submit_form(form) except: logging.error(traceback.format_exc()) def get_birthday_notifications(self): ''' This function will take the browser to the page... 'https://m.facebook.com/notifications' ...and return a list of links that relate to birthdays. ''' logging.debug('Fetching birthday notifications.') try: self.browser.open(self.fb_url_notifs) link_pattern = re.compile(r'((Today is ).+(s birthday))', re.IGNORECASE) bday_links = self.browser.get_links(link_pattern) except: logging.error(traceback.format_exc()) if not bday_links: logging.debug('Single person notification not found, trying multi.') try: link_pattern = re.compile(r'(have birthdays today.)') bday_links = self.browser.get_links(link_pattern) except: logging.error(traceback.format_exc()) logging.debug('%s birthday notifications found.' % str(len(bday_links))) return bday_links def link_valid(self, link): ''' Takes the unix timestamp in the link and returns True if it is from today, else False. ''' logging.debug('Check validity of link: %s' % str(link)) epoch_start = datetime.datetime(1970, 1, 1) # Get the 10 digit unix time from the link epoch_ptn = re.compile(r'[0-9]{10}') link = str(link) epoch = re.search(epoch_ptn, link) if epoch: logging.debug('Unix timestamp found: %s' % epoch) epoch = int(epoch.group()) if epoch_start.date() + datetime.timedelta(0, epoch) == self.date.date(): logging.debug('Link date is valid') return True logging.debug('Link date is valid') return False def send_greetings(self, bdays): ''' The function iterates through the links in 'bdays' and posts a message from taken randomly from the list of messages. ''' logging.debug('Start sending messages.') for link in bdays: # Skip if not valid if not self.link_valid(link): continue try: # Go to the friends page self.browser.follow_link(link) # Get all forms because the post form has no id forms = self.browser.get_forms(method='post') except: logging.error(traceback.format_exc()) continue for form in forms: logging.debug('Attempting form.') try: form['xc_message'] = random.choice(self.messages) # This will mimic a button press on the post input element submit_field = form['view_post'] except: try: form['message'] = random.choice(self.messages) # This will mimic a button press on the post input element submit_field = form['post'] except: logging.error(traceback.format_exc()) try: self.browser.submit_form(form, submit=submit_field) logging.debug('Form submitted.') except: logging.error(traceback.format_exc()) if __name__ == '__main__': # Expects to be started form a batch file vars_ = sys.argv if not vars_: sys.exit() email_ = vars_[1] password_ = vars_[2] facebookBirthdayBot(email_, password_, log=True).start() sys.exit()
8be0717b0ebadb8b59dbdc96ffd18e5db9c4c84d
cvnlab/GLMsingle
/glmsingle/ols/olsmatrix.py
4,644
3.609375
4
import numpy as np from sklearn.preprocessing import normalize import scipy.linalg def olsmatrix_ulen(X, mode=0): """ olsmatrix(X, mode, verbose) <X> is samples x parameters <mode> (optional) is 0 means normal operation 1 means use inv instead of '\' and omit unit-length normalization. the point of this mode is to reduce memory usage (i think). default: 0. what we want to do is to perform OLS regression using <X> and obtain the parameter estimates. this is accomplished by inv(X'*X)*X'*y = f*y where y is the data (samples x cases). what this function does is to return <f> which has dimensions parameters x samples. to ensure well-conditioning, we unit-length normalize each column of <X> before doing the inv.m operation. also, we actually use left-slash ('\'), which apparently is equivalent to inv.m but faster and more accurate (see code for details). if you pass <mode> as 1, we omit the normalization and use the inv method instead of the '\' method. also, in the case that one or more regressors in <X> are all zero, then without special handling, then this case will result in warnings and NaN results. what we do is to explicitly ensure that all-zero regressors are ignored and that there are all-zero rows for these regressors in <f>. this makes it such that the weights estimated for these regressors are simply zero. history: 2011/06/27 - explicitly ignore 0 2011/03/29 - mode 1 now omits unit length normalization. 2011/03/28 - add <mode> input. 2010/08/05: now, we do not try to detect weird cases with low variance. instead, we just blindly unit-length normalize each column. """ # input # deal with degenerate regressors good = np.invert(np.all(X == 0, axis=0)) # initialize result f = np.zeros((X.shape[1], X.shape[0])) # do it if mode == 0: X, length = normalize(X[:, good], axis=0, return_norm=True) di = np.diag(1/length) XT = np.transpose(X) glm = scipy.linalg.solve( np.einsum('ij,jk', XT, X), XT) temp = np.einsum('ij,jk', di, glm) elif mode == 1: X = X[:, good] XT = np.transpose(X) temp = np.einsum('ij,jk', np.linalg.inv(np.einsum('ij,jk', XT, X)), XT) # return if np.any(good): f[good, :] = temp return f def olsmatrix(X, lambd=0, verbose=True): """OLS regression what we want to do is to perform OLS regression using <X> and obtain the parameter estimates. this is accomplished by np.linalg.inv(X.T @ X) @ X.T @ y = f @ y where y is the data (samples x cases). what this function does is to return <f> which has dimensions parameters x samples. we check for a special case, namely, when one or more regressors are all zeros. if we find that this is the case, we issue a warning and simply ignore these regressors when fitting. thus, the weights associated with these regressors will be zeros. if any warning messages are produced by the inversion process, then we die. this is a conservative strategy that ensures that the regression is well-behaved (i.e. has a unique, finite solution). (note that this does not cover the case of zero regressors, which is gracefully handled as described above.) note that no scale normalization of the regressor columns is performed. Args: X (ndarray): Samples by parameters Returns: (f): 2D parameters by Samples """ bad = np.all(X == 0, axis=0) good = np.invert(bad) # report warning if not np.any(good) == 1: if verbose: print( "regressors are all zeros. \n" "we will estimate a 0 weight for those regressors." ) f = np.zeros((X.shape[1], X.shape[0])).astype(np.float32) return f # do it if np.any(bad): if verbose: print( "One or more regressors are all zeros. \n" "we will estimate a 0 weight for those regressors." ) f = np.zeros((X.shape[1], X.shape[0])).astype(np.float32) X = X[:, good] XT = np.transpose(X) XTX = np.einsum('ij,jk', XT, X) f[good, :] = np.einsum( 'ij,jk', np.linalg.inv(XTX), XT) else: XT = np.transpose(X) XTX = np.einsum('ij,jk', XT, X) f = np.einsum('ij,jk', np.linalg.inv(XTX), XT) return f.astype(np.float32)
56acca97e95440e33174419bd98b6f47481bec1e
Ainzll/Python
/Turtle-Code.py
1,510
3.921875
4
#MODULE 7 - Pythin Turtle graphics #https://docs.python.org/3/library/turtle.html (Links to an external site.) #Before using turtle install turtle graphics. #sudo apt install python3-tk python-tk # #Try this code: import turtle from random import randrange w = turtle.Screen() w.clear() w.bgcolor("#ffffff") t = turtle.Turtle() t2 = turtle.Turtle() #turtle.tracer(0, 0) # - - - - - n = 0 colors = ['#ff0000','#ffff00','#00ff00','#00ffff','#0000ff','#ff00ff'] a=1 siz = randrange(10,50) pencol = colors[randrange(0,6)] t.speed('fastest') t2.speed('fastest') crdX = randrange(-500,500) crdX2 = randrange(-500,500) crdY = randrange(-500,500) crdY2 = randrange(-350,350) while a==1: def petal1(angle,length,coordx,coordy): t.penup() t.pencolor(pencol) t.goto(coordx,coordy) t.pendown() t.right(angle) t.forward(length) t.right(angle + 17) t.forward(length) t.right(17) t.forward(length) t.goto(coordx,coordy) def petal2(angle,length,coordx2,coordy2): t2.penup() t2.pencolor(pencol) t2.goto(coordx2,coordy2) t2.pendown() t2.right(angle) t2.forward(length) t2.right(angle + 17) t2.forward(length) t2.right(17) t2.forward(length) t2.goto(coordx2,coordy2) petal1(0,siz,crdX,crdY) petal2(0,siz,crdX2,crdY2) n += 1 if n % 1 == 0: pencol = colors[randrange(0,6)] if n == 21: n = 0 siz = randrange(10,50) crdX = randrange(-800,800) crdX2 = randrange(-800,800) crdY = randrange(-350,350) crdY2 = randrange(-350,350) #turtle.update() w.exitonclick()
a146fe8f1e56a8c5b6dde11406d57f4f4754ddfe
ayk-dev/python-fundamentals
/lists-advanced/demo_my_map.py
403
4.03125
4
def my_map(function, items): new_items = [] for item in items: new_item = function(item) new_items.append(new_item) return new_items strings = ['1', '2', '3', '4', '5'] my_map_result = my_map(lambda string: string + 'hello', strings) map_result = list(map(lambda string: string + 'hello', strings)) print(strings) print(my_map_result) print(map_result)
5a9f974041a1ef33a97255f89f084099d468fe7f
NikhilBhargav/Joy_Of_Learning_Python
/RockPaperScissor.py
1,566
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 4 15:27:43 2020 Rock, Paper Scissor game @author: nikhil1.bhargava """ def rockPaperScissor(player1_choice,player2_choice,secretbit_player1,secretbit_player2): p1=int(player1_choice[secretbit_player1]) p2=int(player2_choice[secretbit_player2]) if(player1[p1]==player2[p2]): print("Draw") elif(player1[p1]=="Rock" and player2[p2]=="Scissor"): print("Player 1 wins") elif(player1[p1]=="Rock" and player2[p2]=="Paper"): print("Player 2 wins") elif(player1[p1]=="Paper" and player2[p2]=="Scissor"): print("Player 2 wins") elif(player1[p1]=="Paper" and player2[p2]=="Rock"): print("Player 1 wins") elif(player1[p1]=="Scissor" and player2[p2]=="Paper"): print("Player 1 wins") elif(player1[p1]=="Scissor" and player2[p2]=="Rock"): print("Player 2 wins") player1={0:'Rock',1:'Paper',2:'Scissor'} player2={0:'Paper',1:'Rock',2:'Scissor'} while(True): player1_choice=input("Player 1, Enter your choice as 3 or more digit number ") player2_choice=input("Player 2, Enter your choice as 3 or more digit number ") #Secret bit position secretbit_player1=int(input("Player 1, Enter your secret bit position (0-2) ")) secretbit_player2=int(input("Player 2, Enter your secret bit position (0-2) ")) rockPaperScissor(player1_choice,player2_choice,secretbit_player1,secretbit_player2) ch=input("Do you want to continue? (y/n)") if(ch=='n'): break