blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4485a43120b9ad713f361135d19c5b2b61634a63
tup916/Summer2016_ComputerScience-Research-AudioProcessing
/semantic_metrics_IBM.py
1,408
3.828125
4
#Author: Tushita Patel #June, 2016 #Human Computer Interaction Lab #Department of Computer Science #University of Saskatchewan #Semantic Metrics #imports import speech_recognition as sr #input .wav file to be transcribed from the user #the file should be located at the same folder as this code fileName = input('Enter the name of the file in the same directory as this script: ') # obtain path to fileName in the same folder as this script from os import path AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), fileName) # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) # read the entire audio file # recognize speech using IBM Speech to Text IBM_USERNAME = "" # IBM Speech to Text usernames are strings of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX IBM_PASSWORD = "" # IBM Speech to Text passwords are mixed-case alphanumeric strings if IBM_USERNAME == "" or IBM_PASSWORD == "": print("Username or password not provided) try: print("IBM Speech to Text thinks you said: \n" + r.recognize_ibm(audio, username=IBM_USERNAME, password=IBM_PASSWORD)) except sr.UnknownValueError: print("IBM Speech to Text could not understand audio") except sr.RequestError as e: print("Could not request results from IBM Speech to Text service; {0}".format(e))
ae711ea94ac8f301b9baecb44d7e0c81356d6236
MattySly/python-training-code
/scratches/functions.py
259
3.515625
4
def function3(x, y): return x + y e = function3(1, 2) print(e) def function4(x): print(x) print("still in function") return 3*x f = function4(4) print(f) def function5(some_argument): print(some_argument) print("weee") function5(4)
1cc5122e5c66d396e0dc0b524d9525bc39c29fb8
miikanissi/python_course_summer_2020
/week6_nissi_miika/week6_ass10_nissi_miika.py
219
3.78125
4
def search(array, n): for i in array: if i == n: return True return False arr = [23,4,89,19,0,700,30] print("Number 19 found: ", search(arr, 19)) print("Number 20 found: ", search(arr, 20))
81a862b2546e197be70de7e1c0e7d85dc190a9b2
dandurden/dandurden
/lab4/lab_4v1.py
3,347
3.875
4
import pygame from pygame.draw import * from random import randint pygame.init() FPS = 30 screen = pygame.display.set_mode((1200, 900)) RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) BLACK = (0, 0, 0) COLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN] class Newgame: def __init__(self): self.score = 0 self.name = input('имя нового игрока: ') def __add__(self, other): self.score += other class NewBall: """ этот класс предназначен для создания шарика с координатами x, y и радуусом r, а также выбирает рандомный цвет из списка """ def __init__(self): self.speedx = randint(5, 10) self.speedy = randint(5, 10) self.x = randint(103, 1097) self.y = randint(103, 797) self.r = randint(50, 100) self.color = COLORS[randint(0, 5)] def new_ball(self): '''рисует новый шарик ''' circle(screen, self.color, (self.x, self.y), self.r) def new_fig(self): rect(screen, self.color, (self.x, self.y, self.r, self.r)) def move_ball(self): """двигает шарик и отражает от стен""" self.x += self.speedx self.y += self.speedy if self.y + self.r >= 900 or self.y - self.r <= 0: self.speedy *= -1 if self.x + self.r >= 1200 or self.x - self.r <= 0: self.speedx *= -1 def move_fig(self): """двигает квадрат и отражает от стен""" self.x += self.speedx self.y += self.speedy if self.y + self.r >= 900 or self.y <= 0: self.speedy *= -1 if self.x + self.r >= 1200 or self.x <= 0: self.speedx *= -1 # balls создать список шариков balls = [NewBall(), NewBall(), NewBall(), NewBall(), NewBall()] fig = NewBall() game = Newgame() pygame.display.update() clock = pygame.time.Clock() finished = False while not finished: clock.tick(FPS) with open('best_score.txt', "a") as file: for event in pygame.event.get(): if event.type == pygame.QUIT: file.write(f"{game.name} = {game.score}\n") finished = True elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() for ball in balls: if ball.x - ball.r < pos[0] < ball.x + ball.r and \ ball.y - ball.r < pos[1] < ball.y + ball.r: # клик попал в диапазон (площадь) шарика if ball in balls[:3]: game + 1 print(f"{game.name} = {game.score}") pygame.display.update() else: game + 5 print(f"{game.name} = {game.score}") pygame.display.update() for ball in balls[:3]: ball.new_ball() ball.move_ball() for fig in balls[3:]: fig.new_fig() fig.move_fig() pygame.display.update() screen.fill(BLACK) pygame.quit()
c47c529812d8f82caa24a8bb52470955e6358317
anondev123/F20-1015
/Lectures/18/op1.py
104
3.6875
4
a = 2 b = 3 c = 4 x = a + b * c # Will Print 14 becasue 3 * 4 = 12, then add + 2 print ( f"x={x}" )
4c08b92478d1a151d0076137ffd8752861562ef0
stayfu0705/python1
/homework/hw1.py
1,809
3.71875
4
''' num=eval(input('input ur month:')) if num in (12,1,2): print("冬天!") elif num in (3,4,5): print("春天!") elif num in (6,7,8): print("夏天!") elif num in (9,10,11): print("秋天!") else: print("輸入錯誤") ''' '''a=eval(input('輸入你的工時:')) if a<60: print(a*120,'元') elif a>=61 and a<=80: print(60*120+(a-60)*120*1.25,'元') elif a>=81: print(60*120+20*120*1.25+(a-80)*120*1.5,'元') else: print('滾拉廢物')''' # a=eval(input('輸入你的用電種類 1=家用,2=工業用:')) # b=eval(input('輸入你的用電量:')) # if a==1 or a==2: # if a==1 and b<=240: # print(b*0.15) # elif a==1 and 240<b<=540: # print(240*0.15+(b-240)*0.25) # elif a == 1 and b>540: # print(240 * 0.15+300*0.25+(b - 540) * 0.45) # elif a==2 and b>0: # print(b*0.45) # else: # print("掰掰") '''a=eval(input('輸入一個西元年分:')) if a%4000==0: print('非潤') elif a%400==0: print('潤') elif a%100==0: print('非潤') elif a%4==0: print('潤') else: print('選個偶數再來吧')''' '''a=eval(input('購買金額:')) b=eval(input('實付金額:')) if a<b: print((b-a)//1000,'張一千',(b-a)//500,"張五百" ,(b-a)%500//100,"張一百" ,(b-a)%100//50,"個50元",(b-a)%50//10,"個10元" ,(b - a) % 10 // 5, "個五元" ,(b-a)%5,"個1元") elif a==b: print("免找") else: print("付錢拉廢物")''' '''import math print('ax^2+bx+c') a=eval(input('係數a:')) b=eval(input('係數b:')) c=eval(input('係數c:')) d=b**2-4*a*c if d>0: print("有相異實根") print((-b + math.sqrt(d)) / 2 * a) print((-b - math.sqrt(d)) / 2 * a) elif d==0: print((-b + math.sqrt(d)) / 2 * a,"重根") else: print("虛根")'''
28ed8aaaf62478641dad42413a557615adba29cf
mitchell-johnstone/PythonWork
/PE/P051.py
3,030
4.15625
4
# By replacing the 1st digit of the 2-digit number *3, # it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. # # By replacing the 3rd and 4th digits of 56**3 with the same digit, # this 5-digit number is the first example having seven primes # among the ten generated numbers, yielding the family: # 56003, 56113, 56333, 56443, 56663, 56773, and 56993. # Consequently 56003, being the first member of this family, # is the smallest prime with this property. # # Find the smallest prime which, by replacing part of the number # (not necessarily adjacent digits) with the same digit, # is part of an eight prime value family. # general notes: # can never replace the last digit. # otherwise, it'll be a family of max 5 primes. # if replacing the first digit, don't use 0. #this methods finds the indexes of the different digits #return a list of digits and where they are in the number #indexes = digit, -1 = digit not present def findSimilarDigits(n): #10 possible digits digits = [[-1]]*10 # print(digits) n=str(n) index = 0 while(index<len(n)): digit = int(n[index]) if(digits[digit] == [-1]): digits[digit] = [index] else: digits[digit] += [index] #the last digit will only have 5 possible primes. all others are even. #thus, change if(index == len(n)-1): digits[digit] = [-1] index+=1 return digits #method to return an array with the family of numbers #parameters: original number, indexes to replace def family(n, indexes): n = str(n) members = [] if indexes[0] == -1: return [] start = 0 if(indexes[0] == 0): start = 1 for digit in range(start, 10): for index in indexes: n = n[:index] + str(digit) + n[index+1:] members += [int(n)] return members def main(): #var to hold all primes up to 1 mil AllPrimes = [] f = open("C:\\Programming\\Work\\Python\\PE\\AllPrimes.txt") # import the primes needed for line in f: words = line.split(); for word in words: if(int(word)<100000000 and int(word)>10): AllPrimes+=[int(word)] #loop through all primes for prime in AllPrimes: #get digits of the prime digits = findSimilarDigits(prime) # print(prime) #for every prime, find the family for i in range(10): fam = family(prime, digits[i]) if(fam == []): continue # print(fam) familySize = 0 indexForPrime = 0 for member in fam: while(indexForPrime < len(AllPrimes)-1 and AllPrimes[indexForPrime] < member): indexForPrime+=1 if(AllPrimes[indexForPrime] == member): familySize+=1 if(familySize == 8): print("\n",fam) return print() if __name__ == '__main__': main()
44ee0b3b2c3fdc991e13a586f68ead4ef485f040
anuragchhipa123/ASD1998
/Day 3/intersection.py
206
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu May 9 12:35:09 2019 @author: DELL """ list1=set(input("Enter the set 1 : ")) list2=set(input("Enter the set 2 : ")) list3=list1.intersection(list2) print(list3)
313719a07a183df0ac5dd8f35adc3fbbda5b0129
refanr/2020
/sequence_analysis.py
2,731
3.71875
4
# Take in file names # For each file, open it and read it # Check if each number is actually a number and then put it in a sequence # Make a sorted sequence and an ordered sequence # Take the ordered sequence and find the median value # Finally print the results def process_all_files(filename_list): for file in filename_list: try: file_obj = open(file, "r") print('\nFile', file) read_from_file(file_obj) file_obj.close() except FileNotFoundError: print('\nFile', file, 'not found') def read_from_file(file_obj): sequence = [] working_number = 0.0 for line in file_obj: try: working_number = float(line.strip()) sequence.append(working_number) except ValueError: pass process_sequences(sequence) def process_sequences(sequence): cumulative_sequence = [] sorted_sequence = [] sorted_sequence += sequence working_number = 0.0 for num in sequence: working_number += float(num) cumulative_sequence.append(round(working_number,1)) sorted_sequence.sort() median = find_median(sorted_sequence) stringify_all(sequence, cumulative_sequence, sorted_sequence, median) def stringify_all(sequence, cumulative_sequence, sorted_sequence, median): sequen = '' cumulative = '' sorted = '' for i in range(0,len(sequence)): sequen = sequen + ' ' + str(sequence[i]) cumulative = cumulative + ' ' + str(cumulative_sequence[i]) sorted = sorted + ' ' + str(sorted_sequence[i]) print_all(sequen, cumulative, sorted, median) def find_median(sequence): length = len(sequence) median = 0.0 index = length // 2 try: if length % 2 == 0: median = (sequence[index-1] + sequence[index]) / 2 else: median = sequence[index] except IndexError: pass return round(median,2) def print_all(sequence, cumulative_sequence, sorted_seq, median): if len(sequence) != 0: sequence, cumulative_sequence, sorted_seq = sequence.strip() + ' ', cumulative_sequence.strip() + ' ', sorted_seq.strip() + ' ' else: sequence, cumulative_sequence, sorted_seq = sequence.strip(), cumulative_sequence.strip(), sorted_seq.strip() print("\tSequence:\n\t\t" + sequence) print("\tCumulative sum:\n\t\t" + cumulative_sequence) print("\tSorted sequence:\n\t\t" + sorted_seq) print("\tMedian:") if median != 0.0: print("\t\t" + str(median).strip()) else: print("\t\t") # Main program starts here filename_list = input("Enter filenames: ").split() process_all_files(filename_list)
84b41e6e8f04660a9328d3757e6900ba52311a5b
jacealan/eulernet
/level2/43-Sub-string divisibility.py
2,047
3.96875
4
#!/usr/local/bin/python3 ''' Problem 43 : Sub-string divisibility The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. https://projecteuler.net/problem=43 --- 프로그래머 Programmer : 제이스 Jace (https://jacealan.github.io) 사용언어 Language : 파이썬 Python 3.6.4 OS : macOS High Sierra 10.13.3 에디터 Editor : Visual Studio Code ''' def is_prime(x): '''솟수 여부 확인 솟수이면 True 솟수가 아니면 False''' if x == 1: return False for i in range(2, x // 2 + 1): if x % i == 0: return False return True def pandigital_list(digit, nums=[], n=['0', '1', '2', '3', '4']): '''Pandigital 만들기 n = ['1', '2', '3', '4'] pandigitals = pandigital_list(3, n, n) print(pandigitals[1]) ''' if digit == 1: return 0, nums, n new_nums = [] for num in nums[:]: for i in sorted(list(set(n) - set(num))): new_nums.append(num + i) return pandigital_list(digit - 1, new_nums, n) def solution(): divs = [2, 3, 5, 7, 11, 13, 17] n = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] pandigitals = pandigital_list(10, n, n) substring_divisibility = [] for num in pandigitals[1]: for i in range(2, 9): if int(num[i - 1:i + 2]) % divs[i - 2] != 0: break else: print(num, 'is Sub-string divisibility') substring_divisibility.append(int(num)) print(sum(substring_divisibility)) if __name__ == '__main__': solution()
bac4fec5d177b34c71b35dc5d55f0fc46d0a3c69
oshtyrov/Python-basics
/Shtyrov_Aleksandr_dz4/Shtyrov_Aleksandr_dz4/task_06.py
1,793
3.625
4
# 6. Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. # Обратите внимание, что создаваемый цикл не должен быть бесконечным. # Необходимо предусмотреть условие его завершения. # Например, в первом задании выводим целые числа, начиная с 3,а # при достижении числа 10 завершаем цикл. Во втором также необходимо # предусмотреть условие, при котором повторение элементов списка будет прекращено. from itertools import count, cycle from sys import argv # user_args = argv user_args = ('название файла', '3') def first_iter(*args): if len(args) == 2: for element in count(int(args[1])): if element > 10: break else: print(element) else: print('Неверное количество аргуметов') first_iter(*user_args) # some_list = argv some_list = ['1', '2', '3', '4', '5', '6', 'seven', 'eight', 'nine', 'ten'] def second_iter(*args): flag = 0 for element in cycle(args): print(element) flag += 1 if flag >= len(args): break second_iter(*some_list)
ee856624e0eee7fd7015064e72d544478b8caa73
yanivn2000/Python
/Syntax/Module6/05_exc_solution.py
491
3.640625
4
import re def find_match(pattern, string, index): x = re.search(pattern, string) if x: print(f"{index} - Match") else: print(f"{index} - No Match") find_match('^[0-9][0-9][^-].', 'a1a3', 1) # Y find_match('^[a-z][0-9][^-].', 'a1a3w', 1) # Y find_match('^[a-z][0-9][^-].', 'a1a', 1) # N (missing extra char for the period) find_match('^[a-z][0-9][^-].', '11a3', 1) # N find_match('^[a-z][0-9][^-].', 'aaa3', 1) # N find_match('^[a-z][0-9][^-].', 'a1-3', 1) # N
d698cf66a28a7564b335a532b2bc57f7fd8510fc
bimri/learning-python
/chapter_20/combining_items_in_iterables_reduce.py
1,273
4.09375
4
"Reduce function lives in functools module" # Accepts aan iterable to process, but it's bot an iterable itself # - it returns a single result. from functools import reduce # Import in 3.X # reduce passes the current sum or product. respectively print( reduce((lambda x, y: x + y), [1, 2, 3, 4]) ) print( reduce((lambda x, y: x * y), [1, 2, 3, 4]) ) # for loop equivalent of first case L = [1,2,3,4] res = L[0] for x in L[1:]: res = res + x print(res) "Custom own version of reduce" def myreduce(function, sequence): tally = sequence[0] for next in sequence[1:]: tally = function(tally, next) return tally print( myreduce((lambda x, y: x + y), [1,2,3,4,5]) ) print( myreduce((lambda x, y: x * y), [1, 2, 3, 4, 5]) ) ''' The built-in reduce also allows an optional third argument placed before the items in the sequence to serve as a default result when the sequence is empty ''' ''' operator module, which provides functions that correspond to builtin expressions and so comes in handy for some uses of functional tools ''' import operator, functools print( functools.reduce(operator.add, [2, 4, 6]) # function-based+ ) print( functools.reduce((lambda x, y: x + y), [2, 4, 6]) )
c812247a6f71e564c190b45916e4b969c6ce8ccc
jsgf/EyeFiServer
/Server/EyeFiCrypto.py
2,715
3.5
4
import binascii import struct import array import hashlib class EyeFiCrypto(): # The TCP checksum requires an even number of bytes. If an even # number of bytes is not passed in then nul pad the input and then # compute the checksum def calculateTCPChecksum(self, bytes): # If the number of bytes I was given is not a multiple of 2 # pad the input with a null character at the end if(len(bytes) % 2 != 0 ): bytes = bytes + "\x00" counter = 0 sumOfTwoByteWords = 0 # Loop over all the bytes, two at a time while(counter < len(bytes) ): # For each pair of bytes, cast them into a 2 byte integer (unsigned short) # Compute using little-endian (which is what the '<' sign if for) unsignedShort = struct.unpack("<H",bytes[counter:counter+2]) # Add them all up sumOfTwoByteWords = sumOfTwoByteWords + int(unsignedShort[0]) counter = counter + 2 # The sum at this point is probably a 32 bit integer. Take the left 16 bits # and the right 16 bites, interpret both as an integer of max value 2^16 and # add them together. If the resulting value is still bigger than 2^16 then do it # again until we get a value less than 16 bits. while (sumOfTwoByteWords >> 16): sumOfTwoByteWords = (sumOfTwoByteWords >> 16) + (sumOfTwoByteWords & 0xFFFF) # Take the one's complement of the result through the use of an xor checksum = sumOfTwoByteWords ^ 0xFFFFFFFF # Compute the final checksum by taking only the last 16 bits checksum = (checksum & 0xFFFF) return checksum def calculateIntegrityDigest(self, bytes, uploadkey): # If the number of bytes I was given is not a multiple of 512 # pad the input with a null characters to get the proper alignment while(len(bytes) % 512 != 0 ): bytes = bytes + "\x00" counter = 0 # Create an array of 2 byte integers concatenatedTCPChecksums = array.array('H') # Loop over all the bytes, using 512 byte blocks while(counter < len(bytes) ): tcpChecksum = self.calculateTCPChecksum(bytes[counter:counter+512]) concatenatedTCPChecksums.append(tcpChecksum) counter = counter + 512 # Append the upload key concatenatedTCPChecksums.fromstring(binascii.unhexlify(uploadkey)) # Get the concatenatedTCPChecksums array as a binary string integrityDigest = concatenatedTCPChecksums.tostring() # MD5 hash the binary string m = hashlib.md5() m.update(integrityDigest) # Hex encode the hash to obtain the final integrity digest integrityDigest = m.hexdigest() return integrityDigest
6c7ed0e8148d7f93313f5cffecb58c3f71010dd0
wzoreck/Curso_Python_Django
/Associacao_entre_classes/classes.py
1,019
3.796875
4
class Aluno: def __init__(self, nome, sexo): self.__nome = nome self.__sexo = sexo @property def nome(self): return self.__nome @nome.setter def nome(self, nome): self.__nome = nome @ property def sexo(self): return self.__sexo @sexo.setter def sexo(self, sexo): self.__sexo = sexo class Curso: def __init__(self, nome, aluno): self.__nome = nome self.__aluno = aluno @property def nome(self): return self.__nome @nome.setter def nome(self, nome): self.__nome = nome @property def aluno(self): return self.__aluno @aluno.setter def aluno(self, aluno): self.__aluno = aluno def mostrar_aluno(self): print(f'O aluno {self.__aluno.nome} está cadastrado no curso {self.__nome}') # MAIN a1 = Aluno('Daniel', 'Masculino') a1.nome = 'Daniel Wzoreck' print(a1.nome, a1.sexo) c1 = Curso('ADS', a1) c1.mostrar_aluno()
e1cf5c479c79e70f69b26a6f99ff480001384393
takaping/Hangman
/Hangman/task/hangman/hangman.py
1,161
3.8125
4
# Write your code here import random word_list = ['python', 'java', 'kotlin', 'javascript'] print('H A N G M A N') while input('Type "play" to play the game, "exit" to quit: ') == 'play': correct_word = random.choice(word_list) input_letters = set() mistakes = 0 while mistakes < 8: answer_word = ''.join([c if c in input_letters else '-' for c in correct_word]) print('\n' + answer_word) if '-' not in answer_word: print('You guessed the word!\nYou survived!') break letter = input('Input a letter: ') if len(letter) != 1: print('You should print a single letter') continue if not letter.isalpha() or not letter.islower(): print('It is not an ASCII lowercase letter') continue if letter in input_letters: print('You already typed this letter') continue if letter not in correct_word: mistakes += 1 print('No such letter in the word') input_letters.add(letter) else: print('You are hanged!') print()
465ef6df4694640dd49574c6d8e994e1ffd6eaff
AMEERAZAM08/Codeinplace-Stringoperation
/main.py
1,758
4.34375
4
#Strings are bits of text. They can be defined as anythi astring = "Hello world!" astring2 = 'Hello world!' astring = "Hello world!" print("single quotes are ' '") print(len(astring))#12 #count char in given string astring = "Hello world!" print(astring.count("l"))#3 #indexing in srting but can't change the string data astring = "Hello world!" print(astring[3:7]) ''' for example want to change the index char by other copy and run from outside the comment astring[0]='r' print(astring) this show the error while once you run ''' ''' There is no function like strrev in C to reverse a string. But with the above mentioned type of slice syntax you can easily reverse a string like this try please astring = "Hello world!" print(astring[::-1]) this is same while code for palindrom the string ''' ''' try Copy and past outside the comment and run astring = "Hello world!" afewwords = astring.split(" ") in split it will take some input as for which using you can split the string for example comma(,) undescore(_) etc ''' ''' lower case and upper case try Copy and past outside the comment and run astring = "Hello world!" print(astring.upper()) print(astring.lower())''' #follow this link for more with string '''https://www.w3schools.com/python/python_ref_string.asp''' #Upper case the first letter in this sentence: txt = "hello, and welcome to my world." x = txt.capitalize() print (x) # See what happens if the first character is a number: txt = "36 is my age." x = txt.capitalize() print (x) #Make the string lower case: txt = "Hello, And Welcome To My World!" x = txt.casefold() print(x) ''' next is based on Conditions like if else or using greater than equal to '''
ca2347e83c3e4315ae82462813910b4f6d26eabb
lumy/moulinette_simplon
/tests/rendu/lumy/part2/valid_password.py
529
3.609375
4
def has_alpha(string): for i in string: if 'a' <= i <= 'z' or 'A' <= i <= 'Z': return True return False def has_digit(string): for i in string: if '0' <= i <= '9': return True return False def has_special(string): for i in string: if not '0' <= i <= '9' and not 'a' <= i <= 'z' or 'A' <= i <= 'Z': return True return False def valid_password(string): return all((len(string) > 8, has_digit(string), has_alpha(string), has_special(string)) )
783c62937be52c125bc796749230c95e1da423a1
Skared15/Homework
/homework_1.py
1,266
3.953125
4
# Task=1 print("----------Que.-1--------") x,y,z=10,20.20,'Hello' print(x) print(y) print(z) print("--------Que.-2----------") a=2+4j b=2 a,b=b,a print("a=",a,"and","b=",b) print("---------Que.-3----------") a=1 b=2 q=a a=b b=q print("a=",a,"and","b=",b) a,b=b,a print("a=",a,"and","b=",b) print("----------Que.-4----------") type_here=input() print(type_here) print("----------Que.-5----------") print("Enter the two value in the range of 1 and 10") a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) if a and b in range (0,10): result=a+b+30 print(result) print("----------Que.-6-----------") print("Enter any data to see it's data type") h=input() p=type(h) print("The input value Data type is:",p) print("----------Que.-7-----------") s =str(input()) def convert(s): if(len(s) == 0): return s1 = '' s1 += s[0].upper() for i in range(1, len(s)): if (s[i] == ' '): s1 += s[i + 1].upper() i += 1 elif(s[i - 1] != ' '): s1 += s[i] print("CamelCase:",s1) convert(s) print("Uppercase:",s.upper()) print("Lowercase:",s.lower()) print("----------Que.-8-----------") g=3 print(g) print(type(g)) g="three" print(g) print(type(g))
81d96fdb11384cac3875c564e3110148ca479d31
jiangyihong/PythonTutorials
/chapter9/my_die.py
253
3.578125
4
from chapter9.die import Die six_die = Die() for i in range(0, 10): six_die.roll_die() print("\n") ten_die = Die(10) for j in range(0, 10): ten_die.roll_die() print("\n") twenty_die = Die(20) for k in range(0, 10): twenty_die.roll_die()
53a43f3febef8c5fb2351ea735d2644a4fa189c8
sylverpyro/python-the-hard-way
/ex5.py
685
4
4
name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print ( "Let's talk about %s." % name ) print ( "He's %r inches tall." % height ) print ( " Which is %f cm." % ( height * 30.48 ) ) print ( "He's %r pounds heavy." % weight ) print ( " Which is %f kilograms." % ( weight * 0.453592 ) ) print ( "Actually that's not too heavy." ) print ( "He's got %s eyes and %s hair." % (eyes, hair) ) print ( "His teeth are usually %s depending on the coffee." % teeth ) # this line is tricky, try to get it exactly right print ( "If I add %r, %r, and %r I get %r." % ( age, height, weight, age + height + weight ) )
3450e4977d454ca636eb5d02e711c89047b8c7c3
VerdantFox/flask_course
/02-Flask-Basics/05-Routing_Exercise.py
834
3.5
4
# Set up your imports here! from flask import Flask, request app = Flask(__name__) @app.route("/") # Fill this in! def index(): # Welcome Page # Create a generic welcome page. page = "<h1>Welcome! Go to /puppy_latin/name to see your name in puppy latin</h1>" return page @app.route("/puppy_latin/<name>") # Fill this in! def puppy_latin(name): # This function will take in the name passed # and then use "puppy-latin" to convert it! # HINT: Use indexing and concatenation of strings # For Example: "hello"+" world" --> "hello world" if name.endswith('y'): new_name = name[:-1] + 'iful' else: new_name = name + 'y' page = f"<h1>Hi {name}! Your puppylatin name is {new_name}</h1>" return page if __name__ == "__main__": # Fill me in! app.run(debug=True)
6b3e4b5a126c41224f67b823597dd6c22e3f8a73
hnm6500/csci141---python
/findWord (1).py
1,166
4.34375
4
#Hrishikesh N Moholkar import turtle def Count_Words(textFileName): """ this function counts the no.of spaces between the words and adds one which equals to number of words. :param:textFileName :return: """ count=0 """count variable is assigned to count number of spaces. no.of words=no.of spaces between words+1. """ """ s.strip()command removes white spaces and new lines in the string. """ for line2 in open(textFileName): line1=line2.strip() for char1 in line1: """counts only the no.of spaces between words.whose var1=0 and it becomes one when encountered space character and increases count. """ if char1==" ": if var1==0: count=count+1 var1=1 else: var1=0 if line1 != "" : count=count+1 print("number of words in file",count) def main(): textFileName=input("Enter filename:") Count_Words(textFileName) main() input("press enter to exit")
2a9eed6bfbee5b1c83bcadb3f4096eaa336c7c0b
hellyhe/python-django-sample
/alg/sort.py
774
4.125
4
# -*- coding: utf-8 -*- import random def sort_print(func, items=None): """ Create random data and sort """ if items is None: items = [random.randint(-50, 100) for c in range(32)] print 'before sort use <%s>: %s' % (func.func_name, items) sorted_items = func(items) print 'before sort use <%s>: %s' % (func.func_name, sorted_items) def bubble_sort(items): """ Implementation of bubble sort """ len_items = len(items) # 第i大/小 for i in range(len_items): # 从剩余的LEN-i中冒泡得到 for j in range(len_items - 1 - i): if items[j] > items[j + 1]: items[j], items[j + 1] = items[j + 1], items[j] return items if __name__ == '__main__': sort_print(func=bubble_sort)
0e3359fd8cf67053951719097aa567a20bd4f3e2
Adam1997/extended_euclidean_solver
/matrix.py
1,121
3.53125
4
class Matrix: #functional def __init__(self, r, c): self.nrow = r self.ncol = c self.data = [[0]*r,[0]*c] #other parameterised constructors needed def getCol(self): return self.ncol def getRow(self): return self.nrow #setters def setData(self, list): for row in range(len(list)): for col in range(len(list[row])): self.data[row][col] = list[row][col] def multiply(self, other): #need to check if defined result = Matrix(self.getRow(), other.getCol()) for row in range(self.getRow()): for col in range(other.getCol()): for item in range(self.getCol()): result.data[row][col] += self.data[row][item] * other.data[item][col] return result def __str__(self): result = "" for row in range(len(self.data)): result = result + "[" for col in range(len(self.data[row])): result = result + str(self.data[row][col]) + " " result = result + "] \n" return result
5272bf8112c361cf7e64a978a875f73e8d593783
share020/dl
/assignments/mp2/src/utils.py
4,084
3.953125
4
""" HW2: Implement and train a convolution neural network from scratch in Python for the MNIST dataset (no PyTorch). The convolution network should have a single hidden layer with multiple channels. Due September 14 at 5:00 PM. @author: Zhenye Na @date: Sep 9 """ import h5py import numpy as np def mnist_loader(path, one_hot=False, debug=True): """ Load MNIST Dataset. inputs: path: str, path to dataset outputs: (x_train, y_train), (x_test, y_test): training set, test set """ # load MNIST data print(">>> Loading MNIST dataset...") MNIST_data = h5py.File(path, 'r') x_train = np.float32(MNIST_data['x_train'][:]) y_train = np.int32(np.array(MNIST_data['y_train'][:, 0])) x_test = np.float32(MNIST_data['x_test'][:]) y_test = np.int32(np.array(MNIST_data['y_test'][:, 0])) MNIST_data.close() # reshape input images shape = (-1, 1, 28, 28) x_train = x_train.reshape(shape) x_test = x_test.reshape(shape) if one_hot: y_train = one_hot_encode(y_train, 10) y_test = one_hot_encode(y_test, 10) if debug: num_training, num_test = 20480, 10000 x_train, y_train = x_train[range(num_training)], y_train[range(num_training)] x_test, y_test = x_test[range(num_test)], y_test[range(num_test)] return (x_train, y_train), (x_test, y_test) def one_hot_encode(y, num_class): """ One-Hot Encoding inputs: y: ground truth label num_class: number of classes return: onehot: one-hot encoded labels """ m = y.shape[0] onehot = np.zeros((m, num_class), dtype="int32") for i in range(m): onehot[i][y[i]] = 1 return onehot def softmax(x): """ Perform Softmax return: np.exp(x) / np.sum(np.exp(x)) """ exp_x = np.exp(x - np.max(x, axis=1, keepdims=True)) return exp_x / np.sum(exp_x, axis=1, keepdims=True) def get_im2col_indices(x_shape, field_height=3, field_width=3, padding=1, stride=1): # First figure out what the size of the output should be N, C, H, W = x_shape assert (H + 2 * padding - field_height) % stride == 0 assert (W + 2 * padding - field_height) % stride == 0 out_height = (H + 2 * padding - field_height) / stride + 1 out_width = (W + 2 * padding - field_width) / stride + 1 i0 = np.repeat(np.arange(field_height, dtype='int32'), field_width) i0 = np.tile(i0, C) i1 = stride * np.repeat(np.arange(out_height, dtype='int32'), out_width) j0 = np.tile(np.arange(field_width), field_height * C) j1 = stride * np.tile(np.arange(out_width, dtype='int32'), int(out_height)) i = i0.reshape(-1, 1) + i1.reshape(1, -1) j = j0.reshape(-1, 1) + j1.reshape(1, -1) k = np.repeat(np.arange(C, dtype='int32'), field_height * field_width).reshape(-1, 1) return (k, i, j) def im2col_indices(x, field_height=3, field_width=3, padding=1, stride=1): """ Implement im2col util function """ # Zero-pad the input p = padding x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant') k, i, j = get_im2col_indices( x.shape, field_height, field_width, padding, stride) cols = x_padded[:, k, i, j] C = x.shape[1] cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1) return cols def col2im_indices(cols, x_shape, field_height=3, field_width=3, padding=1, stride=1): """ Implement col2im based on fancy indexing and np.add.at """ N, C, H, W = x_shape H_padded, W_padded = H + 2 * padding, W + 2 * padding x_padded = np.zeros((N, C, H_padded, W_padded), dtype=cols.dtype) k, i, j = get_im2col_indices( x_shape, field_height, field_width, padding, stride) cols_reshaped = cols.reshape(C * field_height * field_width, -1, N) cols_reshaped = cols_reshaped.transpose(2, 0, 1) np.add.at(x_padded, (slice(None), k, i, j), cols_reshaped) if padding == 0: return x_padded return x_padded[:, :, padding:-padding, padding:-padding]
9bd1fc3c3e376535f512e379ff7fbea0f77f8aff
PeterHinge/CodingBat-Python-exercises
/String-2.py
2,223
4.0625
4
# String-2 """Given a string, return a string where for every char in the original, there are two chars.""" def double_char(str): double_str = "" for i in str: double_str += i * 2 return double_str """Return the number of times that the string "hi" appears anywhere in the given string.""" def count_hi(str): hi_count = 0 for i in range(len(str) - 1): if str[i:i + 2] == "hi": hi_count += 1 return hi_count """Return True if the string "cat" and "dog" appear the same number of times in the given string.""" def cat_dog(str): cat_count = 0 dog_count = 0 for i in range(len(str) - 2): if str[i:i + 3] == "cat": cat_count += 1 if str[i:i + 3] == "dog": dog_count += 1 return cat_count == dog_count # A dictionary/hashtable solution: def cat_dog(str): dic = {"cat": 0, "dog": 0} for categorie in dic: for i in range(len(str) - 2): if str[i:i + 3] == categorie: dic[categorie] += 1 return dic["cat"] == dic["dog"] """Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.""" def count_code(str): code_count = 0 for i in range(len(str) - 3): if str[i:i + 2] == "co" and str[i + 3] == "e": code_count += 1 return code_count """Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string.""" def end_other(a, b): low_a = a.lower() low_b = b.lower() short_lst = min(len(a), len(b)) if low_a == low_b[-short_lst:] or low_b == low_a[-short_lst:]: return True return False """Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceded by a period (.). So "xxyz" counts but "x.xyz" does not.""" def xyz_there(str): for i in range(len(str) - 2): if str[i:i + 3] == "xyz" and not str[i - 1] == ".": return True return False
318cb258d178464455cce312121f50125fec5a4f
hassan652/MRSP
/Useful Functions/auto_corr_Axx.py
473
4.09375
4
''' Imagine we have a matrix X = np.matrix([[2.1,6.6],[4.6,5.3]]) Calculate autocorrelation function Axx. In the answer field provide Axx(1,1) using Matlab notation. ''' import numpy as np X = np.matrix([[2.1,6.6],[4.6,5.3]]) print('original matrix\n',X) Xtrans = X.T print('Transpose matrix\n',Xtrans) Auto_correlation = np.dot(Xtrans,X) print('Autocorr matrix\n',Auto_correlation) print("Matlab (1,1) is (0,0) in python") print('required value\n',Auto_correlation[0,0])
59e8f7e90985c0462693ad418a2c109a1b229133
tomervain/vocaptcha
/lib/tts_module.py
2,334
3.734375
4
from google.cloud import texttospeech as tts from playsound import playsound as ps import os def text_to_speech(input_text): # Instantiates a client client = tts.TextToSpeechClient() # Set the text input to be synthesized synthesis_input = tts.SynthesisInput(text=input_text) # Build the voice request, select the language code ("en-US") and the ssml # voice gender ("neutral") voice = tts.VoiceSelectionParams( language_code='en-US', ssml_gender=tts.SsmlVoiceGender.FEMALE) # Select the type of audio file you want returned audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16) # Perform the text-to-speech request on the text input with the selected # voice parameters and audio file type response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config) # The response's audio_content is binary. path = input_text.replace('?', '') + '.wav' with open(path, 'wb') as out: # Write the response to the output file. out.write(response.audio_content) print('Audio content written to file ' + path) # play the file ps(path) os.remove(path) def text_to_speech(input_text, aw): # Instantiates a client client = tts.TextToSpeechClient() # Set the text input to be synthesized synthesis_input = tts.SynthesisInput(text=input_text) # Build the voice request, select the language code ("en-US") and the ssml # voice gender ("neutral") voice = tts.VoiceSelectionParams( language_code='en-US', ssml_gender=tts.SsmlVoiceGender.FEMALE) # Select the type of audio file you want returned audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16) # Perform the text-to-speech request on the text input with the selected # voice parameters and audio file type response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config) # The response's audio_content is binary. path = input_text.replace('?', '') + '.wav' with open(path, 'wb') as out: # Write the response to the output file. out.write(response.audio_content) print('Audio content written to file ' + path) # play the file aw.play(path) os.remove(path)
b212d0fc905e347b54cd948f08ac848293c71c60
hhhhhhhhhh16564/pythonLearn
/11/01.多进程.py
6,753
4.03125
4
# Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。普通的函数调用, # 调用一次,返回一次,但是fork()调用一次,返回两次,因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程), # 然后,分别在父进程和子进程内返回。 # 子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,一个父进程可以fork出很多子进程, # 所以,父进程要记下每个子进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID。 # # Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程: import os #拿到本进程的ID os.getpid() #拿到父进程的ID os.getppid() print('Process (%s) start...' % os.getpid()) # Only works on Unix/Linux/Mac: pid = 1 # pid = os.fork() print('**********') if pid == 0: print('I am child process (%s) and my parent is %s' % (os.getpid(), os.getppid())) else: print('I (%s) just create a child process(%s)' % (os.getpid(), pid)) #因为两个进程,所以下边的代码会打印两便 print('hhhh %s' % os.getpid()) # Process (6752) start... # # I (6752) just create a child process(6753) # # hhhh 6752 # # I am child process (6753) and my parent is 6752 # # hhhh 6753 # 由于Windows没有fork调用,上面的代码在Windows上无法运行。 # 有了fork调用,一个进程在接到新任务时就可以复制出一个子进程来处理新任务, # 常见的Apache服务器就是由父进程监听端口,每当有新的http请求时,就fork出子进程来处理新的http请求。 # multiprocessing # 由于Python是跨平台的,自然也应该提供一个跨平台的多进程支持。multiprocessing模块就是跨平台版本的多进程模块。 # multiprocessing模块提供了一个Process类来代表一个进程对象,下面的例子演示了启动一个子进程并等待其结束: print('\n\n\n\n\n') from multiprocessing import Process import os # 子进程要执行的代码 def run_proc(name): print('Run child process %s (%s)' % (name, os.getpid())) if __name__ =='__main__': print('parent process %s' % os.getpid()) p = Process(target=run_proc, args=('test', )) print('child process will start.') p.start() p.join() print('Child process end.') #运行结果 # parent process 8520 # child process will start. # Run child process test (8521) # Child process end. # # 创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动,这样创建进程比fork()还要简单。 # join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。 #如果要启动大量的子进程,可以用进程池的方式批量创建子进程: from multiprocessing import Pool import os, time, random #random.random()用于生成一个0到1的随机浮点数 0 <= n <= 1.0 print('\n\n\n\n\n------------------') def long_time_task(name): print('Run task %s (%s)...' %(name, os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() print('Task % run %0.2f seconds.' % (name, (end-start))) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocess done...') p.close() p.join() print('All subprocesses done.') # 对Pool对象调用join()方法会等待所有子进程执行完毕, # 调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。 # task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行, # 这是因为Pool的默认大小是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。 # 子进程 # subprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出。 # # 下面的例子演示了如何在Python代码中运行命令nslookup www.python.org,这和命令行直接运行的效果是一样的: print('\n\n\n\n\n^^^^^^^^^^^^^^^^^^') import subprocess print('$ nslookup www.python.org') r = subprocess.call(['nslookup', 'www.python.org']) print('Exit Code:', r) # 如果子进程还需要输入,则可以通过communicate()方法输入: print('\n\n\n\n\n*************') import subprocess print('$ nslookup') p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = p.communicate(b'set q=mx\npython.org\nexit\n') print(output.decode('utf-8')) print('Exit code;', p.returncode) # 上面的代码相当于在命令行执行命令nslookup,然后手动输入: # # set q=mx # python.org # exit print('\n\n\n\n\n\\\\\\\\\\\\\\\\\\\\\\\\\\') #进程间通信 # Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。 # 我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据: from multiprocessing import Process, Queue import os, time, random # # #写数据进程执行的代码 def write(q): print('Process to write %s' % os.getpid()) for value in ('A', 'B', 'C'): print('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) def read(q): print('Process to read : %s' % os.getpid()) while True: value = q.get(True) print('Get %s from queue. ' % value) if __name__ == '__main__': #父进程创建Queue, 并传给各个子进程 q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) #启动子进程,写入 pw.start() # 启动子进程pr,读取: pr.start() # 等待pw结束 pw.join() # pr进程里是死循环,无法等待其结束,只能强行终止: pr.terminate() # # 在Unix/Linux下,multiprocessing模块封装了fork()调用,使我们不需要关注fork()的细节。由于Windows没有fork调用,因此,multiprocessing需要“模拟”出fork的效果,父进程所有Python对象都必须通过pickle序列化再传到子进程去,所有,如果multiprocessing在Windows下调用失败了,要先考虑是不是pickle失败了。 # # 小结 # 在Unix/Linux下,可以使用fork()调用实现多进程。 # # 要实现跨平台的多进程,可以使用multiprocessing模块。 # # 进程间通信是通过Queue、Pipes等实现的。
11a6a3e6103a49eb24c254ceef533d8f9b515dac
thisLexic/csci-51.01-proj
/proj.py
17,009
3.5
4
def get_details(process_list): process_list.sort() process_count = len(process_list) total_waiting_time = 0 total_turnaround_time = 0 total_response_time = 0 print("Waiting times: ") for p in process_list: print(" Process ", p[0], ": ", p[4], "ns", sep="") total_waiting_time += p[4] print("Average waiting time: ", total_waiting_time/process_count, "ns", sep="") print("Turnaround times: ") for p in process_list: print(" Process ", p[0], ": ", p[5], "ns", sep="") total_turnaround_time += p[5] print("Average turnaround time: ", total_turnaround_time/process_count, "ns", sep="") print("Response times: ") for p in process_list: print(" Process ", p[0], ": ", p[6], "ns", sep="") total_response_time += p[6] print("Average response time: ", total_response_time/process_count, "ns", sep="") def FCFS(process_list): ready_queue = [] terminated = [] elapsed_time = 0 completed = 0 total_burst_time = 0 process_count = len(process_list) while completed != process_count: # Checks if there are processes we can add to the ready queue for process in process_list: # If there are processes available to be added # to the ready queue, then this moves # the process to the ready queue if process[1] <= elapsed_time: ready_queue.append(process) process_list.remove(process) if (len(ready_queue)!= 0): while (len(ready_queue)!= 0): for p in ready_queue: if p[1] > elapsed_time: p[7] = p[1] else: p[7] = elapsed_time if p[1] < elapsed_time: p[4] = elapsed_time - p[1] p[5] = p[4] + p[2] p[6] = p[4] elapsed_time += p[2] total_burst_time += p[2] print(p[7], " ", p[0], " ", p[2],"X", sep="") terminated.append(p) ready_queue.remove(p) completed += 1 else: elapsed_time += 1 print("Total time elapsed: ", elapsed_time, "ns", sep="") print("Total CPU burst time: ", total_burst_time, "ns", sep="") print("CPU Utilization: ", (total_burst_time/elapsed_time)*100, "%", sep="") print("Throughput: ", (process_count/elapsed_time), " processes/ns", sep="") get_details(terminated) def SJF(process_list): ready_queue = [] terminated = [] elapsed_time = 0 completed = 0 total_burst_time = 0 process_count = len(process_list) process_list = sorted(process_list, key=lambda x: x[2]) while completed != process_count: # Checks if there are processes we can add to the ready queue for process in process_list: # If there are processes available to be added # to the ready queue, then this moves # the process to the ready queue if process[1] <= elapsed_time: ready_queue.append(process) process_list.remove(process) break if (len(ready_queue)!= 0): while (len(ready_queue)!= 0): for p in ready_queue: if p[1] > elapsed_time: p[7] = p[1] else: p[7] = elapsed_time if p[1] < elapsed_time: p[4] = elapsed_time - p[1] p[5] = p[4] + p[2] p[6] = p[4] elapsed_time += p[2] total_burst_time += p[2] print(p[7], " ", p[0], " ", p[2],"X", sep="") terminated.append(p) ready_queue.remove(p) completed += 1 else: elapsed_time += 1 print("Total time elapsed: ", elapsed_time, "ns", sep="") print("Total CPU burst time: ", total_burst_time, "ns", sep="") print("CPU Utilization: ", (total_burst_time/elapsed_time)*100, "%", sep="") print("Throughput: ", (process_count/elapsed_time), " processes/ns", sep="") get_details(terminated) ready_queue = [] terminated = [] elapsed_time = 0 # completed = 0 total_burst_time = 0 process_count = len(process_list) # process_list = sorted(process_list, key=lambda x: x[2]) while len(terminated) != process_count: for p in process_list: if p[1] <= elapsed_time: ready_queue.append(p) process_list.remove(p) ready_queue = sorted(ready_queue, key=lambda x: x[2]) if (len(ready_queue) != 0): previous_burst_pid = ready_queue[0][0] # Shortest burst changed in ready queue changed if (previous_burst_pid != ready_queue[0][0]): print(p[7], " ", p[0], " ", p[2],"X", sep="") ready_queue[0][2] -= 1 elapsed_time += 1 if(ready_queue[0][2]==0): terminated.append(ready_queue[0]) ready_queue.remove(ready_queue[0]) print("Total time elapsed: ", elapsed_time, "ns", sep="") print("Total CPU burst time: ", total_burst_time, "ns", sep="") print("CPU Utilization: ", (total_burst_time/elapsed_time)*100, "%", sep="") print("Throughput: ", (process_count/elapsed_time), "processes/ns", sep="") get_details(terminated) def RR(process_list, time_quantum): round_robin_queue = [] arrival_queue = [] terminated = [] original_burst_times = [] for p in process_list: original_burst_times.append(p[2]) elapsed_time = 0 total_burst_time = 0 process_count = len(process_list) while len(terminated) != process_count: # Adds all viable processes in round robin queue for p in process_list[:]: if p[1] <= elapsed_time and p[9] == 0: p[9] = 1 # Flag Bit p[7] = p[1] # Start Time arrival_queue.append(p) process_list.remove(p) # print("Process",p[0], "added to ready queue at", elapsed_time, "entered with the state", p) if len(arrival_queue) != 0: for p in arrival_queue: # print("Process",p[0], "at", elapsed_time, "entered arrival queue with the state", p) if p[6] == -1: p[6] = elapsed_time - p[7] # Response Time time_before_processing = elapsed_time for i in range(time_quantum): p[2] -= 1 elapsed_time += 1 total_burst_time += 1 if p[2] == 0: print(time_before_processing," ",p[0]," ",elapsed_time-time_before_processing, "X", sep="") p[5] = elapsed_time - p[1] # Turnaround Time terminated.append(p) arrival_queue.remove(p) break if p[2]>0: print(time_before_processing, p[0], elapsed_time-time_before_processing) # p[4] = elapsed_time-time_before_processing # Waiting Time # print("Process",p[0], "at", elapsed_time, "added to rr queue from arrival", p) round_robin_queue.append(p) arrival_queue.remove(p) elif len(round_robin_queue) != 0: for p in round_robin_queue[:]: if p[10] == 0: # print("Process",p[0], "at", elapsed_time, "entered if with the state", p) p[9] = 0 # Arrival Queue Bit p[10] = 1 # Passed Bit time_before_processing = elapsed_time for i in range(time_quantum): p[2] -= 1 total_burst_time += 1 elapsed_time += 1 if p[2] == 0: print(time_before_processing," ",p[0]," ",elapsed_time-time_before_processing, "X", sep="") # print("Process",p[0], "terminated at:", elapsed_time) p[5] = elapsed_time - p[1] # Turnaround Time terminated.append(p) round_robin_queue.remove(p) break p[4] += elapsed_time-time_before_processing # Waiting Time if p[2] > 0: print(time_before_processing, p[0], elapsed_time-time_before_processing) # print("Process",p[0], "at", elapsed_time, "exited if with the state", p) else: # print("Process",p[0], "at", elapsed_time, "entered else") elements_passed = 0 for p in round_robin_queue: elements_passed += p[10] if elements_passed == len(round_robin_queue): # print("Process",p[0], "at", elapsed_time, "RESET THE QUEUE") for p in round_robin_queue: # print("Process",p[0], "'s p[10] modified at:", elapsed_time) p[10] = 0 break # Check if there are new processes to be added to the round robin queue for p in process_list[:]: if p[1] <= elapsed_time and p[9] == 0: p[9] = 1 # Flag Bit p[7] = p[1] # Start Time arrival_queue.append(p) process_list.remove(p) # print("Process",p[0], "added to arrival queue at", elapsed_time, "entered with the state", p) if(len(arrival_queue)>0): break else: elapsed_time += 1 terminated = sorted(terminated, key=lambda x: x[0]) # Waiting Time for i in range(process_count): terminated[i][4] = terminated[i][5] - original_burst_times[i] # print(original_burst_times) print("Total time elapsed: ", elapsed_time, "ns", sep="") print("Total CPU burst time: ", total_burst_time, "ns", sep="") print("CPU Utilization: ", (total_burst_time/elapsed_time)*100, "%", sep="") print("Throughput: ", (process_count/elapsed_time), " processes/ns", sep="") get_details(terminated) def PRIO(process_list): ready_queue = [] terminated = [] elapsed_time = 0 total_burst_time = 0 time_before_processing = 0 previous_tbp = 0 process_count = len(process_list) original_burst_times = [] for p in process_list: original_burst_times.append(p[2]) while len(terminated) != process_count: for p in process_list[:]: if p[1] <= elapsed_time: p[7] = elapsed_time # Start Time ready_queue.append(p) process_list.remove(p) ready_queue = sorted(ready_queue, key=lambda x: x[3]) if len(ready_queue) != 0: if ready_queue[0][6] == -1: ready_queue[0][6] = elapsed_time - ready_queue[0][7] # Response Time ready_queue[0][2] -= 1 elapsed_time += 1 total_burst_time += 1 if ready_queue[0][2] == 0: ready_queue[0][8] = elapsed_time # End Time ready_queue[0][5] = ready_queue[0][8] - ready_queue[0][7] # Turnaround Time print(time_before_processing," ",ready_queue[0][0]," ",elapsed_time-time_before_processing,"X",sep="") terminated.append(ready_queue[0]) ready_queue.pop(0) time_before_processing = elapsed_time # Checks if new element can be added for p in process_list[:]: previous_shortest = ready_queue[0] previous_tbp = time_before_processing if p[1] <= elapsed_time: time_before_processing = elapsed_time p[7] = elapsed_time # Start Time ready_queue.append(p) process_list.remove(p) ready_queue = sorted(ready_queue, key=lambda x: x[3]) # If new shortest if previous_shortest[0] != ready_queue[0][0]: print(previous_tbp," ",previous_shortest[0]," ",time_before_processing-previous_tbp, sep="") else: elapsed_time += 1 terminated = sorted(terminated, key=lambda x: x[0]) # Waiting Time for i in range(process_count): terminated[i][4] = terminated[i][5] - original_burst_times[i] print("Total time elapsed: ", elapsed_time, "ns", sep="") print("Total CPU burst time: ", total_burst_time, "ns", sep="") print("CPU Utilization: ", (total_burst_time/elapsed_time)*100, "%", sep="") print("Throughput: ", (process_count/elapsed_time), " processes/ns", sep="") get_details(terminated) def SRTF(process_list): ready_queue = [] terminated = [] elapsed_time = 0 total_burst_time = 0 time_before_processing = 0 previous_tbp = 0 process_count = len(process_list) original_burst_times = [] for p in process_list: original_burst_times.append(p[2]) while len(terminated) != process_count: for p in process_list[:]: if p[1] <= elapsed_time: p[7] = elapsed_time # Start Time ready_queue.append(p) process_list.remove(p) ready_queue = sorted(ready_queue, key=lambda x: x[2]) if len(ready_queue) != 0: if ready_queue[0][6] == -1: ready_queue[0][6] = elapsed_time - ready_queue[0][7] # Response Time ready_queue[0][2] -= 1 elapsed_time += 1 total_burst_time += 1 if ready_queue[0][2] == 0: ready_queue[0][8] = elapsed_time # End Time ready_queue[0][5] = ready_queue[0][8] - ready_queue[0][7] # Turnaround Time print(time_before_processing," ",ready_queue[0][0]," ",elapsed_time-time_before_processing,"X",sep="") terminated.append(ready_queue[0]) ready_queue.pop(0) time_before_processing = elapsed_time # Checks if new element can be added for p in process_list[:]: previous_shortest = ready_queue[0] previous_tbp = time_before_processing if p[1] <= elapsed_time and previous_shortest[2] > p[2]: time_before_processing = elapsed_time p[7] = elapsed_time # Start Time ready_queue.append(p) process_list.remove(p) ready_queue = sorted(ready_queue, key=lambda x: x[2]) # If new shortest if previous_shortest[0] != ready_queue[0][0]: print(previous_tbp," ",previous_shortest[0]," ",time_before_processing-previous_tbp, sep="") else: elapsed_time += 1 terminated = sorted(terminated, key=lambda x: x[0]) # Waiting Time for i in range(process_count): terminated[i][4] = terminated[i][5] - original_burst_times[i] print("Total time elapsed: ", elapsed_time, "ns", sep="") print("Total CPU burst time: ", total_burst_time, "ns", sep="") print("CPU Utilization: ", (total_burst_time/elapsed_time)*100, "%", sep="") print("Throughput: ", (process_count/elapsed_time), " processes/ns", sep="") get_details(terminated) if __name__ =="__main__": t = int(input("Enter number of test cases: ")) for i in range(t): processes = [] s = input("Enter number of processes and the algorithm: ").split() for j in range(int(s[0])): # Process ID [0], Arrival Time [1], Burst Time [2], Priority [3], Wait Time [4], # Turnaround Time [5], Response Time [6], Start Time [7], Finish Time [8], Flag Bit [9], Terminated [10] processes.append([j+1]+list(map(int, input().split()))+[0,-1,-1,-1,0,0,0]) print(str(i+1), ". ", s[1], sep="") if (s[1] == "FCFS"): FCFS(processes) elif(s[1] == "SJF"): SJF(processes) elif(s[1] == "SRTF"): SRTF(processes) elif(s[1] == "P"): PRIO(processes) elif(s[1] == "RR"): RR(processes, int(s[2]))
ecc0fd5e604b877595013cacf25667129d7b0c01
nirajgolhar/python-basics-programs
/Python Basics/age.py
160
3.90625
4
a=int(input('Enter a age')) if(a>=18): print(a,'you are Eligible') else: print(a,'you are not Eligible') print("wait for",18-a,"Years")
38be9854a7c30f8c7974c4647028e65fb55eda09
Elmorew3721/CTI110
/P1Lab3_Interleved_ElmoreWalker.py
71
3.8125
4
print('Enter x: ') x = int(5) print(x) print('x doubled is:', (2 * x))
29cd5f99db6ba2b33f5dab647417c50f96c740a8
jackson-leite/Atividade-PBD-Semana03
/ex04.py
2,142
3.890625
4
"""2 Uma pista de Kart permite 10 voltas para cada um de 6 corredores. Escreva um programa que leia todos os tempos em segundos e os guarde em um dicionário, em que a chave é o nome do corredor. Ao final diga de quem foi a melhor volta da prova e em que volta; e ainda a classificação final em ordem (1o o campeão). O campeão é o que tem a menor média de tempos.""" num_corredores = 6 num_voltas = 10 i = 0 dicionario = {} d = {} #entrada de dados while i < num_corredores: melhor_volta, menor_volta, soma, j, k = 0, 0, 0, 0, 0 media = 0.0 lista_tempos = [] lista_aux = [] nome = input(f'Informe o nome do {i+1}o corredor: ') while j < num_voltas: tempo = float(input(f'Informe o tempo da {j+1}a volta: ')) lista_tempos.append(tempo) soma = soma + tempo j += 1 media = soma/num_voltas lista_aux = sorted(lista_tempos) menor_volta = lista_aux[0] while k < len(lista_tempos): if menor_volta == lista_tempos[k]: melhor_volta = k+1 break k += 1 #populando o dicionario com informaçoes fornecidas d[nome] = [media, menor_volta, melhor_volta] #dicionario[nome], dicionario['media'], dicionario['menor volta'], dicionario['melhor volta'] = lista_tempos, media, menor_volta, melhor_volta i += 1 #menor volta de todos melhor_media = d[nome][1] melhor_corredor = nome i = 0 for corredor in d: while i < num_voltas: if d[corredor][0] < melhor_media: melhor_corredor = corredor else: pass i += 1 print('O melhor corredor foi '+ melhor_corredor + '. Que fez a menor volta:', d[melhor_corredor][1], '. Na volta:', d[melhor_corredor][2]) print('Classificação final:') colocacao = 1 #invertendo os pares chave-valor dic_m = {} for n in d: m = d[n][0] dic_m[m] = n l = sorted(dic_m) #mostrando as colocações agora com a média ordenada sendo a chave e o nome dos colocados, o valor for item in l: print(f'{colocacao}o Lugar:', dic_m[item]) colocacao += 1
0d9a064535819a28860bfdd63aaba84760b407f9
Daksh-CodingCamp/Python-Tutorial-
/List in Python Part1.py
180
3.796875
4
list1 = ['pencil', 'pen', 'eraser', 'sharpner'] print(type(list1)) list2 = [45, 44, 85, 99, 100] list2.append("hi") print(list2[2:5:2]) xyz = list2[2:5:2] xyz.reverse() print(xyz)
954197923782f9e7ef53983149b2172bba88e0d8
XxdpavelxX/Python-Algorithms-and-Problems
/Interview Questions Practice/absolute_min.py
619
3.671875
4
#Given three arrays A,B,C containing unsorted numbers. Find three numbers a, b, c from each of array A, B, C such that |a-b|, #|b-c| and |c-a| are minimum Please provide as efficient code as you can. Can you better than this ??? list1 = [1,3,5,4,9] list2 = [0,8,7,6,2] list3= [12,3,9,6,15] def finder(listy1,listy2,listy3): listy1.sort() listy2.sort() listy3.sort() min=999999999999999 for a in listy1: for b in listy2: for c in listy3: if abs(a-b)+abs(b-c)+abs(c-a) < min: min = abs(a-b)+abs(b-c)+abs(c-a) x1=a x2=b x3=c print min, x1,x2,x3 finder(list1,list2,list3)
b48509aa24efaf8763f44cf7b467797b53bbd570
Nurtal/NETABIO
/netabio/na_manager.py
10,932
3.5625
4
""" => Deal with NA in data files """ import matplotlib matplotlib.use('TkAgg') from matplotlib import pyplot as plt import operator def check_NA_proportion_in_file(data_file_name): """ -> data_file_name is a csv file, generate via the reformat_luminex_raw_data() function -> Evaluate the proportion of NA values in each variable -> return a dictionnary """ position_to_variable = {} variable_to_NA_count = {} ## Count NA values for each variable ## in data file. cmpt = 0 input_data = open(data_file_name, "r") for line in input_data: line = line.split("\n") line = line[0] line_in_array = line.split(",") if(cmpt == 0): index = 0 for variable in line_in_array: position_to_variable[index] = variable variable_to_NA_count[variable] = 0 index +=1 else: index = 0 for scalar in line_in_array: if(scalar == "NA" or scalar == "" or scalar == " "): variable_to_NA_count[position_to_variable[index]] += 1 index+=1 cmpt += 1 input_data.close() ## Compute the % for key in variable_to_NA_count.keys(): variable_to_NA_count[key] = float((float(variable_to_NA_count[key]) / float(cmpt)) * 100) ## return dict return variable_to_NA_count def display_NA_proportions(data_file_name): ## ## -> Generate bar chart of NA values for ## each variables in data_file_name ## -> use the check_NA_proportion_in_file() function ## to get the NA proportion ## -> Show the bar plot ## ## Get informations variable_to_NA_count = check_NA_proportion_in_file(data_file_name) ## Create Plot plt.bar(range(len(variable_to_NA_count)), variable_to_NA_count.values(), align='center') plt.xticks(range(len(variable_to_NA_count)), variable_to_NA_count.keys(), rotation=90) ## [DISABLE] Save plot #plt.savefig("") ## Show plot plt.show() def filter_NA_values(data_file_name): """ -> Evaluate the proportion of NA values in each variable (use the check_NA_proportion_in_file() function). -> Find the minimum proportion of NA (minimum_score, i.e almost patient have non NA values for this feature, except a few ones wich have a lot of NA) -> Rewrite a file (data/Luminex_phase_I_raw_data_filtered.csv) with only the selected variables """ ## Structure initialization score_list = [] variable_saved = [] ## Get information on NA proportion in data file variable_to_NA_proportion = check_NA_proportion_in_file(data_file_name) ## find minimum score of NA among variables ## Exluding OMICID and DISEASE (every patient should have one) for key in variable_to_NA_proportion.keys(): if(key != "\\Clinical\\Sampling\\OMICID" and key != "\\Clinical\\Diagnosis\\DISEASE" and key != "Diagnostic" and key != "Disease"): score_list.append(variable_to_NA_proportion[key]) minimum_score = min(score_list) ## Use minimum score as a treshold for ## selecting variables for key in variable_to_NA_proportion.keys(): if(float(variable_to_NA_proportion[key]) > float(minimum_score)): variable_saved.append(key) ## Log message print("[+] Selecting "+str(len(variable_saved))+" variables among "+str(len(variable_to_NA_proportion.keys())) +" ["+str((float(len(variable_to_NA_proportion.keys()))-float(len(variable_saved))) / float(len(variable_to_NA_proportion.keys()))*100)+"%]") ## Create a new filtered data file index_to_keep = [] cmpt = 0 input_data_file = open(data_file_name, "r") output_data_file_name = data_file_name.split(".") output_data_file_name = output_data_file_name[0] +"_NA_filtered.csv" output_data_file = open(output_data_file_name, "w") for line in input_data_file: line = line.split("\n") line = line[0] line_in_array = line.split(",") if(cmpt == 0): header_in_line = "" index = 0 for variable in line_in_array: score = float(variable_to_NA_proportion[variable]) if(score <= minimum_score): header_in_line += str(variable) +"," index_to_keep.append(index) index +=1 header_in_line = header_in_line[:-1] output_data_file.write(header_in_line+"\n") else: line_to_write = "" index = 0 for scalar in line_in_array: if(index in index_to_keep): line_to_write += str(scalar) + "," index += 1 line_to_write = line_to_write[:-1] output_data_file.write(line_to_write+"\n") cmpt += 1 output_data_file.close() input_data_file.close() def na_block_change(input_data_file, display): """ *input_data_file is a string, the name of the data file *display is a boolean, set to True to display grid optimization in console. Algorithm to deal with na values in data file. Tries to minimize the loss of information and drop all NA in datafile by perform only two type of actions: - drop patients (i.e lines) - drop variables (i.e col) each action is associated to a cost, given by the formula: - Cost = (1/nb_variable_type)*information_lost Where nb_variable_type is the number of line or column left in the dataset and information_lost is the number of scalar lost if the column/line is deleted. The algorithm stop if: - The number of patients left is too small (below a treshold) - The number of variables left is too small (below a treshold) - No missing values left in data file - Iteration reach the mawimum of authorized iteration (treshold) require operator Generate an csv output file with the tag "_NaBlockManaged" """ ##--------------------## ## General parameters ## ##--------------------## ## Tresholds and structure min_variable_authorized = 3 min_patient_authorized = 3 maximum_number_of_iteration = 1000 na_values = ["NA", "na", "Na", ""] number_of_iteration = 0 action_list = [] ## Check variable patients_left_in_grid = True variables_left_in_grid = True na_left_in_grid = True action_authorized = True under_max_iteration = True ##---------------------## ## Grid initialisation ## ##---------------------## ## Create Grid grid = [] data_file = open(input_data_file, "r") for line in data_file: line = line.rstrip() vector = line.split(",") grid.append(vector) data_file.close() ##-------------------## ## Grid optimisation ## ##-------------------## while(action_authorized): ##---------------------## ## Check authorization ## ##---------------------## ## check the number of iteration if(number_of_iteration >= maximum_number_of_iteration): under_max_iteration = False print("[-] reach maximum number of iteration :"+str(number_of_iteration)) ## count variables in grid if(len(grid[0]) < min_variable_authorized): variables_left_in_grid = False print("[-] reach minimum number of variables :"+str(len(grid[0]))) ## count patients in grid if(len(grid) < min_patient_authorized): patients_left_in_grid = False print("[-] reach minimum number of patients :"+str(len(grid))) ## count NA values in grid na_count = 0 for vector in grid: for scalar in vector: if(scalar in na_values): na_count += 1 if(na_count == 0): na_left_in_grid = False ## Check if we can do something if(na_left_in_grid and patients_left_in_grid and variables_left_in_grid and under_max_iteration): action_authorized = True else: action_authorized = False ##--------------## ## Optimization ## ##--------------## if(action_authorized): ##--------------## ## Display grid ## ##--------------## if(display): print("-"*len(grid[0])*3) display_grid = [] na_char = "?" good_char = "#" na_values = ["NA", "na", "Na", ""] ## create display grid for vector in grid: display_vector = [] for elt in vector: if(elt in na_values): display_vector.append(na_char) else: display_vector.append(good_char) display_grid.append(display_vector) ## display display_grid_in_string = "" for display_vector in display_grid: display_vector_in_string = "" for scalar in display_vector: display_vector_in_string += " " + str(scalar)+ " " print(display_vector_in_string) print("-"*len(grid[0])*3) ##-------------------------## ## Screen possible actions ## ##-------------------------## ## compute cost of deleting patients possibles_action = {} na_in_vector = 0 number_of_patients = len(grid) cmpt = 0 for vector in grid: deleting_cost = 0 na_in_vector = 0 information_in_vector = 0 for scalar in vector: if(scalar in na_values): na_in_vector += 1 else: information_in_vector += 1 ## cost of deleting this specific patient deleting_cost = float((1.0/number_of_patients)*information_in_vector) cmpt += 1 possibles_action["line_"+str(cmpt)] = deleting_cost ## compute cost of deleting columns columns_list = [] for scalar in grid[0]: columns_list.append([]) for vector in grid: index = 0 for scalar in vector: columns_list[index].append(scalar) index += 1 number_of_columns = len(columns_list) cmpt = 0 for vector in columns_list: deleting_cost = 0 na_in_vector = 0 information_in_vector = 0 for scalar in vector: if(scalar in na_values): na_in_vector += 1 else: information_in_vector += 1 ## cost of deleting this specific variable deleting_cost = float((1.0/number_of_columns)*information_in_vector) cmpt += 1 possibles_action["col_"+str(cmpt)] = deleting_cost ## Select best possible action (i.e the lowest cost) possibles_action = sorted(possibles_action.items(), key=operator.itemgetter(1)) action_selected = possibles_action[0] ##----------------## ## Perform action ## ##----------------## instruction = action_selected[0].split("_") variable_type = instruction[0] target = int(instruction[1]) - 1 action_list.append(action_selected) ## => delete patient if(variable_type == "line"): new_grid = [] cmpt = 0 for vector in grid: if(cmpt != target): new_grid.append(vector) cmpt += 1 ## => delete variable elif(variable_type == "col"): new_grid = [] cmpt = 0 for vector in grid: new_vector = [] index = 0 for scalar in vector: if(index != int(target)): new_vector.append(scalar) index += 1 cmpt += 1 new_grid.append(new_vector) ## Update grid grid = new_grid number_of_iteration += 1 ##-------------------------## ## Write the new data file ## ##-------------------------## output_filename = input_data_file.split(".") output_filename = str(output_filename[0])+"_NaBlockManaged.csv" output_file = open(output_filename, "w") cmpt = 1 for vector in grid: line_to_write = "" for scalar in vector: line_to_write += str(scalar)+"," if(cmpt != len(grid)): line_to_write = line_to_write[:-1]+"\n" else: line_to_write = line_to_write[:-1] output_file.write(line_to_write) cmpt += 1 output_file.close()
10e828b76fd1dc2ddd2f737a937702e4c2170e24
amanansari10106/onlinec-linux
/temp/python practical/one.py
1,923
3.828125
4
def fib(n): if n==1: return 1 return n*fib(n-1) global b def numpalindrome(n): b=0 z=n while(True): if n<10: b = (b*10)+n break a = n%10 n = int(n/10) b = (b*10)+a if z==n: print("number is palindrome") else: print("number is not palindrome") return b def armstrong(n): c=0 z=n while True: if n<1: break n = int(n/10) c = c+1 n =z sum =0 while(True): if n<10: sum = sum + (n**c) print(sum) break r = n%10 n = int(n/10) sum = sum + (r**c) def sumofdigit(n): sum =0 while(True): if n<10: sum = sum + n print(sum) break r = n%10 n = int(n/10) sum = sum + r def prime(n,i): if n==0 or n==1: return True if n == i: return True if n%i == 0: return False return prime(n, i+1) def reversenum(n): b=0 while(True): if n<10: b = (b*10)+n break a = n%10 n = int(n/10) b = (b*10)+a print(b) return b reversenum(100) def smallest(): a = input("enter the number") min =a for x in range(3): a = input("enter the number") if a<min: min =a print("smallest number is ", min) # smallest() def custom1(): a = int(input("Enter a")) e = int(input("Enter e")) if a<0 or e<0: z=a a=e e=z print("a : ",a, "| e : ",e ) print("the power is ",a**e) custom1() # b = int(input("Enter the number")) # a = prime(b, 2) # if(a): # print("number is prime") # else: # print("number is not prime") # sumofdigit(123) # armstrong(211) # p = numpalindrome(101) # a = fib(3) # print(a)
afd5ff953e1fb850eea7dbd8b3366f14da736a97
aaychen/Headstart
/hangman.py
2,246
4.09375
4
import random def getWord(fileName): with open(fileName, 'r') as file: word_list = file.read().split('\n') # assuming each word is on a separate line random.seed(3) i = random.randint(0, len(word_list)-1) # random index for word_list return word_list[i] # return a random word def askAttempts(): while True: num = input("How many incorrect attempts do you want? [1-25]\n") if not num.isdigit(): # checking if input is a positive integer print("Invalid input: Enter a number") elif not (1 <= int(num) <= 25): # if input is not in range 1-25 print("Invalid input: Enter a number between 1 and 25 inclusive") else: break return int(num) def askLetter(letters, num): while True: char = input("Choose the next letter:\n") if len(char) == 1: ascii = ord(char) if (65 <= ascii <= 90) or (97 <= ascii <= 122): # if input is a valid letter char = char.lower() # converting letter guessed to lowercase if char not in letters: break else: print("Letter has been guessed already") else: print("Invalid input: Enter a letter") else: print("Invalid input: Enter a letter") return char def display(word, letters): res = "" win = False for char in word: if char in letters: res += char else: res += '*' print(f"Word: {res}") if '*' not in res: win = True return win def main(): word = getWord("wordlist.txt") num = askAttempts() letters = [] display(word, letters) for i in range(num, 0, -1): print(f"Attempts Remaining: {i}") print(f"Previous guesses: {letters}") char = askLetter() letters.append(char) win = display(word, letters) if win: break print(f"The word was {word}") if win: print("Congratulations! You won!") else: print("Try again next time!") user_in = input("Enter y/Y to try again") if user_in.toUpper() == 'Y': main() if __name__ == '__main__': main()
04c3dea40e51d1e61db8ad6c3cadf9af8e8b0cec
RancyChepchirchir/AI-1
/Module-2/AAI_Assignment_1_AI_Graphs_Uninformed_Search (1).py
48,166
4.125
4
# coding: utf-8 # # Introduction to Artificial Intelligence # # ------------ # # _Authors: Jacob Koehler, Dhavide Aruliah_ # # # ## Representing and Visualizing Graphs with Python # # This assignment prefaces later work with graph traversal problems. As preparation, you will cover ways to represent basic graphs and trees using base Python and then the [**networkx**](https://networkx.github.io/) library. The main goals in this portion of the assignment are: # # - to apply Python idioms for representing graphs & trees; # - to apply Python idioms for manipulating graphs & trees; # - to use Python to visualize graphs and trees; # - to apply Python for uniformed search in graphs. # <a id="questions"></a> # ## Questions # # + [**Question 01: Build a Graph as a `dict`**](#q01) # + [**Question 02: Construct & Visualize a Graph object**](#q02) # + [**Question 03: Interrogating Graph Properties**](#q03) # + [**Question 04: Determining Graph Connectedness**](#q04) # + [**Question 05: Representing Network of Airports as a Graph**](#q05) # + [**Question 06: Finding Paths in a Graph**](#q06) # + [**Question 07: Building a Tree**](#q07) # + [**Question 08: Using Trees for Mathematical Formulas**](#q08) # + [**Question 09: Using a `Tree` class**](#q09) # + [**Question 10: Traversing a Tree using In-order Traversal**](#q10) # + [**Question 11: Finding paths between all vertices with `shortest_path`**](#q11) # + [**Question 12: Determining a Traversal using DFS**](#q12) # + [**Question 13: Determining Paths using DFS**](#q13) # + [**Question 14: Determining a Traversal using BFS**](#q14) # + [**Question 15: Determining Paths using BFS**](#q15) # + [**Question 16: Using `networkx` for DFS and BFS**](#q16) # ## Graphs in Python # # In discrete mathematics, [a **graph**](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics) is a collection of *vertices* (or *nodes*) and *edges* (which are connections between vertices). Graphs are typically visualized with _labelled circles_ for vertices and _lines connecting the circles_ for edges. # # ![](https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/6n-graf.svg/440px-6n-graf.svg.png) # # Notes: # + If the edges are arrows (implying a connection *from* one vertex *to* another), the graph is a *directed graph*. Otherwise, the graph is *undirected*. # + An edge that connects one vertex to itself is a *loop* # + A graph that permits multiple edges connecting one vertex to another is a *multigraph*. For example, if the vertices represent airports, then multiple edges connecting two distinct airports would represent multiple flights between those two airports. # # Graphs are ubiquitous in computer science due to their tremendous utility in applications: # + transportation networks (e.g., roads between cities, flights between airports, etc.) # + communication networks (e.g., physical cables between computers, wired or wireless connections between devices, etc.) # + social networks (e.g., relationships between individuals) # # A non-graphical way to represent graphs is more useful for programmatic exploration in Python (or any other programming language). One strategy is to use the *adjacency* information (i.e., how vertices are connected by edges) to describe a graph. This approach describes a graph explicitly and unambiguously in a manner suitable for manipulating programmatically. # # For example, the graph displayed above has six vertices. This graph can be described completely by summarizing its adjacency information in a table: # # | Vertex | Adjacencies | # | :------: | :-----------: | # | 1 | 2, 5 | # | 2 | 1, 5, 3 | # | 3 | 2, 4 | # | 4 | 3, 5, 6 | # | 5 | 1, 2, 4 | # | 6 | 4 | # # Observe there is some redundancy in the preceding table (e.g., vertex 1 is adjacent to vertex 5 and vertex 5 is adjacent to vertex 1). # # The preceding table can be represented in Python using a dictionary with vertices as keys and lists of adjacent vertices as values. # In[1]: graph_int_labels = { 1: [2, 5], 2: [1, 3, 5], 3: [2, 4], 4: [3, 5, 6], 5: [1, 2, 4], 6: [4] } # This [dictionary-based approach](https://www.python.org/doc/essays/graphs/) was suggested by Guido van Rossum, the creator of the Python language. You will use this article as a guide to write some basic algorithms for traveling around on a graph. # # Usually, you don't want integer values as keys in Python dictionaries, so instead you can change to representing the graph with strings (in the case above, replacing the numerals `1` through `6` with the letters `A` through `F` respectively). # In[2]: graph_str_labels = { 'A': ['B', 'E'], 'B': ['A', 'C', 'E'], 'C': ['B', 'D'], 'D': ['C', 'E', 'F'], 'E': ['A', 'B', 'D'], 'F': ['D'] } # ### Plotting Graphs # # [Networkx](https://networkx.github.io/) is a Python library working with graphs. # From the [`networkx` documentation](): # # > NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. # # When using `networkx`, you can construct an object of class `networkx.classes.graph.Graph` (or `Graph` from hereon). This has the advantage that many utilities for working with graphs have already been built into `networkx` for you. # # If you start from a graph representation as a dictionary with lists of adjacencies, the `networkx` function `from_dict_of_lists` can construct a `Graph` object; simply pass in a dictionary of lists with the adjacency information. Once you've created the `Graph` object, you can extract information about the graph such as vertices and edges and adjacency. You can also visualize the graph using the function `draw_networkx`. # In[4]: get_ipython().magic('matplotlib inline') import networkx as nx # "nx" is a conventional alias for "networkx" when importing import pandas as pd import warnings warnings.filterwarnings("ignore") # To suppress matplotlib warning messages # In[5]: G = nx.from_dict_of_lists(graph_str_labels) print(type(G)) # In[5]: nx.draw_networkx(G, with_labels=True, node_color='cyan', node_size=500) # see help(nx.draw_networkx for more optional keyword arguments) # In[ ]: # #### Graphs from Data # # Rather than constructing a graph from a dictionary, you may be using a dataset in the form of a data file (which is more useful for a graph of a reasonable size that would arise in any application). Here, you can experiment with an example dataset from the [*Stanford Large Network Dataset Collection* on Facebook social circles](https://snap.stanford.edu/data/index.html): # # Here is the description of the data from the source: # # # >This dataset consists of 'circles' (or 'friends lists') from Facebook. # Facebook data was collected from survey participants using this Facebook app. The dataset includes node features (profiles), circles, and ego networks. # > # > Facebook data has been anonymized by replacing the Facebook-internal ids for each user with a new value. Also, while feature vectors from this dataset have been provided, the interpretation of those features has been obscured. For instance, where the original dataset may have contained a feature "political=Democratic Party", the new data would simply contain "political=anonymized feature 1". Thus, using the anonymized data it is possible to determine whether two users have the same political affiliations, but not what their individual political affiliations represent. # # We easily read in the data using the [Pandas](https://pandas.pydata.org) function `read_csv` to produce a Pandas DataFrame. The rows of the DataFrame `facebook` created below correspond to edges in a graph (i.e., an edge connecting the node from column `A` to the node from column `B`). The DataFrame `facebook` is then in a suitable form to pass to the `networkx` function `from_pandas_edgelist` to create a `Graph` object. # In[6]: FACEBOOK_PATH = './resource/asnlib/publicdata/facebook_combined.txt' facebook = pd.read_csv(FACEBOOK_PATH, sep=' ', names=['A', 'B']) # In[7]: print(facebook.info()) facebook.head() # In[8]: # Construct a networkx Graph object from a Pandas DataFrame G = nx.from_pandas_edgelist(facebook, 'A', 'B') # A `networkx` Graph object can be visualized with the `networkx` function `draw_networkx`. In the case of the Faceboook data set, this would be created as below (but you won't execute this code here because it takes a while to run for this many nodes & edges; the result is the plot shown here). # # ```python # nx.draw_networkx(G) # this takes a long time. # ``` # ![](./resource/asnlib/publicdata/facebook_graph.png) # <a id="q01"></a> # [Return to top](#questions) # ### Question 01: Build a Graph as a `dict` # # ![](./resource/asnlib/publicdata/graphh.png) # # Your task here is to construct a `dict` with the strings `'A'` through `'H'` as keys (vertices) and lists of adjacent vertices as values. # # + Do *not* use a `networkx` Graph object (that construction comes in the next question). # + Assign the resulting `dict` to `ans_1`. # + The precise sequence of vertices in your adjacency lists is not important, as long as all adjacent vertices are listed. # In[1]: ans_1 = { 'A': ['B', 'G', 'H'], 'B': ['A', 'D', 'C'], 'C': ['B', 'D', 'E'], 'D':['B','C','E','F','G','H'], 'E': ['C', 'D', 'F'], 'F': ['E', 'D', 'G'], 'G': ['A', 'F', 'D', 'H'], 'H':['G','D','A'] } P= nx.from_dict_of_lists(ans_1) nx.draw_networkx(P,with_labels=True,node_color='cyan',node_size=500) # In[10]: ### GRADED ### QUESTION 01: ### Construct a dictionary of lists of strings that represents ### the graph in the diagram above. ### Bind the resulting dict to the identifier ans_1. ans_1 = { 'A': ['B', 'G', 'H'], 'B': ['A', 'D', 'C'], 'C': ['B', 'D', 'E'], 'D':['B','C','E','F','G','H'], 'E': ['C', 'D', 'F'], 'F': ['E', 'D', 'G'], 'G': ['A', 'F', 'D', 'H'], 'H':['G','D','A'] } # In[11]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # <a id="q02"></a> # [Return to top](#questions) # ### Question 02: Construct & Visualize a Graph object # # You can now create a `networkx` Graph object from `ans_1` and produce a plot. # + To do instantiate the Graph object, use the `networkx` function `from_dict_of_lists`. # + To produce a plot, use the `networkx` function `draw_networkx` (using the `with_labels` keyword argument labels the vertices). # In[12]: ### GRADED ### QUESTION 02 ### Create a networkx graph using ans_1 (your dictionary of lists of vertices from Question 01). ### Save this Graph object as ans_2 and use the nx.draw_networkx function to visualize it. ans_2 = nx.from_dict_of_lists(ans_1) nx.draw_networkx(ans_2,with_labels=True,node_color='cyan',node_size=500) # In[13]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # <a id="q03"></a> # [Return to top](#questions) # ### Question 03: Interrogating Graph Properties # # A principal reason to use `networkx` is that it has numerous functions, classes, and methods that simplify working with graphs. For instance, you can access the total number of **vertices** and **edges** in a graph object using two useful methods: `number_of_nodes` (remember, nodes is an equivalent term for *vertices* in a graph) and `number_of_edges` respectively. # # + Assign the number of vertices to `ans_3_nodes` & the number of edges to `ans_3_edges` respectively. # + Remember, these are accessor methods so you'll invoke them as functions. Consult the [`networkx` documentation](https://networkx.github.io/documentation/stable/reference/classes/graph.html#methods) if you need to. # In[14]: ### GRADED ### QUESTION 03 ## Determine the number of edges ## and vertices in your graph from above ## and save the results to ans_3_edges and ## ans_3_verts below ans_3_edges = nx.number_of_edges(ans_2) ans_3_verts = nx.number_of_nodes(ans_2) print(nx.number_of_nodes(ans_2)) print('The graph ans_2 has {} vertices.'.format(ans_3_verts)) print('The graph ans_2 has {} edges.'.format(ans_3_edges)) # In[15]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # ### Paths and Graph Connectedness # # Given any nonempty graph, a *path* is an ordered sequence of at least two vertices each of which is connected to its immediate predecessor by at least one edge. Think of vertices as cities in a land-locked country and think of edges as roads connecting cities; in that case, a path represents a route from one city to another (even if the two vertices are not adjacent in the graph). # # Per [Wikipedia](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)]), here is a definition of a *connected* graph: # # > An undirected graph is connected when it has at least one vertex and there is a path between every pair of vertices. # # The graph shown here is an example of a graph that is not connected or *disconnected*; it does have three connected components. # # ![](./resource/asnlib/publicdata/disconnected_graph.png) # <a id="q04"></a> # [Return to top](#questions) # ### Question 04: Determining Graph Connectedness # # Your task here is to use `networkx` to check that the graph displayed above is not connected. # # + Create a `networkx` Graph object `ans_4` that corresponds to the diagram above (i.e., with nodes `A` through `G` and the same disconnected components). # + You can invoke the function `nx.is_connected` to assess whether a graph is connected (code provided for you). # # You can also use the function `nx.connected_components` to determine the nodes of the connected subgraphs if the original graph is itself not connected. # In[16]: ### GRADED ### QUESTION 04 ### Construct a disconnected networkx Graph object that corresponds ### to the diagram above. ### Save your graph object to ans_4 below. ### You can test your solution with nx.is_connected() P={ 'A':['B','C'], 'B':['A','C'], 'C':['A','B'], 'D':[], 'E':['F','G'], 'F':['G','E'], 'G':['E','F'] } ans_4 = nx.from_dict_of_lists(P) print('Is ans_4 a connected graph: {}.'.format(nx.is_connected(ans_4))) print('The components of ans_4 are:') for subgraph in nx.connected_components(ans_4): print('\t{}'.format(subgraph)) # print sets of vertices # In[17]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # ### A Graph to represent airport connections # # Below, you will use a dataset containing information about airline flights between airports. In the next two questions, you will import the data into a `networkx` `Graph` object and identify paths in the graph. To begin, you need to examine the structure of the data. # # This is what the data file `air_routes.csv` looks like: # # ``` # ,source,dest,count # 0,AAE,ALG,1 # 1,AAE,CDG,1 # ``` # $\qquad\vdots,\ \vdots\ ,\ \vdots\ , \vdots$ # ``` # 37593,ZYI,XMN,1 # 37594,ZYL,DAC,4 # ``` # There are slightly more than 37,500 rows with the row number, departure (`source`) airport, arrival (`dest`) airport, and number of flights (`count`) as columns. The airports are represented using three-letter [IATA](http://www.iata.org/publications/Pages/code-search.aspx) codes. # # Run the cell below to load the data into a Pandas `DataFrame` and display the first few rows. # In[18]: ROUTES_PATH = './resource/asnlib/publicdata/air_routes.csv' routes = pd.read_csv(ROUTES_PATH, usecols=['source','dest','count']) routes.head() # <a id="q05"></a> # [Return to top](#questions) # ### Question 05: Representing a Network of Airports as a Graph # # Your task here is to construct a Graph object from the Pandas DataFrame `routes` containing the airline data from the file `air_routes.csv` (the `routes` DataFrame has already been constructed for you). The DataFrame is formatted as an *edgelist* (because each row corresponds to an edge in the graph). In addition, because there are multiple flights between each pair of airports recorded in the `count` column (the number of connecting flights), you want to retain this information in your graph by associating an *edge attribute* (`count`) with each edge. # # To summarize, your goal is to construct a `Graph` from `routes` using the `source` and `dest` columns with the `count` column as an edge attribute. # # + You can use the `networkx` function `from_pandas_edgelist` (as you did earlier with Facebook data). # + This time, use the optional keyword argument `edge_attr` to obtain a `Graph` object with *weighted* edges (the weights being the contents of the `count` column, i.e., the number of distinct flights connecting two given airports). You can use the [`networkx` documentation for `from_pandas_edgelist`](https://networkx.github.io/documentation/stable/reference/convert.html) for clarification. # + Assign the resulting object to `ans_5`. # In[19]: ### GRADED ### QUESTION 05 ### Create a graph ans_5 from the dataframe routes using "nx.from_pandas_edgelist". ### Regard each row as an edge between the "source" and "dest" columns. ### Use the count column as an attribute for each edge (using the "edge_attr" keyword). ### Save your graph object to ans_5 below. ans_5 = nx.from_pandas_edgelist(routes,'source','dest',edge_attr='count') # In[20]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # <a id="q06"></a> # [Return to top](#questions) # ### Question 06: Finding Paths in a Graph # # Once you have a graph representation of connected airports, you can use built-in algorithms in `networkx` to determine paths from one airport to another. For example, the airports located in Albany, New York and San Francisco, California are coded as `ALB` and `SFO` respectively. You can determine the shortest paths between the two airports using the `nx.shortest_paths.all_shortest_paths` function. # # Your task here is to obtain *all* the shortest paths from `ALB` to `SFO` (there are more than one). # # + Use `all_shortest_paths` from the submodule `networkx.shortest_paths` to compute all the paths required. # + Assign the result to `ans_6a` after converting it to a list (the result returned by `all_shortest_paths` is a Python generator to permit [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation)). # + Assign the length of the shortest path to the identifier `ans_6b`. Notice that each path is a list of nodes including the initial and terminal node. The path length corresponds to the number of edges in the path. # + Assign the number of shortest paths to the identifier `ans_6c`. # # Notice that this graph model does *not* include *geographical distances between airports*. As such, the use of the adjective "shortest" is somewhat counter-intuitive (especially if you have any sense of the relative geographical locations of these airports). In this example, "the shortest path" refers to "the path involving the fewest connecting flights" (i.e., edges) irrespective of geographical distance. If precise coordinates for each airport had been included with the input data, you could have used the geographical distance as an edge attribute for each edge (in which case, the "shortest path" can be computed in the more conventional sense). # In[21]: ### GRADED ### QUESTION 06 ### Assign the list of all shortest paths between the airports in ### Albany, NY (ALB) and San Francisco, CA (SFO) to ans_6a. ### Assign the length of any of the shortest paths from ALB to SFO to ans_6b. ### Assign the number of shortest paths from ALB to SFO to ans_6c. ans_6a = [] # Default value is incorrect ans_6b = -1 # Default value is incorrect ans_6c = -1 # Default value is incorrect # Verification: print('Length of any shortest path from ALB to SFO: {}'.format(ans_6b)) print('Number of shortest paths from ALB to SFO: {}'.format(ans_6c)) print('\nShortest paths from ALB to SFO:\n' + (31*'=')) for path in ans_6a: print(path) # In[22]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # ## Trees # # A *tree* is a special kind of a graph. Any *acyclic* graph (i.e., one that does not contain a *cycle*) is a tree. The diagram below is one such example. # # ![](https://s3.amazonaws.com/hr-assets/0/1527626183-88c8070977-isitBSTSample0.png) # <a id="q07"></a> # [Return to top](#questions) # ### Question 07: Building a Tree # # You can represent trees just as you did with more general graphs with `networkx`. Moreover, you can use the `is_tree()` function to check if a graph is in fact a tree. # In[23]: ### GRADED ## Build a graph with networkx to ## represent the tree above. ## Save your graph to ans_7 below. G= { '1':['2'], '2':['1','3','4'], '3':['2'], '4':['2','6'], '5':['6'], '6':['4','7'], '7':['6'] } ans_7 = nx.from_dict_of_lists(G) print('Is ans_7 a tree: {}'.format(nx.is_tree(ans_7))) nx.draw_networkx(ans_7, node_color='magenta') # In[24]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # <a id="q08"></a> # [Return to top](#questions) # ### Question 08: Using Trees for Mathematical Formulas # # One application of a simple binary tree is for representing mathematical expressions or formulas. For example, let's consider the arithmetic expression # # $$9\times(2+3)+7.$$ # In[25]: ### GRADED ### QUESTION 08 ### What is the numerical value of the expression above when evaluated? ### Save your answer as ans_8 below. ans_8 = 9*(2+3)+7 # Verification: print('The numerical value of the expression "9*(2+3)+7" is {}.'.format(ans_8)) # In[26]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # The formula $9\times(2+3)+7$ is associated with a particular *expression tree* with nodes labelled with the arithmetic operators and operands (numbers or algebraic variables): # # ![](./resource/asnlib/publicdata/expr_tree_1.png) # # When calculators or computer programs parse formulas like this, an expression tree is built up to carry out the computation. Notice this expression tree is in fact a *binary* tree (i.e., one with at most two outgoing edges from each node) and it is a *directed acyclic graph (DAG)*: it is not only a tree (an acyclic graph) but also the edges are directional. Notice also that the leaves of the tree (the nodes without any outgoing edges) have numerical values as labels; the internal nodes labeled with operators have a left child and a right child corresponding to the operands of the binary operators (which may be another subtree or a leaf). # Here is a standard implementation of a binary tree as a class `Tree`. This example makes use of standard Python object-oriented program idioms to define functions for the standard *magic methods* `__init__`, `__str__`, & `__repr__` (see the [Python tutorial](https://docs.python.org/3.7/tutorial/classes.html) for further explanation). # In[41]: class Tree: 'A simple implementation of a binary tree' def __init__(self, val, left_child = None, right_child = None): self.val = val self.left = left_child self.right = right_child def __str__(self): if self.left is None and self.right is None: return '%s(%s)' % (self.__class__.__name__, str(self.val)) else: return '%s(%s, %s, %s)' % (self.__class__.__name__, self.val, self.left, self.right) def __repr__(self): if self.left is None and self.right is None: return '%s(%s)' % (self.__class__.__name__, repr(self.val)) else: return '%s(%r, %r, %r)' % (self.__class__.__name__, self.val, self.left, self.right) # Notice: # # + We essentially are defining a node and its children which themselves can be trees. # + The edges are *directed* in this definition of a `Tree` class because edges connect *parent* nodes to their *left* and *right* *children*. # + The `val` attribute is some kind of data or object associated with each node. It does not need to be unique, i.e., numerous nodes can have the same `val` attribute. # # With the preceding class definition, the expression tree for the formula $9\times(2+3)+7$ is encoded as an object as follows: # In[42]: # Encoding 9*(2+3)+7 with the Tree class expr_tree = Tree('+', Tree('*', Tree(9), Tree('+', Tree(2), Tree(3))), Tree(7)) expr_tree # <a id="q09"></a> # [Return to top](#questions) # ### Question 09: Using a `Tree` class # # Your task is to express a different arithmetic formula, namely $$3+((4\times5)-(9+6)),$$ as an expression tree using the `Tree` class. The resulting tree, when visualized, looks like this: # # ![](./resource/asnlib/publicdata/expr_tree_2.png) # # + Use the `Tree` class to express the formula $3+((4\times5)-(9+6))$ as a (nested) `Tree` object. # + Use Python strings for the arithmetic operators (with `'*'` for multiplication and `'/'` for division) and integers for the operands. # + You can ignore the parentheses (other than to help determine the order of operations for binding operands to operators). # + Assign the result to `ans_9`. # In[43]: ### GRADED ### QUESTION 09 ### Use the Tree class above to build the given expression tree for the formula ### 3 + ((4*5)-(9+6)) ### with Python strings for the operators & integers for the operands. ### Save your tree to ans_9 below. ans_9 = Tree('+',Tree(3),(Tree('-',(Tree('*',Tree(4),Tree(5))),(Tree('+',Tree(9),Tree(6)))))) print(ans_9) # In[44]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # # Tree Traversals # # In this next questions, you'll explore [tree traversal](https://en.wikipedia.org/wiki/Tree_traversal), the problem of visiting each & every node in a tree (usually to operate on some data associated with the nodes) exactly once under constraints imposed by the edges (i.e., that you must traverse from one node to one of its neighbors). # # You can try this out with the `Tree` class representations of expression trees from the preceding question (which is what is involved in numerically evaluating the expression). As an example, the function `print_tree` below prints the nodes of an expression tree by first printing its `val` attribute, then recursively traversing its *left* branch, and then recursively traversing its *right* branch. # In[45]: def print_tree(tree): "Process Tree to print node values" if tree is None: return print(tree.val) print_tree(tree.left) print_tree(tree.right) # In[46]: tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3))) print('The original representation: {}\n\nThe "pre-order" traversal:'.format(tree)) print_tree(expr_tree) # In[47]: # Try again using the expression tree for 9*(2+3)+7 print('The original representation: {}\n\nThe "pre-order" traversal:'.format(expr_tree)) print_tree(expr_tree) print('-----') ans_9 = Tree('+',Tree('-', Tree('+', Tree(9), Tree(6)), Tree('*', Tree(4), Tree(5))), Tree(3)) print_tree(ans_9) # <a id="q10"></a> # [Return to top](#questions) # ### Question 10: Traversing a Tree using In-order Traversal # # The preceding function `print_tree` first prints the `val` attribute of a node, then visits the left child and the right child, printing their corresponding branches (sometimes called the [pre-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))). You can adjust this [tree traversal](https://en.wikipedia.org/wiki/Tree_traversal) to display the tree node labels in a different sequence. For example, an [*in-order traversal*](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)) would process the left branch first, the node itself, and then the right branch of the tree (in this case, just processing a node means printing its `val` attribute or doing nothing if the node is `None`). So, for the expression tree `tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3)))` representing the formula $1+(2\times3)$, printing the node labels using an *in-order traversal* would yield # # ``` # 1 # + # 2 # * # 3 # ``` # # Your task, then, is to complete a function `print_tree_inorder` that displays the node labels for a binary expression tree using an in-order traversal. # # + Complete the function `print_tree_inorder` as required. # + You can use the preceding function `print_tree` as a template. # # Notice the function `print_tree` does not have a return value; it simply prints the node labels to standard output as a side effect. # In[49]: ### GRADED ### QUESTION 10 ### Complete the function below to produce an in-order traversal of a tree. def print_tree_inorder(tree): "Process Tree to print node values using in-order traversal" if tree is None: return print_tree_inorder(tree.left) print(tree.val) print_tree_inorder(tree.right) # Verification: print('Print tree "9*(2+3)+7" inorder:') print_tree_inorder(expr_tree) # In[50]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # For the next explorations, you will start with a representation of a graph as a dictionary containing adjacency lists. As a reminder, you can construct and visualize a simple graph, and then use `networkx` to find paths in the graph. # In[51]: graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} graph_nx = nx.from_dict_of_lists(graph) nx.draw_networkx(graph_nx, with_labels=True, node_color='violet', node_size=500, alpha=0.75) # ### Finding paths # # The `networkx` function `shortest_path` has the following signature (from the documentation): # # ``` # nx.shortest_path(G, source=None, target=None, weight=None, method='dijkstra') # # Parameters # ---------- # G : NetworkX graph # # source : node, optional # Starting node for path. If not specified, compute shortest # paths for each possible starting node. # # target : node, optional # Ending node for path. If not specified, compute shortest # paths to all possible nodes. # # weight : None or string, optional (default = None) # If None, every edge has weight/distance/cost 1. # If a string, use this edge attribute as the edge weight. # Any edge attribute not present defaults to 1. # ``` # # In particular, calling `nx.shortest_path(graph_nx)` yields the following output: # In[52]: nx.shortest_path(graph_nx) # <a id="q11"></a> # [Return to top](#questions) # ### Question 11: Finding paths between all vertices with `shortest_path` # # Use the preceding output from `nx.shortest_path(graph_nx)` to identify two particular shortest paths: # one from node `D` to node `A` & one from node `B` to node `E`. # * Assign the results to `ans_11a` and `ans_11b` respectively. # * Represent both paths as lists of strings (i.e., the vertex labels). # * Include the initial and terminal vertices in the lists representing paths (so, e.g., a path specified by 4 vertex labels comprises 3 edges). # In[ ]: ### GRADED ### QUESTION 11 ### For the graph graph_nx from above, identify: ### a shortest path from node D to node A (as ans_11a) ### a shortest path from node B to node E (as ans_11b) ### Use lists of strings to represent both paths. ### Include starting & ending vertices in the lists. ### YOUR SOLUTION HERE: ans_11a = [] ans_11b = [] # To verify solutions: print('A shortest path from node D to node A: {}'.format(ans_11a)) print('A shortest path from node B to node E: {}'.format(ans_11b)) # In[ ]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # ## Uninformed Search Algorithms # # Now that you have some vocabulary and tools for working with graphs and trees, you can examine some basic approaches to **uninformed search** algorithms. The main problem involves finding a path&mdash;a sequence of vertices connected by edges&mdash;from one vertex in a graph to another. In some circumstances, a shortest path may be desirable, but for the moment consider the problem of simply determining whether a connecting path between two distinct vertices exists at all. # # The qualifier "uninformed" refers to the fact that, while looking through the graph for a path, the only information available is the adjacency lists of nodes explored so far. Later, you will work with *informed* search in which other information (e.g., geographic distance between cities in a geographical path-finding application) is available beyond adjacency. With informed search, the sequence in which adjacent nodes are chosen differs due to the additional information which can improve search performance. # ### Depth-First Search (DFS) # # [Depth-First Search (DFS)](https://en.wikipedia.org/wiki/Depth-first_search) is a strategy for traversing or searching through a graph or a tree. The traversal/search begins at a prescribed vertex (called the *root*) and, # after choosing a vertex adjacent to the root, exploration proceeds down each branch before backtracking. That is, DFS favors visiting undiscovered vertices sooner so the resulting search trees tend to be deep. # # It's likely easier to picture this using, for example, the animated GIF below (by [Steven Skeina](https://www3.cs.stonybrook.edu/~skiena/combinatorica/animations/search.html) using [Combinatorica](http://www.combinatorica.com/)): # # ![](./resource/asnlib/publicdata/dfs_combinatorica.gif) # DFS produces a sequence of vertices (starting at the root) by which the graph can be traversed (i.e., each node visited, assuming that the graph is connected). If specified with an initial root node as well as a terminal node, DFS can then yield a *path* between any two vertices in a connected graph. # # In the lectures, you were shown a pseudocode for DFS as below. The *goalTest* in practice, is often a terminal node or empty. In the former case, DFS can provide a path from the root to the terminal node (if possible); in the latter case, DFS provides a node sequence for traversing the entire graph (or at least the connected component containing the root). # # --- # # __function__ DEPTH-FIRST-SEARCH(initialState, goalTest)<br> # &emsp;_returns_ __SUCCESS__ or __FAILURE__<br> # <br> # &emsp;frontier = Stack.new()<br> # &emsp;explored = Set.new()<br> # <br> # &emsp;__while__ __not__ frontier.isEmpty():<br> # &emsp;&emsp;state = frontier.pop()<br> # &emsp;&emsp;explored.add(state)<br> # <br> # &emsp;&emsp;__if__ goalTest(state):<br> # &emsp;&emsp;&emsp;__return__ __SUCCESS__(state)<br> # <br> # &emsp;&emsp;__for__ neighbor __in__ state.neighbors():<br> # &emsp;&emsp;&emsp;__if__ neighbor __not__ __in__ frontier $\cup$ explored:<br> # &emsp;&emsp;&emsp;&emsp;frontier.push(state)<br> # <br> # &emsp;__return__ __FAILURE__ # # DFS relies on a *stack* (sometimes called a *LIFO* for *Last-In-First-Out*) for maintaining the frontier. In Python, this is also easy to do with a list. To remove an item from the top of the stack `frontier`, simply use invoke the method `frontier.pop()`. # # The Python function `dfs` as implemented here (adapted from a post by [Edd Mann](https://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/)) captures the essence of the preceding pseudocode with some differences: # # + `explored` is implemented using a Python `list` rather than a `set` (so we can preserve the order in which nodes are visited). # + the value returned is the `list` `explored` (rather than **SUCCESS** or **FAILURE**). # In[ ]: def dfs(graph, initial): explored, stack = list(), [initial] # stack == frontier while stack: state = stack.pop() if state not in explored: explored.append(state) stack.extend([neighbor for neighbor in graph[state] if not ((neighbor in stack) or (neighbor in explored))]) return explored # You can see how the function `dfs` works on this example graph (represented as a `dict` of `list`s). # In[ ]: graph_dict = {'A': (['B', 'C']), 'B': (['A', 'D', 'E']), 'C': (['A', 'F']), 'D': (['B']), 'E': (['B', 'F']), 'F': (['C', 'E'])} print("A DFS traversal starting from 'A': {}".format(dfs(graph_dict, 'A'))) print("A DFS traversal starting from 'E': {}".format(dfs(graph_dict, 'E'))) # The preceding function `dfs` can be tweaked to yield a recursive implementation to generate all possible paths between the initial and terminal vertex. A Python generator function (i.e., that uses `yield` instead of `return`) can construct all the paths. # In[ ]: def dfs_paths(graph, initial, goal): stack = [(initial, [initial])] while stack: (state, path) = stack.pop() for neighbor in [v for v in graph[state] if not (v in path)]: if neighbor == goal: yield path + [neighbor] else: stack.append((neighbor, path + [neighbor])) # The default output of this implementation is a *generator* object. This has the advantage of using lazy evaluation (so as not to consume memory until required) but makes it difficult to examine. For small examples like this, it is okay to convert the generator to a list so you can examine it. # In[ ]: paths = dfs_paths(graph_dict,'A', 'D') print('type(paths): {}'.format(type(paths))) paths = list(paths) # Explicitly transform generator to a list print("Paths from 'A' to 'D': {}".format(paths)) # As a slightly larger and more compelling example, you can consider this Python `dict` describing cities of Romania connected by roads (as used extensively in Russell & Norvig's [*Artificial Intelligence: a Modern Approach*](http://aima.cs.berkeley.edu/): # In[ ]: romania_graph = {'Arad': ['Zerind', 'Sibiu', 'Timisoara'], 'Bucharest': ['Urziceni', 'Pitesti', 'Giurgiu', 'Fagaras'], 'Craiova': ['Drobeta', 'Rimnicu', 'Pitesti'], 'Drobeta': ['Craiova', 'Mehadia'], 'Eforie': ['Hirsova'], 'Fagaras': ['Bucharest', 'Sibiu'], 'Giurgiu': ['Bucharest'], 'Hirsova': ['Eforie', 'Urziceni'], 'Iasi': ['Vaslui', 'Neamt'], 'Lugoj': ['Timisoara', 'Mehadia'], 'Mehadia': ['Drobeta', 'Lugoj'], 'Neamt': ['Iasi'], 'Oradea': ['Zerind', 'Sibiu'], 'Pitesti': ['Bucharest', 'Craiova', 'Rimnicu'], 'Rimnicu': ['Craiova', 'Pitesti', 'Sibiu'], 'Sibiu': ['Arad', 'Fagaras', 'Oradea', 'Rimnicu'], 'Timisoara': ['Arad', 'Lugoj'], 'Urziceni': ['Bucharest', 'Hirsova', 'Vaslui'], 'Vaslui': ['Iasi', 'Urziceni'], 'Zerind': ['Arad', 'Oradea']} # The above `dict` describes roads between Romanian cites as in the image below (without distances; later, you'll use the distances as well with *informed* search algorithms in the next assignment). # ![](./resource/asnlib/publicdata/romania_map.png) # <a id="q12"></a> # [Return to top](#questions) # ### Question 12: Determining a Traversal using DFS # # Use the Python implementation of Depth-First-Search `dfs` to determine the traversal order for the Romanian cities in `romania_graph` starting from `Giurgiu`. # # + Assign your answer (a Python list of strings) to `ans_12`. # In[ ]: ### GRADED ### QUESTION 12 ### What traversal order does DFS yield for romania_graph starting at 'Giurgiu'? ### Save your answer as ans_12 ans_12 = [] # Verifying solution print("A DFS traversal starting from 'Giurgiu':\n{}".format(ans_12)) # In[ ]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # <a id="q13"></a> # [Return to top](#questions) # ### Question 13: Determining Paths using DFS # # Use the Python function `dfs_paths` to determine all paths in the Romanian cities in `romania_graph` ending at `Sibiu` & starting from `Giurgiu`. # # + Provide your answer as a *list* (the default output of `dfs_paths` is a generator object, so you will have to explicitly convert it to a `list`). # + Assign the resulting `list` to `ans_13`. # In[ ]: ### GRADED ### QUESTION 13 ### What simple paths does DFS find in romania_graph between 'Giurgiu' & 'Sibiu'? ### Save your answer as ans_13 ans_13 = [] # Verifying solution for path in ans_13: print(path) # In[ ]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # ### Breadth-First Search (BFS) # # [Breadth-First Search (BFS)](https://en.wikipedia.org/wiki/Breadth-first_search) is an alternative strategy to DFS for traversing or searching through a graph. Again, the traversal/search begins at a prescribed *root* vertex; this time, it examines each of its neighbors, and then each of those neighbors, and so on. Intuitively, BFS radiates out from the root to visit vertices in order of their distance from the root (as measured by number of edges). Thus, vertices that are closer to the initial vertex get visited first. # # ![](./resource/asnlib/publicdata/bfs_combinatorica.gif) # As with DFS, BFS can produce a sequence of vertices (starting at the root) by which the graph can be traversed (i.e., each node visited, assuming that the graph is connected). If specified with an initial root node as well as a terminal node, BFS can then yield a *path* between the two vertices. # # Here is a pseudocode for BFS as from the lectures: # # --- # # __function__ BREADTH-FIRST-SEARCH(initialState, goalTest)<br> # &emsp;_returns_ __SUCCESS__ or __FAILURE__<br> # <br> # &emsp;frontier = Queue.new(initialState)<br> # &emsp;explored = Set.new()<br> # <br> # &emsp;__while__ __not__ frontier.isEmpty():<br> # &emsp;&emsp;state = frontier.dequeue()<br> # &emsp;&emsp;explored.add(state)<br> # <br> # &emsp;&emsp;__if__ goalTest(state):<br> # &emsp;&emsp;&emsp;__return__ __SUCCESS__(state)<br> # <br> # &emsp;&emsp;__for__ neighbor __in__ state.neighbors():<br> # &emsp;&emsp;&emsp;__if__ neighbor __not__ __in__ frontier $\cup$ explored:<br> # &emsp;&emsp;&emsp;&emsp;frontier.enqueue(state)<br> # <br> # &emsp;__return__ __FAILURE__ # By contrast with DFS, BFS relies on a *queue* (sometimes called a *FIFO* for *First-In-First-Out*) for maintaining the frontier. In Python, this is also easy to do with a list. To remove an item from the front of the queue `frontier`, simply use invoke the method `frontier.pop(0)`. # # The Python function `bfs` as implemented here captures the essence of the preceding pseudocode with some differences: # # + `explored` is implemented using a Python `list` rather than a `set` (so we can preserve the order in which nodes are visited). # + the value returned is the `list` `explored` (rather than **SUCCESS** or **FAILURE**). # In[ ]: def bfs(graph, initial): explored, queue = list(), [initial] # stack == frontier while queue: state = queue.pop(0) if state not in explored: explored.append(state) queue.extend([neighbor for neighbor in graph[state] if not ((neighbor in queue) or (neighbor in explored))]) return explored # Here's an example of using the function `bfs` on the same toy graph from before. # In[ ]: graph_dict = {'A': (['B', 'C']), 'B': (['A', 'D', 'E']), 'C': (['A', 'F']), 'D': (['B']), 'E': (['B', 'F']), 'F': (['C', 'E'])} print("A BFS traversal starting from 'A': {}".format(dfs(graph_dict, 'A'))) print("A BFS traversal starting from 'E': {}".format(dfs(graph_dict, 'E'))) # As with DFS, BFS can construct paths from the initial to the terminal node by tweaking the implementation of `bfs` to yield a generator function `bfs_paths`. Notice that, with the breadth-first approach, BFS will identify shortest paths first (in the sense of fewest edges; they may not be shortest in a geographical sense). # In[ ]: def bfs_paths(graph, initial, goal): queue = [(initial, [initial])] while queue: (state, path) = queue.pop(0) for neighbor in [v for v in graph[state] if not (v in path)]: if neighbor == goal: yield path + [neighbor] else: queue.append((neighbor, path + [neighbor])) # Again, the default output of this implementation is a *generator* object so you'll convert the generator to a list for convenience (assuming the totality of paths is small enough to fit in memory easily). # In[ ]: paths = bfs_paths(graph_dict,'A', 'D') print('type(paths): {}'.format(type(paths))) paths = list(paths) # Explicitly transform generator to a list print("BFS Paths from 'A' to 'D': {}".format(paths)) # Here is the map of the Romanian cities to assist you with Questions 14 & 15. # ![](./resource/asnlib/publicdata/romania_map.png) # <a id="q14"></a> # [Return to top](#questions) # ### Question 14: Determining a Traversal using BFS # # Use the Python implementation of Breadth-First-Search `bfs` to determine the traversal order for the Romanian cities in `romania_graph` starting from `Giurgiu`. # # + Assign your answer (a Python list of strings) to `ans_14`. # In[ ]: ### GRADED ### QUESTION 14 ### What traversal order does DFS yield for romania_graph starting at 'Giurgiu'? ### Save your answer as ans_14 ans_14 = [] # Verifying solution print("A BFS traversal starting from 'Giurgiu':\n{}".format(ans_14)) # In[ ]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # <a id="q15"></a> # [Return to top](#questions) # ### Question 15: Determining Paths using DFS # # Use the Python function `bfs_paths` to determine all paths in the Romanian cities in `romania_graph` ending at `Sibiu` & starting from `Giurgiu`. # # + Provide your answer as a *list* (the default output of `bfs_paths` is a generator object, so you will have to explicitly convert it to a `list`). # + Assign the resulting `list` to `ans_15`. # In[ ]: ### GRADED ### QUESTION 15 ### What simple paths does DFS find in romania_graph between 'Giurgiu' & 'Sibiu'? ### Save your answer as ans_15 ans_15 = [] # Verifying solution for path in ans_15: print(path) # In[ ]: ### ### AUTOGRADER TEST - DO NOT REMOVE ### # ## Graph Search Algorithms in `networkx` # # The implementations of Depth-First-Search & Breadth-First-Search developed here are fairly simple. NetworkX provides implementations of numerous graph algorithms including DFS and BFS. # # + `dfs_edges` and `bfs_edges` produces an edge generator of the DFS & BFS traversals respectively # + `dfs_tree` and `bfs_tree` produce the tree representation of the DFS & BFS traversals respectively # + `dfs_successors` and `bfs_successors` produces a dict mapping nodes to lists of their successors of nodes starting from the root (using DFS & BFS respectively) # # In[ ]: graph_dict = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D', 'F'], 'D': ['B', 'C'], 'E': ['F'], 'F': ['C', 'E']} G = nx.from_dict_of_lists(graph_dict) # In[ ]: bfs(graph_dict, 'A') # In[ ]: # same result attained using networkx edges = nx.bfs_edges(G, 'A') nodes = ['A'] + [v for u, v in edges] nodes # In[ ]: list(nx.bfs_successors(G, 'A')) # result of bfs_successors is a generator # <a id="q16"></a> # [Return to top](#questions) # ### Question 16: Using `networkx` for DFS and BFS # # For this question, you'll work with the `networkx` representation of `romania_graph` (created for you here as `G_romania`). # In[ ]: G_romania = nx.from_dict_of_lists(romania_graph) nx.draw_networkx(G_romania, with_labels=True, node_color='yellow') # Use the `networkx` functions `dfs_successors` & `bfs_successors` to determine two `dict`s mapping nodes to lists of their successors as found in a depth-first & a breadth-first traversal (respectively) starting from `Sibiu`. # # + Assign the result of the DFS traversal to ans_16_dfs. # + Assign the result of the BFS traversal to ans_16_bfs. # + Make sure both results are `dict`s (you may have to explicitly cast them if the function returns a generator). # In[ ]: ### GRADED ### QUESTION 16 ### Save dicts to ans_16_dfs & ans_16_bfs that match vertices to their successors found in ### a DFS or BFS traversal (respectively) initiated at 'Sibiu' in romania_graph ### YOUR ANSWER HERE ans_16_dfs = {} ans_16_bfs = {} # For verification from pprint import pprint print('DFS successors:') pprint(ans_16_dfs) print('\nBFS successors:') pprint(ans_16_bfs) # In[ ]: ### ### AUTOGRADER TEST - DO NOT REMOVE ###
e8e7f1cdcf7128a85bc329cccd097c9131a4e55f
RuchiBor/machine_learning_problems
/tensorflow_1_x/7_kaggle/learntools/sql/ex1.py
2,307
3.625
4
from learntools.core import * class CountTables(EqualityCheckProblem): _var = 'num_tables' _expected = 1 _hint = \ """Run `chicago_crime.list_tables()` in the top cell. Interpret the output to fill in `num_tables`""" _solution = CS( """ chicago_crime.list_tables() num_tables = 1 # also could have done num_tables = len(chicago_crime.list_tables()) """ ) class CountTimestampFields(EqualityCheckProblem): _var = 'num_timestamp_fields' _expected = 2 _hint = \ """Run `chicago_crime.table_schema('crime')` and count the number of fields with TIMESTAMP type""" _solution = CS( """ chicago_crime.table_schema('crime') num_timestamp_fields = 2 """ ) class IdentifyFieldsForPlotting(CodingProblem): _var = 'fields_for_plotting' _hint = "There are a couple options, but two of the fields are things commonly used to plot on maps. " + \ "Both are FLOAT types. Use quotes around the field names in your answer" _solution = CS("fields_for_plotting = ['latitude', 'longitude']") def check(self, fields_for_plotting): assert (type(fields_for_plotting) is list), "fields_for_plotting should be a list" assert (len(fields_for_plotting) == 2), "fields for plotting should have exactly two strings. Your answer had {}".format(len(fields_for_plotting)) assert (type(fields_for_plotting[0] == str), "The first item in fields_for_plotting should be a string") assert (type(fields_for_plotting[1] == str), "The second item in fields_for_plotting should be a string") lower_case_fields = [i.lower() for i in fields_for_plotting] if ('x_coordinate' in lower_case_fields) and ('y_coordinate' in lower_case_fields): print("latitude and longitude would be better and more standard than the x_coordinate and y_coordinate, but this might work.") else: assert (('latitude' in lower_case_fields) and ('longitude' in lower_case_fields)), \ ('There are two fields or variables that are commonly used to plot things on maps. {} is not exactly right'.format(fields_for_plotting)) qvars = bind_exercises(globals(), [ CountTables, CountTimestampFields, IdentifyFieldsForPlotting, ], tutorial_id=169, var_format='q_{n}', ) __all__ = list(qvars)
e6b5b10fc8ada75fdeff86c469719b85efba4837
noamm19-meet/meet2017y1final-proj
/eman.py
1,624
3.734375
4
###########the food and the score############# import turtle import random square_size=20 score=0 pos_list=[] stamp_list=[] food_pos=[] food_stamps=[] turtle.register_shape('car.gif') car = turtle.clone() car.shape("car.gif") turtle.hideturtle() turtle.penup() number_of_burgers=random.randint(1,5) turtle.register_shape("burger.gif") food = turtle.clone() food.shape("burger.gif") food_pos=[] food_stamps=[] food_list = [] wall_list = [] all_points = [] for x in range(-250, 250 - square_size + 1, square_size): for y in range(-250 + square_size, 250 + 1, square_size): all_points.append((x,y)) s_all_points = set(all_points) s_wall_points = set(wall_list) s_free_points = s_all_points - s_wall_points free_points = list(s_free_points) def make_food(): for i in range(number_of_burgers): food_list.append(food.clone()) if car.pos() in food_pos: food_ind=food_pos.index(car.pos()) food.clearstamp(food_stamps[food_ind]) food_pos.pop(food_ind) food_stamps.pop(food_ind) print("You have eaten the food!") score+=1 for clone in food_list: rand_index = random.randint(0, len(free_points) - 1) position = free_points[rand_index] while position in wall_list: rand_index = random.randint(0, len(free_points) - 1) position = free_points[rand_index] food_pos.append(position) clone.goto(position) b=clone.stamp() food_stamps.append(b) clone.hideturtle() make_food() make_food() ############################################
e2460d910deda577b21586db4f4724b66f42e9c3
juliancamilocamachotorres/learn-python
/example-2.py
113
3.5
4
Lado=int(input("ingrese el lado del cuadrado: ")) Perimetro=Lado*4 print("el perimetro es: ") print(Perimetro)
64eebb8ed6b01f3858629684704cba4f5bcf03c4
Amruta329/123pythonnew-
/list.py
319
4.0625
4
thislist = ["apple", "banana", "cherry"] #used to extend the elemts or it will add the second list into first list tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) thislist.insert(2, "watermelon") #used to insert the elements aat index print(thislist)
2f9ac2f3935ed75b444df0d0defb19a2df863b60
demar01/python
/Chapter_PyBites/107_Filter_numbers_with_a_list_comprehension/list_comprehensions.py
580
4.09375
4
from collections import namedtuple numbers= [1,2,3,4] #easier to create two functions first and then use them in the list comprehension def is_even(num): return num % 2 == 0 def is_positive(num): return num > 0 BeltStats = namedtuple('BeltStats', 'score ninjas') ninja_belts = {'yellow': BeltStats(50, 11), 'orange': BeltStats(100, 7), 'green': BeltStats(175, 1), 'blue': BeltStats(250, 5)} def filter_positive_even_numbers(numbers): return [number for number in numbers if is_even(number) and is_positive(number)]
36011880ba535c33782d318ce77dee5a44c4b5f7
AlexJamesWright/Blackjack
/src/Table.py
5,781
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 19 18:42:56 2019 @author: ajw1e16 Table class """ from DeckAndShoe import Shoe from HandSeatAndDealer import Seat, Dealer import utilityFunctions as ut class Table(object): """ Physical table. Has seats, a dealer, and a shoe. Parameters ---------- broadcast : object Broadcast object maxNumberOfSeats : int Maximum number of seats at the table. minBet : int Minimum bet size maxBet : int Maximum bet size """ maxNumberOfSeats = 6 def __init__(self, broadcast, numberOfSeats=6, minBet=1, maxBet=100): self.broadcast = broadcast self.dealer = Dealer() self.seats = [] self.numberOfSeats = numberOfSeats self.newShoe() for i in range(self.numberOfSeats): if i < self.maxNumberOfSeats: self.newSeat() def newShoe(self, penPosition=250): """ Generate a new shoe. """ self.broadcast.reset() self.shoe = Shoe(self.broadcast) self.shoe.penetrate(penPosition) def newSeat(self): """ Add a new seat to the table. """ self.seats.append(Seat()) def playerActions(self): """ Go round the table and perform all player actions. """ for seat in self.seats: for hand in seat.hands: # Start of hand, deal with doubling and splitting firest if len(hand.cards) == 1: # Player must have split so take another card hand.addCard(self.shoe.nextCard()) elif len(seat.hands) == 1 and ut.canSplit(hand) and seat.player.wantsToSplit(hand) and seat.player.bank >= 2*hand.bet: seat.newBet(hand.bet) seat.hands[1].addCard(hand.cards[1]) hand.cards.remove(hand.cards[1]) hand.addCard(self.shoe.nextCard()) elif ut.canDoubleDown(hand) and seat.player.wantsToDoubleDown(hand) and seat.player.bank >= 2*hand.bet: seat.player.roundBetting += hand.bet hand.doubleDown(self.shoe) # Special actions have been delt with, now play normally while ut.canBePlayed(hand): if seat.player.wantsToHit(hand): hand.hit(self.shoe) else: hand.stick() def cleanSeats(self): """ Delete all hands. """ for seat in self.seats: seat.resetSeat() self.dealer.resetHand() def getBets(self): """ Go around the table requesting bets from the players/ """ # Get the bets from the seats for seat in self.seats: if seat.player: # Get players bet size seat.newBet(seat.player.getBet()) def deal(self): """ Go round the table dealing cards to the players and dealer. """ # Hand out two cards to each player and the dealer # First card for seat in self.seats: if seat.player: for hand in seat.hands: hand.addCard(self.shoe.nextCard()) # Dealer's first self.dealer.hand.addCard(self.shoe.nextCard()) # Second card for seat in self.seats: if seat.player: for hand in seat.hands: hand.addCard(self.shoe.nextCard()) # Dealers second self.dealer.hand.addCard(self.shoe.nextCard()) # Update the broadcast with dealers up card self.broadcast.dealersTotal = self.dealer.total() def dealerAction(self): """ Dealer plays until theys stick or bust. """ self.dealer.playHand(self.dealer.hand, self.shoe) def nextRound(self): """ Play the next round of blakjack """ # Need to initialise some new bets/hands self.cleanSeats() self.getBets() self.deal() self.playerActions() self.dealerAction() self.settleUp() def getPlayers(self): """ Get all the players current at the table. Returns ------- player : list A list of all Player objects at the table """ players = [] for seat in self.seats: if seat.player not in players and seat.player is not None: players.append(seat.player) return players def settleUp(self): """ Casino pays out winning hands. """ for seat in self.seats: for hand in seat.hands: tot = ut.getTotal(hand) # Only pay out if player isnt bust if tot <= 21: # Recall that bet has already been taken, so payouts must # include this again. I.e. a push requires bank+=bet # Payout 1.5x if player got blackjack if ut.isBlackjack(hand): seat.player.payout += hand.bet*2.5 # Pay out if dealer busts elif ut.isBust(self.dealer.hand): seat.player.payout += hand.bet*2 # Pay out if higher score than dealer elif tot > self.dealer.fullTotal(): seat.player.payout += hand.bet*2 # Push, give bet back elif tot == self.dealer.fullTotal(): seat.player.payout += hand.bet for player in self.getPlayers(): player.settleRound()
24dccf28929b3bf5770f2646ff0f6fa0441f0247
midhorse/hft-verilog-generator
/src/generator/gen_testbench.py
3,995
3.671875
4
''' This file takes a csv formatted input data file and an algorithm name and generates two files: a raw data file and a test bench in verilog used to run the the specified algorithm on the raw data file. ''' import sys, csv, struct def get_bin_from_int(num): return bin(struct.unpack('!i',struct.pack('!f',float(num)))[0]) def bin_to_hex(b): hexi = {"0000": 0, "0001": 1, "0010": 2, "0011": 3, "0100": 4, "0101": 5, "0110": 6, "0111": 7, "1000": 8, "1001": 9, "1010": 'a', "1011": 'b', "1100": 'c', "1101": 'c', "1110": 'e', "1111": 'f'} i = 0 retstr = "" while i < 32: retstr += str(hexi[b[i:i+4]]) i+=4 return retstr def gen_raw(csv_file, algo): fields = None try: with open(csv_file, newline='') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') i = 0 data_file = open(csv_file.split(".")[0]+".hex", "w") for row in csv_reader: if i == 0: fields = row data_file.write(str(hex(len(row))[2:])) data_file.write("\n") else: for num in row: b = get_bin_from_int(int(num)) b = b[2:].zfill(32) b = bin_to_hex(b) data_file.write(b) data_file.write("\n") i += 1 return fields, i except: print("Error: couldn't read csv file.") def gen_tb(fields, rows, algo_v, data_csv): tb_name = algo_v.split(".")[0]+"_tb.v" with open(tb_name, "w") as f: f.write("`timescale 1ns / 1ps") f.write("\n") f.write('`include "{}"'.format(algo_v.split("/")[-1])) f.write("\n\n") f.write("module {}();\n".format(tb_name.split(".")[0].split("/")[-1])) args_list = ".out1(w_o1), .out2(w_o2)" mon_list = "" mon_args = "" for i in range(len(fields)): fields[i] = fields[i] f.write(" reg [31:0] {};\n".format(fields[i])) args_list += ", .{}({})".format(fields[i], fields[i]) mon_list += fields[i] + "=%d, " mon_args += fields[i] + ", " f.write(' reg [31:0] data[{}:0];\n\n'.format(rows-1)) f.write(' wire w_o1, w_o2;\n') f.write(' {} uut ({});\n\n'.format(algo_v.split(".")[0].split("/")[-1], args_list)) f.write(' integer i, f;\n') f.write(' initial begin\n') f.write(' f = $fopen("{}_out.txt", "w");\n'.format(algo_v.split(".")[0].split("/")[-1])) f.write(' $monitor("{}OUT1=%b, OUT2=%b", {}w_o1, w_o2);\n'.format(mon_list, mon_args)) f.write(' $dumpfile("{}.vcd");\n'.format(algo_v.split(".")[0].split("/")[-1])) f.write(' $dumpvars(0, {});\n\n'.format(tb_name.split(".")[0].split("/")[-1])) f.write(' $readmemh("{}", {});\n\n'.format(data_csv.split(".")[0]+".hex", "data")) f.write(' for (i = 1; i <= {}; i = i + {})\n'.format(str(rows-1), str(len(fields)))) f.write(' begin\n') for i in range(len(fields)): f.write(' {} = data[i+{}];\n'.format(fields[i], str(i))) f.write(' #1000;\n') f.write(' $fwrite(f, "{}OUT1=%b, OUT2=%b{}{}", {}w_o1, w_o2);\n'.format(mon_list, "\\", "n", mon_args)) f.write(' #1000;\n') f.write(' end\n') f.write(' $fclose(f);\n') f.write(' $finish;\n') f.write(' end\n') f.write('endmodule') if __name__ == "__main__": assert len(sys.argv) == 3, "Oops, make sure you run $ python gen_testbench.py [path/to/data.csv] [path/to/algo_mod.v]" data_csv = sys.argv[1] algo_v = sys.argv[2] fields, rows = gen_raw(data_csv, algo_v) rows = 1 + (rows-1)*len(fields) #print(fields, rows) gen_tb(fields, rows, algo_v, data_csv)
922a23937c3a89c62c7cd8909852add27f2dd14b
meetofleaf/password-transformer
/firepass.py
2,043
3.90625
4
import random as r print("\nFire Password") print("_____________\n") user_pass = input("Password: ") def passgen(upass): chars = list(upass) for i in range(len(chars)): if chars[i] == 'a': chars[i] = '@' elif chars[i] == 'A': chars[i] = '4' elif chars[i] == 'E': chars[i] = '3' elif chars[i] == 'g': chars[i] = '9' elif chars[i] == 'i': chars[i] = 'I' elif chars[i] == 'I': chars[i] = '|' elif chars[i] == 'K': chars[i] = '|<' elif chars[i] == 'l': chars[i] = '1' elif chars[i] == 'L': chars[i] = '\_' elif chars[i] == 'o' or chars[i] == 'O': chars[i] = '0' elif chars[i] == 'p': chars[i] = 'P' elif chars[i] == 's': chars[i] = 'S' elif chars[i] == 'S': chars[i] = '5' elif chars[i] == 't' or chars[i] == 'T': chars[i] = '+' elif chars[i] == 'v': chars[i] = '\/' elif chars[i] == 'V': chars[i] = '\/' elif chars[i] == 'w': chars[i] = 'vv' elif chars[i] == 'W': chars[i] = 'VV' elif chars[i] == 'x' or chars[i] == 'X': chars[i] = '><' elif chars[i] == '0': chars[i] = ')' elif chars[i] == '1': chars[i] = '!' elif chars[i] == '2': chars[i] = '@' elif chars[i] == '3': chars[i] = '#' elif chars[i] == '4': chars[i] = '$' elif chars[i] == '5': chars[i] = '%' elif chars[i] == '6': chars[i] = '^' elif chars[i] == '7': chars[i] = '&' elif chars[i] == '8': chars[i] = '*' elif chars[i] == '9': chars[i] = '(' else: continue firepass = "".join(chars) + "_" + str(r.randint(0,1000)) return firepass print(passgen(user_pass))
7ab593a2c86294ad12248e47f7dce12560349759
prashant97sikarwar/leetcode
/Tree/Validate_Binary_Search_Tree_naive.py
711
4.0625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: ## function to check whether the Tree is binary search tree or not. def isValidBST(self, root): ans = [] self.inorder(root,ans) for i in range(len(ans)-1): if ans[i+1] <= ans[i]: return False return True ## function to perform the inorder traversal of the Tree def inorder(self,root,ans): if root is None: return [] self.inorder(root.left,ans) ans.append(root.val) self.inorder(root.right,ans)
0c0e3c9c7951469857b332abf43a5099eb8d1a16
jongpal/AlgorithmPrac
/karp-rabin.py
1,099
3.5
4
#karp rabin #make time complexity of string search to O(n), linear time s = 'jong' t = 'songhyunham is very nice jong' s_list = [] temp=[] def init_calc (str_list, base = 10): sum = 0 for i in range(len(str_list)): sum += str_list[i]*(base**((len(str_list)-1)-i)) return sum def hash(num, m): return num % m #return the first position of the found word #if not founded return False def find_pos (s, t, base) : if(t[0:len(s)] == s): # if the word is located in the first place return 0 for i in range(len(s)): # O(s) s_list.append(ord(s[i])) temp.append(ord(t[i])) r_temp = init_calc(temp) # O(s) r_s = init_calc(s_list) # O(s) for i in range(len(t)-len(s)): # O(t-s) r_temp -= ord(t[i])*base**(len(s)-1) r_temp *= base r_temp += ord(t[i+len(s)]) if(hash(r_temp, len(s) + 1) == hash(r_s, len(s)+1)): if(s == t[i+1:i+len(s)+1]): #for the matched one , each of those + O(s) return i+1 return False # total complexity : O(t + #of matched * s) # if hash function is fine, then it would be just O(t) print(find_pos(s,t, 10))
1a57be66e483479f2ef7d3aab11f7ef292ffe9e8
frankShih/LeetCodePractice
/75-sortColor/solution.py
1,466
3.546875
4
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ ''' # 80% two-run, naive solution counter = [0]*3 for n in nums: counter[n]+=1 ind=0 for i in range(len(counter)): for j in range(counter[i]): nums[ind]=i ind+=1 # return nums ''' # 30% left, right, ind = -1, len(nums), 0 while(ind<right): if nums[ind]==0: left+=1 temp=nums[left] nums[left]=nums[ind] nums[ind]=temp if left==ind: ind+=1 elif nums[ind]==1: ind+=1 else: right-=1 temp=nums[right] nums[right]=nums[ind] nums[ind]=temp # 60% left, right = 0, len(nums)-1 for i in range(len(nums)): while(nums[i]==2 and i<right): temp = nums[right] nums[right] = nums[i] nums[i] = temp right-=1 while(nums[i]==0 and i>left): temp = nums[left] nums[left] = nums[i] nums[i] = temp left+=1
99e99cc2191e4cdf0bec54227943e2813f3a3c09
AnnKuz1993/Python
/lesson_04/example_01.py
734
3.859375
4
""" Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. """ import sys from lesson_04 import test try: file, user, make, salery, prize = sys.argv except ValueError: print("Invalid args") exit() test.hello(user) print(test.cal(int(make), int(salery), int(prize)))
5d5486fcebf8ee5d8968fc877c01065279dad1aa
biosvos/algorithm
/프로그래머스/모의고사/main.py
730
3.53125
4
import itertools def solution(answers): patterns = [ [1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] ] scores = [] for pattern in patterns: scores.append(len([1 for a, b in zip(answers, itertools.cycle(pattern)) if a == b])) answer = [] max_score = 0 for i, score in enumerate(scores, start=1): if score > max_score: max_score = score answer.clear() answer.append(i) elif score == max_score: answer.append(i) return answer def main(): assert solution([1, 2, 3, 4, 5]) == [1] assert solution([1, 3, 2, 4, 2]) == [1, 2, 3] if __name__ == '__main__': main()
3a42780034aab34280a2d9c6090bc39db94456bc
DomantasJonasSakalys/arnoldclark
/rock_paper_scissors.py
1,133
4.03125
4
import random #The following describe the basic rules and selections. Key beats Values. rules = { 'Rock' : ['Lizard', 'Scissors'], 'Paper' : [ 'Rock', 'Spock'], 'Scissors' : [ 'Paper', 'Lizard' ], 'Lizard' : ['Spock', 'Paper'], 'Spock' : ['Scissors', 'Rock'] } #Making selections from the keys selections = ', '.join(list(rules.keys())) def run(): #Selection statement print('\nTo play enter one of the selections:\n' + selections) #Player selection player = input('You choose: ').capitalize() #Check for valid input while player not in rules.keys(): print('\nInvalid input, try again\n') player = input('You choose: ').capitalize() #AI selection ai = random.choice(list(rules.items()))[0] print('AI selected: ' + str(ai)) #Check and tell who won if ai in rules[player]: print('You Won, ' + player + ' beats ' + ai) return 1 elif player in rules[ai]: print('You Lost, ' + ai + ' beats ' + player) return 2 else: print("It's a Tie") return 3 #Start the game print('Welcome to the '+ selections + ' game!') run() #Play again? while input('Play again? ').capitalize()[0:1] == 'Y': run() exit()
2f388e1a73bb97d833155706185c919f3825176a
Omri627/geo_war
/backend/facts/religion.py
8,975
3.8125
4
from db.business_logic.countries import CountriesData from db.business_logic.religions import ReligionsData from random import randint # more_common_religion # the method receives name of a country, and boolean variable indicate whether to build a true fact or a fake one # and construct a fact claiming certain random religion is more common then another religion in country X # the player should determine whether it is true or false def more_common_religion(country: str, real_or_fake: bool): # get random religions religions_data = ReligionsData() religions = religions_data.get_country_religions(country) if religions is None or len(religions) < 2: return None if country == 'Germany': return None second_religion = randint(1, len(religions) - 1) first_religion = randint(0, second_religion - 1) if not real_or_fake: first_religion, second_religion = second_religion, first_religion if religions_data.is_invalid_religion(religions[first_religion].religion) or \ religions_data.is_invalid_religion(religions[second_religion].religion): return None return { 'topic': 'Religion', 'fact': 'The religion ' + religions[first_religion].religion + ' is more common then ' + religions[second_religion].religion + ' in the country ' + country, 'hint': 'The estimated percentage of religion ' + religions[second_religion].religion + ' in the country ' + country + ' is ' + str(religions[second_religion].percentage) + '%', 'answer': real_or_fake, 'detail': 'The approximated percentage of religion ' + religions[first_religion].religion + ' in the country ' + country + ' is ' + str(religions[first_religion].percentage) + '%' + ' whereas the estimated percentage of religion ' + religions[second_religion].religion + ' in the country ' + country + ' is ' + str(religions[second_religion].percentage) + '%', } # above_percentage # the method receives name of a country, and boolean variable indicate whether to build a true fact or a fake one # and construct a fact claiming certain random religion is The chance to run into a person from # certain religion is above X% - the player should determine whether it is true or false def religion_above_percentage(country: str, real_or_fake: bool): # get a random religion religions_data = ReligionsData() religions = religions_data.get_country_religions(country) if religions is None or len(religions) == 0: return None if country == 'Germany': return None religion_position = randint(0, len(religions) - 1) religion = religions[religion_position] if religions_data.is_invalid_religion(religion.religion): return None # compute the percentage appeared in the fact fact_percentage = int(religion.percentage) if fact_percentage > 9: fact_percentage = fact_percentage - (fact_percentage % 10) if not real_or_fake: fact_percentage += 10 else: fact_percentage = 10 if fact_percentage >= 5 else 5 answer = religion.percentage > fact_percentage if fact_percentage == 100 or answer != real_or_fake: return None return { 'topic': 'Religion', 'fact': 'The chance to run into a person of ' + religion.religion + ' religion in the country ' + country + ' is above ' + str(fact_percentage) + '%', 'hint': 'The religion ' + religion.religion + ' is the ' + str(religion_position + 1) + 'th common religion in the country ' + country, 'answer': real_or_fake, 'detail': 'The estimated percentage of people pursuing the religion ' + religion.religion + ' in the country ' + country + ' is ' + str(religion.percentage) + '%', } # is_common # the method receives name of a country, and boolean variable indicate whether to build a true fact or a fake one # and construct a fact claiming certain religion is common in the given country # the player should determine whether it is true or false def is_common_religion(country: str, real_or_fake:bool): # get country religions religions_data = ReligionsData() religions = religions_data.get_country_religions(country) if religions is None or len(religions) < 2: return None if country == 'Germany': return None # select randomly specific religion selected_religion_idx = randint(1, len(religions) - 1) selected_religion = religions[selected_religion_idx] if religions_data.is_invalid_religion(selected_religion.religion): return None # other religions for the hint del religions[selected_religion_idx] other_religions = '' for religion in religions: other_religions += religion.religion + ', ' other_religions = other_religions[:-2] return { 'topic': 'Religion', 'fact': 'The religion ' + selected_religion.religion + ' is common in ' + country + '. (common means there is non-zero proportion of the population which pursue this religion in the country)', 'hint': 'The religions that are common in the country ' + country + ' is ' + other_religions, 'answer': True, 'detail': 'The estimated percentage of religion ' + selected_religion.religion + ' in the country ' + country + ' is ' + str(selected_religion.percentage), } # compare_common_religion # the method receives name of a country, and boolean variable indicate whether to build a true fact or a fake one # and construct a fact claiming the proportion of certain religion is more common in the first # country then the second country - the player should determine whether it is true or false def compare_common_religion(first: str, second: str): # get common religions of the given countries religion_data = ReligionsData() common_religions = religion_data.common_religions(first, second) if common_religions is None or len(common_religions) == 0: return None selected_religion = common_religions[randint(0, len(common_religions) - 1)] if religion_data.is_invalid_religion(selected_religion['first'].religion) or \ religion_data.is_invalid_religion(selected_religion['second'].religion): return None if first == 'Germany' or second == 'Germany': return None return { 'topic': 'Society', 'fact': 'The proportion of religion ' + selected_religion['first'].religion + ' in the country ' + first + ' is larger then its proportion in the country ' + second, 'hint': 'The proportion of the religion ' + selected_religion['first'].religion + ' in the country ' + first + ' is ' + str(selected_religion['first'].percentage), 'answer': selected_religion['first'].percentage > selected_religion['second'].percentage, 'detail': 'The proportion of the religion ' + selected_religion['first'].religion + ' in the country ' + first + ' is ' + str(selected_religion['first'].percentage) + ' whereas its proportion in the country ' + second + ' is ' + str(selected_religion['second'].percentage), } # compare_main_groups # the method receives name of two countries and # construct a fact claiming the main group in first country is more common then the main group in second country # the player should determine whether it is true or false def compare_main_religions(first: str, second: str): religion_data = ReligionsData() first_main_religion = religion_data.main_religion(country=first) second_main_religion = religion_data.main_religion(country=second) if first_main_religion is None or second_main_religion is None or \ religion_data.is_invalid_religion(first_main_religion.religion) or religion_data.is_invalid_religion(second_main_religion.religion): return None if first == 'Germany' or second == 'Germany': return None answer = first_main_religion.percentage > second_main_religion.percentage return { 'topic': 'Society', 'fact': 'The main religion in the country ' + first + ' (' + first_main_religion.religion + ') has a bigger proportion then the most common religion in the country ' + second + ' (' + second_main_religion.religion + ')', 'hint': 'The proportion of the religion ' + first_main_religion.religion + ' in the country ' + first + ' is ' + str(first_main_religion.percentage), 'answer': answer, 'detail': 'The proportion of the religion ' + first_main_religion.religion + ' in the country ' + first + ' is ' + str(first_main_religion.percentage) + ' whereas the proportion of the religion ' + second_main_religion.religion + ' in the country ' + second + ' is ' + str(second_main_religion.percentage) }
93d5790bad4024588d166b66f58746b2a817d340
daniel26082/Practice
/main.py
398
3.609375
4
import turtle as trtl # draw left curve 90 degrees trtl.pendown() for i in range(6): trtl.forward(10) trtl.left(15) trtl.penup() def draw_y_axis(): trtl.goto(0,0) trtl.pendown() trtl.forward(100) trtl.backward(200) trtl.penup() def draw_x_axis(): trtl.goto(0,0) trtl.left(90) trtl.pendown() trtl.forward(100) trtl.backward(200) trtl.penup() draw_y_axis() draw_x_axis()
46e8a5b2300112ccec6940fe52f38f678a7caa10
RocketDonkey/project_euler
/python/problems/euler_002.py
942
3.703125
4
"""Project Euler - Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Proof that every number is = 4*(n-3) + (n-6): E(n) = E(n-1) + E(n-2) = E(n-2) + E(n-3) + E(n-3) + E(n-4) = 3*E(n-3) + 2*E(n-4) = 3*E(n-3) + E(n-4) + E(n-5) + E(n-6) = 4*E(n-3) + E(n-6) Looks like it can be used recursively but don't think it will save any time. """ def Euler002(): """Every third number is even.""" n = 4000000 s = 0 p_prev = 1 prev = 1 num = p_prev + prev while num < n: s += num p_prev = prev + num prev = num + p_prev num = p_prev + prev return s def main(): print Euler002() if __name__ == '__main__': main()
ecfe7e4abc05b198df98311fa433a296a80c22bc
AbrahamCain/Chemistry
/molesFromAtoms.py
86
3.734375
4
a = float(input("Atoms: ")) moles = a/(6.022*(10**23)) print("Moles = " + str(moles))
624f4f48e466cd470885dbdca5ac79db422af69b
anarchy-muffin/web-spider
/spider.py
2,979
3.609375
4
import HTMLParser import urllib2 import parser #make class LinkParser that inherits methods from #HTMLParser which is why its passed to LinkParser definition. #This is a function that HTMLParser normally has #but we add functionality to it. def handle_starttag(self, tag, attrs): #looking for the beginning of a link # <a href="www.exampleurl.com"></a> if tag == 'a': for (key, value) in attrs: if key == 'href': #grabbing URL(s) and adding #base URL to it. For example: #www.example.com is the base and #newpage.html is the new URL (a relative URL) # #Combining a relative URL with the base HTML page #to create an absolute URL like: #www.example.com/newpage.html newURL = parse.urljoin(self.baseUrl, value) #add it to collection of links: self.links = self.links + [newUrl] #New function to get links that #spider() function will call def get_links(self, url): self.links = [] #Remember base URL which will be important #when creating absolute URLs self.baseUrl = url #use urlopen function from standard Python3 library response = urlopen(url) #Make sure you're looking @ HTML only!! #(No CSS, JavaScript, etc...) if response.getheader('Content-Type')=='text/html': htmlBytes = response.read() #note that feed() handles strings well but not bytes #A change from Python2.x to 3.x htmlString = htmlBytes.decode("utf-8") self.feed(htmlString) return htmlString, self.links else: return "",[] #This is the actual "spider" porton of the webspider (Hooray!) #it takes a URL, a word to find, and a number of pages to search #before giving up. def spider(url, word, maxPages): pagesToVisit = [url] numberVisited = 0 foundWord = False #above is the main loop creates a link parser and grabs all #links on the page, also searching through the page for the #desired quote or string, in getLinks function we return the page. #(helps with where to go next) while numberVisited < maxPages and pagesToVisit != [] and not foundWord: numberVisited = numberVisited +1 #Start from the beginning of our collection of pages url = pagesToVisit[1:] try : print (numberVisited, "Visiting: ", url) parser = LinkParser() data, links = parser.getlinks(url) if data.find(word)>-1: foundWord = True #Adds pages we found to end of the collection #of pages to visit. pagesToVisit = pagesToVisit + links print ("**SUCCESS**") except: print ("**FAILED**") if foundWord: print "The word", word, "was found at:" , url else: print "Word not found."
56307a7262a79bb325f815f29401a59bf0cbf12a
wuping5719/PythonTest
/src/test/test24.py
352
3.875
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 14 日 @author: Nick ''' ''' 题目:一个5位数,判断它是不是回文数。 即12321是回文数,个位与万位相同,十位与千位相同。 ''' a = input("输入一串数字: ") b = a[::-1] if a == b: print("%s 是回文数."% a) else: print("%s 不是回文数."% a)
8354909c36c866a82a0d3a237fdfaf331dae4b24
szewczykmira/adventofcode
/2022/day3/solution.py
1,014
3.625
4
from typing import Set from functools import reduce from math import floor from string import ascii_letters INPUT_FILE = "input.txt" def items_in_the_rucksack(line: str) -> Set[str]: length = len(line) half = floor(length / 2) first = set(line[:half]) second = set(line[half:]) return first.intersection(second) def run1(): with open(INPUT_FILE) as rucksacks: priority_sum = 0 for line in rucksacks: for item in items_in_the_rucksack(line): priority_sum += ascii_letters.index(item) + 1 print(priority_sum) def run2(): with open(INPUT_FILE) as rucksacks: priority_sum = 0 try: while True: three_lines = [set(next(rucksacks).strip()) for _ in range(3)] badge = list(reduce(lambda x, y: x.intersection(y), three_lines))[0] priority_sum += ascii_letters.index(badge) + 1 except StopIteration: pass print(priority_sum) run1() run2()
cc0dcdf0f55cbe6a8cf595a55c244339dc063eb6
ilya0296/Artezio-Academy
/Lesson 1/ex8.py
224
3.84375
4
def hvalues(d): a = list(d.values()) a.sort(reverse=True) b = [] for x in range(3): b.append(a[x]) return b dt = {'a': 400, 'b': 500, 'c': 100, 'd': 800, 'e': 200} print(hvalues(dt))
d2dd776609a7efe0d141343df4062e74d8f8407c
Yinghuochongxiaoq/Python_Succinctly
/functionDefault.py
795
4.09375
4
def say_hello(): print('Hello every one.') say_hello() def say_hello(name='FreshMan'): print('Hello {}!'.format(name)) say_hello('FreshMan') say_hello() say_hello(name='FreshMan and JunJun') def say_hello(first,last='FreshMan'): '''Say hello''' print('Hello {} {}!'.format(first,last)) say_hello('JunJun'); help(say_hello) def even_or_odd(number): '''Datermine if a number is odd or even''' if number%2==0: return 'Even' return 'Odd' print(even_or_odd(9)) def get_name(): '''Get and return a name''' name=input('What is your name?' ) return name def say_name(name): '''Say a name''' print('Your name is {}'.format(name)) def get_and_say_name(): '''Get and display name''' name=get_name() say_name(name) get_and_say_name()
409f67723d5479566826bcd909eac84cea0d99b0
Natsu1270/Codes
/Hackerrank/LinkedList/DeleteNode.py
505
3.796875
4
from LinkedList import * def deleteNode(head,pos): if pos == 0: return head.next temp = head prev = None while pos > 0: prev = temp temp = temp.next pos -= 1 prev.next = temp.next del temp return head def deleteNodeRec(head,pos): if pos == 0: return head.next head.next = deleteNodeRec(head.next,pos-1) return head llist = input_linkedlist() pos = int(input()) head = deleteNode(llist.head,pos) print_linkedlist(head)
d0bdc0a5818ad52fbbe564366b151d3c1e1f515d
LudicrousWhale/CSES-Problem-Set
/Permutations.py
207
3.796875
4
n = int(input()) if n == 1: print (n) elif n < 4: print("NO SOLUTION") else: for i in range(2, n + 1, 2): print(i, end = " ") for i in range(1, n + 1, 2): print(i, end = " ")
23b4da3cd321145b89afaef4488510b11e11850a
sathishmepco/Python-Basics
/basic-concepts/data_structures/queue_demo.py
843
4.34375
4
from collections import deque queue = deque(["Eric", "John", "Michael"]) print('The items in the queue are :',queue) queue.append("Terry") print('After appending Terry :',queue) queue.append("Graham") print('After appending Graham :',queue) print('Pop the item from the queue :',queue.popleft()) print('After Pop :',queue) print('Pop the item from the queue :',queue.popleft()) print('After Pop :',queue) ''' OUTPUT ------ The items in the queue are : deque(['Eric', 'John', 'Michael']) After appending Terry : deque(['Eric', 'John', 'Michael', 'Terry']) After appending Graham : deque(['Eric', 'John', 'Michael', 'Terry', 'Graham']) Pop the item from the queue : Eric After Pop : deque(['John', 'Michael', 'Terry', 'Graham']) Pop the item from the queue : John After Pop : deque(['Michael', 'Terry', 'Graham']) '''
daaff54dd2784623d979924a82d891d8eec74c3f
sivajipr/python-course
/days/4/classes/exercises/counter/counter.py
485
3.609375
4
class Counter: def __init__(self,count): self.i=0 self.count=count def __str__(self): return "counter:%d" %(self.i) def show(self): print self.count def increment(self): self.i += 1 def decrement(self): self.i -= 1 #c = Counter() #c.show() # prints 0. #c.increment() #c.show() # prints 1 #c.decrement() #c.show() # prints 0 #print c # prints 'Counter: 0' (implement the __str__ method) c = Counter(10) # __init__ should accept an argument c.show() # prints 10
3226a1cd3c39aa7705968b94a10da6a5e0960430
eelanpy/edabit
/76_disarium_num.py
441
3.765625
4
def is_disarium(n): num_disarium = 0 for i,j in enumerate(str(n)): num_disarium += int(j) ** int(i+1) print(num_disarium == n) arg_is_disar = [1, 518, 6, 135, 75, 876, 175, 466, 372, 598, 696, 89] correct_value = [True, False, True, False, False, True, True, False, False, True, True, True] dict_arg_true_false = {} for i,j in enumerate(arg_is_disar): dict_arg_true_false[j] = correct_value[i] print(dict_arg_true_false)
a90ff3c43438300e686ac9bab589e0c124de9b0a
runnz121/Python_boot
/2weeks/2.py
612
3.921875
4
def grader(name,score): grade = '' if(100 >= score >= 95): grade = 'A+' elif(94 >= score > 90): grade = 'A' elif(89 >= score > 85): grade = 'B+' elif(84 >= score > 80): grade = 'B' elif(79 >= score > 75): grade = 'C+' elif (74 >= score > 70): grade = 'C' elif (69 >= score > 65): grade = 'D+' elif (64 >= score > 60): grade = 'D' elif (60 > score): grade = 'F' print("학생이름:" + str(name)) print("점수:" + str(score)) print("학점:" + str(grade)) print(grader("이호창",99))
5e43682ca4a3d63f0ff22d91aaaf608e7092d9c7
bijiawei0818/Learning-Python
/阶乘.py
210
3.796875
4
def recuration(n): result=1 for i in range(1,n+1): result*=i return result num=int(input("请输入一个整数:")) result=recuration(num) print("%d的阶乘是%d"%(num,result))
41048f520507adfddf2bc1ec2f5b1a2a6cf1a1f0
yash1-2000/AxenousTest
/Q2_YashwantGaikwad.py
550
4
4
string = "EduCatiON" lower = 0 upper = 0 for i in range(0, len(string)): # for j in range(i+1, len(string)): # if(string[i] == string[j] and string[i] != ' '): # count = count + 1; if(string[i].islower()): string= string[0:i] + string[i].upper() + string[i+1: ] lower = lower + 1 else: string= string[0:i] + string[i].lower() + string[i+1: ] upper = upper + 1 print ("lower characters = ", lower) print ("upper characters = ", upper) print ("formatted string = ", string)
6446f61ee7eb29db193dbd84a53effdf9e8e9608
testcg/python
/code_all/day17/exercise04.py
967
4.40625
4
""" 练习:使用学生列表封装以下三个列表中数据 list_student_name = ["悟空", "八戒", "白骨精"] list_student_age = [28, 25, 36] list_student_sex = ["男", "男", "女"] """ class Student: def __init__(self, name="", age=0, sex=""): self.name = name self.age = age self.sex = sex # list_student_name = ["悟空", "八戒", "白骨精"] # list_student_age = [28, 25, 36] # list_student_sex = ["男", "男", "女"] # list_student = [] # for data in zip(list_student_name, list_student_age, list_student_sex): # stu = Student(data[0],data[1],data[2]) # list_student.append(stu) # print(list_student) list_datas = [ ["悟空", "八戒", "白骨精"], [28, 25, 36], ["男", "男", "女"] ] # list_student = [] # for data in zip(*list_datas): # stu = Student(*data) # list_student.append(stu) list_student = [Student(*data) for data in zip(*list_datas)] print(list_student)
bfbfc45e55c0112d2f690cd77279d2977adae490
dennisnderitu254/Andela-Exercises
/multiplicationtable.py
463
4.4375
4
# Nested for loop Example # Print a multiplication table to 10 * 10 # Print column heading print(" 1 2 3 4 5 6 7 8 9 10") print(" +---------------------------------------------") for row in range(1, 11): if row < 10: print(" ", end=" ") print(row, "| ", end=" ") for column in range(1, 11): product = row*column; if product < 100: print(end=" ") if product < 10: print(end=" ") print(product, end=" ") print()
4cf6c7d37888acbb8755d5a949acbf1b0721475d
sachio222/socketchat_v3
/chatutils/db.py
2,703
3.5
4
import sqlite3 from sqlite3.dbapi2 import Cursor def table_exists(cursor: sqlite3.Cursor, table_name: str) -> bool: cursor.execute( "SELECT count(name) FROM sqlite_master WHERE TYPE = 'table' AND name = '{}'" .format(table_name)) if cursor.fetchone()[0] == 1: return True else: return False def create_table(cursor: sqlite3.Cursor, table_name: str) -> None: cursor.execute("""CREATE TABLE '{}'( user_name TEXT, public_key TEXT ) """.format(table_name)) def add_user(conn: sqlite3.Connection, cursor: sqlite3.Cursor, table_name: str, user_name: str, public_key: str): cursor.execute( """INSERT INTO '{}' (user_name, public_key) VALUES (?, ?) """.format(table_name), (user_name, public_key)) conn.commit() def get_user(cursor: sqlite3.Cursor, table_name: str, user_name: str) -> list: cursor.execute(""" SELECT * FROM '{}' WHERE user_name = '{}' """.format(table_name, user_name)) data = [] for row in cursor.fetchall(): data.append(row) return data def get_users(cursor: sqlite3.Cursor, table_name: str) -> list: cursor.execute(""" SELECT * FROM '{}' """.format(table_name)) data = [] for row in cursor.fetchall(): data.append(row) return data def update_user(conn: sqlite3.Connection, cursor: sqlite3.Cursor, table_name: str, user_name: str, user_dict: dict) -> None: valid_keys = ["user_name", "public_key"] for key in user_dict.keys(): if key not in valid_keys: raise Exception("Invalid field name.") else: if type(user_dict[key]) == str: stmt = """UPDATE '{}' SET {} = '{}' WHERE user_name = '{}'""".format(table_name, key, user_dict[key], user_name) cursor.execute(stmt) conn.commit() cursor.execute("""""".format()) def delete_user(conn: sqlite3.Connection, cursor: sqlite3.Cursor, table_name: str, user_name: str): cursor.execute(""" DELETE FROM '{}' WHERE user_name = '{}' """.format(table_name, user_name)) conn.commit() def delete_all_users(conn: sqlite3.Connection, cursor: sqlite3.Cursor, table_name: str): cursor.execute(""" DELETE FROM '{}' """.format(table_name)) conn.commit()
8211695ff52afae09515900b6d27fb1290501399
rituc/Programming
/geesks4geeks/array/pair_sum.py
726
3.828125
4
# http://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there # -exist-two-elements-in-s-whose-sum-is-exactly-x/ def main(): print "Enter number of test cases:" T = int(input()) print "Enter array size and sum: " for t in range(T): N = int(input()) x = int(input()) a = [] for i in range(N): a.append(int(input())) print find_pair_sum(a, x, N) def find_pair_sum(a, x, N): a.sort() start = 0 end = N for i in a: num = x - i while(start <= end): mid = (start + end)/2 if(num == a[mid]): return True elif(num <= a[mid]): end = mid -1 else: start = mid + 1 return False if __name__ == "__main__": main()
9cb014ec7b545c617daa0ae014b3f0954d6737d5
tjmode/placement
/13_hunter.py
68
3.578125
4
a=input() s=a[::-1] if a==s: print("YES") else: print("NO")
4fce18838ef35d85f42fcc4070cc3de52cdbd3b0
ivnxyz/evaluador-expresiones-algebraicas
/operators.py
978
4.53125
5
# Operadores permitidos OPERATORS = [ '^', '*', '/', '+', '-' ] # Regresa la posición en la jerarquía de algún operador def get_operator_weight(operator): if operator == '^': return 3 elif operator == '*' or operator == '/': return 2 elif operator == '+' or operator == '-': return 1 else: return 0 # Función de suma addition = lambda x, y: x + y # Función de resta subtraction = lambda x, y: x - y # Función de multiplicación multiplication = lambda x, y: x * y # Función de división division = lambda x, y: x / y # Función de elevar a una potencia power = lambda x, y: x ** y # Devuelve la función correspondiente al caracter dado def get_operator_related_function(operator:str): if operator == '^': return power elif operator == '*': return multiplication elif operator == '/': return division elif operator == '+': return addition elif operator == '-': return subtraction else: raise "Operador desconocido"
b4f5f77c333e1082204c86c9ba88b6a6024aea67
roxyHan/Calculator-
/calculator.py
422
3.703125
4
# Design of the program # Calculator program def main(): # Get user input for the expression to calculate # Evaluate the expression as a string # Use infix concept for correct outputs # Can use helper functions to recude code redundancy # Ideas of helper functions would be: is_parity_of_parentheses, order_of_operations, compute_operation, display_result if __name__ == "__main__": main()
669eebede787b6672e6ad5ca9229ce69070dc5f4
kulala2014/LeetCode_python
/get_vowel_num.py
241
3.734375
4
def getCount(input_str): num_vowels = 0 vowel_str = ['a', 'e', 'i', 'o', 'u'] num_vowels = len([id for i in input_str if i in vowel_str]) return num_vowels input_str = 'abracadabra' result = getCount(input_str) print(result)
b5f505b7b0ff634019252f6ccfa806ca3874a635
Gabriel300p/Computal_Thinking_Using_Python_Exercicios
/Exercicios Extras/exercicio04.py
172
3.765625
4
senha = int(input("Digite a senha: ")) senha_correta = 1234 if senha == senha_correta: print("Acesso permitido") else: print("Você não tem acesso ao sistema")
5f3d600ccd9efad8a8391256a50722c1afdeed0e
Syliel/Python-learning
/jennyfun.py
208
3.6875
4
#!/usr/bin/env python3 def changeme( mylist): mylist = [1,2,3,4]; print "Values inside the function: ", mylist return mylist = [10,20,30] changeme( mylist); print "Values outside the function: ", mylist
b16ccc7ca22d7836d601bf5fdfbb199e078a0d6b
ubnt-intrepid/project-euler
/002/002_gen.py
216
3.515625
4
#!/usr/bin/env python def fibonatti(n_max=4000000): f1, f2 = 1, 1 while f2 <= n_max: yield f2 f2 += f1 f1 = f2 - f1 answer = sum(f for f in fibonatti() if f % 2 == 0) print(answer)
fff01b304fdfc8de3c8fa9e3a5ec691ec6e9eaa1
Simeon117/GUI-
/main.py
11,597
3.859375
4
from tkinter import * import random names = [] asked = [] score = 0 def randomiser(): global qnum qnum = random.randint(1,10) if qnum not in asked: asked.append(qnum) elif qnum in asked: randomiser() class QuizStarter: def __init__(self, parent):#constructor, The __init__() function is called automatically every time the class is being used to create a new object. background_color="DarkSeaGreen1"# #frame set up self.quiz_frame=Frame(parent, bg = background_color, padx=100, pady=100) # self.quiz_frame.grid()# #widgets goes below self.heading_label = Label(self.quiz_frame, text="MRGS School Map", font = ("Helvetica","18","bold"),bg="DarkSeaGreen2") self.heading_label.grid(row = 0, padx = 20) self.var1 = IntVar() #holds value of radio buttons #label for username self.user_label = Label(self.quiz_frame, text = "Enter your name below to get started", font = ("Helvtica","16"),bg = "DarkSeaGreen2") self.user_label.grid(row = 1, padx = 20, pady = 20) self.error_label= Label(self.quiz_frame, bg = background_color) self.error_label.grid(row = 6, padx = 20, pady =20) #entry box self.entry_box = Entry(self.quiz_frame, bg = 'DarkSeaGreen2') self.entry_box.grid(row=3,padx=20, pady=20) self.exit_button = Button (self.quiz_frame, text = "Exit", font = ("Helvetica", "13", "bold"), bg="IndianRed1", command=self.quiz_frame.destroy) self.exit_button.grid(row=5, padx=5, pady=5) #continue button self.continue_button = Button(self.quiz_frame, text="Enter", font =("Helvetica", "13", "bold"), bg = "DarkSeaGreen2", command = self.name_collection) self.continue_button.grid(row=4, padx = 20) #image #logo = PhotoImage(file="road.gif") #self.logo = Label(self.quiz_frame, image=logo) #self.logo.grid(row=4,padx=20, pady=20) def name_collection(self): name = self.entry_box.get() if name.strip() != "" and len(name) <= 15: names.append(name) # print(names) self.quiz_frame.destroy() Quiz(root) elif len(name) >15: self.error_label.config(text="Please enter a name that is less than 15 characters", fg="IndianRed1") elif len(name) ==0: self.error_label.config(text="Please enter a name", fg="IndianRed1") class Quiz: def __init__(self, parent):#constructor, The __init__() function is called automatically every time the class is being used to create a new object. #Dictionary has key of number (for each question number) and : the value for each is a list that has 7 items, so index 0 to 6 self.questions_answers = { 1: ["What is the name of the hall?", #item 1, index 0 will be the question 'Watson Hall', # Item 2, index 1 will be the first choice 'Ball Hall', # Item 3, index 2 will be the second choice 'Butler Hall', # Item 4, index 3 will be the third choice 'School Hall', # Item 5, index 4 will be the fourth choice 'Cathedral Hall'# Item 6, index 5 will be the write statement we need to dsiplay the right stetment if the user enters the wrong choice ,3], # Item 7, index 6 will be the postion of the right answer (ubdex where right answer sits), this will be our check if answer is correct or no 2: ["How many fields are there?", '2', '4', '7', '3', '6' ,1], 3: ["Where can you find the tuckshop?", 'B Block', 'The Quad', 'Field One', 'Hockey Turf', 'T Block' ,2], 4: ["How many Gyms in school?", '8', '3', '2', '4', '1' ,2], 5: ["What is the street address of Mount Roskill Grammar?", '23 Odessa Crescent', '22 Garden Road', '14 Kesteven Avenue', '17 Granada Place', '37 Frost Road' ,5], 6: ["Where is the Maths Deparment?", 'The Library', 'C Block', 'A Block', 'The Hall', 'E Block' ,3], 7: ["What is the name of the principal?", 'Leon Kennedy', 'Gordon Freeman', 'Marcus Fenix', 'Greg Watson', 'Anthony Carmine' ,4], 8: ["How many turfs are there?", '2', '5', '3', '1', '2' ,1], 9: ["Where is the Commerce department?", 'T Block', 'Gym 4', 'E Block', 'D Block', 'The Library' ,3], 10:["Where is the Music deparment block?", 'E Block', 'S Block', 'D Block', 'G Block', 'M Block' ,5], } background_color = "DarkSeaGreen1"# #frame set up self.quiz_frame = Frame (parent, bg = background_color, padx=100, pady=100) self.quiz_frame.grid()# randomiser() #randomiser will randomly pick a question number which is qnum #widgets goes below self.question_label = Label (self.quiz_frame, text = self.questions_answers[qnum][0], font = ("Helvetica","18","bold"), bg="DarkSeaGreen2") self.question_label.grid(row = 0, padx = 10) self.var1 = IntVar() #holds value of radio buttons #first radio button to hold first choice answer #Radiobutton 1 self.rb1 = Radiobutton (self.quiz_frame, text = self.questions_answers[qnum][1], font = ("Helvetica", "14"), bg = background_color, value = 1, variable = self.var1, padx = 10, pady = 10) self.rb1.grid(row = 1, sticky = W) #Radiobutton 2 self.rb2 = Radiobutton (self.quiz_frame, text = self.questions_answers[qnum][2], font = ("Helvetica", "14"), bg = background_color, value = 2, variable = self.var1, padx = 10, pady = 10) self.rb2.grid (row = 2, sticky = W) #Radiobutton 3 self.rb3 = Radiobutton (self.quiz_frame, text = self.questions_answers[qnum][3], font = ("Helvetica", "14"), bg = background_color, value = 3, variable = self.var1, padx = 10, pady=10) self.rb3.grid (row = 3, sticky = W) #Radiobutton 4 self.rb4 = Radiobutton (self.quiz_frame, text = self.questions_answers[qnum][4], font = ("Helvetica", "14"), bg = background_color, value = 4, variable = self.var1, padx = 10, pady = 10) self.rb4.grid (row = 4, sticky = W) #Radiobutton 5 self.rb5 = Radiobutton (self.quiz_frame, text = self.questions_answers[qnum][5], font = ("Helvetica", "14"), bg = background_color, value = 5, variable = self.var1, padx = 10, pady = 10) self.rb5.grid (row = 5, sticky = W) #Confirm button self.confirm_button = Button (self.quiz_frame, text = "Confirm", font = ("Helvetica", "13", "bold"), bg = background_color, command = self.test_progress) self.confirm_button.grid (row = 6, padx = 5, pady = 5) #Score label self.score_label = Label (self.quiz_frame, text = "SCORE", font = ("Helvetica", "15"), bg = background_color,) self.score_label.grid (row = 7, padx = 10, pady = 1) #Quit Button self.quit= Button(self.quiz_frame, text="Quit", font=("Helvetica", "13", "bold"), bg="IndianRed1", command=self.end_screen) self.quit.grid(row=8, sticky=E, padx=10, pady=20) #Method showing the next questions data def questions_setup (self): randomiser() self.var1.set(0) self.question_label.config(text = self.questions_answers[qnum][0]) self.rb1.config(text = self.questions_answers[qnum][1]) self.rb2.config(text = self.questions_answers[qnum][2]) self.rb3.config(text = self.questions_answers[qnum][3]) self.rb4.config(text = self.questions_answers[qnum][4]) self.rb5.config(text = self.questions_answers[qnum][5]) #This is the method that would get invoked with confrim answer button is clicked, to take care of test_progress def test_progress(self): global score scr_label = self.score_label choice = self.var1.get() if len(asked)>9: #if the question is last if choice == self.questions_answers[qnum][6]: #if the last question is the correct answer score+=1 scr_label.configure(text = score) self.confirm_button.config(text="Confirm") self.end_screen() else: #if the last question is the incorrect answer print(choice) score+=0 scr_label.configure(text = " The correct answer was " + self.questions_answers[qnum][5]) self.confirm_button.config(text="Confirm") self.end_screen() else: #if it is not the last question if choice==0: #checks if the user has made a choice self.confirm_button.config(text="Try again please, you didnt select anyhting") choice=self.var1.get() else: #if a choice was made and its not the last question if choice == self.questions_answers[qnum][6]: #if thier choice is correct score+=1 scr_label.configure(text = score) self.confirm_button.config(text="Confirm") self.questions_setup() #execute the method to move on to the next question else: #if the choice was wrong print(choice) score+=0 scr_label.configure(text="The correct answer was: " + self.questions_answers[qnum][5]) self.confirm_button.configure(text="Confirm") self.questions_setup() def end_screen(self): root.withdraw() name=names[0] file=open("leaderBoard.txt", "a") file.write(str(score)) file.write(" - ") file.write(name+"\n") file.close() inputFile= open("leaderBoard.txt", "r") lineList = inputFile.readlines() lineList.sort() top=[] top5=(lineList[-5:]) for line in top5: point=line.split(" - ") top.append((int(point[0]), point[1])) file.close() top.sort() top.reverse() return_string = "" for i in range (len(top)): return_string +="{} - {}\n".format(top[i][0], top[i][1]) print(return_string) open_end_screen=End() open_end_screen.listLabel.config(text=return_string) class End: def __init__(self): background = "DarkSeaGreen1" self.end_box = Toplevel(root) self.end_box.title("End Box") self.end_frame = Frame (self.end_box, width=1000, height=1000, bg=background) self.end_frame.grid() self.listLabel = Label (self.end_frame, text="1st Place Avaliable", font = ("Helvetica", "18"), width = 40, bg = background, padx=10, pady=10) self.listLabel.grid(column=0, row=2) end_heading = Label (self.end_frame, text = "Well Done", font=("Helvetica", "22", "bold"), bg=background, pady=15) end_heading.grid(row=0) exit_button = Button (self.end_frame, text="Exit", width=10, bg="IndianRed1", font=("Helvetica", "12", "bold"), command=self.close_end) exit_button.grid(row = 4, pady = 20) def close_end(self): self.end_box.destroy() root.destroy() randomiser() if __name__ == "__main__": root = Tk() root.title("Health Survey") quizStarter_object = QuizStarter(root) #instantiation, making an instance of the class Quiz root.mainloop() #so the frame doesnt dissapear
4fc61690089b102743299a81de498d36adbc39a3
damian1421/python
/CommonWords.py
722
4.25
4
#sololearn exercise: sets """Given two sentences, you need to find and output the number of the common words (words that are present in both sentences). Sample Input: this is some text I would like this tea and some cookies Sample Output: 2 The words 'some' and 'this' appear in both sentences. You can use the split() function to get a list of words in a string and then use the set() function to convert it into a set. For example, to convert the list x to a set you can use: set(x) """ #I receive the inputs (two different strings) s1 = input() s2 = input() #I convert strings to sets of words s1 = set(s1.split()) s2 = set(s2.split()) #I find the lenght of the words in common in both texts print(len(s1 & s2))
b0fafb80e4c88b256ce68bfe44ba3233892925f6
Her204/data_analysis_repo
/PRACTICE/mandelbrot.py
684
3.5625
4
from PIL import Image, ImageDraw MAX_ITER = 80 WIDTH = 600 HEIGHT = 400 RE_START = -2 RE_END = 1 IM_START = -1 IM_END = 1 palette = [] im = Image.new("RGB",(WIDTH,HEIGHT),(0,0,0)) draw = ImageDraw.Draw(im) def mandelbrot(c): z=0 n=0 while abs(z) <=2 and n <MAX_ITER: z = z*z +c n+=1 return n for x in range(0,WIDTH): for y in range(0,HEIGHT): c = complex(RE_START+(x/WIDTH)*(RE_END-RE_START), IM_START+(y/HEIGHT)*(IM_END-IM_START)) m = mandelbrot(c) color = 255 -int(m*255/MAX_ITER) draw.point([x,y],(color,color,color)) im.save("/mnt/c/users/user/onedrive/escritorio/mandelbrot.png","PNG")
fac7579d30780613a216c608db36f46bb9d87484
avkramarov/gb_python
/lesson 6/Задание 2.py
1,317
3.84375
4
# Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). # Значения данных атрибутов должны передаваться при создании экземпляра класса. # Атрибуты сделать защищенными. Определить метод расчета массы асфальта, # необходимого для покрытия всего дорожного полотна. # Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги асфальтом, # толщиной в 1 см*число см толщины полотна. Проверить работу метода. class Road: _length: int _width: int def __init__(self, _length, _width, _thickness: int = 5, _cost: int = 25): self._length = _length self._width = _width self._thickness = _thickness self._cost = _cost def total_mass(self): mass = self._length * self._width * self._thickness * self._cost print(f"Неоходимо асфальта: {mass} кг.") x = Road(20, 5000) x.total_mass()
ae99cc8bc2cde2b0cdf7d52a1d2e2d1ec84e369a
tanjo3/HackerRank
/Python/Errors and Exceptions/Incorrect Regex.py
207
3.609375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import re t = int(input()) for _ in range(t): try: re.compile(input()) print(True) except: print(False)
657effdfc9e292888d41d212c491411c618c99a2
sjgridley/5023-OOP-scenarios
/turtle_drawing/drawing.py
931
4.1875
4
class Shape: def __init__(self, colour: str, points, my_turtle): self.colour = colour self.points = points self.my_turtle = my_turtle def draw(self): points = self.points # Put the pen up, so the turtle isn't drawing on the canvas and move to first point self.my_turtle.penup() self.my_turtle.goto(points[0].x, points[0].y) # Sets up colour for shape fill colour and puts pen down self.my_turtle.color(self.colour) self.my_turtle.begin_fill() self.my_turtle.pendown() # Moves around to different points to draw the shape for point in points: self.my_turtle.goto(point.x, point.y) # Moves to first point, to close the shape self.my_turtle.goto(points[0].x, points[0].y) self.my_turtle.end_fill() class Point: def __init__(self, x: float, y: float): self.x = x self.y = y
6d39b4791935c78bf8f97a4a41423e87234bca7c
ruijuelu/Techdegree-Project-1
/guessing_game.py
4,306
4.1875
4
import random import time def start_game(best_score = 6): print(""" //////////////////////////////////////////// /////// WELCOME TO THE GUESSING GAME /////// //////////////////////////////////////////// /////////////// INSTRUCTIONS: ////////////// // Guess a random number between 1 to 99 /// // Lesser the attempts the better you are // //////////////////////////////////////////// """) print("Best score so far: {} Attempt(s)".format(best_score)) time.sleep(2) #capture the attention of player to read the game instructions & best score. while True: commence_game = input("Press 'ENTER' to start the game ") try: #ensure that player only key 'enter' to commence the game if commence_game != '': raise ValueError #print statement not require, as input instruction is repetitive break except ValueError: continue time.sleep(1) #provide a brief waiting time for player before the next set of instructions print("LET THE GAME BEGINS!") #https://docs.python.org/2/library/random.html random_number = random.randrange(1,100) attempts = 0 #number of tries starts from 0 while True: try: #exception raise to prevent player from entering a string answer = input("Please enter a numerical value between 0 to 99: ") answer = int(answer) if answer == str: raise ValueError except ValueError: print("Invalid entry, Please try again..") continue try: #exception raise to prevent player from entering a number smaller than 0 or bigger than 99 if answer <= 0 or answer >= 100: raise ValueError except ValueError: print("Invalid entry, Please try again..") continue attempts += 1 #attempts of += 1 placed below both the exceptions, as exception should not be counted as an attempt too_low = answer < random_number too_high = answer > random_number if answer == random_number: time.sleep(1.5) print("CONGRATULATIONS!! {} is the CORRECT Guess!!".format(answer)) print("Your total attempts: {}".format(attempts)) if attempts < best_score: #IF loop applied to update lastest best_score best_score = attempts print(""" ***************************************** *** WOW!! YOU HAVE SET A NEW RECORD!! *** ***************************************** """) #googled tips on https://stackoverflow.com/questions/35873400/python-guessing-game explained by Developer: eskaev else: best_score = min(attempts, best_score) question = input("Press 'Y' if you like to play again. If not press ANY key to end the game: ") if question.upper() == "Y": print(""" ////////////////////////////// //// ...GAME RESETTING... //// ////////////////////////////// """) time.sleep(3) #create a pause effect to signify a start of a new game session start_game(best_score) else: time.sleep(2) #create an effect to suggest closure, set at 2 sec for pause effect (signifying to player that system is discontinuing the game) print(""" ///////////////////// //// !GAME OVER! //// ///////////////////// """) break #end the nested IF loop break #end the WHILE loop elif too_low: time.sleep(1.5)#creates the effect of anticipation print("It's higher") continue elif too_high: time.sleep(1.5) #creates the effect of anticipation print("It's lower") continue if __name__ == '__main__': # Kick off the program by calling the start_game function. start_game()
e9358873f6a3708bae3826f2e6db54341055d286
Shivanibhadange/PythonTraining
/Python/dictionary.py
1,017
3.703125
4
empdata={'empno':101, 'name':'Ravi', 'salary':50000} print(empdata) print(empdata['name']) #Ravi empdata['salary']=130000 print(empdata) del empdata['name'] print(empdata) empdata={'empno':101, 'name':'Ravi', 'salary':50000, 'name':'Anuj'} print(empdata)#if there is duplicate key then new key will be added empdata={'empno':[101,102,103], 'name':['Ravi','anuj','Raj'], 'salary':[90000,120000,32000]} print(empdata) print(empdata['salary']) s={'empno':101,'name':'ravi','salary':78000,'city':'pune'} print(s.keys()) print(s.values()) #none print(s.get('grade')) #N/A in place of none print(s.get('grade','N/A')) a={'grade':'a','leaves':40} #after s ..a will appended s.update(a) print(s) a=s.copy() print(a) a=['name','city','age'] #keys from a value -None d=dict.fromkeys(a) print(d) #keys from a value-10 r=dict.fromkeys(a,10) print(r) d={'empno':101,'name':'abr'} #clear d.clear() print(d)
c756757c4f1b5503ecdaed2b736ddf33d5f2a42b
ChuixinZeng/PythonStudyCode
/PythonCode-OldBoy/Day4/随堂练习/16_pickle序列化2.py
313
3.671875
4
# -*- coding:utf-8 -*- # Author:Chuixin Zeng import pickle def sayhi(name): print("hello,",name) info = { 'name':'alex', 'age':'22', 'func': sayhi } f = open('text.text','wb') # 下面的是另外一种用法,跟f.write(pickle.dumps(info))的意思是完全一样的 pickle.dump(info,f) f.close()
cceb7de39b69d5b0f76d3fefad2070588f6dad9e
utepe/CAA-Library
/TkDriver.py
1,360
3.5
4
import tkinter as tk from tkinter import ttk from FunctionAnalysis import polyAnalysis from linearRegression import linearRegress from linearAlgAnalysis import linAlgAnalysis def getChoice(): print("\nCAA Library Main Menu") print("------------------------") print("[0] Terminate Program") print("[1] Input a Polynomial and Analyze it") print("[2] Find the equation for a Line of Best Fit") print("[3] Solve Matricies and Linear Algebra Related Problems") #WIP return int(input("\nEnter what you would like to do: ")) def programSelector(): selector = { 1 : polyAnalysis().runPolyAnalysis, 2 : linearRegress().runLineFit, 3 : linAlgAnalysis().runLinAlgAnalysis, } selector[choice.get()]() root = tk.Tk() choice = tk.IntVar() choiceLabel = ttk.Label(root, text = "Choice: ").pack(side = 'left') choiceEntry = ttk.Entry(root, width = 15, textvariable = choice).pack(side = 'left') # choiceEntry.focus() choiceButton = ttk.Button(root, text = "Choose", command = programSelector).pack(side = 'left') root.mainloop() ''' def main(): while True: key = getChoice() if key == 0: break else: programSelector(key) if __name__ == '__main__': main() '''
54ff7c83ba31f081cfd08e74cc80edec2cc1b912
priyanshusonii/college-assignment
/2..#Write a Python program to remove duplicates from a list of lists.py
391
3.890625
4
import itertools number = [[110, 120], [240], [330, 456, 425], [310, 220], [133], [240]] print("Original List", number) number.sort() new_number = list(number for number,_ in itertools.groupby(number)) print("New List", new_number) #output: # #Original List [[110, 120], [240], [330, 456, 425], [310, 220], [133], [240]] #New List [[110, 120], [133], [240], [310, 220], [330, 456, 425]] #
9d594fe7c50d0a5b834e9b0267d4327d6eeccac5
wl-cp/example
/py实验1/exmple_3.py
150
3.71875
4
import math a = int(input("请输入直角边a:")) b = int(input("请输入直角边b:")) c = math.sqrt((a**2) + (b**2)) print("斜边c:",c)
904f679ed565e8589612418dc944b5f417fdf3fb
jingzhij/Leetcode
/406 根据身高重建队列.py
453
3.71875
4
### 解题思路 对身高逆序,对键值正序,先排序, 然后插入 为什么这么做?因为比它大的数字只存在与前面,按照键值进行插入一定没错 ### 代码 ```python3 class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key = lambda x:(-x[0],x[1])) output=[] for a in people: output.insert(a[1],a) return output ```
ee93479353b275cb572faadb35dd70818b212ad3
rameshmuruga/guvi_codekata
/ram.py
107
3.890625
4
x=raw_input("") if('a'<x): print("alphabet") elif('A'<x): print("alphabet") else: print("not alphabet")
152ae2bea576ce4e1c00ea3ee2490a7a4c4ac43e
ricklen/PythonTest
/12 Object Oriented Python/demo.py
410
3.671875
4
a_string = "this is \na string split \t\tand tabbed" print(a_string) raw_string = r"this is \na string split \t\tand tabbed" print(raw_string) b_string = "this is" + chr(10) + "a string split" + chr(9) + chr(9) + "and tabbed" print(b_string) backslash_string = "this is a backslash \\followed by some text" print(backslash_string) error_string = r"This string ends with \\" print(error_string)
e69f48626283e08fd44d4af0071c244a6458f7f6
Kings-Ggs-Arthers/CP3-Gun-siri
/assignments/Lecture50_Gun_S.py
252
3.90625
4
def addNum(x,y): print(x + y) def subNum(x,y): print(x - y) def multiNum (x,y): print(x * y) def divideNum (x,y): print(x / y) x = int(input("x :")) y = int(input("y :")) addNum(x,y) subNum(x,y) multiNum(x,y) divideNum(x,y)
a0a527c9713c8772020b322fa4cd4fcca5b0619d
omgitsomg/PythonPractice
/Day21Practice.py
1,473
4.125
4
# Today is day 21 of Python Practice. # Today, I will focus on learning about exception handling # in Python. # This will be part 1. # Python doesn't have a try catch like Java does, but it does have something # similar called try except. import sys def divideBy0(num): return (num / 0) try: divideBy0(10) except ZeroDivisionError: print("ERROR! ") print("You cannot divide by 0!") boolCorrectInput = True while boolCorrectInput: try: print("Please enter a number:") x = int(input()) except ValueError: print("Your input is not a number!") boolCorrectInput = False # input() function simply grabs the input of the user. # int() function simply converts the argument passed in into an int # You can have more than one except clause for a try statement # For example, class B(Exception): pass class C(B): pass class D(C): pass for BCD in [B, C, D]: try: raise BCD except D: print("D") except C: print("C") except B: print("B") # The last except can be used to used to catch all exception # if the previous exception couldn't catch it try: print("Enter a number:") y = int(input()) except ZeroDivisionError as zeroErr: print("{zeroErr} has occured! You cannot divide by 0!}".format(zeroErr)) except OSError as osErr: print("{osErr} has occurred!".format(osErr)) except: print("A random error has occurred!", sys.exc_info()[0])
dfacc93b7c8a7a4338d07b956c6cdc5c80a5595c
Navan05/Designing-a-user-specified-electrical-circuit-using-python
/PSP.py
2,497
3.6875
4
nr=int(input('Enter number of resistors in the first loop')) nr1=int(input('Enter number of resistors in the second loop')) l=180 import turtle t=turtle t.color('red') for i in range(0,nr): t.forward(100) t.left(45) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(10) t.right(90) t.forward(10) t.left(45) t.forward(25) t.penup() t.right(90) t.forward(25) t.right(90) t.forward(l) t.right(180) t.pendown() l=l+1 t.left(90) t.penup() t.forward(25) t.pendown() for i in range(1,nr): t.forward(25) t.right(90) t.penup() t.forward(180) t.right(90) t.pendown() for i in range(1,nr): t.forward(25) t.right(180) t.forward((25*int(nr-1))/2) t.right(90) t.forward(30) t.penup() t.left(90) t.forward((25*int(nr1-1))/2) t.right(90) t.pendown() k=0 for i in range(0,nr1): t.forward(100) t.left(45) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(10) t.right(90) t.forward(10) t.left(45) t.forward(25) t.penup() t.right(90) t.forward(25) t.right(90) t.forward(180) t.right(180) t.pendown() t.left(90) t.penup() t.forward(25) for i in range(1,nr1): t.pendown() t.forward(25) t.penup() t.right(90) t.forward(180) t.right(90) for i in range(0,nr1): t.pendown() t.forward(25) t.right(90) t.forward(180) t.right(90) t.forward(10) t.right(180) t.forward(20) t.right(180) t.forward(10) t.left(90) t.penup() t.forward(5) t.pendown() t.right(90) t.forward(20) t.right(180) t.forward(40) t.right(180) t.forward(20) t.left(90) t.forward(210) t.right(90) for i in range(0,nr): t.forward(25) #z=int(input('Enter the number of branches of parallel circuits')) #for p in range(1,z+1): k=0 for j in range(1,nr+1): r1=int(input('Enter the value of the resistance')) k=k+1/r1 print('The value of resistance in 1st branch of parallel connection is',1/k) n=0 for k in range(1,nr1+1): r2=int(input('Enter the value of resistance')) n=n+1/r2 print('The value of resistance in the 2nd branch of parallel connection is',1/n) print('The equivalent resistance of the circuit is',n+k)