blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
45a2201a6a7220306492cf1baaf47d68f4595d13 | nicholasrokosz/python-crash-course | /Ch. 4/animals.py | 145 | 3.765625 | 4 | animals = ['parrot', 'raven', 'bald eagle']
for animal in animals:
print(f"A {animal} is a pretty cool bird.")
print("And all of them can fly!") |
da5a646c0a2caecadb60485bf3d02d8c0661960b | nicholasrokosz/python-crash-course | /Ch. 8/user_albums.py | 572 | 4.25 | 4 | def make_album(artist, album, no_of_songs=None):
album_info = {'artist': artist, 'album': album}
if no_of_songs:
album_info['no_of_songs'] = no_of_songs
return album_info
while True:
artist_name = input("Enter the artist's name: ")
album_title = input("Enter the album title: ")
no_of_songs = input("Enter the number of songs (optional): ")
album_info = make_album(artist_name, album_title, no_of_songs)
print(album_info)
repeat = input("\nWould you like to enter another album? Enter Y or N: ")
if repeat == 'Y' or repeat == 'y':
continue
else:
break |
d684985ffbb5d2889c1a4449c497b4255f33fba2 | nicholasrokosz/python-crash-course | /Ch. 3/changing_guest_list.py | 825 | 3.90625 | 4 | guests = ['Bertrand Russell', 'Elon Musk', 'Claude Shannon']
print(f"Dear Mr. {guests[0]}, are you available to attend a dinner at my home this weekend?")
print(f"Dear Mr. {guests[1]}, are you available to attend a dinner at my home this weekend?")
print(f"Dear Mr. {guests[2]}, are you available to attend a dinner at my home this weekend?")
popped_guest = guests.pop(1)
new_guests = guests.append('Lex Fridman')
print(f"Unfortunately, it seems that Mr. {popped_guest} will not be able to attend. We are happy to announce that Mr. {guests[-1]} will be attending.")
print(f"Dear Mr. {guests[0]}, are you available to attend a dinner at my home this weekend?")
print(f"Dear Mr. {guests[1]}, are you available to attend a dinner at my home this weekend?")
print(f"Dear Mr. {guests[2]}, are you available to attend a dinner at my home this weekend?") |
72e6fb8ef93a3874f3fedd4814e264f37a36ff14 | nicholasrokosz/python-crash-course | /Ch. 3/seeing_the_world.py | 381 | 3.75 | 4 | destinations = ['Oslo', 'Edinburgh', 'Copenhagen', 'London', 'Stockholm']
print(destinations)
print(sorted(destinations))
print(destinations)
print(sorted(destinations, reverse=True))
print(destinations)
destinations.reverse()
print(destinations)
destinations.reverse()
print(destinations)
destinations.sort()
print(destinations)
destinations.sort(reverse=True)
print(destinations) |
6b492cfcbb3103babf24f542e10168773ef5a2a1 | nicholasrokosz/python-crash-course | /Ch. 2/personal_message.py | 164 | 3.625 | 4 | # Nick Rokosz 06/17/20
# simple program using variables and an f-string
name = "Nick"
message = f"Hello {name},would you like to learn some python today?"
print(message) |
883496ed245b3f4248700a9253e60324a4fdffb3 | nicholasrokosz/python-crash-course | /Ch. 10/cats_and_dogs.py | 218 | 3.5625 | 4 | def read_file(filename):
try:
with open(filename) as f:
content = f.read()
print(content.strip())
except FileNotFoundError:
print(f"We couldn't find {filename}")
read_file('cats.txt')
read_file('dogs.txt') |
120d2294baa8ccfd2155952cf695ee74cd8fade6 | EmreBio/StructureFold | /header/write_file.py | 1,519 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def write_t_file(out_file, a):
with open(out_file, 'w') as h:
if type(a) is list:
for i in range(len(a)):
if type(a[i]) is list:
if len(a[i])>1:
for j in range(len(a[i])-1):
h.write(str(a[i][j])+"\t")
j = j+1
h.write(str(a[i][j])+"\n")
else:
if len(a[i]) == 1:
h.write(str(a[i][0])+"\n")
else:
h.write("\n")
else:
h.write(str(a[i])+"\n")
else:
h.write(str(a)+"\n")
def write_c_file(out_file, a):
with open(out_file, 'w') as h:
if type(a) is list:
for i in range(len(a)):
if type(a[i]) is list:
if len(a[i])>1:
for j in range(len(a[i])-1):
h.write(str(a[i][j])+",")
j = j+1
h.write(str(a[i][j])+"\n")
else:
if len(a[i]) == 1:
h.write(str(a[i][0])+"\n")
else:
h.write("\n")
else:
h.write(str(a[i])+"\n")
else:
h.write(str(a)+"\n")
|
dd2a8c8533a753c3a60df4c438728208300a7ca2 | YashYadav-github/project59 | /Exercise3.py | 608 | 3.953125 | 4 | x = 74
num_of_guesses = 1
print("Welcome to guess the number")
print("Number of guesses is limited to only 6 times: ")
while (num_of_guesses <= 6):
guess_number = int(input("Guess the number :\n"))
if guess_number < 74:
print("Please Increase the number")
elif guess_number > 74:
print("Please Decrease the number")
else:
print("You win🎉 🎉 ")
print(num_of_guesses, "guesses you took to finish.")
break
print(6 - num_of_guesses,"guesses left")
num_of_guesses = num_of_guesses + 1
if(num_of_guesses > 9):
print("Game Over:( Try again") |
fa96e104a2fede922275517586cbc44e026ba202 | sirenkov/ising | /ising.py | 2,668 | 3.96875 | 4 | #!/usr/bin/env python
import numpy as np
import math as m
import random
import matplotlib.pyplot as plt
import ising_functions as isf
#FOR 2-D SQUARE LATTICE
#code implementing Metropolis algorithm
#user inputs size (n) and temperature (T)
#code outputs T, M, E, X, C, S at equilibrium
#we have to run export PYTHONPATH="${PYTHONPATH}:/home/vlad/Documents/Python/modules"
#on terminal before we can use ising_functions as intended
#FOR TRIANGLURAR LATTICE, REPLACE isf.energy(matrix, h, J) with isf.hex_energy(matrix, h, J)
#FOR NON-PERIODIC BC, REPLACE isf.energy(matrix, h, J) with isf.np_energy(matrix, h, J)
#FOR NON-RANDOM INITIAL CONFIGURATION, REPLACE isf.lattice(n) with isf.c_lattice(n,1) or chequer_lattice(n) or half_lattice(n)
#print "input n (size) and T (temperature), space separated"
n, T=raw_input().split()
n=float(n)
T=float(T)
h, J, k =1.0,-1.0,1.0
matrix=isf.lattice(n) #initializes 2d lattice
mc_steps=n**3 #code will run throught the entire lattice 'mc_steps' times
s=0
while s<(mc_steps):
i=0
while i<n:
j=0
while j<n:
#now implement metropolis algorithm
matrix_new=np.copy(matrix)
matrix_new[i,j]=-matrix[i,j]
E_new=isf.energy(matrix_new,h,J)
E_old=isf.energy(matrix,h,J)
dE=E_new-E_old
if dE<0:
matrix=matrix_new
if dE>0:
p_flip=m.exp((-1.0/(T*k))*dE)
rand_num=random.random() #random numbers for flip probability
if rand_num<=p_flip:
matrix=matrix_new
j=j+1
i=i+1
s=s+1
#now we are 'close enough' to equilibrium and we can start taking measurements
s=0
sum_mag=0
sum_mag_sq=0
sum_E=0
sum_E_sq=0
S_sum=0
collect=mc_steps*2
while s<(collect):
i=0
while i<n:
j=0
while j<n:
matrix_new=np.copy(matrix)
matrix_new[i,j]=-matrix[i,j]
E_new=isf.energy(matrix_new,h,J)
E_old=isf.energy(matrix,h,J)
dE=E_new-E_old
if dE<0:
matrix=matrix_new
if dE>0:
p_flip=m.exp((-1.0/(T*k))*dE)
rand_num=random.random()
if rand_num<=p_flip:
matrix=matrix_new
j=j+1
i=i+1
#collect values of M, S, etc. for averaging
M=isf.total_mag(matrix)
mag_eq=float(M)/(n*n)
S=m.log(isf.choose(int(n*n), int(n*n+M)//2))
S_sum=S_sum+S
E_eq=isf.energy(matrix,h,J)/(n*n)
sum_mag=sum_mag+mag_eq
sum_mag_sq=sum_mag_sq+mag_eq*mag_eq
sum_E=sum_E+E_eq
sum_E_sq=sum_E_sq+E_eq*E_eq
s=s+1
#now take averages
av_mag=sum_mag/(collect)
av_mag_sq=sum_mag_sq/(collect)
av_E=sum_E/(collect)
av_E_sq=sum_E_sq/(collect)
av_S=S_sum/(collect)
S_max=m.log(isf.choose(int(n*n), int(n*n//2)))
xi=(av_mag_sq-av_mag*av_mag)/(T)
C_v=(av_E_sq-av_E*av_E)/(T*T)
print T, " ", av_mag, " ", av_E , " ", xi, " ", C_v, " ", av_S/S_max
|
d9b5e57a5ae65532d0837b82c0bf624e189a4cc5 | mumarkhan999/UdacityPythonCoursePracticeFiles | /24_class_object.py | 830 | 3.875 | 4 | #self is like this pointer in C ,C# , java
#it is the object itself whose for the method is
#called
class student:
#constructor
#automatically call whenever we create an object of
#the class
#used to initialize the object
#parametraised constructor
def __init__(self,name,roll,age):
self.name = name
self.roll = roll
self.age = age
self.attendance = 0
self.marks = []
def print_details(self):
print("Name:{}\nRoll:{}\nAge:{}\nAttendance:{}\nMarks:{}"
.format(self.name,self.roll,self.age,self.attendance,self.marks))
def add_marks(self , mark):
self.marks.append(mark)
def add_attendance(self):
self.attendance += 1
def get_avg(self):
return sum(self.marks) / len(self.marks)
|
e2a6910a80bbaf913eb4bb912a263214caa8267b | mumarkhan999/UdacityPythonCoursePracticeFiles | /19_file_rename_remove.py | 279 | 3.8125 | 4 | #before running this code make "b.txt" file and "a.txt" file
#in files folder as it will be deleted in this code
#renaming or removing a file
#os.rename ( oldName , newName)
#os.remove( fileName )
import os
os.rename("files/a.txt" , "files/aaa.txt")
os.remove("files/b.txt")
|
8acf2d209472782794a6c01a189b356056cca591 | mumarkhan999/UdacityPythonCoursePracticeFiles | /30_changing_size_position_of_window.py | 506 | 3.65625 | 4 | from tkinter import *
my_gui = Tk()
my_gui.title("Hello")
#500x500 is the height and width
#+100+100 are the coordinates where the
#window should be loacted
#you can just give height and width like
#my_gui.geometry("500x500")
my_gui.geometry("500x500+300+100")
#the following method is to sustain the
#created window when the .exe file is run
#otherwise it will be closed simultaneously as
#it created
#this is just like we did earlier by this line
#input("Press any key to quit...")
my_gui.mainloop()
|
96645d773bd8d26aa377f4d060f7e3fb4e7d28ed | mumarkhan999/UdacityPythonCoursePracticeFiles | /6_factorial.py | 293 | 4.09375 | 4 | #calculating factorial of a number using while loop
num = int(input("Enter any number:\n"))
if(num < 0):
print("It's a negative number.")
else:
fact = 1
while(num > 0):
fact = fact * num
num = num - 1
print("Answer:\t",fact)
input("Press any key to quit...")
|
af5ab9aad7b047b9e9d061e22ab7afe7e64a4b01 | mumarkhan999/UdacityPythonCoursePracticeFiles | /9_exponestial.py | 347 | 4.5 | 4 | #claculating power of a number
#this can be done easily by using ** operator
#for example 2 ** 3 = 8
print("Assuming that both number and power will be +ve\n")
num = int(input("Enter a number:\n"))
power = int(input("Enter power:\n"))
result = num
for i in range(1,power):
result = result * num
print(result)
input("Press any key to quit...")
|
a6fc7a95a15f7c98ff59850c70a05fdb028a784f | mumarkhan999/UdacityPythonCoursePracticeFiles | /8_multi_mulTable.py | 208 | 4.25 | 4 | #printing multiple multiplication table
num = int(input("Enter a number:\n"))
for i in range (1, (num+1)):
print("Multiplication Table of",i)
for j in range(1,11):
print(i,"x",j,"=",i*j)
|
c5ca14c217ef69d939e703af6b6874ae5ad83a48 | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week3/assignment/problem_1.py | 962 | 3.9375 | 4 | """
Task: The goal in this problem is to find the minimum number of coins needed to change
the input value (integer) into coins with denominations of 1, 5, 10.
Input format: single integer m. (1<=m<=10^3)
Output: minimum number of coins with denominations 1, 5, 10 that changes m.
"""
def greedy_strategy(m, print_dist=False):
denominations = [10, 5, 1] # assumption is denomination is sorted.
total_coins = 0
change_left = m
coin_distribution = []
while change_left > 0:
coin_value = denominations.pop(0)
no_of_coins = int(change_left/coin_value)
coin_distribution.append((coin_value, no_of_coins))
total_coins += no_of_coins
change_left -= coin_value * no_of_coins
return (total_coins, coin_distribution) if print_dist else total_coins
m = int(input())
print(greedy_strategy(m, print_dist=True))
#print(greedy_strategy(1000))
assert 100 == greedy_strategy(1000)
assert 1 == greedy_strategy(1) |
b7cd7e0d5126c9232909b35170173b1dec9fa535 | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week3/assignment/problem_3.py | 1,225 | 3.765625 | 4 | # python3
"""
Maximizing Revenue in Online ad placement.
You have n ads to place on a popular internet page. For each
ad, you know how much is the advertiser willing to pay for one
click on this ad. You have set up n slots on your page and
estimated the expected number of clicks per day for each slot.
Now your goal is to distribute the ads among the slots to maximize
the total revenue.
Task: Given two sequences a1, a2, ... an (ai is the profit per click of the ith
ad) and b1, b2.. bn (bi is the average number of clicks per day of the i-th slot),
we need to partition them into n pair (ai, bi) such that the sum of their products
is maximized.
Input format: 1<= n <= 10^3, -10^5<= ai, bi <= 10^5
Output the maximum value of Sum(ai, ci) where c1, c2/.. cn is a permuation of b1, b2..bn.
"""
placements = int(input())
profits = map(int, input().split())
clicks = map(int, input().split())
def greedy_strategy(placements, profits, clicks):
profits = sorted(profits, reverse=True)
clicks = sorted(clicks, reverse=True)
total_revenue = 0
for _ in range(placements):
total_revenue += profits.pop(0) * clicks.pop(0)
return total_revenue
print(greedy_strategy(placements, profits, clicks)) |
162b0739cda0d6fba65049b474bc72fecf547f3d | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week4/assignment/problem_4.py | 2,492 | 4.21875 | 4 | # Uses python3
"""How close a data is to being sorted
An inversion of sequence a0, a1, .. an-1 is a pair of indices 0<= i < j< n
such that ai < aj. The number of inversion of a sequence in some sense measures
how close the sequence is to being sorted. For example, a sorted (in non-decreasing
order) sequence contains no inversions at all, while in a sequence sorted in descending
order any two elements constitute an inversion (for a total of n(n - 1)/ 2 inversions)
Task: the goal is to count the number of inversions of a given sequence.
Input format: First line contains an integer n, the next one contains a sequence of
integers a0, a1.. an-1
Constraints:
1<= n < 10^5, 1 <= ai <= 10^9 for all 0 <= i < n
Output:
The number of inversions of the sequence.
"""
inversion_count = [0]
def merge(a, b):
d = list()
index_a, index_b = 0, 0
len_a = len(a)
while index_a < len(a) and index_b < len(b):
el_a = a[index_a]
el_b = b[index_b]
if el_a <= el_b:
d.append(el_a)
index_a += 1
else:
d.append(el_b)
index_b += 1
inversion_count[0] += (len_a - index_a)
d.extend(a[index_a:])
d.extend(b[index_b:])
return d
def merge_sort(n):
if len(n) == 1:
return n
mid = int(len(n) / 2)
left_half = merge_sort(n[:mid])
right_half = merge_sort(n[mid:])
return merge(left_half, right_half)
#
# def counting_inversions_naive(input_list):
# count = 0
# for i in range(len(input_list)):
# for j in range(i+1, len(input_list)):
# if input_list[i] > input_list[j]:
# count += 1
# return count
#
# import random
# def stress_testing():
# while True:
# n = random.randint(1, 3)
# input_list = [random.randint(1, 100) for _ in range(n)]
# count_naive = counting_inversions_naive(input_list)
# inversion_count[0] = 0
# merge_sort(input_list)
# count_eff = inversion_count[0]
# if count_naive != count_eff:
# print('Failed')
# print(n)
# print(input_list)
# print('count naive; ', count_naive)
# print('optimized: ', count_eff)
# break
#
#
#
# stress_testing()
#
n = input()
input_list = list(map(int, input().split()))
# # inversions = []
# # n = 6
# # input_list = [9, 8, 7, 3, 2, 1]
merge_sort(input_list)
print(inversion_count[0])
# print(counting_inversions_naive(input_list)) |
8513907fa4d6fc28ef69ea6e63e9d6c80fad2dbc | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week3/assignment/problem_6.py | 2,306 | 3.5 | 4 | # python3
from functools import cmp_to_key
import random
# n = int(input())
# numbers = list(map(int, input().split()))
def compare_two_numbers(x, y):
if x == y:
# I don't check two same numbers till the very end.
return x - y
str_x = str(x)
str_y = str(y)
if str_x[0] != str_y[0]:
return int(str_x[0]) - int(str_y[0])
same = True
max_x = len(str_x) - 1
index_x = min(1, max_x)
max_y = len(str_y) - 1
index_y = min(1, max_y)
while same:
if str_x[index_x] != str_y[index_y]:
return int(str_x[index_x]) - int(str_y[index_y])
index_x = min(index_x + 1, max_x)
index_y = min(index_y + 1, max_y)
def compare_two_numbers_improved(x, y):
if x == y:
return x - y
str_x = str(x)
str_y = str(y)
str_xy = str_x + str_y
str_yx = str_y + str_x
return int(str_xy) - int(str_yx)
# Note: This algorithm is incorrect if relied on compare_two_numbers function.
def greedy_strategy(numbers):
numbers_left = len(numbers)
salary = ''
# numbers_sorted = sorted(numbers.copy())
numbers_sorted = sorted(numbers.copy(), key=cmp_to_key(compare_two_numbers), reverse=True)
while numbers_left:
salary += str(numbers_sorted.pop(0))
numbers_left -= 1
return salary
def greedy_strategy_improved(numbers):
numbers_left = len(numbers)
salary = ''
# numbers_sorted = sorted(numbers.copy())
numbers_sorted = sorted(numbers.copy(), key=cmp_to_key(compare_two_numbers_improved), reverse=True)
while numbers_left:
salary += str(numbers_sorted.pop(0))
numbers_left -= 1
return salary
def stress_testing():
tests_pass = True
while tests_pass:
n = random.randint(1, 5)
numbers = [random.randint(1, 1000) for _ in range(n)]
print ('Input: ', numbers)
if greedy_strategy(numbers) != greedy_strategy_improved(numbers):
print('Test failed for: ', numbers)
tests_pass = False
else:
print('Tests Pass: ', numbers)
# stress_testing()
numbers = [804, 939, 39, 396]
# Failing examples:
# [32, 323, 621]
# [32, 323]
# 804, 939, 39, 396
print(greedy_strategy(numbers))
print(greedy_strategy_improved(numbers))
# print(greedy_strategy_improved(numbers)) |
962786e444b2c6b67be7f319dd294e9b700d59a3 | waigani/simplepy | /count.py | 214 | 3.546875 | 4 | # Python 3
def main():
count = 1
# Code block 1
while count < 11:
print(count)
count = count + 1
# Code block 2
if count == 11:
print('Counting complete.')
if __name__ == "__main__": main()
|
96f76b3b40a51e3ac9f01cf8d7669f6dc14b8d55 | project-alchemist/ACIPython | /alchemist/Parameter.py | 2,596 | 3.703125 | 4 | class Parameter:
name = []
datatype = []
value = []
datatypes = {"BYTE": 33,
"SHORT": 34,
"INT": 35,
"LONG": 36,
"FLOAT": 15,
"DOUBLE": 16,
"CHAR": 1,
"STRING": 46,
"WORKER_ID": 51,
"WORKER_INFO": 52,
"MATRIX_ID": 53,
"MATRIX_INFO": 54}
def __init__(self, name, datatype, value=[]):
self.name = name
self.datatype = datatype
self.value = value
def set_name(self, name):
self.name = name
def set_datatype(self, datatype):
self.datatype = datatype
def set_value(self, value):
self.value = value
def get_name(self):
return self.name
def get_datatype(self):
return self.datatype
def get_value(self):
return self.value
def to_string(self, space=" "):
if self.datatype == self.datatypes["BYTE"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("BYTE", self.name, space, " ", int(self.value))
elif self.datatype == self.datatypes["CHAR"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("CHAR", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["SHORT"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("SHORT", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["INT"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("INT", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["LONG"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("LONG", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["FLOAT"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("FLOAT", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["DOUBLE"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("DOUBLE", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["STRING"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("STRING", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["MATRIX_ID"]:
return "{0:17s} {1}\n{2} {3:18s} {4}".format("MATRIX ID", self.name, space, " ", self.value)
elif self.datatype == self.datatypes["MATRIX_INFO"]:
return "{0:17s} {1}\n{2:27s} {3}".format("MATRIX INFO", self.name, " ", self.value.to_string(display_layout=True, space=space+"{0:18s}".format(" ")))
|
7526485b8bf02efe669c97fc521151785679c682 | talhaahmed884/AI-Chess | /chess_rafay/minimax_test.py | 8,104 | 3.75 | 4 | '''
This is UNIVERSITY KA CODE
YOU CAN SKIP THIS BAISHAK CLOSE THIS SECTION CUZ IDK KHAIR COULD BE USED FOR HELP
'''
'''
import copy
import math
import random
import sys
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
count = 0
for i in board:
for j in i:
if j:
count += 1
if count % 2 != 0:
return O
return X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
res = set()
board_len = len(board)
for i in range(board_len):
for j in range(board_len):
if board[i][j] == EMPTY:
res.add((i, j))
return res
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
curr_player = player(board)
result_board = copy.deepcopy(board)
(i, j) = action
result_board[i][j] = curr_player
return result_board
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
winner_val = winner(board)
if winner_val == X:
return 1
elif winner_val == O:
return -1
return 0
def minimax(board):
if board == initial_state():
res = set()
row = random.randint(0, 2)
col = random.randint(0, 2)
res.add((row, col))
return res
elif player(board) == 'X':
v = -sys.maxsize
reqAction = None
for action in actions(board):
min = min_value(result(board, action))
if min > v:
v = min
reqAction = action
return reqAction
else:
v = sys.maxsize
reqAction = None
for action in actions(board):
max = max_value(result(board, action))
if max < v:
v = max
reqAction = action
return reqAction
def max_value(board):
if terminal(board):
return utility(board)
v = -sys.maxsize
for action in actions(board):
v = max(v, min_value(result(board, action)))
return v
def min_value(board):
if terminal(board):
return utility(board)
v = sys.maxsize
for action in actions(board):
v = min(v, max_value(result(board, action)))
return v
if __name__ == "__main__":
user = None
board = initial_state()
ai_turn = False
print("Choose a player")
user = input()
while True:
game_over = terminal(board)
playr = player(board)
if game_over:
winner = winner(board)
if winner is None:
print("Game Over: Tie.")
else:
print(f"Game Over: {winner} wins.")
break;
else:
if user != playr and not game_over:
if ai_turn:
move = minimax(board)
board = result(board, move)
ai_turn = False
print(board)
elif user == playr and not game_over:
ai_turn = True
print("Enter the position to move (row,col)")
i = int(input("Row:"))
j = int(input("Col:"))
if board[i][j] == EMPTY:
board = result(board, (i, j))
print(board)
'''
'''
THIS IS THE VIDEOS CODE THAT I SENT YOU 11 MINS WALLI
'''
'''
def minimax(position, depth, maximizingPLayer):
if depth == or gameOver in position:
return ScoreBoard(gs)
if maximizingPLayer:
maxEval = -infinity
for child in position:
eval = minimax(child, depth - 1, False)
maxEval = max(maxEval, eval)
return maxEval
else:
minEval = +infinity
for child in position:
eval = minimax(child, depth - 1, True)
minEval = min(minEval, eval)
return minEval
'''
'''
THIS IS THE ALGO I THOUGHT OF BUT I DONT THIS THIS IS CORRECT COMPARE KARLO WITH ABOVE ALGOS,
PROBLEM IS THERE ARE 2 LOOPS HERE AND I DONT GET WHY THE OTHER ALGOS ARENT USING THESE 2 LOOPS
'''
# def minimax(gs, depth, isWhiteTurn):
# if depth == 0 or if checkMate is true:
# return the evaluation of the board
#
# score = -infinity
# if its isWhiteTurn:
# for all the pieces of white in the current game state:
# for moves in all the moves that this piece can play:
# play move
# score = minimax(gs, depth - 1, False)
# if the score > max:
# max == score
# if depth == the depth of the branches we specified:
# save this move
#
# else:
# vice versa for black
'''
THIS IS US BANDAY KI VIDEO KA CODE THAT WE ARE FOLLOWING THE ONE WE USED TO MAKE THE BOARD TOO
THIS WORKS FINE BUT A) PLEDGE AND B) IM NOT SURE IF I IMPLEMENTED THIS CORRECTLY OR IF THE ALGO IS WORKING CORRECTLY
'''
def ScoreTheBoard(gs):
score = 0
# if gs.CheckMate:
# if gs.whiteToMove:
# return -sys.maxsize # Black Wins
# else:
# return sys.maxsize
# elif gs.StaleMate:
# return 0
for row in gs.board:
for piece in row:
if piece:
score += scores_dict[piece.identity[1]] if piece.identity[0] == 'w' else -scores_dict[piece.identity[1]]
return score
def findBestMoveMinMax(gs, valid_moves):
global nextMove
nextMove = None
print()
_MinimaxFunc(gs, valid_moves, 2, gs.whiteToMove)
print()
print("================> THE NEXT MOVE OF THE PLAYER IS: ", nextMove)
return nextMove
def _MinimaxFunc(gs, valid_movesList, depth, player_IsWhite):
global nextMove
if depth == 0:
return ScoreTheBoard(gs)
if player_IsWhite:
maxScore = -sys.maxsize - 1
for move in valid_movesList:
gs.makeMove(move)
moveList = gs.getAllPossibleMovesOfASide()
score = _MinimaxFunc(gs, moveList, depth - 1, False)
print("White Back From Recursive Calls Score is: ", score)
if score >= maxScore:
maxScore = score
if depth == DEPTH:
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
print("SETTING THE MOVE OF THE PLAYER TO: ", move.startSQ, " --> ", move.targetSQ)
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
nextMove = move
gs.undoMove()
print("--------------------------------------END OF WHITE LOOP------------------------------------------------")
return maxScore
else:
minScore = sys.maxsize
selected_move = None
for move in valid_movesList:
print("BLACK: Move: ", move.startSQ, " --> ", move.targetSQ, " DEPTH: ", depth)
gs.makeMove(move)
moveList = gs.getAllPossibleMovesOfASide()
copyDepth = depth
score = _MinimaxFunc(gs, moveList, copyDepth - 1, True)
print("Black Back From Recursive Calls Score is: ", score)
if score <= minScore:
minScore = score
if depth == DEPTH:
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
print("SETTING THE MOVE OF THE PLAYER TO: ", move.startSQ, " --> ", move.targetSQ)
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
nextMove = move
gs.undoMove()
print("--------------------------------------END OF BLACK LOOP------------------------------------------------")
return minScore
|
8c41e6813d5e137bf3acbe883b08d269d9cb7d7b | Smellly/weighted_training | /BinaryTree.py | 1,813 | 4.25 | 4 | # simple binary tree
# in this implementation, a node is inserted between an existing node and the root
import sys
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def setNodeValue(self,value):
self.rootid = value
def getNodeValue(self):
return self.rootid
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.right = self.right
self.right = tree
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
self.left = tree
tree.left = self.left
def printTree(tree):
if tree != None:
# sys.stdout.write('<')
tmp = ''
tmp += printTree(tree.getLeftChild())
#print(tree.getNodeValue())
tmp += ' ' + tree.getNodeValue()
tmp += ' ' + printTree(tree.getRightChild())
#sys.stdout.write('>')
return tmp
else:
return ''
def getAllLeaves(tree):
leaves = set()
if tree != None:
if tree.getLeftChild() is None and tree.getRightChild() is None:
leaves.add(tree.getNodeValue())
else:
if tree.getLeftChild() is not None:
leaves = leaves.union(getAllLeaves(tree.getLeftChild()))
if tree.getRightChild() is not None:
leaves = leaves.union(getAllLeaves(tree.getRightChild()))
return leaves
# else:
# return None
|
5f5f35f563656072b345ad7752970759b12de47d | ShuhengWang/530-391-13 | /readwrite.py | 341 | 3.640625 | 4 | def read():
f=open("input",'r')
#read a
line=f.readline()
split=line.split()
print(split)
a=float(split[2])
#read b
line=f.readline()
split=line.split()
print(split)
b=float(split[2])
#read c
line=f.readline()
split=line.split()
print(split)
c=float(split[2])
#clean up
f.close()
#return a, b, c
return(a,b,c)
|
6a4fbb6594b38db7b23c3de89aedbe166bae0ae2 | pastrouveedespeudo/ste-fois-c-la-bonne | /imageimage1.2/outils_main.py | 927 | 3.578125 | 4 | class outils_main:
def pos_liste_traitement(self, liste, liste_main, compteur):
self.liste = liste
self.compteur = compteur
self.liste_main = liste_main
c = 0
for i in range(self.compteur + 1):
for i in self.liste_main:
for j in i :
if self.liste[c][0] == j:
del self.liste[c][1]
c+=1
def ajout_verbe(self, liste, compteur):
self.liste = liste
self.compteur = compteur
c = 0
for i in self.liste:
print(self.liste[c])
break
c += 1
print(c)
print(self.compteur)
if c < self.compteur:
for i in range(self.compteur):
self.liste.append("présent ou future faire la fonction")
|
b7fcd7060e743f687f37a49b33cb7edf0e78b9f2 | pastrouveedespeudo/ste-fois-c-la-bonne | /imageimage/essais.py | 682 | 3.90625 | 4 | liste = [['le', 'Article défini', 'None', 'prénom'],
['chien', 'Nom commun', 'None', 'pas prénom'],
['noir', 'Article défini', 'None', 'pas prénom']]
c = 0
for i in liste:
if liste[c][3] == "prénom" and liste[c][1] == "Article défini"\
or liste[c][1] == "Article indéfini":
print("pas prénom")
elif liste[c][3] == "prénom" and liste[c+1][1] == "Nom commun":
print("pas prénom")
elif liste[c][3] == "prénom" and liste[c+1][2] == "Verbe":
print("prenom")
elif liste[c][3] == "prénom" and liste[c-1][2] == "Préposition":
print("prénom")
c+=1
|
a5f8cf2de38a252d3e9c9510368419e5a763cf74 | TheFibonacciEffect/interviewer-hell | /squares/odds.py | 1,215 | 4.28125 | 4 | """
Determines whether a given integer is a perfect square, without using
sqrt() or multiplication.
This works because the square of a natural number, n, is the sum of
the first n consecutive odd natural numbers. Various itertools
functions are used to generate a lazy iterable of odd numbers and a
running sum of them, until either the given input is found as a sum
or the sum has exceeded n.
"""
from itertools import accumulate, count, takewhile
import sys
import unittest
is_square = lambda n: n > 0 and n in takewhile(lambda x: x <= n, accumulate(filter(lambda n: n & 1, count())))
class SquareTests(unittest.TestCase):
def test_squares(self):
for i in range(1, 101):
if i in (1, 4, 9, 16, 25, 36, 49, 64, 81, 100):
assert is_square(i)
else:
assert not is_square(i)
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(unittest.main())
value = None
try:
value = int(sys.argv[1])
except TypeError:
sys.exit("Please provide a numeric argument.")
if is_square(value):
print("{} is a square.".format(value))
else:
print("{} is not a square.".format(value))
|
5a4252b8e3fb28d08b328634902434343b172875 | itroot/projecteuler | /lib/PythagoreanTriples.py | 460 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
http://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples
"""
pairMN=(2, 1)
def nextLevel(pairMN):
(m, n)=pairMN
return ((2*m-n, m), (2*m+n, m), (m+2*n, n))
def MN2ABC(pairMN):
(m, n)=pairMN
return (m**2-n**2, 2*m*n, m**2+n**2)
def traverse(pairMN, condition):
if (condition(pairMN)):
threePairMN=nextLevel(pairMN)
for pairMN in threePairMN:
traverse(pairMN, condition)
|
ecb7b0ddcbcc020b2ef0ccf52375a5079e141c1f | itroot/projecteuler | /solved/level-1/14/solve.py | 1,655 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Tail:
def __init__(self, number, length):
self.number=number
self.length=length
def __repr__(self):
return self.__str__()
def __str__(self):
return "(%d, %d)" % (self.number, self.length)
class Sequence:
def __init__(self):
self.__cache={
2: Tail(1, 0)
}
def __advance(self, number):
if (0==number%2):
return number/2
else:
return 3*number+1
def cache(self):
return self.__cache
def populateTo(self, upperBound):
for i in range(1, upperBound):
if not i in self.__cache:
self.populate(i)
def populate(self, number):
sequence=[]
while True:
sequence.append(number)
if number in self.__cache:
tail=self.__cache[number]
length=tail.length+len(sequence)
for i in range(0, len(sequence)-1):
length-=1
self.__cache[sequence[i]]=Tail(sequence[i+1], length)
return
else:
number=self.__advance(number)
def build(self, number):
result=[]
if not number in self.__cache:
self.populate(number)
result.append(number)
while 1!=number:
tail=self.__cache[number]
number=tail.number
result.append(number)
return result
sequence=Sequence()
sequence.populateTo(1000000)
cache=sequence.cache()
longestStart=max(cache.iterkeys(), key=lambda k: cache[k].length)
print longestStart
|
0bdb2ec8f43ae4ac159422ad8a6c4743772e26cf | itroot/projecteuler | /lib/SequenceNumber.py | 819 | 3.875 | 4 | # -*- coding: utf-8 -*-
class SequenceNumber:
def __init__(self):
self.__n=0
def advance(self):
self.__n+=1
def n(self):
return self.__n
class TriangleNumber(SequenceNumber):
def generate(self):
n=self.n()
return n*(n+1)/2
class SquareNumber(SequenceNumber):
def generate(self):
n=self.n()
return n**2
class PentagonalNumber(SequenceNumber):
def generate(self):
n=self.n()
return n*(3*n-1)/2
class HexagonalNumber(SequenceNumber):
def generate(self):
n=self.n()
return n*(2*n-1)
class HeptagonalNumber(SequenceNumber):
def generate(self):
n=self.n()
return n*(5*n-3)/2
class OctagonalNumber(SequenceNumber):
def generate(self):
n=self.n()
return n*(3*n-2)
|
4f98a689da42bbf1cfd4eaf975ae171d0044512a | itroot/projecteuler | /solved/level-1/04/solve.py | 391 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def isPalindromic(number):
s=str(number)
if (0!=len(s)%2):
return False
halfLen=len(s)/2
return s[0:halfLen]==s[halfLen:][::-1]
palindromic=[]
for num1 in range(900, 999):
for num2 in range(900, 999):
num=num1*num2
if isPalindromic(num):
palindromic.append(num)
print palindromic[-1]
|
d6621b45b61e1dc72d8e336dde42f02281fff1e8 | itroot/projecteuler | /solved/level-4/78/solve.py | 738 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://en.wikipedia.org/wiki/Partition_(number_theory)#Generating_function
"""
def pentagonal(n):
return n*(3*n-1)/2
cache=[1]
def p(n):
result=0
if n<0:
pass
elif n==0:
result=1
else:
k=0
while True:
value=k/2+1
sign=(-1)**(k)
shift=pentagonal(sign*value)
rshift=n-shift
if rshift<0:
break
else:
result+=(-1)**(k/2)*cache[rshift]
k+=1
return result
for i in range(1, 1000000):
#print i
number=p(i)
delimiter=10**6
cache.append(number)
if number%delimiter==0:
print i
break
|
4e4cc7f028fc3c91d5c3c634767d703e2f78a0f0 | itroot/projecteuler | /solved/level-2/39/solve.py | 799 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# FIXME copy-paste from #09
import math
tripletSum=1000
def is_square(number):
sqrtNumber=int(math.sqrt(number))
return sqrtNumber*sqrtNumber==number
def verifyFirstTwoNumbers(first, second):
sumOfSquares=first**2+second**2
if is_square(sumOfSquares):
return True
perimeters={}
for first in range (1,1000):
for second in range(first, 1000):
if verifyFirstTwoNumbers(first, second):
third=int(math.sqrt(first**2+second**2))
sum=(first+second+third)
if sum>1000:
continue
if sum in perimeters:
perimeters[sum]+=1
else:
perimeters[sum]=1
print max(perimeters.iterkeys(), key=lambda k: perimeters[k])
|
cc7e18c5de2b5850b830c808c13cc68f86f8aceb | itroot/projecteuler | /solved/level-3/62/solve.py | 399 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
upperLimit=10000;
hash2numberList={}
for number in range(0, upperLimit):
hash="".join(sorted(str(number**3)))
if not hash in hash2numberList:
hash2numberList[hash]=[]
numberList=hash2numberList[hash]
numberList.append(number)
if (len(numberList)==5):
print min(numberList)**3
break
#print hash2numberList
|
56a38618d02c94538519c056cca65d409714f1e1 | itroot/projecteuler | /solved/level-4/100/solve.py | 981 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
see: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Pell.27s_equation
"""
"""
Let A be number of blue discs, B - number of all discs
Than, (A/B)*((A-1)*(B-1) == 1/2 -> 2*A**2-2*A == B**2 - B
Than, B**2 - 2*A**2 == B - 2*A
Than, (2*B-1)**2 - 2*(2*A-1)**2 = -1
It's like a Pell's equation, only with -1 sign
"""
upperLimit = 10**12
pellSolutionList = [
(1, 0),
(1, 1),
]
def addNextSolution(pellSolutionList):
lastSolution = pellSolutionList[-1]
prevLastSolution = pellSolutionList[-2]
nextSolution = lambda l, p, i: 2*l[i]+p[i]
newSolution = (nextSolution(lastSolution, prevLastSolution, 0), nextSolution(lastSolution, prevLastSolution, 1))
pellSolutionList.append(newSolution)
while True:
addNextSolution(pellSolutionList)
overallDiskNumber = (pellSolutionList[-1][0]+1)/2
if overallDiskNumber > upperLimit:
print (pellSolutionList[-1][1]+1)/2
break
|
ad6c98d8748b42d2ec0eaffd2e40708888f02e96 | kingyau991319/python_learning-W- | /rename_file.py | 1,325 | 3.5625 | 4 | # this prgoram is for rename the file in windows
# because windows does not support with the bash shell
# -> made on 20-7-2021
import os
import pathlib
def renameFile(dir_path = None, out_path = None):
# to 2get the filelist of the current inputing dir
file_paths = os.listdir(dir_path)
file_lens = len(file_paths)
print("file_len:",file_lens)
# set the output file if None:
if out_path == None:
out_path = str(dir_path) + '/outdir'
print("out_path",out_path)
# dir_path = os.path.join('C:\\Users\\User\\Desktop', timestr)
os.mkdir(out_path)
for k in range(0,file_lens):
file_format,file_extension = os.path.splitext(file_paths[k])
out_file_name = out_path + "/" + str(k+1) + str(file_extension)
print("out_file_name",out_file_name)
f1 = open(file_paths[k], mode='r', encoding='utf-8')
f2 = open(out_file_name, mode='w+', encoding='utf-8')
f2.write(f1.read())
f1.close()
f2.close()
if __name__ == "__main__":
#
# mode -> 0, get the path here and make the outpath
# mode -> 1, get the inpath and outpath
#
mode = 0
# to get the curpath if need
if mode == 0:
curPath = pathlib.Path(__file__).parent.resolve()
renameFile(curPath)
# print(curPath)
|
3672c7869cb913068693ba8bb90b402efbbe9f49 | JKayathri/Part-of-my-Brain | /binary to decimal.py | 174 | 3.84375 | 4 | n=int(input("Enter the binary value"))
count=-1
sum=0
while(n!=0):
r=n%10
n=int(n/10)
count=count+1
sum=sum+(2**count)*r
print("Decimal value is "+ str(sum))
|
b09d81da93681e8f4e40dac4d70673b32f694ac1 | sully90/dp-search-service | /src/main/python/modules/ONS/text_processing.py | 1,926 | 3.5625 | 4 | from gensim.utils import lemmatize
from nltk.corpus import stopwords
def get_stopwords():
return set(stopwords.words('english')) # nltk stopwords list
def get_bigram(train_texts):
import gensim
bigram = gensim.models.Phrases(train_texts) # for bigram collocation detection
return bigram
def build_texts_from_file(fname):
import gensim
"""
Function to build tokenized texts from file
Parameters:
----------
fname: File to be read
Returns:
-------
yields preprocessed line
"""
with open(fname) as f:
for line in f:
yield gensim.utils.simple_preprocess(line, deacc=True, min_len=3)
def build_texts_as_list_from_file(fname):
return list(build_texts_from_file(fname))
def build_texts(texts):
import gensim
"""
Function to build tokenized texts from file
Parameters:
----------
fname: File to be read
Returns:
-------
yields preprocessed line
"""
for line in texts:
yield gensim.utils.simple_preprocess(line, deacc=True, min_len=3)
def build_texts_as_list(texts):
return list(build_texts(texts))
def process_texts(texts, stops=get_stopwords()):
"""
Function to process texts. Following are the steps we take:
1. Stopword Removal.
2. Collocation detection.
3. Lemmatization (not stem since stemming can reduce the interpretability).
Parameters:
----------
texts: Tokenized texts.
Returns:
-------
texts: Pre-processed tokenized texts.
"""
bigram = get_bigram(texts)
texts = [[word for word in line if word not in stops] for line in texts]
texts = [bigram[line] for line in texts]
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
texts = [[word for word in lemmatizer.lemmatize(' '.join(line), pos='v').split()] for line in texts]
return texts |
85c2f479e4b060f19627fb529a86fdf67e8b8a63 | UdalovPS/Coach-book-v1 | /Widtext/head_main.py | 498 | 3.75 | 4 | """
This module return text for widget for main window.
Text depends about choice language.
"""
def main_text(language='eng'):
if language == 'eng':
text = {'title': 'Coach Book', 'database': 'Database',
'training': 'Training'}
if language == 'rus':
text = {'title': 'Книга тренера', 'database': 'База данных',
'training': 'Тренеровки'}
return text
if __name__ == '__main__':
print(main_text('eng'))
|
705face115e3e0a175693d6c21e4ccf2895c4dd6 | SUHAYB-MACHINELEARNING-FULL-STACK/Twaiq-Python-Project | /Twaiq-Python-project.py | 387 | 3.9375 | 4 | info = {
"1212121212":"mohammed" # For Example
}
Input = input('Your Name Or Phone Number: ').lower()
print("Sorry, The number is not found" if Input not in info.keys() and Input not in info.values() else "This is invalid number" if len([i for i in Input if i in "0123456789"])!=len(Input) else [i for i in info.keys() if info[i]==Input][0] if Input in info.values() else info[Input])
|
ec04bfd6ff4eec392140b68f911dee0974598c88 | reikolaski/BootCamp2018 | /ProbSets/Comp/ProbSet1/shut_the_box.py | 1,317 | 3.65625 | 4 | import box, sys, time, random
if len(sys.argv) != 3:
print("Three command line arguments required.")
else:
start = time.time()
name = sys.argv[1]
time_limit = float(sys.argv[2])
remaining = list(range(1, 10))
def lose():
print("Game Over!\n")
print("Score for player ", name, ": ", sum(remaining), " points")
print("Time played: ", round(time.time() - start, 2), " seconds")
print("Better luck next time >:)")
while (len(remaining) != 0):
print("Numbers left: ", remaining)
if sum(remaining) <= 6:
roll = random.randint(1, 6)
else:
roll = random.randint(2, 12)
if box.isvalid(roll, remaining):
print("Roll: ", roll)
current = True
while current:
time_elapsed = time.time() - start
print("Seconds left ", round(time_limit - time_elapsed, 2))
eliminate = box.parse_input(input("Numbers to eliminate: "), remaining)
time_elapsed = time.time() - start
if time_limit - time_elapsed <= 0:
lose()
break
if (len(eliminate) == 0) | (sum(eliminate) != roll):
print("Invalid input")
else:
current = False
print("\n")
for i in eliminate:
remaining.remove(i)
else:
lose()
break
if len(remaining) == 0:
print("Score for player ", name, ": 0 points")
print("Time played: ", round(time.time() - start, 2))
print("Congratulations!! You shut the box!")
|
30da914f2d9e223617fe71e51f7036db05dcac23 | OliValur/Forritunar-fangi-1 | /1september.py | 1,424 | 4.09375 | 4 | # upto = int(input("Input an int: ")) # Do not change this line
# for num in range(0,upto):
# print(num)
# highest = int(input("Input an int: "))
# for num in range(1,highest+1):
# if num % 3 == 0:
# print(num)
# max_days = int(input("Input max number of days: "))
# target = int(input("Input dollar target: "))
# dollars = 1
# days_when_amount_acquired = 0
# for num in range(1,max_days+1):
# dollars *= 2
# if dollars >= target:
# days_when_amount_acquired = num
# break
# print('Days needed:',days_when_amount_acquired)
# Write a Python program using nested for loops that, given an integer n as input, prints all consecutive sums from 1 to n.
# For example, if 5 is entered, the program will print five sums of consecutive numbers:
# 1
# 3
# 6
# 10
# 15
# because
# 1 = 1
# 1 + 2 = 3
# 1 + 2 + 3 = 6
# 1 + 2 + 3 + 4 = 10
# 1 + 2 + 3 + 4 + 5 = 15
# length = int(input("Input the length of series: "))
# sum = 0
# final_sum = 0
# for i in range(length):
# sum += 2
# if i % 2 == 0:
# print(sum)
# final_sum += sum
# else:
# print(sum*(-1))
# final_sum -= sum
# print(final_sum)
max_days = 4
target = 16
dollars = 1
days_when_amount_acquired = 0
for num in range(1,max_days+1):
dollars *= 2
if dollars >= target:
days_when_amount_acquired = num
break
print('Days needed:',days_when_amount_acquired) |
959fc6191262d8026e7825e50d80eddb08d6a609 | OliValur/Forritunar-fangi-1 | /20agust.py | 2,173 | 4.28125 | 4 | import math
# m_str = input('Input m: ') # do not change this line
# # change m_str to a float
# # remember you need c
# # e =
# m_float = float(m_str)
# c = 300000000**2
# e = m_float*c
# print("e =", e) # do not change this line)
# Einstein's famous equation states that the energy in an object at rest equals its mass times the square of the speed of light. (The speed of light is 300,000,000 m/s.)
# Complete the skeleton code below so that it:
# * Accepts the mass of an object (remember to convert the input string to a number, in this case, a float).
# * Calculate the energy, e
# * Prints e
# import math
# x1_str = input("Input x1: ") # do not change this line
# y1_str = input("Input y1: ") # do not change this line
# x2_str = input("Input x2: ") # do not change this line
# y2_str = input("Input y2: ") # do not change this line
# x1_int = int(x1_str)
# y1_int = int(y1_str)
# x2_int = int(x2_str)
# y2_int = int(y2_str)
# formula =(y1_int-y2_int)**2+(x1_int-x2_int)**2
# d = math.sqrt(formula)
# print(formula)
# print("d =",d) # do not change this line
# weight_str = input("Weight (kg): ") # do not change this line
# height_str = input("Height (cm): ") # do not change this line
# # weight_int = int(weight_str)
# # height_int = int(height_str)
# weight_float = float(weight_str)
# height_float = float(height_str)
# bmi = weight_float / (height_float**2)
# print("BMI is: ", bmi) # do not change this line75,290.6
n_str = input("Input n: ")
# remember to convert to an int
n_int = int(n_str)
first_three = n_int//100
last_two =n_int % 100
print("first_three:", first_three)
print("last_two:", last_two)
# Write a Python program that:
# Accepts a five-digit integer as input
# Assign the variable first_three (int) to be the first three digits.
# Assign the variable last_two (int) to be the last two digits.
# Prints out the two computed values.
# Hint: use quotient (//) and remainder (%)
# For example, if the input is 12345, the output should be:
# first_three: 123
# last_two: 45
# If the fourth digit is a zero, like 12305, the output should be:
# first_three: 123
# last_two: 5
# (even though that is not strictly correct). |
53e13545217802aaaaf8109eeccbb6d31ab1748a | zoomzoomTnT/DataLab379k | /lab1/problem1.py | 561 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
@author: Josh M, Zhicong Z
"""
import numpy as np
import matplotlib.pyplot as plt
# Mean Calculation
def mean(n):
return float(sum(n))/max(len(n),1)
mu, sigma = -10, 5
s = np.random.normal(mu, sigma, 1000)
mu2, sigma2 = 10, 5
s2 = np.random.normal(mu2, sigma2, 1000)
s3 = s + s2
print("Problem 1a: The Sum of two gaussians is gaussian")
print("\n")
count, bins, ignored = plt.hist(s3, 30, normed=True)
print("Problem 1b: Estimated Mean : 0, Estimated Varience : 5")
plt.show()
|
7cfc1bf5b32ba019052f824ae10df73541da2ff5 | Barnettxxf/DateStructureAndAlgorithm | /example/huffmantree.py | 608 | 3.5 | 4 | # -*- coding: utf-8 -*-
from DateStructureAndAlgorithm.bintree import BinTree, BinTNode, PrioQueue
__author__ = 'barnett'
class HTNode(BinTNode):
def __lt__(self, othernode):
return self.data < othernode.data
class HuffmanPrioQ(PrioQueue):
def number(self):
return len(self._elems)
def huffman_tree(weights):
trees = HuffmanPrioQ()
for w in weights:
trees.enqueue(HTNode(w))
while trees.number() > 1:
t1 = trees.dequeue()
t2 = trees.dequeue()
x = t1.data + t2.data
trees.enqueue(HTNode(x, t1, t2))
return trees.dequeue()
|
fc19470b4215bec744c797d5600c1e562fab08c6 | VicFinistere/macgyver | /item.py | 1,091 | 3.65625 | 4 | """
Item Class : Where you can resize the ability of Mac Gyver to get Swiss Army Knives
"""
import os
import pygame
from config import ASSETS_DIR
from random import randint
class Item(pygame.sprite.Sprite):
"""
This class is handling properties and methods for all kind of item
:returns any player without specialities
"""
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(os.path.join(ASSETS_DIR, "gfx/item.png"))
self.image = pygame.transform.scale(self.image, (32, 32))
# Here we want Mac Gyver to be able to catch the item from a small distance ( normal rect.(x/y): 32)
self.rect = pygame.Rect(pos[0] * 32, pos[1] * 32, 64, 64)
random_orientation = randint(0, 3)
if random_orientation == 0:
self.image = pygame.transform.rotate(self.image, 90)
elif random_orientation == 1:
self.image = pygame.transform.rotate(self.image, 180)
elif random_orientation == 2:
self.image = pygame.transform.rotate(self.image, 270)
|
8973081798e44e438007c5537e05e6d2a6f1b825 | Dhiraj3108/myfirstcode | /9917103154_Assignment1_Stack.py | 530 | 4 | 4 | stack = []
def pushit():
ch = 'y'
while (ch == 'y'):
inp = input("Enter some character")
stack.append(inp)
ch = input("Do you want to enter more values? Enter y/n")
def popit():
if len(stack) == 0:
print('Cannot pop from an empty stack!')
else:
print('Removed[',stack.pop(),']')
def viewstack():
print(stack)
pushit()
viewstack()
inp_ch = input("Do you want to pop some value? Enter y/n")
if inp_ch == 'y':
popit()
viewstack()
|
6fb7db8a66df18d4b501c64cf22b34e739226bda | id774/sandbox | /python/math/stats.py | 5,398 | 3.546875 | 4 | from math import sqrt, exp, log, pi, ceil, floor
from functools import reduce
import re
import random
def add(x, y):
"""足し算"""
return x + y
def average(l):
"""算術平均を求める"""
return reduce(add, l, 0.0) / float(len(l))
def standard_deviation(l):
"""標準偏差を求める"""
avg = average(l)
l2 = [(x - avg) ** 2 for x in l]
return sqrt(reduce(add, l2, 0.0) / (float(len(l2) - 1.0)))
def class_size(l):
"""
階級の個数を求める
スタージェスの公式
"""
return int(ceil(1 + (log(len(l), 10) / log(2, 10))))
def class_interval(l):
"""階級の幅を求める"""
max = sorted(l)[-1]
min = sorted(l)[0]
return int(ceil((max - min) / class_size(l)))
def median(l):
"""中央値を求める"""
if len(l) % 2 == 0:
x = floor(len(l) / 2)
return (l[x - 1] + l[x]) / 2.0
else:
return l[floor(len(l) / 2)]
def class_list(l):
"""階級値のリストを求める"""
interval = class_interval(l)
size = class_size(l)
min = sorted(l)[0]
result = []
for i in range(0, size):
if i == 0:
result.append(min)
else:
result.append(result[i - 1] + interval)
return result
def frequency_distribution(l):
"""度数分布を求める"""
result = {}
interval = class_interval(l)
for c in class_list(l):
for i in l:
if c <= i and i < (c + interval):
val = result.setdefault(c, [])
val.append(i)
result[c] = val
return result
def relative_frequency(l):
"""相対度数を求める"""
result = {}
total = float(len(l))
for k, v in frequency_distribution(l).items():
result[k] = len(v) / total
return result
def standard_value(x, l):
"""基準値を求める"""
avg = average(l)
return (x - avg) / standard_deviation(l)
def deviation(x, l):
"""偏差値を求める"""
return (standard_value(x, l)) * 10 + 50
def probability_density(x, l):
"""確率密度関数"""
avg = average(l)
sd = standard_deviation(l)
return (1 / (sqrt(2 * pi) * sd)) * exp((- (1 / 2)) * (((x - avg) / sd) ** 2))
def sum_of_products(avg1, avg2, l1, l2):
"""積和を求める"""
xx = [(x - avg1) for x in l1]
yy = [(y - avg2) for y in l2]
return reduce(add, [x * y for x, y in zip(xx, yy)], 0.0)
def sum_of_squared_deviation(avg, l):
"""偏差平方和を求める"""
return reduce(add, [(x - avg) ** 2 for x in l], 0.0)
def single_correlation_coefficient(l1, l2):
"""単相関係数を求める"""
avg1 = average(l1)
sxx = sum_of_squared_deviation(avg1, l1)
avg2 = average(l2)
syy = sum_of_squared_deviation(avg2, l2)
sxy = sum_of_products(avg1, avg2, l1, l2)
return sxy / (sqrt(sxx * syy))
def correlation_ratio(m):
"""相関比を求める"""
categories = set([x[1] for x in m.values()])
groups = {}
for i in categories:
for j in m.values():
if i == j[1]:
val = groups.setdefault(i, [])
val.append(j[0])
groups[i] = val
avgs = {k: ((reduce(add, v, 0.0)) / len(v)) for k, v in groups.items()}
within_class_variation = {}
for k, v in groups.items():
avg = avgs.get(k)
val = within_class_variation.setdefault(k, 0.0)
v2 = [(x - avg) ** 2 for x in v]
val = reduce(add, v2, 0.0)
within_class_variation[k] = val
all_avg = reduce(add, [v[0] for k, v in m.items()], 0.0) / len(m)
between_class_variation = 0.0
for k, v in groups.items():
between_class_variation += len(v) * ((avgs.get(k) - all_avg) ** 2)
return (between_class_variation / (reduce(add, [v for v in within_class_variation.values()], 0.0) + between_class_variation))
if __name__ == '__main__':
JP_TOKEN = re.compile("[一-龠]|[ぁ-ん]|[ァ-ヴ]")
def f(s, l):
w = str(16 - len(JP_TOKEN.findall(s)))
return '{:<{}}{}'.format(s, w, l)
l = [1, 2, 3, 4, 5, 6, 10, 12]
print(f("標本", l))
print(f("算術平均", average(l)))
print(f("標準偏差", standard_deviation(l)))
print(f("階級の個数", class_size(l)))
print(f("階級の幅", class_interval(l)))
print(f("中央値", median(l)))
print(f("階級値のリスト", class_list(l)))
print(f("度数分布", frequency_distribution(l)))
print(f("相対度数", relative_frequency(l)))
rnd = random.choice(l)
print(f("基準値", [rnd, standard_value(rnd, l)]))
print(f("偏差値", [rnd, deviation(rnd, l)]))
print(f("確率密度関数", [rnd, probability_density(rnd, l)]))
l1 = [1000, 2000, 4000, 6000, 10000]
l2 = [6000, 11000, 22500, 34000, 50000]
print(f("単相関係数1", [single_correlation_coefficient(l, l)]))
print(f("単相関係数2", [single_correlation_coefficient(l1, l2)]))
m1 = {1: (16, 'A'), 2: (18, 'A'), 3: (20, 'B'), 4: (
22, 'A'), 5: (24, 'C'), 6: (26, 'B'), 7: (28, 'C')}
print(f("相関比1", [correlation_ratio(m1)]))
m2 = {1: (23, 'A'), 2: (26, 'A'), 3: (27, 'A'), 4: (28, 'A'), 5: (25, 'B'), 6: (26, 'B'), 7: (29, 'B'), 8: (
32, 'B'), 9: (33, 'B'), 10: (15, 'C'), 11: (16, 'C'), 12: (18, 'C'), 13: (22, 'C'), 14: (26, 'C'), 15: (29, 'C')}
print(f("相関比2", [correlation_ratio(m2)]))
|
7f948cb92a2de44ce96485a83b6b2c44ae0c36ff | id774/sandbox | /python/math/gaussian-function.py | 430 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ガウス関数
# http://en.wikipedia.org/wiki/Gaussian_function
# 正規分布における確率密度を示す関数
import math
def gaussian(dist, sigma=10.0):
exp = math.e ** (-dist ** 2 / (2 * sigma ** 2))
return (1 / (sigma * (2 * math.pi) ** .5)) * exp
# print gaussian(0.1)
# print gaussian(1.0)
# print gaussian(5.0)
# print gaussian(0.0)
# print gaussian(3.0)
|
23b6ffcb6352e7c045387c2d3c385c300e4cf7e0 | id774/sandbox | /python/math/dice.py | 543 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def dice(v1, v2):
numerator = sum([c in v2 for c in v1])
denominator = len(v1) + len(v2)
return 2 * float(numerator) / denominator if denominator != 0 else 0
if __name__ == '__main__':
v1 = {"ほげ": 1, "ふが": 2, "ぴよ": 3}
v2 = {"ほげ": 2, "ふが": 1, "ほへ": 2}
v3 = {"ほげ": 3, "ふが": 2, "ぴよ": 1}
result = dice(v1, v2)
print("dice v1,v2 is %(result)s" % locals())
result = dice(v1, v3)
print("dice v1,v3 is %(result)s" % locals())
|
d425b27c817f89239b47a90e38b577af89484663 | id774/sandbox | /python/math/prime.py | 228 | 3.640625 | 4 | from itertools import count
def prime_generator():
g = count(2)
while True:
prime = next(g)
yield prime
g = filter(lambda x, prime=prime: x % prime, g)
for pr in prime_generator():
print(pr)
|
82b6fd6d60e1501c70df693a70257c63f5d5173f | id774/sandbox | /python/list.py | 747 | 3.546875 | 4 | import sys
class List(list):
def head(self):
return self[0]
def tail(self):
return self[1:]
def init(self):
return self[0:-1]
def last(self):
return self[-1]
def shift(self):
try:
return self.pop(0)
except IndexError:
return None
def test_data():
return List(['a', 'b', 'c', 'd', 'e'])
def main(args):
list = test_data()
print(list.head())
print(list.tail())
print(list.init())
print(list.last())
list = test_data()
print(list.shift())
print(list.shift())
print(list.shift())
print(list.shift())
print(list.shift())
print(list.shift())
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
87c2f162f60d1ae47ea420fbb33e890518ef471e | id774/sandbox | /python/machine-learning/poisson-distribution.py | 539 | 3.6875 | 4 | # -*- coding:utf-8 -*_
import matplotlib.pyplot as plt
import numpy as np
import math
def poisson(lambd):
def f(x):
return float(lambd ** x) * np.exp(-lambd) / math.factorial(x)
return f
N = 8
L = []
score_mean = 0.8
f = poisson(score_mean)
L.append([f(k) for k in range(N + 1)])
for prob in L:
plt.plot(range(N + 1), prob, 'r')
ax = plt.axes()
ax.set_xlim(0, N)
ax.set_ylim(-0.01, 0.5)
plt.title('Soccer Score')
plt.xlabel('Score')
plt.ylabel('Probability')
plt.grid(True)
plt.show()
plt.savefig("image.png")
|
11070e9df380011576950b7fb7ee24d666bc182a | id774/sandbox | /python/shufflesequence.py | 719 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pprint import pformat
import random
def randomize(items):
randomized = []
while 0 < len(items):
idx = random.randint(0, len(items) - 1)
popped = items[idx]
del items[idx]
randomized.append(popped)
return randomized
if __name__ == '__main__':
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50, 60, 70]
z = [111, 222, 333, 444, 555, 666, 777, 888, 999]
print('x = %s' % pformat(x))
print('randomized x = %s' % pformat(randomize(x)))
print('y = %s' % pformat(y))
print('randomized y = %s' % pformat(randomize(y)))
print('z = %s' % pformat(z))
print('randomized z = %s' % pformat(randomize(z)))
|
73374d322193bbc0263446af998b4c8ad7853811 | NamanBhoj/PlotlyDash | /plotlydash/plotlytuts/barchart.py | 982 | 3.953125 | 4 | import plotly.graph_objects as go
import plotly.express as px #read data
#plot data
from plotly.offline import plot
import os
import pandas as pd
# DIRECTORY_PATH = os.path.abspath(os.path.dirname(__file__))
# data_path = os.path.join(DIRECTORY_PATH , '/data/csv/', 'aggregated_score.csv')
#reading data
data = pd.read_csv(r"data/csv/aggregated_scores.csv")
# graph object is used to define how the graph should look
# THIS IS TO SEE THE WHOLE DATA NOW SAY YOU WANT TO COMPARE TWO BANKS THATS NETX
fig = go.Figure([go.Bar(x = data['bank'], y = data['cx_quantitative_score'], marker_color = 'green')])
fig.update_layout(title= "Bar Chart of " + "Bank V/S Cx_quantitative_score" , xaxis_title = "Bank", yaxis_title= "Cx_qunatitative_Score" )
# TODO: "MAKE THE UPDAATION OF THIS NAME DYNAMIC IN LINE 17"
#COMPARE TWO Bankers
# data1 = data.query("bank='Bendigo'")
# # data2 = data.query("bank='ANZ'")
# print(data1)
# now plot it using plot function
plot(fig)
|
9077eea0e23378ce9768dfb7e7126cbd25e33081 | SilentThorns/Basic-Python-Projects | /DiceRollingSimulator.py | 772 | 3.9375 | 4 | import random
max=1
min=6
print("Heres your roll!",end=" ")
print(random.randint(max,min))
yesno = input("Reroll? Y/N: ")
while yesno == 'Y' or yesno== 'y':
pass
print("Heres your roll!",end=" ")
print(random.randint(max,min))
yesno = input("Reroll? Y/N: ")
print("Heres your roll!",end=" ")
while yesno == 'N' or yesno == 'n':
pass
print("Goodbye! ")
exit()
while yesno != 'N' or yesno != 'n':
pass
print("Invalid! ",end="")
yesno = input("Reroll? Y/N: ")
while yesno == 'Y' or yesno== 'y':
pass
print(random.randint(max,min))
yesno = input("Reroll? Y/N: ")
print("Heres your roll!",end=" ")
while yesno == 'N' or yesno == 'n':
pass
print("Goodbye! ")
exit()
|
bf33705f0a6af867dfd505807e2387a5f740eaa5 | aptro/codeme | /Problems/coincount.py | 1,156 | 3.5625 | 4 | import sys
sys.setrecursionlimit(10000)
#dynamic testing fibonnaci
def fib(n):
if n <= 1:
return 1
else:
return fib(n-1) + fib(n-2)
def coincount(l):
if l[2] == 0:
return 1
if l[2] < 0:
return 0
if (l[1]<=0 and l[2]>=1):
return 0
return coincount([l[0], l[1]-1, l[2]]) + coincount([l[0], l[1], l[2]-l[0][l[1]-1]])
#dynamic programming
def memory(f):
def memf(*x):
i=0
arglist ={}
if x not in arglist.values():
i+=1
arglist[i] = x
cache[i] = f(*x)
return cache[i]
cache ={}
return memf
def memoize(f):
# define "wrapper" function that checks cache for
# previously computed answer, only calling f if this
# is a new problem.
def memf(*x):
if x not in memf.cache:
memf.cache[x] = f(*x)
return memf.cache[x]
# initialize wrapper function's cache. store cache as
# attribute of function so we can look at its value.
memf.cache = {}
return memf
coincountd = memory(coincount)
fibd = memoize(fib)
fibm = memory(fib) |
d0e02d65fe7d8c42f6cdf51f003a071cd5f2f60c | aptro/codeme | /Problems/pythonutility.py | 222 | 3.734375 | 4 | import os
def printdir(dir):
filenames=os.listdir(dir)
for filename in filenames:
print filename
print os.path.join(dir, filename)
print os.path.abspath(os.path.join(dir, filename))
|
355a495c5cb9d403ad1b8f960919d211c3810479 | saxsoares/IA-Python | /problem-5/knn.py | 2,980 | 3.5625 | 4 | import math
import random
#import matplotlib.pyplot as plt
# Retorna a media das respostas das k entradas mais proximas ao novo_exemplo
# 1) Calcula a distancia euclidiada (sqrt(sum((x - y)^2))) entre novo_exemplo e cada uma das entradas
# 2) Monta uma tupla (distancia, resposta)
# 3) Ordena as tuplas, da menor distancia para a maior
# 4) Pega os valores das k respostas ordenadas
# 5) Calcula a media e retorna o valor
def knn(novo_exemplo, entradas, respostas, k):
melhores = sorted(
[
[
math.sqrt(
sum(
[(n - e)**2 for n, e in zip(novo_exemplo, entradas[j])] # Calculo da distancia euclidiana entre dois vetores
)
), respostas[j], "id="+str(j)
] for j in range(len(entradas))
],
key=lambda tupla: tupla[0]
)[:k]
valores = [m[1] for m in melhores]
# return float(sum(valores))/len(valores)
###### IMPLEMENTE AQUI O RETORNO DA RESPOSTA MAIS FREQUENTE DENTRE OS K VIZINHOS MAIS PROXIMOS
########################
# Main
########################
# Le a linha com as configuracoes
config = sys.stdin.readline().strip().split(';')
random.seed(int(config[0]))
nDim = int(config[1])
tamTreino = int(config[2])
tamTeste = int(config[3])
cores = ['r', 'b', 'g', 'k', 'm']
dadosTreino = [ [random.uniform(-1.0, 1.0) for i in range(nDim)] for j in range(tamTreino)]
dadosTeste = [ [random.uniform(-1.5, 1.5) for i in range(nDim)] for j in range(tamTeste)]
respTreino = [random.choice(cores[:nDim]) for _ in range(tamTreino)]
respTeste = [random.choice(cores[:nDim]) for _ in range(tamTeste)]
vetK = [1, 3, 5]
for valK in vetK:
erros = []
estimado = []
for i in range(tamTeste):
estimado.append(knn(dadosTeste[i], dadosTreino, respTreino, valK))
#erros.append(abs(estimado[i] - respTeste[i]))
#erroMedio = sum(erros)/float(len(erros))
###### IMPLEMENTE AQUI O CALCULO DA ACURACIA
# Saida
for valor in erros:
print ("%.3f" % valor)
# Desenha os conjuntos de dados
#plt.figure()
#
#for i in range(tamTreino):
# plt.plot( dadosTreino[i][0], dadosTreino[i][1], 'x', markersize=10, color = respTreino[i], mew=3)
# plt.text(dadosTreino[i][0], dadosTreino[i][1], str(i), fontsize=14, color="whitesmoke")
# plt.text(dadosTreino[i][0]-0.005, dadosTreino[i][1]+0.005, str(i), fontsize=14)
#
#for i in range(tamTeste):
# plt.plot( dadosTeste[i][0], dadosTeste[i][1], 'o', markersize=10, color = respTeste[i])
# plt.text(dadosTeste[i][0], dadosTeste[i][1], str(i), fontsize=14, color="whitesmoke")
# plt.text(dadosTeste[i][0]-0.005, dadosTeste[i][1]+0.005, str(i), fontsize=14)
#
#plt.draw()
#plt.show()
|
0f3e6670dc78b9115b61a2eaca34f81bb8f09ed9 | saxsoares/IA-Python | /codes-Professor/meuknn_reg.py | 3,333 | 3.65625 | 4 | # carrega e mistura
import math
import random
import matplotlib.pyplot as plt # required for plotting
from mpl_toolkits.mplot3d import Axes3D
# Retorna a media das respostas das k entradas mais proximas ao novo_exemplo
# 1) Calcula a distancia euclidiada (sqrt(sum((x - y)^2))) entre novo_exemplo e cada uma das entradas
# 2) Monta uma tupla (distancia, resposta)
# 3) Ordena as tuplas, da menor distancia para a maior
# 4) Pega os valores das k respostas ordenadas
# 5) Calcula a media e retorna o valor
def knn(novo_exemplo, entradas, respostas, k):
melhores = sorted(
[
[
math.sqrt(
sum(
[(n - e)**2 for n, e in zip(novo_exemplo, entradas[j])] # Calculo da distancia euclidiana entre dois vetores
)
), respostas[j], "id="+str(j)
] for j in range(len(entradas))
],
key=lambda tupla: tupla[0]
)[:k]
print " ".join([m[2] for m in melhores]),
valores = [m[1] for m in melhores]
return float(sum(valores))/len(valores)
random.seed(1)
# Funcao objetivo
objfun = lambda x: x[0]**2 + x[1]
nDim = 2
tamTreino = 10
tamTeste = 5
dadosTreino = [ [random.uniform(-1.0, 1.0) for i in range(nDim)] for j in range(tamTreino)]
dadosTeste = [ [random.uniform(-1.5, 1.5) for i in range(nDim)] for j in range(tamTeste)]
respTreino = [ objfun(variaveis) for variaveis in dadosTreino ]
respTeste = [ objfun(variaveis) for variaveis in dadosTeste ]
fig=plt.figure(1)
ax = fig.add_subplot(111, projection='3d')
for i in range(tamTreino):
ax.scatter(dadosTreino[i][0], dadosTreino[i][1], respTreino[i], c='steelblue', marker='o', s=50)
ax.text(dadosTreino[i][0], dadosTreino[i][1], respTreino[i], str(i), fontsize=14, color="whitesmoke")
ax.text(dadosTreino[i][0]-0.005, dadosTreino[i][1]+0.005, respTreino[i], str(i), fontsize=14)
for i in range(tamTeste):
ax.scatter(dadosTeste[i][0], dadosTeste[i][1], respTeste[i], c='darkorange', marker='o', s=50)
ax.text(dadosTeste[i][0], dadosTeste[i][1], respTeste[i], str(i), fontsize=14, color="whitesmoke")
ax.text(dadosTeste[i][0]-0.005, dadosTeste[i][1]+0.005, respTeste[i], str(i), fontsize=14)
plt.draw()
#plt.show()
plt.figure(2)
plt.plot( range(tamTeste), respTeste, 'o-', markersize=10, label='Original' )
vetK = [1, 2, 3]
for valK in vetK:
erros = []
estimado = []
print "\n\nTreino: azul Teste: laranja"
for i in range(tamTeste):
print "Os k=" + str(valK) + " pontos mais proximos do id=" + str(i) + " sao:",
estimado.append(knn(dadosTeste[i], dadosTreino, respTreino, valK))
erros.append(abs(estimado[i] - respTeste[i]))
print " Real: %.3f Estimado: %.3f Erro: %.3f" % (respTeste[i], estimado[-1], erros[-1])
erroMedio = float(sum(erros))/len(erros)
print "Erro medio=", erroMedio, "\n\n"
#print (erros)
plt.plot( range(tamTeste), estimado, 'o-', markersize=10, label='k='+ str(valK) )
# plt.title("K = " + str(valK) + " erroMedio=" + str(erroMedio))
plt.legend(['Original'] + ['k='+str(valK) for valK in vetK])
plt.draw()
plt.show()
|
0837151d119a5496b00d63ae431b891e405d11cb | Shubham1744/Python_Basics_To_Advance | /Divide/Prog1.py | 249 | 4.15625 | 4 | #Program to divide two numbers
def Divide(No1,No2):
if No2 == 0 :
return -1
return No1/No2;
No1 = float(input("Enter First Number :"))
No2 = float(input("Enter Second Number :"))
iAns = Divide(No1,No2)
print("Division is :",iAns);
|
8bb3ca89be52df473d6b8b1a296c124c6094493d | Shubham1744/Python_Basics_To_Advance | /Reverse_Range/rev_range.py | 196 | 4.21875 | 4 | # Program to print 5 to 1 numbers on screen.
def DispRev(int n):
for i in range(n,0,-1): #range(start,stop,increment/decrement)
print(i)
n = int(input("Enter Number"))
DispRev()
|
ddc72147f7844b39ff06a73ffea009d96e8de69d | Scorcherfjk/practicas-en-Python | /hecho_en_el_trabajo/manejo_de_strings/encontrar_mayusculas.py | 366 | 3.609375 | 4 | def mayusculas(cadena):
letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
coincidencias = ''
for x in cadena:
for y in letras:
if x == y:
coincidencias = coincidencias + x
return coincidencias
cadena = input("Introduce una cadena de texto")
print("Se han encontrado {} mayusculas y estas fueron las letras {}.".format(len(mayusculas(cadena)),mayusculas(cadena)))
|
8f02e78c31165d76db121a3ff54e5604e2c36e54 | Osabutey/Azubi_time_tracking_Faith_Emma_assignment | /Time_tracking_Faith_Emma.py | 1,541 | 3.78125 | 4 | #!/usr/bin/python
from datetime import datetime
datearr=[] #create an array to store date
wage_per_hour = 5
client_name = input("Name of client: ")
task_name = input("What is the name of this task?: ")
started = input("When did "+task_name+" start? (YYYY-MM-DD HH:MM): ")
datearr.append(started)
#end = input("When did "+task_name+" end? (YYYY-MM-DD HH:MM): ")
now = datetime.now() #end time
datearr.append(now)
print("Amazing, let us process your payroll now!")
format='%Y-%m-%d %H:%M'
try:
startdate = datetime.strptime(datearr[0], format ) #convert string to datetime format
#enddate = datetime.strptime(datearr[1], format)
enddate= datearr[1]
print ('So uhm ',startdate,'to ' , enddate," ")
confirm = input("Did I get that right?Y/n: ")
if confirm and confirm.lower()=="y":
timediff = round(((enddate-startdate).total_seconds() / 3600), 2)
wages = round((timediff * wage_per_hour), 2)
print ('Okay it took ', timediff, 'hours so $5/hr for you comes to $'+str(wages))
else:
print("Aww snap. Please run me again and start from the top")
except Exception as e:
print("Sorry but there was this issue with your entries!: "+e)
#store output a in csv file
import pandas as pd
mydata={'client name': [client_name],'task name': [task_name], 'working hours':[timediff], 'wages':[wages]}
mydataset=pd.DataFrame(mydata, columns=['client name','task name', 'working hours', 'wages'])
print(mydataset)
mydataset.to_csv('Time_tracking.csv', sep='\t', mode='a', header=None)
|
b57b724347cc8429c3178723de6182e741940b16 | DarioDistaso/senai | /logica_de_programação/sa4etapa1.py | 1,614 | 4.15625 | 4 | #Disciplina: [Logica de Programacao]
#Professor: Lucas Naspolini Ribeiro
#Descricao: SA 4 - Etapa 1: PILHA
#Autor: Dario Distaso
#Data atual: 06/03/2021
pilha = []
def empilhar(): # opção 1
if len(pilha) < 20:
produto = str(input("Digite o produto: ")).strip()
pilha.append(produto)
print(f'O produto inserido foi: {produto}')
elif len(pilha) == 20:
print("A pilha já está cheia!")
def desempilhar(): # opção 2
if len(pilha) == 0:
print("A pilha está vazia!")
else:
topo = pilha.pop()
print(f'O produto removido foi: {topo}')
def limpar(): # opção 3
if len(pilha) == 0:
print("A pilha já está vazia!")
else:
pilha.clear()
print("A pilha foi limpa!")
def listar(): # opção 4
if len(pilha) == 0:
print("A pilha está vazia!")
else:
print(f'\nA pilha atual é {pilha}')
def vazia(): # opção 5
if len(pilha) == 0:
print("A pilha está vazia!")
else:
print("A pilha não está vazia!")
while True:
print("""\n\t1 - Empilhar
\t2 - Desempilhar
\t3 - Limpar
\t4 - Listar
\t5 - A pilha está vazia?
\t6 - Encerrar""")
opcao = int(input("\nDigite uma opção: "))
if opcao == 1:
empilhar()
elif opcao == 2:
desempilhar()
elif opcao == 3:
limpar()
elif opcao == 4:
listar()
elif opcao == 5:
vazia()
elif opcao == 6:
print("\nVocê encerrou o programa!\n")
break
else:
print("Opção inválida!")
|
d2c3755214d8cd933f7e687f1e804d2f7fadcc83 | iNSDX/AI | /Practise2/búsqueda_espacio_estados.py | 6,693 | 3.5 | 4 | import collections
import heapq
import types
class ListaNodos(collections.deque):
def añadir(self, nodo):
self.append(nodo)
def vaciar(self):
self.clear()
def __contains__(self, nodo):
return any(x.estado == nodo.estado
for x in self)
class PilaNodos(ListaNodos):
def sacar(self):
return self.pop()
class ColaNodos(ListaNodos):
def sacar(self):
return self.popleft()
class ColaNodosConPrioridad:
def __init__(self):
self.nodos = []
self.nodo_generado = 0
def añadir(self, nodo):
heapq.heappush(self.nodos, (nodo.heurística, self.nodo_generado, nodo))
self.nodo_generado += 1
def sacar(self):
return heapq.heappop(self.nodos)[2]
def vaciar(self):
self.__init__()
def __iter__(self):
return iter(self.nodos)
def __contains__(self, nodo):
return any(x[2].estado == nodo.estado and
x[2].heurística <= nodo.heurística
for x in self.nodos)
class NodoSimple:
def __init__(self, estado, padre=None, acción=None):
self.estado = estado
self.padre = padre
self.acción = acción
def es_raíz(self):
return self.padre is None
def sucesor(self, acción):
Nodo = self.__class__
return Nodo(acción.aplicar(self.estado), self, acción)
def solución(self):
if self.es_raíz():
acciones = []
else:
acciones = self.padre.solución()
acciones.append(self.acción.nombre)
return acciones
def __str__(self):
return 'Estado: {}'.format(self.estado)
class NodoConProfundidad(NodoSimple):
def __init__(self, estado, padre=None, acción=None):
super().__init__(estado, padre, acción)
if self.es_raíz():
self.profundidad = 0
else:
self.profundidad = padre.profundidad + 1
def __str__(self):
return 'Estado: {0}; Prof: {1}'.format(self.estado, self.profundidad)
class NodoConHeurística(NodoSimple):
def __init__(self, estado, padre=None, acción=None):
super().__init__(estado, padre, acción)
if self.es_raíz():
self.profundidad = 0
self.coste = 0
else:
self.profundidad = padre.profundidad + 1
self.coste = padre.coste + acción.coste_de_aplicar(padre.estado)
self.heurística = self.f(self)
@staticmethod
def f(nodo):
return 0
def __str__(self):
return 'Estado: {0}; Prof: {1}; Heur: {2}; Coste: {3}'.format(
self.estado, self.profundidad, self.heurística, self.coste)
class BúsquedaGeneral:
def __init__(self, detallado=False):
self.detallado = detallado
if self.detallado:
self.Nodo = NodoConProfundidad
else:
self.Nodo = NodoSimple
self.explorados = ListaNodos()
def es_expandible(self, nodo):
return True
def expandir_nodo(self, nodo, problema):
return (nodo.sucesor(acción)
for acción in problema.acciones_aplicables(nodo.estado))
def es_nuevo(self, nodo):
return (nodo not in self.frontera and
nodo not in self.explorados)
def buscar(self, problema):
self.frontera.vaciar()
self.explorados.vaciar()
self.frontera.añadir(self.Nodo(problema.estado_inicial))
while True:
if not self.frontera:
return None
nodo = self.frontera.sacar()
if self.detallado:
print('{0}Nodo: {1}'.format(' ' * nodo.profundidad, nodo))
if problema.es_estado_final(nodo.estado):
return nodo.solución()
self.explorados.añadir(nodo)
if self.es_expandible(nodo):
nodos_hijos = self.expandir_nodo(nodo, problema)
for nodo_hijo in nodos_hijos:
if self.es_nuevo(nodo_hijo):
self.frontera.añadir(nodo_hijo)
class BúsquedaEnAnchura(BúsquedaGeneral):
def __init__(self, detallado=False):
super().__init__(detallado)
self.frontera = ColaNodos()
class BúsquedaEnProfundidad(BúsquedaGeneral):
def __init__(self, detallado=False):
super().__init__(detallado)
self.frontera = PilaNodos()
self.explorados = PilaNodos()
def añadir_vaciando_rama(self, nodo):
if self:
while True:
último_nodo = self.pop()
if último_nodo == nodo.padre:
self.append(último_nodo)
break
self.append(nodo)
self.explorados.añadir = types.MethodType(añadir_vaciando_rama,
self.explorados)
class BúsquedaEnProfundidadAcotada(BúsquedaEnProfundidad):
def __init__(self, cota, detallado=False):
super().__init__(detallado)
self.Nodo = NodoConProfundidad
self.cota = cota
def es_expandible(self, nodo):
return nodo.profundidad < self.cota
class BúsquedaEnProfundidadIterativa:
def __init__(self, cota_final, cota_inicial=0, detallado=False):
self.cota_inicial = cota_inicial
self.cota_final = cota_final
self.detallado = detallado
def buscar(self, problema):
for cota in range(self.cota_inicial, self.cota_final):
bpa = BúsquedaEnProfundidadAcotada(cota, self.detallado)
solución = bpa.buscar(problema)
if solución:
return solución
class BúsquedaPrimeroElMejor(BúsquedaGeneral):
def __init__(self, f, detallado=False):
super().__init__(detallado)
self.Nodo = NodoConHeurística
self.Nodo.f = staticmethod(f)
self.frontera = ColaNodosConPrioridad()
self.explorados = ListaNodos()
self.explorados.__contains__ = types.MethodType(
lambda self, nodo: any(x.estado == nodo.estado and
x.heurística <= nodo.heurística
for x in self),
self.explorados)
class BúsquedaÓptima(BúsquedaPrimeroElMejor):
def __init__(self, detallado=False):
def coste(nodo):
return nodo.coste
super().__init__(coste, detallado)
class BúsquedaAEstrella(BúsquedaPrimeroElMejor):
def __init__(self, h, detallado=False):
def coste(nodo):
return nodo.coste
def f(nodo):
return coste(nodo) + h(nodo)
super().__init__(f, detallado)
|
af96e03ed2f237582cab288b6dd423ea09857039 | lovecure/py_test | /day2.2-var.py | 982 | 3.546875 | 4 | # -*- coding: utf-8 -*-
n = 123
f = 456.789
s1 = 'Hello,world'
s2 = 'Helo,\'Adam\''
s3 = r'''Hello,
Lisa!'''
s4 = 'Hello,"Bart"'
print(n)
print(f)
print(s1)
print(s2)
print(s3)
print(s4)
print ('True is:',True)
print ('False is:',False)
print('3>2 is:',3>2)
print('3>5 is:',3>5)
print('True and True is:',True and True)
r'''只有所有都为True,and结果才为"True"'''
print('True and False is:',True and False)
print('False and False is:',False and False)
print('5>3 and 3>1 is:',5>3 and 3>1)
print('True or True is:',True or True)
print('False or True is:',False or True)
print('False or False is:',False or False)
print('5>3 or 1>3 is:',5>3 or 1>3)
print('not True is:',not True)
print('not False is:',not False)
print('not 1>2 is',not 1>2)
age = 20
if age >= 18:
print('adult')
else:
print('teenager')
a = 123 #a是整数
print(a)
t_007 = 'T007' #t_007是字符串
print(t_007)
Answer = True #Answer是布尔值
print(Answer)
哈哈 = '大傻瓜'
print(哈哈)
|
b37606444c1fb9f60ca5efbcec093ccc10946ed8 | UMassPlecprep/ShoppingCart | /backups/auto_corrector.py | 1,120 | 3.84375 | 4 | # Being built...
# Slightly better correcting
# Rather than just finding letter similarities, it looks for substring similarities
def advancedGuessing(list_of_people, name):
confidence = {prof : 0 for prof in list_of_people}
# Find common substrings
for prof in list_of_people:
name_iterator = iter(name)
last_position = 0
on_a_roll = False
# Iterate until the iterator has no next() value
while 1:
# Find any substrings in name that're in prof as well
try:
on_a_roll = False
letter = next(name_iterator)
while letter in prof:
confidence[prof] += on_a_roll
on_a_roll = True
letter += next(name_iterator)
except:
break
# Greater size difference, less confident
confidence[prof] -= abs(len(name) - len(prof)) * 0.1
# Initial confidence rating is done
# Now, enhance confidence level based on size, letters given (not in substring), etc.
return max(confidence,key=confidence.get)
|
3b64db7db4ec638a168afd5ba896b113ff466907 | AbhishekBhattacharya/Python-MOOC | /matrixmultiply.py | 468 | 3.640625 | 4 | def matmult (A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
return
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
return C
|
4aa8c209c3b54723b198b405cdb2fff6d78c5a07 | kandura/logicaprogramacao | /prova2.py | 327 | 3.828125 | 4 | def nota_do_aluno():
print("Média do aluno é:")
primeiranota = (input(7))
segundanota = (input(6))
terceiranota = (input(8))
return (primeiranota + segundanota + terceiranota) / 3
nota_do_aluno()
N = int(input(7))
lista = [4,5,2,8,6,3,7]
def funcao_da_lista():
i = 0
while i < N:
num = input(7)
|
c35d93f5359f710db0bb6d3db7f4c8af1724b1e9 | umberahmed/hangman- | /index.py | 586 | 4.25 | 4 | # This program will run the game hangman
# random module will be used to generate random word from words list
import random
# list of words to use in game
list_of_words = ["chicken", "apple", "juice", "carrot", "hangman", "program", "success", "hackbright"]
# display dashes for player to see how many letters are in the word to guess
print random.choice(list_of_words)
def greet_user():
"""greets user to hangman"""
print "Welcome to Hangman!"
greet_user()
def player():
"""stores player's name"""
name = input("What's your name? ")
return name
player()
|
aa9010cbb6ecdcec92ba34816ceb8c6bd15cea73 | mihalyvaghy/tdd_katas | /calculator/src/calculator.py | 1,250 | 3.8125 | 4 | import re
def find_delimiter(numbers):
if len(numbers) > 0:
if re.match("//(?P<delimiter>.)\n\d+(?:(?P=delimiter)\d+)*", numbers):
return numbers[2], numbers[4:]
elif re.match("//(?P<delimiter>\[.*\])\n\d+(?:(?P=delimiter)\d+)*", numbers):
first_newline = numbers.find("\n")
return numbers[3:first_newline-1], numbers[first_newline+1:]
else:
return ",", numbers
else:
return "_", "0"
def remove_big_numbers(numbers):
return [number for number in numbers if number <= 1000]
def split_numbers(numbers):
delimiter, numbers = find_delimiter(numbers)
print(delimiter, numbers)
numbers = re.sub("\n",delimiter,numbers)
numbers = [int(number) for number in numbers.split(delimiter)]
numbers = remove_big_numbers(numbers)
return numbers
def find_negative_numbers(numbers):
return [number for number in numbers if number < 0]
def raise_negative_numbers_error(numbers):
raise Exception("Negative numbers not allowed", *numbers)
def add(numbers):
numbers = split_numbers(numbers)
if len(negative_numbers := find_negative_numbers(numbers)) > 0:
raise_negative_numbers_error(negative_numbers)
return sum(numbers)
|
993385aca8c15768b4815cc7cddef93fde3c74a3 | yangzhoudeni/day01 | /src/21.while.py | 480 | 3.71875 | 4 | '''
while: 负责不固定次数的循环
while 条件:
xxxx
'''
# 制作 猜数字游戏:
import random
# 0-1000之间 随机获取数字
target = random.randint(0, 1000)
count = 0
while True:
count += 1
num = input('请猜测一个数字(0-1000):')
num = int(num)
if num == target:
print('恭喜您, 猜对了, 共猜了%s次' % count)
break
if num < target:
print('猜小了')
if num > target:
print('猜大了')
|
40378be4bb95c0670ebc830730efea465be5b0b2 | yangzhoudeni/day01 | /src/14.san.py | 201 | 3.84375 | 4 | # 三目运算符
# 条件 ? 真值 : 假值
# python坚持 语义化特点: 外国人习惯倒装语法
# 真值 if 条件真 else 假值
married = False
print('已婚' if married else '未婚')
|
10016492cba7d82dae2866612a5540686d810f43 | gsliu/python | /foo.py | 462 | 3.75 | 4 | #!/usr/bin/python
def in_the_fridge() :
try:
count = fridge[want_food]
except KeyError:
count = 0
return count
fridge = {"milk" :1, "banana" :2, "apple":3}
want_food = "aaa"
c = in_the_fridge()
print c
A = 1
B = 2
C = 3
if (A == 1 and
B == 2 and
C == 3) :
print('spam'*3)
while True:
reply = raw_input()
if (reply == "stop") :
break
print("input %s wrong" % (reply.upper()))
if "Py" in "Python" :
print "yes"
|
600cf2ecb0e69dd2b30f582f097d34af8cf0408c | gsliu/python | /checkpara.py | 356 | 3.96875 | 4 | #!/usr/bin/python
def check ( para={"aaa":1, "ccc":2}):
if type(para) == type( {}):
print "dict"
elif type(para) == type ([]):
print "list"
elif type(para) == type (""):
print "string"
else:
print "I don't know this type"
a = {"aaa":1, "bbb":2}
b = [1,2,3]
c = "jjjj"
check(a)
check(b)
check(c)
check()
|
8bcc479bb3a9fa632e730b052ffbf0cedc945195 | OlehPalka/Second_semester_labs | /labwork7/task345/4/document.py | 5,693 | 4.375 | 4 | """
This module contains classes which will help you to edit document.
"""
class Document:
"""
This class allows you to control editing of a basic document.
>>> doc = Document()
>>> doc.filename = "test_document"
>>> doc.filename
'test_document'
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('l')
>>> doc.insert('l')
>>> doc.insert('o')
>>> doc.save()
>>> doc.string
'hello'
"""
def __init__(self):
self.characters = []
self.cursor = Cursor(self)
self.filename = ''
def insert(self, character):
"""
This method allows you to insert something to your file.
>>> doc = Document()
>>> doc.filename = "test_document"
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('l')
>>> doc.insert('l')
>>> doc.insert('o')
>>> doc.string
'hello'
"""
self.characters.insert(self.cursor.position, character)
self.cursor.forward()
def delete(self):
"""
This method allows you to delete letter by moving cursor before it.
An error will raise if you would like to delete impossible character.
>>> doc = Document()
>>> doc.filename = "test_document"
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('l')
>>> doc.insert('l')
>>> doc.insert('o')
>>> doc.cursor.back()
>>> doc.delete()
>>> doc.string
'hell'
"""
try:
del self.characters[self.cursor.position]
except IndexError:
raise SymbolError("There is no symbol to delete.")
def save(self):
"""
THis method saves your file with given name.
Saving without a name is impossible.
In that case there will be an error.
"""
if self.filename == '':
raise NameError("The document you want to save hs no name!")
f = open(self.filename, 'w')
f.write(''.join(self.characters))
f.close()
@property
def string(self):
"""
This method returns symbols in file written together.
>>> doc = Document()
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('y')
>>> doc.string
'hey'
"""
return "".join((str(c) for c in self.characters))
class Cursor:
"""
this class creates cursor, which helps you with navigating in file.
>>> doc = Document()
>>> curs = Cursor(doc)
>>> curs.position
0
"""
def __init__(self, document):
self.document = document
self.position = 0
def forward(self):
"""
This method helps to move cursor forward in the file.
If you try to move cursor over the file error will be raised.
>>> doc = Document()
>>> curs = Cursor(doc)
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('y')
>>> curs.forward()
>>> curs.position
1
"""
if self.position + 1 > len(doc.string):
raise CursorError("Cursor went over the file")
self.position += 1
def back(self):
"""
This method helps to move cursor back in the file.
If you try to move cursor over the file error will be raised.
>>> doc = Document()
>>> curs = Cursor(doc)
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('y')
>>> curs.forward()
>>> curs.back()
>>> curs.position
0
"""
if self.position - 1 < 0:
raise CursorError("Cursor went over the file")
self.position -= 1
def home(self):
"""
This method moves cursor to the beggining of the row.
"""
while self.document.characters[self.position-1].character != '\n':
self.position -= 1
if self.position == 0:
break
def end(self):
"""
This method moves cursor to the end of the row.
"""
while self.position < len(self.document.characters) and self.document.characters[self.position].character != '\n':
self.position += 1
class Character:
"""
This class creates objects - stirng from your input.
>>> char = Character("a")
>>> char.character
'a'
"""
def __init__(self, character, bold=False, italic=False, underline=False):
assert len(character) == 1
self.character = character
self.bold = bold
self.italic = italic
self.underline = underline
def __str__(self):
"""
This method returns string from character.
>>> char = Character("a")
>>> char.__str__()
'a'
"""
bold = "*" if self.bold else ''
italic = "/" if self.italic else ''
underline = "_" if self.underline else ''
return bold + italic + underline + self.character
class CursorError(Exception):
def __init__(self, text):
self.text = text
class NameError(Exception):
def __init__(self, text):
self.text = text
class SymbolError(Exception):
def __init__(self, text):
self.text = text
if __name__ == "__main__":
doc = Document()
doc.filename = "test_document"
doc.insert('h')
doc.insert('e')
doc.insert('l')
doc.insert('l')
doc.insert('o')
print(doc.cursor.position)
doc.cursor.back()
doc.delete()
doc.delete()
doc.cursor.back()
doc.cursor.back()
doc.cursor.back()
doc.cursor.back()
doc.cursor.back()
print(doc.string)
|
1db2c36a281249ea00fa1328903ef8910a521845 | OlehPalka/Second_semester_labs | /labwork12/2/stack_to_queue.py | 824 | 3.71875 | 4 | """
Stack to queue converter.
"""
import copy
from arraystack import ArrayStack # or from linkedstack import LinkedStack
from arrayqueue import ArrayQueue # or from linkedqueue import LinkedQueue
def stack_to_queue(stack):
"""
This function returns queue from stack.
"""
stack_copy = copy.deepcopy(stack)
queue = ArrayQueue()
stack_lenth = len(stack_copy)
for _ in range(stack_lenth):
queue.add(stack_copy.pop())
return queue
stack = ArrayStack()
for i in range(10):
stack.add(i)
queue = stack_to_queue(stack)
print(queue)
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(stack)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(stack.pop())
# 9
print(queue.pop())
# 9
stack.add(11)
queue.add(11)
print(queue)
# [8, 7, 6, 5, 4, 3, 2, 1, 0, 11]
print(stack)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 11]
|
4896af0a999d2e29edcc559326c52a9efea0ca19 | OlehPalka/Second_semester_labs | /labwork10/2.py | 10,852 | 3.890625 | 4 |
import ctypes
class LifeGrid:
"""
Implements the LifeGrid ADT for use with the Game of Life.
"""
# Defines constants to represent the cell states.
DEAD_CELL = 0
LIVE_CELL = 1
def __init__(self, num_rows, num_cols):
"""
Creates the game grid and initializes the cells to dead.
:param num_rows: the number of rows.
:param num_cols: the number of columns.
"""
# Allocates the 2D array for the grid.
self._grid = Array2D(num_rows, num_cols)
# Clears the grid and set all cells to dead.
self.configure(list())
def num_rows(self):
"""
Returns the number of rows in the grid.
:return: the number rows in the grid.
"""
return self._grid.num_rows()
def num_cols(self):
"""
Returns the number of columns in the grid.
:return:Returns the number of columns in the grid.
"""
return self._grid.num_cols()
def configure(self, coord_list):
"""
Configures the grid to contain the given live cells.
:param coord_list:
:return:
"""
for rows in range(self._grid.num_rows()):
for col in range(self._grid.num_cols()):
self._grid.__setitem__((rows, col), "D")
for i in coord_list:
self._grid.__setitem__(i, "L")
return self._grid
def is_live_cell(self, row, col):
"""
Does the indicated cell contain a live organism?
:param row: row of the cell.
:param col: column of the cell.
:return: the result of check.
"""
return self._grid.__getitem__((row, col)) == "L"
def clear_cell(self, row, col):
"""
Clears the indicated cell by setting it to dead.
:param row: row of the cell.
:param col: column of the cell.
"""
self._grid.__setitem__((row, col), "D")
def set_cell(self, row, col):
"""
Sets the indicated cell to be alive.
:param row: row of the cell.
:param col: column of the cell.
"""
self._grid.__setitem__((row, col), "L")
def num_live_neighbors(self, row, col):
"""
Returns the number of live neighbors for the given cell.
:param row: row of the cell.
:param col: column of the cell.
:return:
"""
num_of_live = 0
for x_coor in range(3):
for y_coor in range(3):
try:
if self._grid.__getitem__((row - 1 + x_coor, col - 1 + y_coor)) == "L":
if row != row - 1 + x_coor or col != col - 1 + y_coor:
num_of_live += 1
except AssertionError:
continue
return num_of_live
def __str__(self):
"""
Returns string representation of LifeGrid
in form of:
DDLDD
DLDLD
DLDLD
DDLDD
DDDDD
Where D - dead cell, L - live cell
"""
result = ""
for row in range(self._grid.num_rows()):
for col in range(self._grid.num_cols()):
result += self._grid.__getitem__((row, col))
result += "\n"
return result[:-1]
# Implements the Array ADT using array capabilities of the ctypes module.
class Array:
# Creates an array with size elements.
def __init__(self, size):
assert size > 0, "Array size must be > 0"
self._size = size
# Create the array structure using the ctypes module.
PyArrayType = ctypes.py_object * size
self._elements = PyArrayType()
# Initialize each element.
self.clear(None)
# Returns the size of the array.
def __len__(self):
return self._size
# Gets the contents of the index element.
def __getitem__(self, index):
assert 0 <= index < len(self), "Array subscript out of range"
return self._elements[index]
# Puts the value in the array element at index position.
def __setitem__(self, index, value):
assert 0 <= index < len(self), "Array subscript out of range"
self._elements[index] = value
# Clears the array by setting each element to the given value.
def clear(self, value):
for i in range(len(self)):
self._elements[i] = value
# Returns the array's iterator for traversing the elements.
def __iter__(self):
return _ArrayIterator(self._elements)
# An iterator for the Array ADT.
class _ArrayIterator:
def __init__(self, the_array):
self._array_ref = the_array
self._cur_index = 0
def __iter__(self):
return self
def __next__(self):
if self._cur_index < len(self._array_ref):
entry = self._array_ref[self._cur_index]
self._cur_index += 1
return entry
else:
raise StopIteration
# Implementation of the Array2D ADT using an array of arrays.
class Array2D:
# Creates a 2 -D array of size numRows x numCols.
def __init__(self, num_rows, num_cols):
# Create a 1 -D array to store an array reference for each row.
self.rows = Array(num_rows)
# Create the 1 -D arrays for each row of the 2 -D array.
for i in range(num_rows):
self.rows[i] = Array(num_cols)
# Returns the number of rows in the 2 -D array.
def num_rows(self):
return len(self.rows)
# Returns the number of columns in the 2 -D array.
def num_cols(self):
return len(self.rows[0])
# Clears the array by setting every element to the given value.
def clear(self, value):
for row in range(self.num_rows()):
row.clear(value)
# Gets the contents of the element at position [i, j]
def __getitem__(self, index_tuple):
assert len(index_tuple) == 2, "Invalid number of array subscripts."
row = index_tuple[0]
col = index_tuple[1]
assert 0 <= row < self.num_rows() and 0 <= col < self.num_cols(), \
"Array subscript out of range."
array_1d = self.rows[row]
return array_1d[col]
# Sets the contents of the element at position [i,j] to value.
def __setitem__(self, index_tuple, value):
assert len(index_tuple) == 2, "Invalid number of array subscripts."
row = index_tuple[0]
col = index_tuple[1]
assert 0 <= row < self.num_rows() and 0 <= col < self.num_cols(), \
"Array subscript out of range."
array_1d = self.rows[row]
array_1d[col] = value
class DynamicArray:
"""A dynamic array class akin to a simplified Python list."""
def __init__(self):
"""Create an empty array."""
self._n = 0 # count actual elements
self._capacity = 1 # default array capacity
self._A = self._make_array(self._capacity) # low-level array
def __len__(self):
"""Return number of elements stored in the array."""
return self._n
def __getitem__(self, k):
"""Return element at index k."""
if not 0 <= k < self._n:
raise IndexError('invalid index')
return self._A[k] # retrieve from array
def append(self, obj):
"""Add object to end of the array."""
if self._n == self._capacity: # not enough room
self._resize(2 * self._capacity) # so double capacity
self._A[self._n] = obj
self._n += 1
def _resize(self, c): # nonpublic utitity
"""Resize internal array to capacity c."""
B = self._make_array(c) # new (bigger) array
for k in range(self._n): # for each existing value
B[k] = self._A[k]
self._A = B # use the bigger array
self._capacity = c
@staticmethod
def _make_array(c): # nonpublic utility
"""Return new array with capacity c."""
return (c * ctypes.py_object)() # see ctypes documentation
def insert(self, k, value):
"""Insert value at index k, shifting subsequent values rightward."""
# (for simplicity, we assume 0 <= k <= n in this verion)
if self._n == self._capacity: # not enough room
self._resize(2 * self._capacity) # so double capacity
for j in range(self._n, k, -1): # shift rightmost first
self._A[j] = self._A[j - 1]
self._A[k] = value # store newest element
self._n += 1
def remove(self, value):
"""Remove first occurrence of value( or raise ValueError)."""
# note: we do not consider shrinking the dynamic array in this version
for k in range(self._n):
if self._A[k] == value: # found a match!
for j in range(k, self._n - 1): # shift others to fill gap
self._A[j] = self._A[j + 1]
self._A[self._n - 1] = None # help garbage collection
self._n -= 1 # we have one less item
return # exit immediately
raise ValueError("value not found") # only reached if no match
# Program for playing the game of Life.
# Define the initial configuration of live cells.
INIT_CONFIG = [(1, 1), (1, 2), (2, 2), (3, 2)]
# Set the size of the grid.
GRID_WIDTH = 5
GRID_HEIGHT = 5
# Indicate the number of generations.
NUM_GENS = 8
def main():
# Constructs the game grid and configure it.
GRID_WIDTH = input("Enter grid width: ")
GRID_HEIGHT = input("Enter grid height: ")
NUM_GENS = input("Enter grid num of generations: ")
grid = LifeGrid(GRID_WIDTH, GRID_HEIGHT)
grid.configure(INIT_CONFIG)
# Plays the game.
draw(grid)
for _ in range(NUM_GENS):
evolve(grid)
draw(grid)
# Generates the next generation of organisms.
def evolve(grid):
# List for storing the live cells of the next generation.
live_cells = []
# Iterate over the elements of the grid.
for i in range(grid.num_rows()):
for j in range(grid.num_cols()):
# Determine the number of live neighbors for this cell.
neighbors = grid.num_live_neighbors(i, j)
# Add the (i,j) tuple to liveCells if this cell contains
# a live organism in the next generation.
if (neighbors == 2 and grid.is_live_cell(i, j)) or (neighbors == 3):
live_cells.append((i, j))
# Reconfigure the grid using the liveCells coord list.
grid.configure(live_cells)
# Prints a text based representation of the game grid.
def draw(grid):
return grid.__str__()
# Executes the main routine.
# main()
x = LifeGrid(5, 5)
print(draw(x))
print(x.num_live_neighbors(0, 0))
x.set_cell(0, 4)
x.set_cell(0, 3)
x.set_cell(1, 3)
x.set_cell(2, 3)
x.set_cell(2, 4)
x.set_cell(1, 4)
print(draw(x))
print(x.num_live_neighbors(1, 4))
|
046cf121410bcf4d686768c851facb314b9fa666 | OlehPalka/Second_semester_labs | /labwork5/5task/game.py | 3,528 | 4.21875 | 4 | """
This module contains classes for game.
"""
monst_count = 0
class Room:
"""
this class creates rooms in a game
"""
def __init__(self, name: str):
self.list_of_rooms = list()
self.name = name
self.descr = ""
self.character = None
self.room_item = None
def set_description(self, descr: str):
"""
This method sets a description of the room.
"""
self.descr = descr
return descr
def link_room(self, another_room: object, world_part: str):
"""
this method sets rooms conected with your`s.
"""
self.list_of_rooms.append(
(another_room.name, world_part, another_room))
return self.list_of_rooms
def get_details(self):
"""
This method gives information about room.
"""
print(self.name)
print("--------------------")
print(self.set_description(self.descr))
for i in self.list_of_rooms:
print("The " + i[0] + " is " + i[1])
if self.room_item != None:
print("The [" + self.room_item.name + "] is here - ", end="")
print(self.room_item.describe())
def move(self, command: str):
"""
This method allows you to movw to another room.
"""
for i in self.list_of_rooms:
if command == i[1]:
self = i[2]
return self
def set_character(self, character: object):
"""
This method sets an enemy to the room.
"""
self.character = character
def get_character(self):
"""
This method returns enemy.
"""
return self.character
def set_item(self, item: object):
"""
This method sets item to the room.
"""
self.room_item = item
def get_item(self):
"""
This method returns item.
"""
return self.room_item
class Enemy:
"""
This class creates enemies.
"""
def __init__(self, name: str, desc: str):
self.name = name
self.desc = desc
self.defeat = False
def describe(self):
"""
Enemy description.
"""
print(self.name + " is here!")
print(self.desc)
def set_conversation(self, convers):
"""
This method sets conversation.
"""
self.convers = convers
def set_weakness(self, weak):
"""
This method sets enemies weakness.
"""
self.weak = weak
def talk(self):
"""
This method prints setted talk.
"""
print("[" + self.name + " says]: " + self.convers)
def fight(self, weapon):
"""
This method returns a result of the fight.
"""
if weapon == self.weak:
self.defeat = True
return self.defeat
def get_defeated(self):
"""
This method returns a number of defeated enemies.
"""
global monst_count
monst_count += 1
return monst_count
class Item:
"""
This class cretes room items
"""
def __init__(self, name):
self.name = name
def set_description(self, descr):
"""
Item description.
"""
self.descr = descr
def describe(self):
"""
Returns item description.
"""
return self.descr
def get_name(self):
"""
returns item name.
"""
return self.name
|
69612c6e4aaf8674e47d8b074dbb22ddb6e996a8 | OlehPalka/Second_semester_labs | /labwork6/bird.py | 6,679 | 3.71875 | 4 | # class Bird:
# def __init__(self, name):
# self.name = name
# self.eggs = []
# def __repr__(self):
# if len(self.eggs) == 1:
# return f"{self.name} has {len(self.eggs)} egg"
# return f"{self.name} has {len(self.eggs)} eggs"
# def count_eggs(self):
# return len(self.eggs)
# def get_eggs(self):
# return self.eggs.copy()
# def fly(self):
# return "I can fly!"
# def lay_egg(self):
# self.eggs.append(Egg())
class Egg:
def __str__(self):
return "egg"
# class Penguin(Bird):
# def fly(self):
# return "No flying for me."
# def swim(self):
# return "I can swim!"
# class MessengerBird(Bird):
# def __init__(self, name, message=None):
# self.message = message
# super().__init__(name)
# def deliver_message(self):
# if self.message != None:
# return self.message
# return ""
# def get_local_methods(clss):
# import types
# # This is a helper function for the test function below.
# # It returns a sorted list of the names of the methods
# # defined in a class. It's okay if you don't fully understand it!
# result = []
# for var in clss.__dict__:
# val = clss.__dict__[var]
# if (isinstance(val, types.FunctionType)):
# result.append(var)
# return sorted(result)
# def test_bird_classes():
# print("Testing Bird classes...", end="")
# # A basic Bird has a species name, can fly, and can lay eggs
# bird1 = Bird("Parrot")
# assert (type(bird1) == Bird)
# assert (isinstance(bird1, Bird))
# assert (bird1.fly() == "I can fly!")
# assert (bird1.count_eggs() == 0)
# assert (str(bird1) == "Parrot has 0 eggs")
# # here changes
# assert (bird1.lay_egg() is None)
# eggs = bird1.get_eggs()
# egg = eggs.pop()
# assert (type(egg) == Egg)
# assert (isinstance(egg, Egg))
# # here changes ends
# assert (bird1.count_eggs() == 1)
# assert (str(bird1) == "Parrot has 1 egg")
# bird1.lay_egg()
# assert (bird1.count_eggs() == 2)
# assert (str(bird1) == "Parrot has 2 eggs")
# assert (get_local_methods(Bird) == [
# '__init__', '__repr__', 'count_eggs', 'fly', 'get_eggs', 'lay_egg'])
# # A Penguin is a Bird that cannot fly, but can swim
# bird2 = Penguin("Emperor Penguin")
# assert (type(bird2) == Penguin)
# assert (isinstance(bird2, Penguin))
# assert (isinstance(bird2, Bird))
# assert (bird2.fly() == "No flying for me.")
# assert (bird2.swim() == "I can swim!")
# bird2.lay_egg()
# assert (bird2.count_eggs() == 1)
# assert (str(bird2) == "Emperor Penguin has 1 egg")
# assert (get_local_methods(Penguin) == ['fly', 'swim'])
# # A MessengerBird is a Bird that can optionally carry a message
# bird3 = MessengerBird("War Pigeon", message="Top-Secret Message!")
# assert (type(bird3) == MessengerBird)
# assert (isinstance(bird3, MessengerBird))
# assert (isinstance(bird3, Bird))
# assert (not isinstance(bird3, Penguin))
# assert (bird3.deliver_message() == "Top-Secret Message!")
# assert (str(bird3) == "War Pigeon has 0 eggs")
# assert (bird3.fly() == "I can fly!")
# bird4 = MessengerBird("Homing Pigeon")
# assert (bird4.deliver_message() == "")
# bird4.lay_egg()
# assert (bird4.count_eggs() == 1)
# assert (get_local_methods(MessengerBird)
# == ['__init__', 'deliver_message'])
# print("Done!")
class Book:
def __init__(self, name, author, current_page, ):
def get_current_page()
def test_book_class():
print("Testing Book class...", end="")
# A Book has a title, and author, and a number of pages.
# It also has a current page, which always starts at 1. There is no page 0!
book1 = Book("Harry Potter and the Sorcerer's Stone",
"J. K. Rowling", 309)
assert (str(book1) == "Book<Harry Potter and the Sorcerer's Stone by " +
"J. K. Rowling: 309 pages, currently on page 1>")
book2 = Book("Carnegie Mellon Motto", "Andrew Carnegie", 1)
assert (str(book2) == "Book<Carnegie Mellon Motto by Andrew Carnegie: " +
"1 page, currently on page 1>")
# You can turn pages in a book. Turning a positive number of pages moves
# forward; turning a negative number moves backwards. You can't move past
# the first page going backwards or the last page going forwards
book1.turn_page(4) # turning pages does not return
assert (book1.get_current_page() == 5)
book1.turn_page(-1)
assert (book1.get_current_page() == 4)
book1.turn_page(400)
assert (book1.get_current_page() == 309)
assert (str(book1) == "Book<Harry Potter and the Sorcerer's Stone by " +
"J. K. Rowling: 309 pages, currently on page 309>")
book2.turn_page(-1)
assert (book2.get_current_page() == 1)
book2.turn_page(1)
assert (book2.get_current_page() == 1)
# You can also put a bookmark on the current page. This lets you turn
# back to it easily. The book starts out without a bookmark.
book3 = Book("The Name of the Wind", "Patrick Rothfuss", 662)
assert (str(book3) == "Book<The Name of the Wind by Patrick Rothfuss: " +
"662 pages, currently on page 1>")
assert (book3.get_bookmarked_page() == None)
book3.turn_page(9)
book3.place_bookmark() # does not return
assert (book3.get_bookmarked_page() == 10)
book3.turn_page(7)
assert (book3.get_bookmarked_page() == 10)
assert (book3.get_current_page() == 17)
assert (str(book3) == "Book<The Name of the Wind by Patrick Rothfuss: " +
"662 pages, currently on page 17, page 10 bookmarked>")
book3.turn_to_bookmark()
assert (book3.get_current_page() == 10)
book3.remove_bookmark()
assert (book3.get_bookmarked_page() == None)
book3.turn_page(25)
assert (book3.get_current_page() == 35)
book3.turn_to_bookmark() # if there's no bookmark, don't turn to a page
assert (book3.get_current_page() == 35)
assert (str(book3) == "Book<The Name of the Wind by Patrick Rothfuss: " +
"662 pages, currently on page 35>")
# Finally, you should be able to compare two books directly
book5 = Book("A Game of Thrones", "George R.R. Martin", 807)
book6 = Book("A Game of Thrones", "George R.R. Martin", 807)
book7 = Book("A Natural History of Dragons", "Marie Brennan", 334)
book8 = Book("A Game of Spoofs", "George R.R. Martin", 807)
assert (book5 == book6)
assert (book5 != book7)
assert (book5 != book8)
book5.turn_page(1)
assert (book5 != book6)
book5.turn_page(-1)
assert (book5 == book6)
book6.place_bookmark()
assert (book5 != book6)
print("Done!")
|
774c04ecf2f74710147affadfbf180c0c53332af | OlehPalka/Second_semester_labs | /labwork5/3-4task/cache_webpage.py | 2,777 | 3.5625 | 4 | """
This is module which contains two classes for cashing data from the webpage.
"""
import doctest
from datetime import datetime
from urllib.request import urlopen
from time import time
clean = open("date_note.txt", 'a')
clean_1 = open("cash_note.txt", 'a')
with open("date_note.txt") as file:
if file.readlines() == []:
with open("date_note.txt", 'w') as file:
file.write("0000-00-00")
class Webpage_my:
"""
This class creates object - chash webpage.
This class works anyhow. As with ones defined object, as with different,
as after closing of the program.
>>> webpage = Webpage_my("https://www.fest.lviv.ua/uk/projects/uku/")
>>> webpage.url
'https://www.fest.lviv.ua/uk/projects/uku/'
"""
def __init__(self, url):
self.url = url
self._content = None
def rewriting_date_data(self, your_datetime):
"""
This method rewrites date of your visit to webpage
if it is bigger than previous.
"""
with open("date_note.txt", 'w') as file:
file.write(your_datetime)
file.close()
clean = open("cash_note.txt", 'w')
clean.close()
with open("cash_note.txt", 'w') as file:
file.write(str(self._content))
file.close()
@property
def content(self):
"""
This method returns html webpage from webpage or from cashed file
"""
with open("date_note.txt") as file:
for i in file:
date = i
file.close()
your_datetime = str(datetime.now())[:10]
if your_datetime > date:
if not self._content:
print("Retrieving New Page...")
self._content = urlopen(self.url).read()
self.rewriting_date_data(your_datetime)
return self._content
else:
with open("cash_note.txt") as file:
return file.readlines()[0]
class WebPage:
"""
This class creates object - chash webpage.
This class works with only ones defined object.
>>> webpage = WebPage("https://www.fest.lviv.ua/uk/projects/uku/")
>>> webpage.url
'https://www.fest.lviv.ua/uk/projects/uku/'
"""
def __init__(self, url):
self.url = url
self._content = None
self.your_date = str(datetime.now())[:10]
@property
def content(self):
"""
This method returns content from webpage according to the visit time.
"""
now_date = str(datetime.now())[:10]
if not self._content or self.your_date < now_date:
print("Getting from cache...")
self._content = urlopen(self.url).read()
self.your_date = now_date
return self._content
|
03e54e71a1ec4850263d789762e38b8230da3e5d | zhuguangxiang/LeetCode | /Topological Sort.py | 1,523 | 3.859375 | 4 | def topological_sort(unsorted_graph):
'''
idea from http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/
deal with a node only if all it's children are sorted, in other words, start from the latest appeared nodes, build
from there. A cycle is defined when in any iteration, none of the node can be solved, i.e 2 nodes point to each other
:param unsorted_graph: list[tuple(node, list[children])]
:return: sorted graph
'''
sorted_nodes = []
while graph_unsorted:
acyclic = False
for idx, (node, children_list) in enumerate(unsorted_graph):
for children in children_list:
if children not in sorted_nodes:
# do not deal with the node who has unsorted child
break
else:
# if all children been sorted, move this node to sorted list
acyclic = True
sorted_nodes.append(node)
unsorted_graph.remove(unsorted_graph[idx])
if acyclic is False:
raise RuntimeError("Cycle formed in the graph")
return sorted_nodes[::-1]
if __name__=="__main__":
graph_unsorted = [(2, []),
(5, [11]),
(11, [2, 9, 10]),
(7, [11, 8]),
(9, []),
(10, []),
(8, [9]),
(3, [10, 8])]
sorted_list = topological_sort(graph_unsorted)
print(sorted_list)
|
191b74137d4b0636cbf401c865279f8c33ef69b0 | zyavuz610/learnPython_inKTU | /python-100/104_numbers_casting.py | 1,147 | 4.46875 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Python 100 - Python ile programlamaya giriş
Python 101 - Python ile Ekrana Çıktı Yazmak, print() fonksiyonu
Python 102 - Değişkenler ve Veri Türleri
Python 103 - Aritmetik operatörler ve not ortalaması bulma örneği
Python 104 - Sayılar, bool ifadeler ve tür dönüşümü
Sayılar
x = -11 # int
y = 1.8 # float
z = 2+3j # complex
tipini öğrenme
print(type(x))
uç örnekler
a = 35656222554887711
x = 35e3 = 35* (10**3)
y = 12E4
z = -87.7e100
x = 3+5j
y = 5j
z = -5j
boolean
print(10 > 9)
print(10 == 9)
print(10 < 9)
Tür Dönüşümü
int, str, float, complex, bool
True değerli ifadeler, içinde değer olan
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
False değerli ifadeler, içerisinde değer olmayan
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Tip Dönüşümleri
x = int(1) # x = 1
y = int(2.8) # y = 2
z = int("3") # z = 3
x = float(1) # x = 1.0
y = float(2.8) # y = 2.8
z = float("3") # z = 3.0
w = float("4.2") # w = 4.2
x = str("s1") # x = 's1'
y = str(2) # y = '2'
z = str(3.0) # z = '3.0'
""" |
d9dd950f5a7dd35e1def63114c2f65ad6c2fb3da | zyavuz610/learnPython_inKTU | /python-100/113_while-loop.py | 1,322 | 4.28125 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
python-113: while döngüsü, 1-10 arası çift sayılar, döngü içinde console programı yazmak
Döngüler, programlamada tekrarlı ifadeleri oluşturmak için kullanılır.
türleri
for
while
döngülerin bileşenleri: 4 adet döngü bileşeni
1. başlangıç
2. bitiş (döngüye devam etme şartı bitişe ulaşmamak)
3. her tekrardan sonra yapılacak artış miktarı
4. dönünün gövdesi, tekrar edilecek ifade
for i in range(1,10):
print(i)
# for döngüsü analizi
# 1. başlangıç:0
# 2. bitiş: 10, 10 dahil değil değil, döngüye devam etmek için i<10 olmalı
# 3. artış miktarı:1
# 4. gövde: print() fonksiyonu (basit kodlar olabileceği gibi karmaşık kodlar da gövde kısmına yazılabilir. gövde kodları girintili bir şekilde döngü içine yazılır)
i = 1
while (i<10):
if(i%2==0):
print(i)
i +=1
"""
# console programı
lst = []
cond = True
while (cond):
s = input("İsim giriniz:")
if (s == "q"):
cond = False
else:
lst.append(s)
print(lst)
"""
cond while? s if? lst
True evet zafer hayır ['zafer']
True evet ali hayır ['zafer','ali']
True evet q evet, cond=False, .....
False hayır
""" |
bfdbff1ee6bfcad011283793b55052eafddd8375 | zyavuz610/learnPython_inKTU | /zylibs/zylib.py | 1,228 | 3.671875 | 4 | def isPrime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
#-----------------------------------------------
def allPrimes(n):
for i in range(2, n):
if isPrime(i):
yield i
################################################
def isPerfect(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
#-----------------------------------------------
def allPerfects(n):
for i in range(1, n):
if isPerfect(i):
yield i
################################################
def isPalindrome(n):
s = str(n)
return s == s[::-1]
#-----------------------------------------------
def allPalindromes(n):
for i in range(1, n):
if isPalindrome(i):
yield i
################################################
def fib(n):
f0,f1,i = 0,1,1
lst = [f0,f1]
while(i<n):
f0,f1,i = f1,f0+f1,i+1
lst.append(f1)
return lst
################################################
def fib2(n):
f0,f1,i = 0,1,1
lst = [f0,f1]
while(i<n):
f0,f1,i = f1,f0+f1,i+1
yield f1
################################################ |
36e6d2c05203975cc1c98d54921dcb92edf2960f | zyavuz610/learnPython_inKTU | /python-100/122_infinite-loop_examples.py | 778 | 4.03125 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Önceki dersler:
değişkenler ve operatörler
koşul ifadeleri: if,else
veri yapıları: string, liste
döngüler: for, while, iç içe döngüler
fonksiyonlar, fonksiyon parametreleri, örnekler
modüller, kendi modülümüzü yazmak
datetime, math
Python - 122 : yuzyıl hesaplama problemi
"""
#girilen yılın hangi yüzyıla ait olduğunu bul
# 1101-1200, 12.
# 1201-1300, 13.
# -100, -1.
# -199 - -100, -1. yy
while(1):
year = input("Year (Press 'q' to quit): ")
if year == 'q':
break
year = int(year)
if (year < 0):
cent = -int(-year/100)
elif (year%100 == 0):
cent = int(year/100)
else:
cent = int(year//100 + 1)
print("Year:",year,"Century:",cent)
print("Good bye...")
|
db985b8f58b3c1ba64a29f48c8b1c1620a22629f | zyavuz610/learnPython_inKTU | /python-100/131_set-intro.py | 1,266 | 4.21875 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Önceki dersler:
değişkenler ve operatörler
koşul ifadeleri: if,else
döngüler: for, while, iç içe döngüler
fonksiyonlar, modüller
veri yapıları:
string,
list,
tuple
...
set *
dict
Python - 131 : Set (Küme) Veri Yapısı
Set(s) - Küme(ler)
Matematikteki kümeler gibi verileri saklayan bir yapıdır
st = {"ali",1,True}
Özellikleri
. Birden çok değer içerir ancak her değer bir kere saklanır (tekrar yok)
. İndis ile erişim yoktur
. İçerik değiştirilemez, ancak eleman çıkarılıp başka bir eleman eklenebilir.
. { } parantezleri ile tanımlanır
. Küme elemanları sıralı değildir, elemanlar herhangi bir sırada olabilir.
. len() ile uzunluk bulunur
. küme elemanları herhangi bir türde olabilir (bool,int,str)
. set() yapıcı fonksiyonu vardır
. st = set(("python", "html", "java"))
"""
# bilinen programlama dilleri
ali_set = {'html','css','java','C','python','css'}
print(ali_set,len(ali_set))
veli_set = {'C','C++','java','python','java'}
print(veli_set,len(veli_set))
for e in ali_set:
print(e)
elm = 'C++'
if elm in ali_set:
print("Ali",elm,"biliyor")
else:
print("Ali",elm,"bilmiyor")
|
fa78bebb898f6de38d40a7b6c91798bfe03c2589 | kschultze/Learning-Python | /Assignment_1/assn_pt_2.py | 1,091 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 17 21:50:33 2016
@author: Schultze
first crack at computing the nth prime number
optimized for simplest code, not fastest run time
"""
#guess = 2
#
#n = 1
#while n < 1000:
# guess = guess + 1
# test = 1
#
# rem = 1
# while rem != 0:
# rem = guess%test
# test = test + 1
#
# if test == guess:
# prime = guess
# n = n + 1
#
#print(prime)
#second part of assignment: prove that the product of primes < n is always e**n
#and this ratio converges on 1 as n increases
import math
n = 2
primeSum = math.log(2)
i = 1
while i < 1000:
n = n + 1
test = 1
rem = 1
while rem != 0:
test = test + 1
rem = n%test
if test == n:
prime = n
primeSum = primeSum + math.log(prime)
i = i + 1
print('n = ' + str(n))
print('primeSum = ' +str(primeSum))
print('ratio = ' +str(primeSum/n))
#Ideas for building on code
# loop to run through lots of n's then store and plot the results of the
# ratio to see it approach 1 |
5c7aeb4928ee50fafc67f0e7075b88af0971af83 | kschultze/Learning-Python | /Assignment_2/diaphantene2_rev1.py | 1,267 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
07/26/16
@Schultze
Script to calculate chicken nuggets combinations
If nuggets are sold in packs of 6, 9, and 20, what combinations are required to
get exactly n nuggets. AKA, all solutions to the diopnantene equation:
6A + 9B + 20C = n for a given n
This is an update to diahpantene_rev1.py in which it calculates the largest number
of nuggets that can't be bought with the combination 6, 9, and 20.
"""
A = 6
B = 9
C = 20
maxTest = 200
isPossible = ()
for n in range(1,maxTest+1):
maxA = n//A
maxB = n//B
maxC = n//C
match = False
for numA in range(0,maxA + 1):
for numB in range(0,maxB + 1):
for numC in range(0,maxC + 1):
total = numA*A + numB*B + numC*C
if total == n:
match = True
if match:
isPossible += (1,)
else:
isPossible += (0,)
if sum(isPossible[-6:]) == 6: #as long as 6 in a row are found, any greater combination can be found
print ('Largest number of McNuggets that cannot be bought in exact quantity: ' + str(n-6))
break
if n == maxTest:
print('No result found up to ' + str(maxTest) + ' McNuggets, try increasing maxTest') |
91677c621750609fdb858b0db7617e604707e125 | kschultze/Learning-Python | /Misc/polackPoker.py | 5,130 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 24 17:34:25 2017
@author: kschultze
"""
import numpy
import random
import copy
def rollDice(player, playerNames, numPlayers, quarters):
"""
prompt user to input the roll and adjust everyone's quarters
inputs
player - int = index of player rolling
quarters - list = list of quarters each player has
returns
quarters2 - list = updated quarters list
"""
quarters2 = copy.copy(quarters)
leftPlayer = (player + 1)%numPlayers
rightPlayer = (player - 1)%numPlayers
roll = raw_input("Enter %s's roll (no spaces)\n" %playerNames[player])
for i in roll:
if i == '4':
quarters2[player] = quarters2[player] - 1
elif i == '5':
quarters2[player] = quarters2[player] - 1
quarters2[leftPlayer] = quarters2[leftPlayer] + 1
elif i == '6':
quarters2[player] = quarters2[player] - 1
quarters2[rightPlayer] = quarters2[rightPlayer] + 1
else:
pass
return quarters2
def playPP(numPlayers, playerNames = 'default'):
"""
input player names as a list of strings in the order they will play
"""
if playerNames == 'default':
playerNames = [str(x + 1) for x in range(numPlayers)]
quarters = [3]*numPlayers
playersLeft = len([x for x in quarters if x > 0])
player = numPlayers - 1
while True:
while playersLeft > 1:
player = (player + 1)%numPlayers #modular division - cycles through players
if quarters[player] > 0:
#rollDice(player, playerNames, numPlayers, quarters)
quarters = autoRoll(player, numPlayers, quarters)
playersLeft = len([x for x in quarters if x > 0])
player = int(numpy.nonzero(quarters)[0]) #select player with quarter(s) remaining
#rollDice(player, playerNames, numPlayers, quarters) #final roll for win
quarters = autoRoll(player, numPlayers, quarters)
playersLeft = len([x for x in quarters if x > 0])
if playersLeft <= 0:
#print 'no Winner' #todo, restart game for 'double pot' scenario
return -1
elif playersLeft == 1 and player == int(numpy.nonzero(quarters)[0]): #player rolled safe and wins
#print 'Player %s wins!' %playerNames[player]
return player
else:
#passes to next player for final roll or back to while loop if more than 1 person has quarters
pass
def autoRoll(player, numPlayers, quarters):
quarters2 = copy.copy(quarters) #avoid mutating original
leftPlayer = (player + 1)%numPlayers
rightPlayer = (player - 1)%numPlayers
roll = []
#only roll the same number of dice as quarters player has
for i in range(quarters2[player]):
roll.append(random.randint(1,6))
#print roll
for i in roll:
if i == 4:
quarters2[player] = quarters2[player] - 1
elif i == 5:
quarters2[player] = quarters2[player] - 1
quarters2[leftPlayer] = quarters2[leftPlayer] + 1
elif i == 6:
quarters2[player] = quarters2[player] - 1
quarters2[rightPlayer] = quarters2[rightPlayer] + 1
else:
pass
return quarters2
def singleQuarter(numPlayers, numRounds):
numWins = (numPlayers + 1)*[0] #last entry is when no player wins
for i in range(numRounds):
winner = None
quarters = [0]*numPlayers
quarters[0] = 1
player = 0
while winner == None:
currentQuarters = copy.copy(quarters)
quarters = autoRoll(player, numPlayers, quarters)
#safe roll
if quarters == currentQuarters:
winner = player
#rolled a 4
elif len([x for x in quarters if x > 0]) == 0:
winner = -1
else:
player = int(numpy.nonzero(quarters)[0])
numWins[winner] += 1
for i in range(len(numWins)):
numWins[i] = numWins[i]/float(numRounds) #convert to win fraction
return numWins
#result of simulating 100 million rounds:
#[0.53124785, 0.09370925, 0.03124571, 0.09378041, 0.25001678]
#[0.53049691, 0.09149945, 0.01828357, 0.01827123, 0.09147946, 0.24996938]
#[0.53034319, 0.09105486, 0.01605794, 0.00535664, 0.01607882, 0.09110872, 0.24999983]
#[0.53040645, 0.09099703, 0.01572068, 0.00313416, 0.00313112, 0.01568113, 0.0910056, 0.24992383]
#[0.53033638, 0.09099488, 0.01563257, 0.00275938, 0.0009247, 0.00275334, 0.01562248, 0.09095831, 0.25001796]
def repeatFullGames(numPlayers,numRounds):
numWins = (numPlayers + 1)*[0] #last entry is when no player wins
winner = None
for i in range(numRounds):
winner = playPP(numPlayers)
numWins[winner] += 1
for i in range(len(numWins)):
numWins[i] = numWins[i]/float(numRounds) #convert to win fraction
return numWins
#for numPlayers in [3,4,5,6,7,8]:
# results = repeatFullGames(numPlayers, 1000000)
# print numPlayers
# print results
|
7a8acb8640e52e9c22c80aaa2ecfab7c2619d30c | groovyspaceman/algo_training | /temp/pair_of_elements_with_sum_x.py | 336 | 4 | 4 | """
Given an integer X and a list L, find the first pair in L whose sum is X
"""
def find_pair_with_sum(X, l):
"""
Returns a tuple with indexes of both elements or None if there is no pair
"""
return (0, 1)
l = [3, 34, 4, 12, 5, 2]
X = 5
print ("In the list {} items {} sum {}".format(l, find_pair_with_sum(X,l), X)) |
420932cc759072920300246b5c0b9720dd629b0e | petr-tik/lscc | /mars_kata.py | 1,531 | 3.84375 | 4 | #! usr/bin/env python
"""
from london software craftsmanship group meetup on python katas
"""
from collections import deque
import unittest
import random as rnd
class Rover(object):
def __init__(self, x, y, direction, min_val, max_val, num_obstacles):
self.x = x
self.y = y
self.direction = direction
self.min_val = min_val
self.max_val = max_val
self.num_obstacles = num_obstacles
self.obstacles = []
for obs in xrange(self.num_obstacles):
new = (rnd.randint(min_val, max_val), rnd.randint(min_val, max_val))
if new not in self.obstacles:
self.obstacles.append(new)
def rotate(self, way):
options = deque(["N", "W", "S", "E"])
if way == "L":
options.rotate(1)
elif way == "R":
options.rotate(-1)
self.direction = options[0]
def move(self):
if self.direction == "N":
self.y += 1
elif self.direction == "S":
self.y -= 1
elif self.direction == "W":
self.x -= 1
elif self.direction == "E":
self.x += 1
def read(self, string):
for x in string:
if x == "L" or x == "R":
self.rotate(x)
elif x == "M":
if (self.x, self.y) in self.obstacles:
print "N"
else: self.move()
else:
raise "Error"
return self.x, self.y, self.direction
|
8cd0e8f2fa5f4af240a800f9a0da13725f2989b7 | tuw-robotics/tuw_geometry | /test/test_cases.py | 924 | 3.5 | 4 | #!/usr/bin/env python
import unittest
import tuw_geometry as tuw
class TestPoint2D(unittest.TestCase):
def runTest(self):
p = tuw.Point2D(3,2)
self.assertEqual(p.x, 3, 'incorrect x')
self.assertEqual(p.y, 2, 'incorrect y')
self.assertEqual(p.h, 1, 'incorrect h')
p = tuw.Point2D(3,2,3)
self.assertEqual(p.x, 3, 'incorrect x')
self.assertEqual(p.y, 2, 'incorrect y')
self.assertEqual(p.h, 3, 'incorrect h')
class TestPose2D(unittest.TestCase):
def runTest(self):
pose = tuw.Pose2D(3,2,0)
p0 = tuw.Point2D(0,0)
self.assertEqual(pose.x, 3, 'incorrect x')
self.assertEqual(pose.y, 2, 'incorrect y')
# self.assertEqual(pose.h, 1, 'incorrect h')
# do some things to my_var which might change its value...
# self.assertTrue(my_var)
if __name__ == '__main__':
unittest.main()
|
33f3c44f5558e7f6af212ddeef9022d1b582b0ee | JanikaScheuer/Janika | /aufgabe_1.py | 1,240 | 3.59375 | 4 | def encode(message, key):
# static variables
msg_len = len(message)
alfa = 'abcdefghijklmnopqrstuvwxyz'
out_message = ''
for letter in message:
if letter.lower() not in alfa:
print('invalid letter')
break
if letter == letter.lower():
# search letter position in alphabet
letter_pos = alfa.index(letter)
# rules for translating shift to letter position
if key > msg_len:
shift = key % msg_len
elif key < msg_len:
shift = msg_len ** key
elif key == msg_len:
shift = key + msg_len
else:
shift = key
new_letter_pos = letter_pos + shift
# make position stay in alphabet
if new_letter_pos > 25:
new_letter_pos = new_letter_pos % 25
# Get new letter and add to output message
new_letter = alfa[new_letter_pos]
else:
new_letter = letter
out_message = out_message + new_letter
return out_message
message_list = [
['SSSSSlkjlkjlkjsdfdFFF', 8],
['asFFfasfasf', 2],
['ljikMMMsdlg', 623],
['luuuukjsdf', 8],
]
for msg in message_list:
output_message = encode(msg[0], msg[1])
print(output_message) |
026a13ce0636a032257396aa79b6d91e98331300 | akashraut1/PYTHON | /Basic Python/file open read.py | 417 | 3.59375 | 4 | fo = open("Akash.txt", "rw+")
#print ("Name of the file: ", fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print ("Read Line: %s" % (line))
# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print ("Read Line: %s" % (line))
# Close opend file
fo.close() |
300c0fb47e6201cc6480159b11cd7f12a39320b8 | robertDurst/huffman_compression | /huffman.py | 5,248 | 3.734375 | 4 | # @robertDurst @ 2020
# Implementation of Huffman Coding:
# https://en.wikipedia.org/wiki/Huffman_coding
from collections import Counter
from utils import encodeASCII, decToBin, binToDec, writeBytesToFile, readBytesFromFile, Node
"""
A completely compressed file is formatted as so:
[padding length][header][encodeding][padding]
"""
def compress(uncompressed):
# first count frequencies of each character
count = Counter(uncompressed)
# use frequency as index and keep a second index array to keep track of indices
index = []
freqToNode = {}
for k in count:
v = count[k]
if not v in freqToNode:
freqToNode[v] = []
index.append(v)
freqToNode[v].append(Node(data=k))
# sort in ascending order
index = sorted(index)
# continuously merge until one node remains
while len(index) > 1 or len(freqToNode[index[0]]) > 1:
# grab first value and key
keyNode1, val1 = freqToNode[index[0]].pop(0), index[0]
# check if index has more, if not delete
if len(freqToNode[val1]) == 0:
del freqToNode[val1]
index.pop(0)
# grab second value and key
keyNode2, val2 = freqToNode[index[0]].pop(), index[0]
# check if index has more, if not delete
if len(freqToNode[val2]) == 0:
del freqToNode[val2]
index.pop(0)
# comine keys and vals to make a "merged" node
combinedVal = val1 + val2
combinedKey = Node(left=keyNode1, right=keyNode2)
# put it in the list, checking if it is a new node
if not combinedVal in freqToNode:
freqToNode[combinedVal] = []
index.append(combinedVal)
# make sure to resort since this may not be largest val
index = sorted(index)
# now we can add the new node
freqToNode[combinedVal].append(combinedKey)
# perform a recursive, preorder traversal, creating a table of characters to
# their bit code
table = {}
def traverseTree(tree, byteStr):
if tree.data != None:
table[tree.data] = byteStr
return
traverseTree(tree.left, byteStr + "0")
traverseTree(tree.right, byteStr + "1")
# now with an array formatted tree, we need to create a table for encoding
tree = freqToNode[index[0]][0]
traverseTree(tree, "")
# compress the str
compressedStr = ""
for c in uncompressed:
compressedStr += table[c]
headerSansPadding = compressHeader(table)
# padding length in header is 8 bits so it is not needed for thic
paddingLen = (8 - len(headerSansPadding + compressedStr) % 8)
padding = "".join(["0"] * paddingLen)
header = decToBin(paddingLen) + headerSansPadding
return header + compressedStr + padding
"""
My approach to compressing the header is as follows:
[key] : 8 bits normal ascii representation
[length] : 3 bits, length of the huffman coding bits
[value] : 1-8 bits, huffamn coding
"""
def compressHeader(table):
length = decToBin(len(table))
klv = ""
for key in table:
k = encodeASCII(key)
v = table[key]
l = decToBin(len(v))
klv += k + l + v
return length + klv
def decompress(compressed):
# first decompress the header and generate a tree
[tree, compressed] = decompressHeader(compressed)
letters, root, cur = [], tree, tree
# using the tree, decode each chracter from the given "bit paths"
for c in compressed:
cur = (cur.left, cur.right)[c == '1']
if (cur.data != None):
letters.append(cur.data)
cur = root
return "".join(letters)
# helper for grabbing x bits
def takeBits(compressed, numBits):
return [compressed[:numBits], compressed[numBits:]]
# helper for generating the tree from the decompressed header. Takes a path and
# creates each of the nodes in the path, finally placing the char at a leaf
def insertIntoTree(tree, data, path):
cur = tree
for c in path:
# "0" --> Left
if c == "0":
if not cur.left:
cur.left = Node()
cur = cur.left
# "1" --> Right
else:
if not cur.right:
cur.right = Node()
cur = cur.right
# at the end of the path, place character in a leaf node
cur.data = data
def decompressHeader(compressed):
# remove padding
padding, compressed = takeBits(compressed, 8)
padding = binToDec(padding)
compressed = compressed[:len(compressed)-padding]
# determine number of values in tree
numKlv, compressed = takeBits(compressed, 8)
numKlv = binToDec(numKlv)
# decode tree pairs and insert into tree
tree = Node()
for _ in range(numKlv):
k, compressed = takeBits(compressed, 8)
data = chr(binToDec(k))
l, compressed = takeBits(compressed, 8)
path, compressed = takeBits(compressed, binToDec(l))
insertIntoTree(tree, data, path)
return [tree, compressed] |
25ece7125e51196b3eb866a06f6cea0910357f81 | genetica/pylator | /testScripts/textTest.py | 1,879 | 3.75 | 4 | ###############################################################################
# Tests to see if string concatenation is slower or faster than
# the .format function.
#
# Conclusion.
# Using variables does slow string creation down(+-5%) but the difference
# between concatenation and .format function is not statistically
# significant. .format is slower than the str() function for floats
# as it apply more formatting to the number than the str() function.
#
###############################################################################
import time
text1 = "Toets hier"
text2 = "Nog so bietjie"
N = 100000
iterations = 100
avg = 0
avg_lst = [0,0,0,0]
for k in range(iterations):
avg = 0
t1 = time.time()
for i in range(N):
text = "Toets hier" + str(i*0.1) + "Nog so bietjie"
t2 = time.time()
avg += t2 - t1
avg_lst[2] += avg
#print("{}".format(avg/N))
avg = 0
t1 = time.time()
for i in range(N):
text = text1 + str(i*0.1) + text2
t2 = time.time()
avg += t2 - t1
avg_lst[0] += avg
avg = 0
t1 = time.time()
for i in range(N):
text = "{} {} {}".format("Toets hier",i*0.1, "Nog so bietjie")
t2 = time.time()
avg += t2 - t1
avg_lst[3] += avg
#print("{}".format(avg/N))
avg = 0
t1 = time.time()
for i in range(N):
text = "{} {} {}".format(text1,i*0.1,text2)
t2 = time.time()
avg += t2 - t1
avg_lst[1] += avg
#print("{}".format(avg/N))
#print("{}".format(avg/N))
for i in range(4):
avg_lst[i] = avg_lst[i]/iterations
print("Variable String Addition: {}".format(avg_lst[0]/min(avg_lst)))
print("Variable Format function: {}".format(avg_lst[1]/min(avg_lst)))
print(" String Addition: {}".format(avg_lst[2]/min(avg_lst)))
print(" Format function: {}".format(avg_lst[3]/min(avg_lst)))
|
a462d5adc2feb9f2658701a8c2035c231595f81e | kristinejosami/first-git-project | /python/numberguessing_challenge.py | 911 | 4.3125 | 4 | '''
Create a program that:
Chooses a number between 1 to 100
Takes a users guess and tells them if they are correct or not
Bonus: Tell the user if their guess was lower or higher than the computer's number
'''
print('Number Guessing Challenge')
guess=int(input('This is a number guessing Challenge. Please enter your guess number:'))
from random import randint
number=int(randint(1,100))
# number=3
if number==guess:
print('Congratulations! Your guess is correct. The number is {} and your guess is {}.'.format(number, guess))
elif number<guess:
print("Sorry, your number is incorrect. The number is {} and your guess is {}."
" Your guess is greater than the number. Please try again.".format(number,guess))
else:
print("Sorry, your number is incorrect. The number is {} and your guess is {}. "
"Your guess is lesser than the number. Please try again.".format(number, guess))
|
2fb684421bc670eaeea15e5c73cb997ce7aa3f04 | ardKelmendi/rf_codingtask | /models.py | 1,383 | 3.890625 | 4 | #Class contains 3 classes that are used to store the data
class Product:
def __init__(self, id, name, unit, quantity, category, measurement_unit):
self.id = id
self.name = name
self.unit = unit
self.quantity = quantity
self.category = category
self.measurement_unit = measurement_unit
'''method to return a JSON format'''
@property
def serialize(self):
return {
'id': self.id,
'name': self.name,
'unit': self.unit,
'quantity': self.quantity,
'category': self.category,
'measurement_unit': self.measurement_unit
}
class Sales:
def __init__(self, id, product, units_sold, sold_date):
self.id = id
self.product = product
self.units_sold = units_sold
self.sold_date = sold_date
'''method to return a JSON format'''
@property
def serialize(self):
return {
'id': self.id,
'name': self.product,
'units sold': self.units_sold,
'sold date': self.sold_date,
}
class Category:
def __init__(self, id, name):
self.id = id
self.name = name
'''method to return a JSON format'''
@property
def serialize(self):
return {
'id' : self.id,
'name': self.name,
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.