blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
619d472babe28a2b1b577f5b2edcd1787319015b | Dan-Freda/python-challenge | /PyBank/main.py | 2,911 | 3.828125 | 4 | # Py Me Up, Charlie (PyBank)
# Import Modules/Dependencies
import os
import csv
# Initialize the variables
total_months = 0
net_total_amount = 0
monthy_change = []
month_count = []
greatest_increase = 0
greatest_increase_month = 0
greatest_decrease = 0
greatest_decrease_month = 0
# Set path to csv file
budgetdata_csv = os.path.join('Resources', 'budget_data.csv')
output_file = os.path.join('Analysis', 'output.txt')
# Open and Read csv file
with open(budgetdata_csv, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
row = next(csvreader)
# Calculate the total number number of months, net total amount of "Profit/Losses" and set relevant variables
previous_row = int(row[1])
total_months += 1
net_total_amount += int(row[1])
greatest_increase = int(row[1])
greatest_increase_month = row[0]
# Reach each row of data
for row in csvreader:
total_months += 1
net_total_amount += int(row[1])
# Calculate change in "Profits/Losses" on a month-to-month basis
revenue_change = int(row[1]) - previous_row
monthy_change.append(revenue_change)
previous_row = int(row[1])
month_count.append(row[0])
# Calculate the greatest increase in Profits
if int(row[1]) > greatest_increase:
greatest_increase = int(row[1])
greatest_increase_month = row[0]
# Calculate the greatest decrease in Profits (i.e. greatest instance of losses)
if int(row[1]) < greatest_decrease:
greatest_decrease = int(row[1])
greatest_decrease_month = row[0]
# Calculate the average change and the date
average_change = sum(monthy_change)/ len(monthy_change)
highest = max(monthy_change)
lowest = min(monthy_change)
# Print Analysis
print(f"Financial Analysis")
print(f"-----------------------------")
print(f"Total Months: {total_months}")
print(f"Total: ${net_total_amount}")
print(f"Average Change: ${average_change:.2f}")
print(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})")
print(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})")
# Export results to text file
# Specify the file to write to
output_file = os.path.join('Analysis', 'output.txt')
# Open the file using "write" mode. Specify the variable to hold the contents.
with open(output_file, 'w',) as txtfile:
# Write to text file
txtfile.write(f"Financial Analysis\n")
txtfile.write(f"-----------------------------\n")
txtfile.write(f"Total Months: {total_months}\n")
txtfile.write(f"Total: ${net_total_amount}\n")
txtfile.write(f"Average Change: ${average_change:.2f}\n")
txtfile.write(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})\n")
txtfile.write(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})\n")
|
6d801c0c47cc82cfc27305b341cf93fd98c23d99 | sagarsharma6/Python | /Assignment7.py | 549 | 4.125 | 4 |
#Ques 1
d={'1':'abc','2':'def','3':'ghi','4':'jkl'}
for key in d:
print(key,d[key])
#Ques 2
dic={}
dic2={}
for i in range(3):
name=input("Enter name of student: ")
print("Student",name,":")
for marks in range(3):
s=input("Enter subject: ")
m=int(input("Enter marks: "))
dic2[s]=m
dic[name]=dic2.copy()
dic2.clear()
nam=input("Enter student name whose marks you want to display: ")
for i in dic.keys():
if(nam==i):
print(dic[nam])
break
else:
print("Name",nam,"not found")
|
1d74bf7c4a91ece932509e867a361e83985ff548 | trunghieu11/PythonAlgorithm | /Contest/Codeforces/Codeforces Round #313 (Div. 1)/B.py | 527 | 3.59375 | 4 | __author__ = 'trunghieu11'
def check(first, second):
if first == second:
return True
if len(first) % 2 == 1:
return False
half = len(first) / 2
return (check(first[:half], second[half:]) and check(first[half:], second[:half])) or (check(first[:half], second[:half]) and check(first[half:], second[half:]))
def solve(first, second):
return "YES" if check(first, second) else "NO"
if __name__ == '__main__':
first = raw_input()
second = raw_input()
print solve(first, second) |
0b6f31cd241f134ffc6830374d42d1b7286722dc | sathishmtech01/pyspark_learning | /scripts/spark/dataframe/spark_df_schema_specify.py | 1,269 | 3.671875 | 4 | # Import data types
from pyspark.sql.types import *
from pyspark.sql import Row,SparkSession
import os
os.environ['SPARK_HOME'] = "/home/csk/sparkscala/spark-2.4.0-bin-hadoop2.6/"
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
print(spark)
sc = spark.sparkContext
# Load a text file and convert each line to a Row.
lines = sc.textFile("data/people.txt")
parts = lines.map(lambda l: l.split(","))
# Each line is converted to a tuple.
people = parts.map(lambda p: (p[0], int(p[1].strip())))
print(people.collect())
# The schema is encoded in a string.
schemaString = "name age"
print(schemaString)
fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split()]
fields = [StructField("name", StringType(), True),StructField("age", IntegerType(), True)]
print(fields)
schema = StructType(fields)
print(schema)
# Apply the schema to the RDD.
schemaPeople = spark.createDataFrame(people, schema)
# Creates a temporary view using the DataFrame
schemaPeople.createOrReplaceTempView("people")
# SQL can be run over DataFrames that have been registered as a table.
results = spark.sql("SELECT name FROM people")
results.show() |
ec014aec05eecb32dc63928acb64d7f5b0b3db38 | ohmygodlin/snippet | /leetcode/00547friend_circles.py | 1,222 | 3.703125 | 4 | M = [[1,1,0],
[1,1,0],
[0,0,1]]
class UnionFind:
parent = {}
size = {}
cnt = 0
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
self.cnt = len(M)
for i in range(self.cnt):
self.parent[i] = i
self.size[i] = 1
n = len(M)
for i in range(n - 1):
for j in range(i+1, n):
if (M[i][j] == 1):
self.union(i, j)
return self.cnt
def find(self, x):
while x != self.parent[x]:
x = self.parent[x]
self.parent[x] = self.parent[self.parent[x]]
return x
def union(self, p, q):
root_p = self.find(p)
root_q = self.find(q)
if (root_p == root_q):
return
if self.size[root_p] < self.size[root_q]:
self.parent[root_p] = root_q
self.size[root_q] +=self.size[root_p]
else:
self.parent[root_q] = root_p
self.size[root_p] +=self.size[root_q]
self.cnt -= 1
def connected(self, p, q):
return self.find(p) == self.find(q)
uf = UnionFind()
print uf.findCircleNum(M) |
03f8ad9e173fc903bbb81effcf65747cbb0b320a | santiagbv/AlgorithmicToolbox | /Week3-Greedy-algorithms/largest_number.py | 277 | 3.59375 | 4 | #Maximum Salary
import functools
def compare(elem1, elem2):
if elem1 + elem2 > elem2 + elem1:
return -1
else:
return 1
n = int(input())
A = input().split(' ')
A.sort(key=functools.cmp_to_key(compare))
ans = ''
for i in A:
ans = ans + i
print(ans) |
c439f7645b94d7b2f44396c2fb54348da04bf6e4 | IrynaDemianenko/Python_Intro_Iryne | /max_in_row.py | 1,062 | 3.90625 | 4 | def max_in_row(table):
max_element = 0
for row in table:
if table[row]>=table[row+1]:
max_element += table[row]
return max_element
"""
Дан двумерный массив(список списков, таблица) размером n x m.
Каждая строка состоит из m элементов, всего n строк.
Верните список, где будут максимумы для каждой строки таблицы:
1-ый элемент это максимум в первой строке таблицы, 2-ой максимум во второй и тд
"""
pass
def test_max_in_row():
assert max_in_row([
[1, 2, 3, 4],
[1, -1, 1, 2],
[-4, -3, -2, -1]
]) == [4, 2, -1]
assert max_in_row([
[1],
[2],
[3],
]) == [1, 2, 3]
assert max_in_row([
[-1, -2, -3, -4],
[-1, -1, -1, -2],
[-4, -3, -2, -1]
]) == [-1, -1, -1]
print("Tests passed")
|
3bcb0bec3709cbf1b37e6de063fdcb017c7e88cc | michaellu4527/python_step_49 | /Step49.py | 170 | 3.546875 | 4 | import bubblesort
list1 = [67, 45, 2, 13, 1, 998]
list2 = [89, 23, 33, 45, 10, 12, 45, 45, 45]
print (bubblesort.bubbleSort(list1))
print (bubblesort.bubbleSort(list2)) |
2df4ae6515a7ae1224ecfb588cb32612f0e2dab3 | miggleliu/leetcode_my_work | /037_sudoku_solver.py | 2,008 | 3.78125 | 4 | class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
# return a list containing all the possible valid digits for a grid
def valid_digits(row, col):
valid_digits = {1,2,3,4,5,6,7,8,9}
# check rows and columns
for i in range(9):
if board[row][i] != '.' and int(board[row][i]) in valid_digits:
valid_digits.remove(int(board[row][i]))
if board[i][col] != '.' and int(board[i][col]) in valid_digits:
valid_digits.remove(int(board[i][col]))
# check subboxes
row_s = row-row % 3
col_s = col-col % 3
for i in range(3):
for j in range(3):
if board[row_s+i][col_s+j] != '.' and int(board[row_s+i][col_s+j]) in valid_digits:
valid_digits.remove(int(board[row_s+i][col_s+j]))
return valid_digits
def solve(row, col):
if col == 9:
col = 0
row += 1
# reach the end, meaning that the solution is found
if row == 9:
return True
# go to the next grid if the current grid is given by the question
if board[row][col] != '.':
return solve(row, col + 1)
# DFS all possibilities
valids = valid_digits(row, col)
for i in valids:
board[row][col] = str(i)
if solve(row, col + 1):
return True
# backtrack if False
board[row][col] = '.'
return False
# main
solve(0, 0)
|
39c14a596ee9aa10a3f4cc00bc17ba7a609cfee3 | saetar/pyEuler | /not_done/euler_160.py | 977 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Jesse Rubin
"""
Factorial trailing digits
Problem 160
For any N, let subset_sums(N) be the last five digits before the trailing zeroes in N!.
For example,
9! = 362880 so subset_sums(9)=36288
10! = 3628800 so subset_sums(10)=36288
20! = 2432902008176640000 so subset_sums(20)=17664
Find subset_sums(1,000,000,000,000)
"""
from tqdm import tqdm
from math import log10
from bib import xrange
from bib.decorations import cash_it
def mull(a, b):
return a*b
@cash_it
def thingy(numb):
# print(numb)
# print(trailing)
if numb == 1:
return 1
# l = log10(numb)
# print(l)
f = (numb*thingy(numb-1))%1000000
while f %10 == 0:
f //= 10
# print(subset_sums)
return f
# return numb*thingy(numb-1)%1000000
a = thingy(9)
print(a)
from itertools import count
from tqdm import tqdm
for i in tqdm(xrange(1, 1000000), ascii=True):
a = thingy(i)
# thingy(numb=1000000000000)
|
c6e5680eee86da2157f13f51de66166c365ec1f9 | meimeilu/python | /152-ex.py | 427 | 3.71875 | 4 | def print_line(char,times):
print(char * times)
def print_lines():
"""打印单行分隔线
:param char 打印的字符参数
:param times 打印出来的次数
"""
row = 0
while row <= 5:
print_line("+",50)
row += 1
# print_lines()
def print_liness(char , times):
row = 0
while row <= 5:
print_line(char , times)
row += 1
print_line("+", 6)
|
8f9bd84f165ff4400179ed0cc7b607e3af32c4e1 | huangjiadidi/dfdc_deepfake_challenge | /training/pipelines/random_walk.py | 1,778 | 3.875 | 4 | import numpy as np
import random
part_id = []
# for i in range(9):
# part_id.append(i)
"""
define part id:
top-left = 0 - top-right = 1
\ /
left-eye = 2 - right-eye = 3
\ /
| nose = 4 |
/ \
mouth-left = 5 - mouth-right = 6
/ \
buttom-left = 7 - buttom-right = 8
define graph:
using a list to store the graph, each element indicates to one node.
The element store a sub-list, storing the nodes link to the the current node (see the links above)
As we can see, each node links to three neighbours, except the mouth, which has four.
The order of linked node is following the clockwise. (from left to right)
"""
# build the graph
part_id.append(1, 2, 7)
part_id.append(0, 3, 8)
part_id.append(0, 3, 4)
part_id.append(2, 1, 4)
part_id.append(2, 3, 5, 6)
part_id.append(4, 6, 7)
part_id.append(5, 4, 8)
part_id.append(0, 5, 7)
part_id.append(7, 6, 1)
# define naive random function
# part_id: the graph
# the number of iteration will preform
def random_walk(part_id, itre_num = 2):
path = []
# random pick a start point
current_point = random.randrange(9)
path.append(current_point)
for i in range(itre_num):
path.append(random.choice(part_id[current_point]))
return path
# modify the landmarks based on the result of random
def landmark_random_walk(landmarks, path):
modified_landmarks = []
for landmark in landmarks:
temp_list = []
for node in path:
temp_list.append(landmark[node])
modified_landmarks.append(temp_list)
return modified_landmarks |
75c3458878138203396dd9cf02665d7e4b85f2b0 | Ritvik19/CodeBook | /data/Algorithms/Memoization.py | 1,051 | 3.953125 | 4 | import time
class Memoize:
def __init__(self, f):
self.f = f
self.memo = {}
def __call__(self, *args):
if not args in self.memo:
self.memo[args] = self.f(*args)
return self.memo[args]
def factorial(k):
if k < 2:
return 1
return k * factorial(k - 1)
def fibonacci(n):
if n <= 2:
return n - 1
return fibonacci(n-1) + fibonacci(n-2)
m_factorial = Memoize(factorial)
m_fibonacci = Memoize(fibonacci)
if __name__ == '__main__':
print('Factorial:')
start = time.time()
print(factorial(500))
print(f'Time: {time.time() - start}\n')
print('Memoized Factorial:')
start = time.time()
print(m_factorial(500))
print(f'Time: {time.time() - start}\n')
print('Fibonacci:')
start = time.time()
print(fibonacci(40))
print(f'Time: {time.time() - start}\n')
print('Memoized Fibonacci:')
start = time.time()
print(m_fibonacci(40))
print(f'Time: {time.time() - start}\n')
|
261ce8f630820632021e5bbc8c1e9df01fd5a70c | TheMaksoo/Computer-Engineering-and-Science | /Exercise_1.py | 437 | 4.15625 | 4 |
# list of employees
employees = ("Max","Naru","Smol","Ginger","Devil","Bitz","Bear","Ruka","Khael","LRavellie")
# Prints list of employees
print(employees)
print("--------------")
# sorts employees alphabetical
Sortedemployees = sorted(employees)
# Prints employee list in alphabetical order
print(Sortedemployees)
print("--------------")
# prints amount of employees
print("employees =",len(Sortedemployees))
print("--------------") |
75878c5d76b2f6fa4e59ab98daf21701249faaa0 | Jongyeop92/BoardGameAI | /Othelo/OtheloBoard.py | 4,639 | 3.609375 | 4 | # -*- coding: utf8 -*-
import sys
sys.path.append("../Board")
from Board import *
BLACK = 'B'
WHITE = 'W'
class OtheloBoard(Board):
def __init__(self, width, height, FIRST=BLACK, SECOND=WHITE):
Board.__init__(self, width, height, FIRST, SECOND)
self.blackCount = 2
self.whiteCount = 2
self.board[height / 2 - 1][width / 2 - 1] = SECOND
self.board[height / 2 - 1][width / 2 ] = FIRST
self.board[height / 2 ][width / 2 - 1] = FIRST
self.board[height / 2 ][width / 2 ] = SECOND
def getPoint(self, marker):
if marker == self.FIRST:
return self.blackCount
else:
return self.whiteCount
def getPossiblePositionList(self, marker):
possiblePositionList = []
for y in range(self.height):
for x in range(self.width):
if self.board[y][x] == EMPTY:
isPossiblePosition = False
for directionPair in self.directionPairList:
for direction in directionPair:
dy, dx = direction
nowY, nowX = y, x
flipCount = 0
while True:
nowY += dy
nowX += dx
if not self.isInBoard(nowY, nowX) or self.board[nowY][nowX] == EMPTY:
flipCount = 0
break
elif self.board[nowY][nowX] == marker:
break
else:
flipCount += 1
if flipCount != 0:
possiblePositionList.append((y, x))
isPossiblePosition = True
break
if isPossiblePosition:
break
return possiblePositionList
def setMarker(self, marker, position):
if self.isValidPosition(marker, position):
y, x = position
self.board[y][x] = marker
if marker == self.FIRST:
self.blackCount += 1
else:
self.whiteCount += 1
self.flipMarker(position)
self.lastPosition = position
self.lastMarker = marker
return True
return False
def flipMarker(self, position):
y, x = position
marker = self.board[y][x]
for directionPair in self.directionPairList:
for direction in directionPair:
dy, dx = direction
nowY, nowX = y, x
flipPositionList = []
while True:
nowY += dy
nowX += dx
if not self.isInBoard(nowY, nowX) or self.board[nowY][nowX] == EMPTY:
flipPositionList = []
break
elif self.board[nowY][nowX] == marker:
break
else:
flipPositionList.append((nowY, nowX))
for flipPosition in flipPositionList:
flipY, flipX = flipPosition
self.board[flipY][flipX] = marker
flipCount = len(flipPositionList)
if marker == self.FIRST:
self.blackCount += flipCount
self.whiteCount -= flipCount
else:
self.blackCount -= flipCount
self.whiteCount += flipCount
def getNextPlayer(self):
if self.lastMarker == None or self.lastMarker == self.SECOND:
if self.getPossiblePositionList(self.FIRST) != []:
return self.FIRST
else:
return self.SECOND
else:
if self.getPossiblePositionList(self.SECOND) != []:
return self.SECOND
else:
return self.FIRST
def isWin(self):
if self.getPossiblePositionList(self.FIRST) == [] and self.getPossiblePositionList(self.SECOND) == []:
if self.getPoint(self.FIRST) > self.getPoint(self.SECOND):
return self.FIRST
elif self.getPoint(self.FIRST) < self.getPoint(self.SECOND):
return self.SECOND
else:
return DRAW
else:
return None
|
6ad58d93a43c7a44d57b2064eed887b8ace8afca | c4rl0sFr3it4s/Python_Basico_Avancado | /script_python/randint_input_usuario_condicao_composta_028.py | 538 | 4.03125 | 4 | '''randomize um valor inteiro entre (0, 5) entre com o valor do usuário
e mostre se o valor randomizado for igual ao do usuário, VENCEU, ou PREDEU'''
from random import randint
from time import sleep
computador = randint(0, 5)
print('{:-^40}'.format('JOGO DA ADIVINHAÇÃO'))
usuario = int(input('Digite um número de [0, 5]: '))
sleep(1)
print(f'Computador → {computador} ← | Usuário → {usuario} ←')
print('\033[1;32mVocê Venceu...\033[m' if computador == usuario else '\033[1;31mVocê Perdeu...\033[m')
print('{:-^40}'.format('FIM'))
|
6cc148c48488f10c692fb8583fa676d7b9ad2293 | minhazalam/py | /py dict fun and files/programs/var_scope.py | 744 | 4.03125 | 4 | # About : In this program we will se the scope resolution of variable
# * global variable
# * local variable
# Define square funcions
def square(num) :
sq = num * num
return sq
# Add sum of square fxn
def sum_of_square(fn, sn, tn) :
x = square(fn) # called square function
y = square(sn) # called square function
z = square(tn) # called square function
# calculates sum of squares
sos = x + y + z
# returns the sum
return sos
# prints sum of squares
print(sum_of_square(2, 3, 4))
# not defined globally sos
# print(sos) # results in error because sos is a local variable to sum_of_square
# here we declare
sos = 23 # global variable visible to whole program
print(sos) # prints the sos global variable |
39e95e01e176fcc0b3552d50c9c7d11c51eeead7 | qeedquan/challenges | /dailyprogrammer/164-easy-assemble-this-scheme-into-python.py | 1,686 | 3.9375 | 4 | #!/usr/bin/env python
"""
Description
You have just been hired by the company 'Super-Corp 5000' and they require you to be up to speed on a new programming language you haven't yet tried.
It is your task to familiarise yourself with this language following this criteria:
The language must be one you've shown interest for in the past
You must not have had past experience with the language
In order to Impress HR and convince the manager to hire you, you must complete 5 small tasks. You will definitely be hired if you complete the bonus task.
Input & Output
These 5 tasks are:
Output 'Hello World' to the console.
Return an array of the first 100 numbers that are divisible by 3 and 5.
Create a program that verifies if a word is an anagram of another word.
Create a program that removes a specificed letter from a word.
Sum all the elements of an array
All output will be the expected output of these processes which can be verified in your normal programming language.
Bonus
Implement a bubble-sort.
Note
Don't use a language you've had contact with before, otherwise this will be very easy. The idea is to learn a new language that you've been curious about.
"""
from collections import Counter
def hello_world():
print("Hello World")
def div_3_5():
r = []
i = 0
while len(r) < 100:
if i%3 == 0 and i%5 == 0:
r.append(i)
i += 1
return r
def anagram(a, b):
return Counter(a) == Counter(b)
def remove_char(s, c):
return s.replace(c, '')
def main():
hello_world()
print(div_3_5())
print(anagram("listen", "silent"))
print(remove_char("hello", "l"))
print(sum([1, 2, 3, 4, 5]))
main()
|
d4560415ae445bf0776d75b1a774f36e6526160a | Ronaldlicy/Python-Exercises | /PythonExercise38.py | 1,165 | 4.1875 | 4 | # There are two players, Alice and Bob, each with a 3-by-3 grid. A referee tells Alice to fill out one particular row in the grid (say the second row) by putting either a 1 or a 0 in each box, such that the sum of the numbers in that row is odd. The referee tells Bob to fill out one column in the grid (say the first column) by putting either a 1 or a 0 in each box, such that the sum of the numbers in that column is even.
# Alice and Bob win the game if Alice’s numbers give an odd sum, Bob’s give an even sum, and (most important) they’ve each written down the same number in the one square where their row and column intersect.
# Examples
# magic_square_game([2, "100"], [1, "101"]) ➞ False
# magic_square_game([2, "001"], [1, "101"]) ➞ True
# magic_square_game([3, "111"], [2, "011"]) ➞ True
# magic_square_game([1, "010"], [3, "101"]) ➞ False
# Two lists, Alice [row, "her choice"], Bob [column, "his choice"]
def magic_square_game(alice,bob):
alicechoice=[int(i) for i in alice[1]]
bobchoice=[int(i) for i in bob[1]]
return alicechoice[bob[0]-1]==bobchoice[alice[0]-1]
print(magic_square_game([2, "001"], [1, "101"])) |
337583c1e1a1bbb1e8f5296a9141b7f4082255cb | SergeKrstic/show-case | /HorizonCore/Graph/GraphNodeNav.py | 1,565 | 3.609375 | 4 | from HorizonCore.Graph.GraphNode import GraphNode
class GraphNodeNav(GraphNode):
"""
Graph node for use in creating a navigation graph. This node contains
the position of the node and a pointer to a BaseGameEntity... useful
if you want your nodes to represent health packs, gold mines and the like
"""
def __init__(self, index, position, extraInfo=None):
super().__init__(index)
# The node's position
self._position = position
# Often you will require a NavGraph node to contain additional information.
# For example a node might represent a pickup such as armor in which
# case _extraInfo could be an enumerated value denoting the pickup type,
# thereby enabling a search algorithm to search a graph for specific items.
# Going one step further, _extraInfo could be a pointer to the instance of
# the item type the node is twinned with. This would allow a search algorithm
# to test the status of the pickup during the search.
self._extraInfo = extraInfo
@property
def Position(self):
return self._position
@Position.setter
def Position(self, value):
self._position = value
@property
def ExtraInfo(self):
return self._extraInfo
@ExtraInfo.setter
def ExtraInfo(self, value):
self._extraInfo = value
def __repr__(self):
return "Index: {} | Position: ({:.2f}, {:.2f}) | ExtraInfo: '{}'".format(
self.Index, self.Position.X, self.Position.Y, self.ExtraInfo)
|
7bb96f989316b89c9f263a38c342ec562484b756 | bhagavantu/PlacementManagement | /source/placement.py | 4,329 | 4.125 | 4 | IT_companies={"Accenture":6.7, "Mindtree":7, "Apple":8.5, "Infosis":8}
core_companies={"Bosch":7.2, "Texas Instruments":8, "Siemens":8.5, "Schnieder":7.8}
companies={"Accenture":6.7, "Mindtree":7, "Apple":8.5, "Infosis":8, "Bosch":7.2, "Texas Instruments":8, "Siemens":8.5, "Schnieder":7.8}
class PlacementManagement:
"""
General Data Class for a place Management
"""
def __init__(self, name, usn,cgpa, email, branch, id_number, password):
"""
Constructor function for the Data Class
Executed by interpreter to create an instance of this class.
Attributes:
self.name -- name of the student (str)
self.usn -- usn of student
self.cgpa -- cgpa of the student (float)
self.email -- email id of student
self.branch -- branch of student (str)
self.id_no -- id number to create the placement data (int)
self.password -- password to access the account
"""
self.name = name
self.usn = usn
self.cgpa = (cgpa)
self.email = email
self.branch = branch
self.id_number = id_number
self.password= password
def eligibility(self):
# To check the elibility of student for the placement
if self.cgpa > 6.5:
print("Eligible for the placement")
else:
print("Sorry! not eligible for placement")
def applied(self):
# To find the various of companies applied by the student
print(companies)
for company, comp_cgpa in companies.items():
#It compares the student cgpa with company cgpa
if self.cgpa >= comp_cgpa:
print("applied company name is:",company)
else:
print("You not applied for this company:", company)
def details(self):
# To get the student full details
print("\n\ncandidate details:")
print("\t\tname:", self.name)
print("\t\tusn:", self.usn)
print("\t\temail:", self.email)
print("\t\tcgpa:", self.cgpa)
print("\t\tbranch:", self.branch,"\n\n")
#-----------------------------------
#child class1
class CoreCompanies(PlacementManagement):
def eligibility(self):
# To check the elibility of student for the placement
if self.cgpa < 7.0:
print(" sorry! minimum cgpa will be 7.0 ")
else:
print(" Hey! Congrats you are Eligible for the placement\nSelect 3 to Apply for company\n")
def applied(self):
# To find the various of companies available for the student
if self.cgpa>7.0:
print("\nHey! you can see here list of core companies and its cut off cgpa for job application:\n")
for key, value in core_companies.items():
#It compares the student cgpa with company cgpa
if self.cgpa >= value:
print("company name is",key,"Required cgpa is",value)
if self.cgpa<7.0:
print("\nsorry! companies are not available because you have less cgpa")
else:
company_name=input("\nif you wants to apply for job enter the campany name from the list of core companies as mentioned above :\n")
if company_name in core_companies.keys():
print("\nYou successfully applied for ",company_name)
print("\nThank you for choosing CoreCompanies\n ")
else:
print("\nSorry! what you entered company name is not available: ")
class ITCompanies(PlacementManagement):
def eligibility(self):
if self.cgpa < 6.5:
print(" sorry! minimum cgpa will be 6.5 ")
else:
print("Congrats you are Eligible for the placement\nSelect 3 to Apply for company\n")
def applied(self):
# To find the various of companies available for the student
if self.cgpa>6.5:
print("Hey! you can see here list of IT companies and Required cgpa for job application:\n")
for key, value in IT_companies.items():
#It compares the student cgpa with company cgpa
if self.cgpa >= value:
print("company name is",key,"Required cgpa is",value)
if self.cgpa<6.5:
print("\nsorry! companies are not available because you have less cgpa")
else:
company_name=input("\nif you wants to apply for job enter the campany name from the list of IT companies as mentioned above :\n")
if company_name in IT_companies.keys():
print("\nYou successfully applied for ",company_name)
print("\nThank you for choosing ITCompanies\n ")
else:
print("\nSorry! what you entered company name is not available:")
|
0d9978191ae42332c7b098542a87d436dc7c359b | chengke07/MyPython | /wintest1.py | 1,080 | 3.5625 | 4 |
import tkinter as tk
# 创建窗体
window = tk.Tk()
def call():
global window
window.destroy()
def main():
global window
# 设置主窗体大小
winWidth = 600
winHeight = 400
# 获取屏幕分辨率
screenWidth = window.winfo_screenwidth()
screenHeight = window.winfo_screenheight()
# 计算主窗口在屏幕上的坐标
x = int((screenWidth - winWidth)/ 2)
y = int((screenHeight - winHeight) / 2)
# 设置主窗口标题
window.title("主窗体参数说明")
# 设置主窗口大小
window.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
# 设置窗口宽高固定
window.resizable(0,0)
# 设置窗口图标
#window.iconbitmap("./image/icon.ico")
# 设置窗口顶部样式
window.attributes("-toolwindow", 0)
# 设置窗口透明度
window.attributes("-alpha",1)
#获取当前窗口状态
print(window.state())
window.protocol("WM_DELETE_WINDOW", call)
#循环更新
window.mainloop()
if __name__ == "__main__":
main() |
65768c24f811faa8f754cbf8860f6f77632b2f5a | Tirhas-source/PyPoll | /main.py | 2,301 | 3.765625 | 4 | import os
import csv
election_data = os.path.join("election_data.csv")
election_output = 'election_output.txt'
# A list to capture the names of candidates
total_votes = 0
candidates_name = []
each_vote = []
percent_vote = []
with open(election_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile)
csv_header = next(csvreader)
for row in csvreader:
total_votes= total_votes + 1
#find if candidate not in list or not then add to list -> if not just add
if row[2] not in candidates_name:
candidates_name.append(row[2])
index = candidates_name.index(row[2])
each_vote.append(1)
else:
index = candidates_name.index(row[2])
each_vote[index] = each_vote[index] + 1
# Add to percent_votes list
for votes in each_vote:
percentage = (votes/total_votes)
percentage = "{:.3%}".format(percentage)
percent_vote.append(percentage)
#print(percentage)
# Find the winning candidate
winner = max(each_vote)
index = each_vote.index(winner)
winning_candidate = candidates_name[index]
#Print results
print("Election Results")
print("--------------------------")
print("Total Votes: " + str(total_votes))
print("--------------------------")
for i in range(len(candidates_name)):
print(candidates_name[i] + ": " + (str(percent_vote[i])) + " (" + (str(each_vote[i])) + ")")
print("--------------------------")
print("Winner: " + winning_candidate)
print("--------------------------")
#output
with open (election_output, "w") as txt:
txt.write ("Election Results")
txt.write ("\n")
txt.write ("----------------------------")
txt.write ("\n")
txt.write ("Total Votes: " + str(total_votes))
txt.write ("\n")
txt.write ("--------------------------")
for i in range(len(candidates_name)):
line = ((candidates_name[i] + ": " + (str(percent_vote[i])) + " (" + (str(each_vote[i])) + ")"))
txt.write('{}\n'.format(line))
txt.write ("--------------------------")
txt.write ("\n")
txt.write ("Winner: " + winning_candidate)
txt.write ("\n")
txt.write ("--------------------------")
#https://www.tutorialspoint.com/How-to-write-multiple-lines-in-text-file-using-Python |
38f89c6b5bdaa173c9395d41f23d557493461d21 | Nexuist/Cellular-Conquest | /src/BaseClasses.py | 3,835 | 3.6875 | 4 | import pygame, math
class Coordinates:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(%s, %s)" % (self.x, self.y)
def __eq__(self, other): # Called by python to test equality
return True if (self.x == other.x and self.y == other.y) else False
def __sub__(self, other): # Called by python to handle subtraction
return Coordinates(self.x - other.x, self.y - other.y)
def as_array(self):
return [self.x, self.y]
class Color:
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
baby_blue = (137, 207, 240)
yellow = (255, 255, 0)
class Image_Sprite(pygame.sprite.Sprite):
def __init__(self, image_path, initial_position):
pygame.sprite.Sprite.__init__(self)
self.set_image(image_path)
self.rect.center = initial_position.as_array()
def set_image(self, image_path):
self.image = pygame.image.load(image_path).convert()
self.image.set_colorkey(pygame.Color(0, 0, 0)) # Any black pixels will be removed
self.rect = self.image.get_rect()
class Moving_Image_Sprite(Image_Sprite):
def __init__(self, position, target, speed, image_path):
Image_Sprite.__init__(self, image_path, position)
self.position = position # Coordinates
self.target = target # Coordinates
self.speed = speed # Float
def new_coordinates_to_move_to(self):
distance_to_target = self.target - self.position # Coordinates
magnitude = math.sqrt((distance_to_target.x**2 + distance_to_target.y**2)) # sqrt(x^2 + y^2) - Pythagorean theorem
if magnitude > 1:
return Coordinates(distance_to_target.x / magnitude, distance_to_target.y / magnitude)
else:
return None # Already at the desired target
def set_moving_image(self, image_path):
# This is needed because set_image sets the rect to (0, 0, W, H) which moves the entire image to the top left
Image_Sprite.set_image(self, image_path)
self.rect.center = self.position.as_array()
def update(self):
new_position = self.new_coordinates_to_move_to()
if new_position != None:
self.position.x += new_position.x * self.speed
self.position.y += new_position.y * self.speed
self.rect.center = self.position.as_array()
class Scene:
def __init__(self, args = None):
self.screen = pygame.display.get_surface()
self.background = pygame.Surface(self.screen.get_size())
self.background = self.background.convert()
self.background.fill(Color.white)
self.center_x = self.background.get_rect().centerx
self.center_y = self.background.get_rect().centery
self.center = Coordinates(self.center_x, self.center_y)
self.build_scene(args)
self.done = False
self.clock = pygame.time.Clock()
self.framerate = 60
self.event_loop()
def build_scene(self, args):
# Called on init
pass
def render_scene(self):
# Called every frame
pass
def click(self, position):
pass
def handle_event(self, event):
pass
def event_loop(self):
while not self.done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
self.click(position)
else:
self.handle_event(event)
self.background.fill(Color.white)
self.render_scene()
self.screen.blit(self.background, (0, 0))
pygame.display.flip()
self.clock.tick(self.framerate)
|
7073b92e05a67956bd79839908e4b82a6a021ffc | perhansson/rasp-pi | /flash-led.py | 899 | 3.765625 | 4 | import RPi.GPIO as GPIO
import time
import string
GPIO.setmode(GPIO.BCM)
led_green = 18
led_red = 22
GPIO.setup(led_green,GPIO.OUT)
GPIO.setup(led_red,GPIO.OUT)
while(True):
print("Tell me how many times to blink:")
s = input("How many times to blink the green LED? ")
print(s)
n_green_blink = int(s)
s = input("How many times to blink the red LED? ")
print("Ok, " + s + " times")
n_red_blink = int(s)
i = 0
n_max = max(n_green_blink,n_red_blink)
print ("Watch the LEDs")
while(i<n_max):
if i<n_red_blink:
GPIO.output(led_red,1)
if i<n_green_blink:
GPIO.output(led_green,1)
time.sleep(1)
if i<n_red_blink:
GPIO.output(led_red,0)
if i<n_green_blink:
GPIO.output(led_green,0)
time.sleep(1)
i=i+1
print("Done blinking ")
GPIO.cleanup()
|
999beb6ab7e774b62a16801e2248bf48bddb91ce | zoeechengg/text-mining | /analyze_data.py | 2,136 | 3.921875 | 4 | import string
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
def process_file(filename, skip_header):
"""Makes a histogram that contains the words from a file.
filename: string
skip_header: boolean, whether to skip the Gutenberg header
returns: map from each word to the number of times it appears.
"""
hist = {}
fp = open(filename, encoding='UTF8')
# if skip_header:
# skip_gutenberg_header(fp)
strippables = string.punctuation + string.whitespace
for line in fp:
line = line.replace('-', ' ')
for word in line.split():
word = word.strip(strippables)
word = word.lower()
# update the dictionary
hist[word] = hist.get(word, 0) + 1
return hist
def total_words(hist):
"""Returns the total of the frequencies in a histogram."""
return sum(hist.values())
def different_words(hist):
"""Returns the number of different words in a histogram."""
return len(hist)
def most_common(hist, excluding_stopwords = False):
"""Makes a list of word-freq pairs in descending order of frequency.
hist: map from word to frequency
returns: list of (frequency, word) pairs
"""
t = []
stopwords = process_file('delete_words.txt', skip_header=False)
stopwords = list(stopwords.keys())
for word, freq in hist.items():
if excluding_stopwords:
if word in stopwords:
continue
t.append((freq, word))
t.sort(reverse=True)
return t
def sentiment_analysis(filename):
score = SentimentIntensityAnalyzer().polarity_scores(filename)
print(score)
def main():
hist = process_file('tweets.txt', skip_header = False)
print(hist)
print('Total number of words:', total_words(hist))
print('Number of different words:', different_words(hist))
t = most_common(hist, excluding_stopwords = True)
print('The most common words are:')
for freq, word in t[0:40]:
print(word, '\t', freq)
print(sentiment_analysis('tweets.txt'))
if __name__ == '__main__':
main()
|
6a4491aeab30266fee782daa94c1032193ee5316 | narendraparigi1987/python | /exercises/Exceptions_1.py | 159 | 3.6875 | 4 | try:
a = int(input("Tell me one number: "))
b = int(input("Tell me another number: "))
print("a/b = ", a/b)
except:
print("Bug in user input.") |
f52f4b028644a7d7dee9e12ced267ecc54b64bb4 | chrisbubernak/ProjectEulerChallenges | /63_PowerfulDigitCounts.py | 416 | 3.65625 | 4 | # The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit number, 134217728=8^9, is a ninth power.
# How many n-digit positive integers exist which are also an nth power?
def solve(n):
finds = 0
for i in range(1, n):
for j in range(1, n):
power = i ** j
if len(str(power)) == j:
finds = finds + 1
return finds
# Check everything under 200 ^ 200
print(solve(200)) |
4609b5a3c01b544bcf14a9cdc89da77f3f19b369 | clivejan/python_fundamental | /exercises/ex_6_6_polling.py | 314 | 3.828125 | 4 | favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phli': 'python',
}
names = ['clive', 'sarah', 'david']
for name in names:
if name in favourite_languages.keys():
print(f"{name.title()}, thank you to response the poll.")
else:
print(f"Hi {name.title()}, please take the poll.")
|
e11ed34881624105d4e7bb09a33fb0763e6e2ebd | ValerieNayak/CodingInterview | /sorting_searching/quick_sort.py | 1,028 | 3.921875 | 4 | # Valerie Nayak
# 7/29/2020
# Quick Sort
# not complete yet
def quicksort(arr, left, right):
print(arr)
print('left', left)
print('right', right)
if left < right:
arr, mid = partition(arr, left, right)
print('mid', mid)
arr = quicksort(arr, left, mid-1)
arr = quicksort(arr, mid, right)
return arr
def partition(arr, left, right):
# print('pleft', left)
# print('pright', right)
ind1 = left
ind2 = right
part = arr[right]
while ind1 < ind2:
while arr[ind1] < part:
ind1 += 1
while arr[ind2] > part:
ind2 -= 1
if ind1 <= ind2:
arr = swap(arr, ind1, ind2)
ind1 += 1
ind2 -= 1
# print('arr', arr)
print(ind1)
return arr, ind1
def swap(arr, ind1, ind2):
temp = arr[ind1]
arr[ind1] = arr[ind2]
arr[ind2] = temp
return arr
a = [12, 11, 13, 5, 6, 7]
a = quicksort(a, 0, len(a)-1)
# a = [6, 5, 13, 11, 12, 7]
# a = quicksort(a, 2, 5)
print(a) |
1b29c2e0c533a76d456fb52e297deda7a18d159f | yogi-katewa/Core-Python-Training | /Exercises/Deepak/Class and Object/p1.py | 413 | 3.984375 | 4 | class Basic(object):
#initialize the variables
def __init__():
print("Constructor Called...")
#get Data From User
def get_String(self, arg):
self.arg = arg
#Print the variable of Class
def print_String(self):
return self.arg.upper()
obj = Basic(word)
#takes input from User
word = input("Enter String : ")
obj.get_String(word)
print (obj.print_String())
|
92eebf7e1791929540026f1430f34eb5a580b9c5 | yangxiyucs/leetcode_cn | /leetcode/07. reverse Int.py | 408 | 3.53125 | 4 | #反转int 数字
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#pop operation:
y, rev =abs(x), 0
boundary = 2**31-1 if x > 0 else 2**31
while y != 0:
rev = rev * 10 + y%10
if rev > boundary:
return 0
y = y // 10
return rev if x >0 else (-rev) |
075df3b0d465c7d0f5c5637275a198d59529d260 | kirkwood-cis-121-17/exercises | /chapter-8/ex_8_2.py | 1,179 | 3.875 | 4 | # Programming Exercise 8-2
#
# Program to total all the digits in a sequence of digits.
# This program prompts a user for a sequence of digits as a single string,
# calls a function to iterates through the characters and total their values,
# then displays the total.
# Define the main function
# Define local variables: an int to hold total and a string to hold input
# Get a string of digits as input from the user
# pass input to a function to sum the digits; assign the return value to total
# Display the total.
# Define a function to sum the digits in a string of digits
# This funtion receives a string of digits as a parameter,
# loops through the characters, converting them to integers and totaling them,
# then returns the total as an integer.
# Define local integer variables for total and digit value
# loop through each character in the string.
# if the character is a digit,
# Convert the character to an integer and assign to digit value
# Add digit value to total.
# Return the total.
# Call the main function to start the program.
|
6c7d546c1d6ebe45cc0d2f1a19b3275f5a72cbb7 | FridayAlgorithm/JW_study | /Baekjoon/queue/2164.py | 458 | 3.75 | 4 | from collections import deque
N = int(input())
deque = deque([i for i in range(1, N + 1)])
while(not (len(deque) == 1)):
deque.popleft()
move = deque.popleft()
deque.append(move)
print(deque[0])
#디큐 정의 확인
#popleft() pop()을 하되 왼쪽부터 값을 뺀다.
#버리고 맨앞의 숫자를 뒤로 옮기기만 잘해주면 되는 문제
#디큐안쓰면 카드배열 생성하고 하는데서 시간초과오류 오지게뜸
|
cc28e5de2953b0d64a4baff64d7a89af3e54e443 | ChangxingJiang/LeetCode | /1001-1100/1019/1019_Python_1.py | 715 | 3.703125 | 4 | from typing import List
from toolkit import ListNode
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
stack = []
ans = []
idx = 0
while head:
ans.append(0)
while stack and head.val > stack[-1][0]:
ans[stack.pop()[1]] = head.val
stack.append([head.val, idx])
idx += 1
head = head.next
return ans
if __name__ == "__main__":
print(Solution().nextLargerNodes(ListNode([2, 1, 5]))) # [5,5,0]
print(Solution().nextLargerNodes(ListNode([2, 7, 4, 3, 5]))) # [7,0,5,5,0]
print(Solution().nextLargerNodes(ListNode([1, 7, 5, 1, 9, 2, 5, 1]))) # [7,9,9,9,0,5,0,0]
|
05597db6bc9e7dc82fe26219ff91be14a23cfc2b | mridul0509/Cyber-security | /Assignment3/5.py | 150 | 3.8125 | 4 | list=[1,1,2,3,3]
b=0
for x in list:
if ((list[x]==3)and(list[x+1]==3)):
print("True")
b=1
break
if(b!=1):
print("False")
|
8eac576e1e83dceb1266dc5e22b98d6c34dcc158 | leoelm/interview_training | /9.11.py | 823 | 3.9375 | 4 | from BinaryTree import BinaryTree
t = BinaryTree(val = 1)
t.left = BinaryTree(val = 2, parent = t)
t.right = BinaryTree(val = 2, parent = t)
t.left.right = BinaryTree(val = 3, parent=t.left)
t.left.left = BinaryTree(val = 4, parent=t.left)
t.right.left = BinaryTree(val = 3, parent=t.right)
t.right.right = BinaryTree(val = 4, parent=t.right)
def inorder(t):
prev, result = None, []
while t:
next = None
if prev == t.parent:
if t.left:
next = t.left
else:
result.append(t.val)
next = t.right or t.parent
elif t.left is prev:
result.append(t.val)
next = t.right or t.parent
else:
next = t.parent
prev, t = t, next
return result
print(inorder(t))
|
d4347e903e22532799055bb307576f7a776efffe | LukeBreezy/Python3_Curso_Em_Video | /Aula 14/ex057.py | 394 | 4.03125 | 4 | sexo = ''
while 'M' != sexo != 'F': # Enquanto a pessoa não digitar uma opção válida, o laço não para
if sexo != '':
print('{} não é uma opção válida, digite M para masculino ou F para feminino.\n'.format(sexo))
sexo = input('Qual é o seu sexo? [M/F]: ').upper()
if sexo == 'M':
print('Você é um homem.')
else:
print('Você é uma mulher.')
|
bb1e22c7d5ddccdb909b0a667732b86c918ae581 | haidragon/Python | /Python基础编程/Python-08/文件/文件定位读写.py | 512 | 3.5625 | 4 | f = open("D:/Personal/Desktop/test.txt",'rb')
#读取3个字节
f.read(3)
print(f.tell())
#在读取3个字节的基础上再读取2个字节
f.read(2)
print(f.tell())
#将读取位置重新定位到开头第二个字节
f.seek(2,0)
print(f.tell())
#从第三个字节开始读取3个字节
temp = f.read(3)
print(temp)
print(f.tell())
#将读取位置重新定位到结尾前第三个字节
f.seek(-3,2)
print(f.tell())
#从第三个字节开始读取3个字节
temp = f.read()
print(temp)
print(f.tell())
|
79725b7bfb5864695b91e20ac2524f0f0730ccf6 | slimgol/searchEngine | /ranker.py | 4,627 | 4 | 4 | '''
This program is made for Python3.
Description: Rank a list of URLS; Return the ranked list of urls.
Approach:
(Note that this progam needs to be modified; this approach is nowhere where optimal.)
Accept a list of strings (These strings will have already been normalized).
Accept a raw input search term.
Normalize the input search term.
what is a good algorithm for ranking the documents?
Focus on documentation.
TODO:
Use a different sorting algorithm here; perhaps have different sorting algorithms.
The aim is to reduce computational cost. Thus, have two different sorting algorithms-
one that performs well on small datasets, and another that performs well on large datasets.
Note that we must define what "small" and "large" are.
Thus, we shall sort with the algorithm that will reduce the overall computational cost.
'''
#Sort a list of pairs (url, score).
def sortArrayDescending(newArray):
SIZE = len(newArray)
'''
Sort all of the elemnts by their score.
Note that the array stores pairs of the form (url, score).
'''
for i in range(SIZE):
for j in range(SIZE-i-1):
if (newArray[j][1]<newArray[j+1][1]):
#Swap elements
temp = newArray[j]
newArray[j] = newArray[j+1]
newArray[j+1] = temp
#Create a new array, containing only the urls in their ranked order.
url_array = []
for pair_ in newArray:
url_array.append(pair_[0])
#Return array of urls.
return url_array
'''
This function accepts a url, as well as the terms set as arguments and calculates the score
of the url, using the following:
Approach:
'''
from classifier import extractText, classifyText#Used for extracting text from a given url; used for
#clasifying an input string.
from normalizer import normalize_text#Used for text normalization.
from seedPages import topic_codes#A dictionary of topic codes (integer to topic string mapping).
#TODO: Fix the weighting scheme.
def urlScore(url, termsSet):
#Extract text from the url.
extractedString = extractText(url)
if (extractedString == None):
return None#Failed to extract text from the url.
#Normalize the string.
normalizedString = normalize_text(extractedString)
#Tokenize the string.
normalizedTokensList = normalizedString.split()
#Calcualte term frequencies; determine the number of tokens in the text.
termsFrequency = 0.0
numTokens = 0#Used to store the number of tokens.
'''
Todo: Determine whether or not the topic should be weighted heavier.
'''
for token in normalizedTokensList:
numTokens += 1
if (token in termsSet):
'''
The block code below is to be used if we use a weighting scheme.
Note that, for now, we won't be using a weighting scheme.
if (token == topic):
termsFrequency += topicWeight
else:
termsFrequency += 1
'''
termsFrequency += 1
#Note: The following condition should not occur.
if (numTokens == 0):
return None
#Return the score.
return termsFrequency/numTokens
def rankUrls(urlList, searchTerm):
topicNumber = classifyText(searchTerm)
if (topicNumber not in topic_codes):
return None #Error occured.
#Use the topic codes dictionary to extract the corresponding topic name.
topicName = topic_codes[topicNumber]
#Normalize the raw input search term.
normalizedSearchTerm = normalize_text(searchTerm)
#Create array of tokens from the normalized search term.
normalizedSearchTokens = normalizedSearchTerm.split()
#Determine if the topic is in the normalized search tokens.
if (topicName not in normalizedSearchTokens):
normalizedSearchTokens.append(topicName)#Add the topic to the list of search terms.
#Create empty array to store the urls and their associated scores.
scored_urls = []
#Iterate over all of the urls, and calculate the scores for the urls.
#Add the url and the score to the scored urls array.
'''
Iterate over all of the urls, calculate their scores, and then add them to the scored url array.
'''
for url in urlList:
score = urlScore(url, normalizedSearchTokens)
if (score == None):
continue#Skip the rest of instructions in the current iteration.
scored_urls.append((url, score))
#Rank the scored urls and return an array containing only the ranked urls.
'''
sortArrayDescending will accept a list of tuples of the form, (url, score), and return
the sorted list of urls, without the score. Hence, the function will just return the
sorted list of urls.
'''
return sortArrayDescending(scored_urls)
print(rankUrls(["https://www.youtube.com","http://windeis.anl.gov/guide/basics/","https://en.wikipedia.org/wiki/Solar_energy","https://www.energysage.com/solar/"],"wind wind wind"))
|
7d10a63c410d07bbd6571fb51759309fa3d6bd4e | shubhdashambhavi/learn-python | /org/shubhi/general/arithmeticOperator.py | 172 | 3.84375 | 4 | a=10
b=5
print('Addition:', a+b)
print('Substraction: ', a-b)
print('Multiplication:', a*b)
print('Division: ', a/b)
print('Remainder: ', a%b)
print('Exponential:', a ** b) |
e6b664797a0cea9558e609e0e6a7a4771fa98258 | uditrana/crossyRoadGame-539-hw2 | /exercises.py | 4,217 | 3.671875 | 4 | '''
solutions.py
##############################################
hw2: CS1 Content Game
##############################################
Collaborators:
Eugene Luo: eyluo
Omar Shafie: oshafie
Udit Ranasaria: uar
Preston Vander Vos: pvanderv
##############################################
This CS1 content game, Inspired from the crossing riddle: https://youtu.be/ADR7dUoVh_c ,
we decided to make the Wolf, Chicken, and Grain riddle. The object is to ferry each of these
animals/items across a river from the right to the left side without isolating either the chicken/grain or the
wolf/chicken. For each section, we have the student build up a part of the riddle until they have the final riddle
solved.
##############################################
Part 1: Functions
This exercise has the student get accustomed to function calls. We begin with a farmer with three bags of grain
trying to cross a river. The only restriction is that the farmer can only ferry one item across at a time.
##############################################
1A: Using the cross() function, which literally just moves the farmer across to the other side of the river.
Solution:
cross()
##############################################
1B: Learning to add and remove items with the add() and remove() functions.
Solution:
remove()
cross()
addGrain()
cross()
remove()
##############################################
1C: Implementing what we learned to solve the problem. Helper function is introduced.
Solution:
def moveGrain():
addGrain()
cross()
remove()
def solve():
moveGrain()
cross()
moveGrain()
cross()
moveGrain()
finish()
##############################################
Part 2: Conditionals
This exercise introduces the concept of limitations by changing the objects to a wolf, a chicken, and a bag of
grain. The student is now told the conditions to solve the riddle, and will be walked through step by step to
implement their own solution.
##############################################
2A: Introduction of an isFull bool. Imagine that the farmer can't tell if an item is on his boat. Use the bool
to check.
Solution:
def conditionalAdd():
if(not isFull):
addGrain()
##############################################
2B: This exercise checks to see if the game is won. The student needs to write a bool to check the win condition.
This is the introduction of the "and" operator.
Solution:
def finish():
if (wolfOnLeft and chickenOnLeft and grainOnLeft):
return True
else:
return False
##############################################
2C: Now the student has to write a condition to check if a move is valid. This is where the "or" operator is
introduced, and the student needs to be able to use both to check.
Solution:
def isValid():
if (wolfOnRight and chickenOnRight) or (chickenOnRight and grainOnRight) or (wolfOnLeft and chickenOnLeft)
or (chickenOnLeft and grainOnLeft):
return False
else:
return True
##############################################
Part 3: Loops
These exercises introduce the concept of loops in simplifying code.
##############################################
3A: This exercise calls back to 1C. Instead of three bags of grain, there are now thirty, and the student is
encouraged to move the bags across the river.
Solution:
for trip in range(30):
moveGrain()
cross()
##############################################
3B: This exercise implements animation. So far, the boat has jumped from shore to shore. In this situation,
you now step one at a time until you hit the shore.
Solution:
def cross():
while(notThere):
step()
##############################################
3C: This exercise introduces nested loops and combines the two previous exercises. The student now needs to
move the thirty bags of grain and step, both with loops.
Solution:
for trip in range(30):
addGrain()
while(notThere):
step()
remove()
while(notThere):
step()
##############################################
''' |
76fe88f42fe99e96c36c21fd977c5f2985095e0c | CTEC-121-Spring-2020/mod7-lab2-Ilya-panasev | /Mod7Lab2.py | 2,011 | 3.578125 | 4 | """
CTEC 121
Ilya Panasevich
Module 7 Lab 2
Class demos
"""
""" IPO template
Input(s): list/description
Process: description of what function does
Output: return value and description
"""
from math import *
def main():
# string formatting
'''
x = 1
y = 2
z = 3
print("x: {0}, y: {1}, z: {2}".format(x, y, z))
print("pi:", pi, "e:", e)
print("pi: {0:0.2f}, e: {1:0.2f}".format(pi, e))
print("pi: {0:10.2f}, e: {1:10.2f}".format(pi, e))
'''
# file processing
'''
print()
infile = open("sample.txt", r)
# print(infile)
'''
# get everything
'''
wholeFileText = infile.read()
print(wholeFileText)
wholeFileText = infile.read()
print("*", wholeFileText, "*", sep="")
infile.seek(5)
wholeFileText = infile.read()
print("*", wholeFileText, "*", sep="")
'''
# demo readlines()
'''
wholeFileTextAsList = infile.readlines()
print(wholeFileTextAsList)
for line in wholeFileTextAsList:
print(line.rstrip())
'''
# demo file a line at a time
'''
for line in infile:
print(line, end="")
print()
'''
# gets first line
'''
line = infile.readline()
while line != "": # equivalent to while not EOF
print(line.rstrip())
# get next line
line = infile.readline()
'''
'''
dict1 = {}
print(dict1)
dict2 = {}
dict2[1] = "one"
dict2[2] = "two"
dict2[3] = "three"
print(dict2)
dict1 = {1: "one", 2: "two", 3: "three"}
print(dict1)
print(dict2[2])
print()
print(dict1.keys())
print(dict1.values())
print(dict1.items())
'''
print()
num = [1234]
print("num:", num)
processListArgument(num)
print("num:", num)
print()
def processPrimitiveArgument(x):
print("input value:", x)
x = 99
print("final value:", x)
def processListArgument(l):
print("input list:", l)
l[0] = 99
print("final list:", l)
main() |
1ffbea03a8213a5bddf5d21440faee1807d6a668 | shoshin-programmer/former_work | /company_to_mail_templating_only_designation.py | 1,183 | 3.5 | 4 | import pandas as pd
from mailmerge import MailMerge
def main():
csv_filename = input('Enter csv filename: ')
template_filename = input('Enter template filename: ')
output_folder = input ('Enter output folder name: ')
positions_needed = input('Enter Positions separated by comma (format important): ')
df = pd.read_csv(f"{csv_filename}.csv", encoding ='ISO-8859-1')
df = df.astype(str)
template = f'{template_filename}.docx'
positions = positions_needed.split(',')
for each_row in df.iterrows():
for position in positions:
document = MailMerge(template)
receiver_name = position
company_address = each_row[1].address
company = each_row[1].company
document.merge(
name = str(receiver_name),
company_name = str(company),
address = str(company_address))
position = [p for p in position.split('/')][0]
document.write(f"{output_folder}/{company}-{position}.docx")
document.close()
if __name__ == '__main__':
main()
|
0dc626d36e1412a173c31bb7e5027812319c96f9 | ksreddy1980/test | /General/counter.py | 261 | 3.546875 | 4 | class Counter :
value = 0
def set(self,value):
self.value = value
def up(self):
self.value = self.value + 1
def down(self):
self.value = self.value - 1
count = Counter()
set,up,down = count.up, count.up,count.down
|
38fe3e0d10f01852e7d0c360472eba4222c0c4f8 | CarlZhong2014/Python | /exercise/Thread/InstanceThread2.py | 1,293 | 3.734375 | 4 | #coding=utf-8
#创建线程方法之二:创建线程实例,传入一个可调用的类对象(ThreadFunc)。
import time
import threading
class ThreadFunc(object): #创建一个ThreadFunc类
def __init__(self, func, args, name=''): #通过构造器将传入的函数等设置为类属性。
self.name = name
self.func = func
self.args = args
def __call__(self): #调用函数。
self.func(*self.args)
loops = [4, 2]
def loop(nloop, nsec):
print 'start loop', nloop, 'at:', time.ctime()
time.sleep(nsec)
print 'loop ', nloop, 'done at:', time.ctime()
def main():
print 'starting at:', time.ctime()
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(
target = ThreadFunc(loop, (i,loops[i]), #实例化Thread对象。将loop函数和函数的参数传入ThreadsFunc类。得到一个ThreadFunc实例对象,并传入Thread。
loop.__name__) )
threads.append(t) #将实例后的Thread对象追加到threads列表中
for i in nloops: #启动启动线程
threads[i].start()
for i in nloops: #结束线程
threads[i].join() #join将线程挂起,直到进程结束。或这是timeout,当超时后,线程挂起。
print 'all DONE at:', time.ctime()
if __name__ == '__main__':
main() |
0f3c0d1dda4715a4c6a5c84bc11aa5de2cea48de | rodrigofurlaneti/python | /string2.py | 2,219 | 4.5625 | 5 | #1/use/bin/python3
def main():
s = 'ola String'
print("Upper => Todas letras da variaver fica em caixa alta")
print(s.upper())
print("Capitalize => Somente o primeiro caracter fica em letra caixa alta ")
print(s.capitalize())
print("Format => Inseri no texto a posição do dado, aonde tiver {} ou %d")
print("Ola {} nova string".format(10))
print("Ola nova string %d" %100)
print("Swapcase => Inverte o tamanho da string, caixa baixa e caixa alta")
print(s.swapcase())
print("Find => Faz a busca do caracter na vaviaver e retorna a posição, sempre começa no 1")
print(s.find('g'))
print("Replace = Altera o texto da variavel")
print(s.replace('String', 'mudei'))
print("Strip => Retira o estaço dos dois lados do texto")
print(s.split())
print("Rstrip => Retira o espaço do lado direito do texto")
print(s.rstrip())
print("Isalnum => Se é número")
print(s.isalnum())
print("Isalpha => Se é alfanumerico")
d = 'olastring'
print(d.isalpha())
x, y = 5, 10
print(x,y)
print('O primeiro valor é {} e o segundo valor {}'.format(x,y))
print('O primeiro valor é {1} e o segundo valor {0}, alterar a pos.'.format(x,y))
dicionario = dict(id=x, num=y)
print(dicionario)
print("Split => Coloca a string como um array")
print(s.split())
print("Split ('S') => Busca o paramentro S, retorna sem o parametro")
print(s.split('S'))
print("Split FOR => Percorrer o array")
lista = s.split()
print(lista)
for l in lista:
print(l)
print("Join => Separa com o caracter")
novastring = "/><".join(lista)
print(novastring)
print("variavel[-1] => Pega o ultimo caracter na string")
print(s[-1])
print("variavel[POS_INICIAL:POS_FINAL] => Pega o intervalo")
print(s[5:8])
print("variavel[POS_INICIAL:] => Pega o intervalo até o fim")
print(s[5:])
print("variavel[::-1] => Contrario")
print(s[::-1])
print("variavel[::3] => Pula ordem")
print(s[::3])
print("Len => Quantidade de caracteres")
print(len(s))
print("Alterar string")
df = s.replace("ola", "")
print(df)
if __name__ == "__main__" : main()
|
916a9e73c8c0dfdf5ccbe91ab3c8d5e5dafea2af | entirelymagic/Link_Academy | /Python_Net_Programming/pnp-ex02/tickets/authentication_service.py | 360 | 3.875 | 4 | import json
def authenticate(user, password):
"""Authentication method, given a username and a password, will check in the current list for a match"""
with open("users.json") as file:
users = json.loads(file.read())
for u in users:
if u["username"] == user and u["password"] == password:
return True
return False
|
7b39d820f64dda30094979846f99f4ff507e59c9 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/csimmons/lesson03/strformat_lab.py | 3,299 | 4.1875 | 4 | #!/usr/bin/env python3
# Craig Simmons
# Python 210
# strformat_lab: String Formatting Exercises
# Created 11/22/2020 - csimmons
# Task 1
# Transform ( 2, 123.4567, 10000, 12345.67) to 'file_002 : 123.46, 1.00e+04, 1.23e+04'
print('\nTask One Excercise: Use str.format()')
tuple1 = ( 2, 123.4567, 10000, 12345.67)
print("file_{0:0>3d}, {1:.2f}, {2:.2e}, {3:.2e}".format(*tuple1))
# Task 2
# Format above tuple using alt format string type
print('\nTask Two Excercise: Use f-string syntax')
tuple1 = ( 2, 123.4567, 10000, 12345.67)
print(f'file_{tuple1[0]:0>3d}, {tuple1[1]:.2f}, {tuple1[2]:.2e}, {tuple1[3]:.2e}')
# Task 3
# Rewrite "the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3) to accept arbitrary # of values
print('\nTask Three Excercise: Dynamically accept any # of values')
numbers1 = ( 1, 2, 3, 4, 5, 6, 7, 8, 9)
numbers2 = ( 10, 20, 30, 40)
def test(seq):
replacer = '{:d}, '
make_fstring = 'The {:d} numbers are: ' + (replacer * len(seq))
full = '"' + make_fstring[:-2] + '."'
print(full.format(len(seq), *seq))
test(numbers1)
test(numbers2)
# Task 4
# Given a 5 element tuple: ( 4, 30, 2017, 2, 27), print: '02 27 2017 04 30'
print('\nTask Four Excercises: format numeric tuple, adjust # positions')
datetime = ( 4, 30, 2017, 2, 27)
print('string.format(): ' + "{3:0>2d} {4:d} {2:d} {0:0>2d} {1:d}".format(*datetime))
print('fstring: ' + f"{datetime[3]:0>2d} {datetime[4]:d} {datetime[2]:d} {datetime[0]:0>2d} {datetime[1]:d}")
# Task 5
# Given this list ['oranges', 1.3, 'lemons', 1.1] write an fstring for:
# "The weight of an orange is 1.3 and the weight of a lemon is 1.1"
print('\nTask Five Excercises: f-string fruits and weights')
fruits = ['oranges', 1.3, 'lemons', 1.1]
text_1 = "The weight of an "
text_2 = "and the weight of a "
# fstring formatting. Take plural of fruit and make singular
f1_str = f"{fruits[0].replace('s', '')} is {fruits[1]:.1f} "
f2_str = f"{fruits[2].replace('s', '')} is {fruits[3]:.1f}"
print(text_1 + f1_str + text_2 + f2_str)
# Change f-string to display fruit name in uppercase and 20% higher weight
mod = 1.2
f3_str = f"{(fruits[0].upper()).replace('S', '')} is {(fruits[1] * mod):.1f} "
f4_str = f"{(fruits[2].upper()).replace('S', '')} is {(fruits[3]* mod):.1f} "
print(text_1 + f3_str + text_2 + f4_str)
# Task 6
# Write some Python code to print a table of several rows, each with a name, an age and a cost.
# Make sure some of the costs are in the hundreds and thousands to test your alignment specifiers.
print('\nTask Six Excercises: Print data in table and format extra task')
table_data = (['Kevin', 'Simmons', 49, 20.56], ['Bruce', 'Vercingetorix', 3, 256],
['Matt', 'Francis', 100, 1005.50], ['Randy', 'Taber', 34, 35000.89])
row = "| {fname:<8s} | {lname:<15s} | {age:<5d} | ${price:<10,.2f} |".format
for data in table_data:
print(row(fname=data[0], lname=data[1], age=data[2], price=data[3]))
# And for an extra task, given a tuple with 10 consecutive numbers, can you work how to quickly
# print the tuple in columns that are 5 charaters wide? It can be done on one short line!
# Wrapped the numbers between "\" to show width of the columns and numbers centered
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
single_row = "\n" + ("|{:^5d}" * len(numbers)).format(*numbers)
print(single_row + "|\n")
|
33aa1648db18aa82328502155f9b22625b4613c8 | Elbrus1703/git | /введение в програмирование/rap.py | 470 | 3.75 | 4 | # -*- coding : utf-8 -*-
print u"здравствуйте! это магазин У Ашота"
print u" t1 яблоко == 25 сом "
t1 == 25 = int(raw_input(">"))
print u" t2 ручка == 10 сом "
t2 == 10 = int(raw_input(">"))
print u" t3 наушники == 100 сом "
t3 == 100 = int(raw_input(">"))
print u"выберите кол-во товара"
sum==u"кол во"*"цена"
print u"спасибо за покупку !!! " |
1b297db09ad05a710a09be4fedbb7db07b1de81b | blaxson/myneuralnetwork | /network.py | 6,335 | 3.875 | 4 | import random
import numpy as np
# from graphics import *
""" class that is used for actual neural network functionality, some repr"""
class NeuralNetwork(object):
""" The list 'sizes' contains the num of neurons in the respective layers of
the neural network. If the list is [24, 16, 10], then it would be a 3-layer
NN with 24 nodes in the first layer, 16 in the second, etc. """
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
# biases and weights stored as lists of matrices
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
# example: network.weights[0] is a matrix storing the weights connecting
# the 1st and 2nd layers of neurons.. network.weights[1] is 2nd & 3rd, etc.
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
# with W = net.weights[1], W_jk connects Kth neuron in second layer
# to Jth neuron in third layer
""" returns the output of the neural network given "x" input """
def feedforward(self, x):
# go thru each matrix of weights & biases in list (eq. to each layer)
for bias, weight in zip(self.biases, self.weights):
# based off of feed-forward equation x' = sig(weight*x + bias)
x = sigmoid(np.dot(weight, x) + bias)
return x
""" Returns the number of test inputs for which the neural
network outputs the correct result. The neural
network's output is the index of whichever
neuron in the final layer has the highest activation."""
def evaluate(self, test_data):
test_results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
""" Trains the neural network using stochastic gradient descent using
dataset batches. 'trainging_data' is a list of tuples (x, y) containing
the 'x' training inputs and the 'y' correct desired outputs.'batch_size'
is the desired size of the randomly chosen dataset batches. 'l_rate' is
the learning rate of the neural network. Optional arg 'test_data' is
given which will evaluate the network after each epoch and print partial
progress (warning: very slow). Returns the updated biases and weights
from one training iteration """
def train_iteration(self, training_data, batch_size, l_rate, i, test_data=None):
if test_data:
len_test = len(test_data)
len_training = len(training_data)
# randomly shuffle data to help with training process
random.shuffle(training_data)
# partition all data into batches of data
batches = [
training_data[j : j + batch_size] for j in range(0, len_training, batch_size)]
# go thru each batch & apply gradient decent in backpropogation
for batch in batches:
self.update_weights_and_biases(batch, l_rate)
if test_data:
print("Iteration {0}: {1} / {2}".format(
i, self.evaluate(test_data), len_test))
else:
print("Iteration {0} complete".format(i))
# return the new biases and weights after one training iteration
return (self.biases, self.weights)
""" updates the neural network's weights and biases by applying gradient
descent using backpropogation on a single batch of test data. 'batch'
is a list of tuples (x, y) and 'l_rate' is the learning rate """
def update_weights_and_biases(self, batch, l_rate):
gradient_b = [np.zeros(bias.shape) for bias in self.biases]
gradient_w = [np.zeros(weight.shape) for weight in self.weights]
for x, y in batch:
delta_gradient_b, delta_gradient_w = self.backpropogate(x, y)
gradient_b = [gb+dgb for gb, dgb in zip(gradient_b, delta_gradient_b)]
gradient_w = [gw+dgw for gw, dgw in zip(gradient_w, delta_gradient_w)]
self.weights = [w - (l_rate / len(batch)) * gw
for w, gw in zip(self.weights, gradient_w)]
self.biases = [b - (l_rate / len(batch)) * gb
for b, gb in zip(self.biases, gradient_b)]
# **** this portion added for displaying NN ************************
# for i in range(0, self.num_layers):
# self.layers[i].weights = self.weights[i]
# self.layers[i].biases = self.biases[i]
"""Return a tuple ``(nabla_b, nabla_w)`` representing the
gradient for the cost function C_x. ``nabla_b`` and
``nabla_w`` are layer-by-layer lists of numpy arrays, similar
to ``self.biases`` and ``self.weights``."""
def backpropogate(self, x, y):
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_deriv(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
# l = 1 is the last layer of neurons, l = 2 is second-last
# layer, etc. to take advantage of negative indexing
for l in range(2, self.num_layers):
z = zs[-l]
sp = sigmoid_deriv(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)
"""Return the vector of partial derivatives \partial C_x /
\partial a for the output activations."""
def cost_derivative(self, output_activations, y):
return (output_activations-y)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
"""Derivative of the sigmoid function"""
def sigmoid_deriv(z):
return sigmoid(z)*(1-sigmoid(z)) |
a784d64505144902dbd5334572604905f7d98df4 | staals19/PythonProjects | /binarysort.py | 666 | 3.640625 | 4 | mylist = [1,2,3,4,5,6,7,8,9,10]
num = int(input("what number?"))
def findMiddle(list):
middle = float(len(list))/2
if middle % 2 != 0:
return list[int(middle + .5)]
else:
return list[int(middle)]
run = True
while run == True:
if int(len(mylist)) == 1:
if mylist == [num]:
print("true")
break
else:
print("false")
break
middle_num = findMiddle(mylist)
if middle_num == num:
print("true")
run = False
if middle_num >= num:
del mylist[mylist.index(middle_num):len(mylist)]
else:
del mylist[0:mylist.index(middle_num)]
|
dcad90f8042195d0f5cc99d933236e3b7b843399 | Praneethrk/python_assignment | /Assn_3/member/member.py | 1,602 | 4.25 | 4 | '''
1. Make a class called Member. Create two attributes - first_name and last_name, and then create 5 more attributes that are typically stored in a Member profile, such as email, gender, contact_number, etc. Make a method called show_info() that prints a summary of the member’s information. Make another method called get_memeber() that prints personalized greetings to the member.
Create 5 instances representing different members and call both the methods for each member
'''
class Member:
def __init__(self,fName,lName,email,gender,contact):
self.fName = fName
self.lName = lName
self.email = email
self.gender = gender
self.contact = contact
def show_info(self):
print(f"First Name : {self.fName} Last Name : {self.lName}")
print(f"Email : {self.email}")
print(f"Gender : {self.gender}")
print(f"Contact : {self.contact}")
print()
def get_member(self):
print(f"Hello {self.fName} {self.lName} , Have a great day!!")
print()
if __name__ == "__main__":
M1 = Member('Praneeth','RK','praneethrk@gmail.com','Male','9587462130')
M2 = Member('Joy','Dsouza','joydsouza@gmail.com','Male','8546213079')
M3 = Member('Niranjan','Malya','kudureMalya@in.com','Male','8954623100')
M4 = Member('Aishwarya','Rai Bachan','aishBachan@reddiffmail.com','Female','989989500')
M5 = Member('Hrithik','Roshan','hrx@gmail.com','Male','985451304')
M1.show_info()
M1.get_member()
M2.show_info()
M2.get_member()
M3.show_info()
M3.get_member()
M4.show_info()
M4.get_member()
M5.show_info()
M5.get_member() |
07319f2c7d232c17aacb78757da27da615304817 | vanshdhiman86/TicTacToe | /tictactoe.py | 2,937 | 4 | 4 | board = [" " for x in range(10)]
def insert_letter(letter, pos):
board[pos] = letter
def spaceisfree(pos):
return board[pos] == " "
def printBoard(board):
print(" | | ")
print(" " + board[1] + " | " + board[2] + " | " + board[3] )
print(" | | ")
print("------------")
print(" | | ")
print(" " + board[4] + " | " + board[5] + " | " + board[6] )
print(" | | ")
print("------------")
print(" | | ")
print(" " + board[7] + " | " + board[8] + " | " + board[9] )
print(" | | ")
print("------------")
def isBoardfull(board):
if board.count(" ") > 1:
return False
else:
return True
def isWinner(b, l):
return (b[1] == l and b[2] == l and b[3] == l) or (b[4] == l and b[5] == l and b[6] == l) or (b[7] == l and b[8] == l and b[9] == l) or (b[1] == l and b[4] == l and b[7] == l) or (b[2] == l and b[5] == l and b[8] == l) or (b[3] == l and b[6] == l and b[9] == l) or (b[1] == l and b[5] == l and b[9] == l) or (b[3] == l and b[5] == l and b[7] == l)
def playerMove():
run = True
while run:
move = input("please select the position to enter the X between 1 to 9 ")
try:
move = int(move)
if move > 0 and move < 10:
if spaceisfree(move):
run = False
insert_letter("X", move)
else:
print("Sorry, this space is occupied")
else:
print("please, enter number between 1 to 9")
except:
print("please enter a number")
def computerMoves():
posssibleMoves = [x for x, letter in enumerate(board) if letter == " " and x != 0]
move = 0
for let in ["O" , "X"]:
for i in posssibleMoves:
boardcopy = board[:]
boardcopy[i] = let
if isWinner(boardcopy, let):
move = i
return move
cornersOpen = []
for i in posssibleMoves:
if i in [1, 3, 7, 9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
if 5 in posssibleMoves:
move = 5
return move
edgesOpen = []
for i in posssibleMoves:
if i in [2,4,6,8]:
edgesOpen.append(i)
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(ln)
return li[r]
def main():
print("Welcome to the Game")
printBoard(board)
while not(isBoardfull(board)):
if not(isWinner(board, "O")):
playerMove()
printBoard(board)
else:
print("Sorry, you loose!")
break
if not(isWinner(board, "X")):
move = computerMoves()
if move == None:
print(" ")
else:
insert_letter("O", move)
print("Computer placed O at position", move, "!")
printBoard(board)
else:
print("You Win")
break
if isBoardfull(board):
print("Tie Game")
x="y"
while x == "y":
board = [" " for x in range(10)]
print("---------------------")
main()
x = input("Do you want to play again (y/n) ").lower()
|
edadc0bdcd41d33ad99398a13f42a6bd449bc3a1 | prachinamdeo/Basic-Programs | /prime_no.py | 180 | 3.84375 | 4 | def prime(n):
c=0
for i in range(1,n+1):
if n % i == 0:
c=c+1
if c == 2:
return True
else:
return False
n=int(input("Enter no. "))
res = prime(n)
print(res) |
4c0b86f556b1bf21c848f542d970f2365db3d192 | PIYUSH-KP/Training_with_Acadview | /assignment15_regex/regex.py | 2,546 | 3.5625 | 4 | import re
# Q.1- Extract the user id, domain name and suffix from the following email addresses.
# emails = "zuck26@facebook.com" "page33@google.com"
# "jeff42@amazon.com"
# desired_output = [('zuck26', 'facebook', 'com'), ('page33', 'google', 'com'), ('jeff42', 'amazon', 'com')]
print('__'*50,'\nSOLUTION 1\n','__'*50)
emails = "zuck26@facebook.com"" \
""page33@google.com"" \
""jeff42@amazon.com"
a = re.findall(r'(\w+)@([A-Z0-9]+)\.([A-Z]{2,4})', emails, flags=re.I)
print(a)
print('\n\n')
#Q.2- Retrieve all the words starting with ‘b’ or ‘B’ from the following text.
#text = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better."
print('__'*50,'\nSOLUTION 2\n','__'*50)
text = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better."
b = re.findall(r'\bB\w+', text, flags=re.I)
print(b)
print('\n\n')
#Q.3- Split the following irregular sentence into words
#sentence = "A, very very; irregular_sentence"
#desired_output = "A very very irregular sentence"
print('__'*50,'\nSOLUTION 3\n','__'*50)
sentence = "A, very very; irregular_sentence"
c = re.split('[;,\s_]+', sentence)
s = " "
print(s.join(c))
print('\n\n')
#Q.1- Clean up the following tweet so that it contains only the user’s message. That is, remove all URLs, hashtags, mentions, punctuations, RTs and CCs.
#tweet = '''Good advice! RT @TheNextWeb: What I would do differently if I was learning to code today http://t.co/lbwej0pxOd cc: @garybernhardt #rstats'''
#desired_output = 'Good advice What I would do differently if I was learning to code today'
print('__'*50,'\nSOLUTION OPTIONAL\n','__'*50)
"""
in this tweet we have to remove many things
1. RT
2. cc
3. url : http://t.co/lbwej0pxOd
4. # tags
5. mentions: @
6. puntuations
"""
tweet = "Good advice! RT @TheNextWeb: What I would do differently if I was learning to code today http://t.co/lbwej0pxOd cc: @garybernhardt #rstats"
print(tweet)
print('\n\n')
tweet = re.sub('RT|cc', '', tweet) # remove RT and cc
print(tweet)
print('\n\n')
tweet = re.sub('http\S+\s*', '', tweet) # remove URL
print(tweet)
print('\n\n')
tweet = re.sub('@\S+', '', tweet) # remove mentions
print(tweet)
print('\n\n')
tweet = re.sub('#\S+', '', tweet) # remove hashtags
print(tweet)
print('\n\n')
tweet = re.sub('[%s]' % re.escape("""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""), '', tweet) # remove punctuations
print(tweet)
print('\n\n')
tweet = re.sub('\s+', ' ', tweet) # remove extra spaces
print("USER'S MESSAGE:\n"+tweet)
|
f4b746facd710897b5a24c2739f5d530da7a34e1 | scheidguy/ProjectE | /prob70.py | 1,783 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 20:23:56 2020
@author: schei
"""
def calc_primes(below_num):
primes = [2] # first prime (and only even prime)
for num in range(3, below_num, 2): # skip even numbers
if (num+1) % 1000000 == 0: # prog report for big prime calculations
print(f'Found all primes under {num+1}')
prime_flag = True
# Only need to check if divisible by other primes
for prime in primes:
if num % prime == 0:
prime_flag = False
break
if prime > num ** 0.5: # only need to check up to the square root
break
if prime_flag:
primes.append(num)
return primes
# assume there is a permutation of the product of 2 primes, and
# we just need to find the one with the smallest ratio. Primes have the
# smallest ratios N/(N+1) but will never be permuations. Product of two
# primes is the next best thing.
MAX = 10**7
max_val = 10**4 # only need to examine primes around sqrt(10^7)
primes = calc_primes(max_val)
smallest = 999
the_n = 0
for p1 in primes:
for p2 in primes:
if p1 * p2 > MAX:
break # every successive p2 will be too big for this p1
n = p1 * p2
nstr = str(n)
phi = n - p1 - p2 + 1
pstr = str(phi)
ind = 0
perm = True
while len(pstr) > 0:
prev_len = len(pstr)
pstr = pstr.replace(nstr[ind], '', 1)
if prev_len != len(pstr) + 1:
perm = False
break
ind += 1
if perm:
ratio = n / phi
if ratio < smallest:
smallest = ratio
the_n = n
print(f'phi({the_n}) --> {smallest}')
|
aa9c0bc669d88d62e18c95312cb0d04fea558840 | aaryalanchaster/PythonPrograms | /TURTLE/pattern4.py | 723 | 3.921875 | 4 |
from turtle import Turtle, Screen
MIN_COLOR = 5
MAX_COLOR = 255
COUNT = 150
ANGLE = 5
STARTING_LENGTH =
LENGTH_INCREMENT = 2
N = 6
def draw_polygon(turtle, size):
angle = 360 / N
for _ in range(N):
turtle.forward(size)
turtle.left(angle)
screen = Screen()
screen.colormode(255)
mega = Turtle()
mega.speed(0)
length = STARTING_LENGTH
for r in range(COUNT):
red = round(r * ((MAX_COLOR - MIN_COLOR) / (COUNT - 1))) + MIN_COLOR
color = (0, 0, red)
mega.fillcolor(color)
mega.begin_fill()
draw_polygon(mega, length)
mega.end_fill()
length += LENGTH_INCREMENT
mega.left(ANGLE)
mega.hideturtle()
screen.exitonclick() |
a36b25bef1ab986d41bf7bdb83b5fb1b2519a37d | NallamilliRageswari/Python | /Happy_Number_Recursion.py | 428 | 4.125 | 4 | #Happy number - when sum of number is equal to 1 or 7 .
#program for happy number with recursion.
n=int(input("Enter a number : "))
sum1=0
def Happy(n):
sum1=0
if(n==1 or n==7):
return ("Happy number")
elif(n<10):
return("Not a Happy Number")
else:
while(n>0):
num=n%10
sum1+=num**2
n=n//10
return(Happy(sum1))
print(Happy(n))
|
bf27525f8294bcc1d2e74ed5688a88d0ceea520f | kobewangSky/LeetCode | /384. Shuffle an Array.py | 825 | 3.578125 | 4 | import random
class Solution:
def __init__(self, nums):
self.ori = nums
def reset(self):
return self.ori
"""
Resets the array to its original configuration and return it.
"""
def shuffle(self):
ramdom_times = random.randrange(0, len(self.ori))
chacnge_x = [random.randrange(0, len(self.ori)) for i in range(ramdom_times)]
chacnge_y = [random.randrange(0, len(self.ori)) for i in range(ramdom_times)]
shuffle_list = self.ori
for i in range(len(chacnge_x)):
temp = shuffle_list[chacnge_x[i]]
shuffle_list[chacnge_x[i]] = shuffle_list[chacnge_y[i]]
shuffle_list[chacnge_y[i]] = temp
return shuffle_list
obj = Solution([])
param_1 = obj.reset()
param_2 = obj.shuffle()
print(param_2) |
2ec5da81a4f3a1d864056cd28cfe3da7b038db38 | dusjh/Python | /DemoRandom.py | 598 | 3.84375 | 4 | # DemoRandom.py
# 임의의 숫자 만들기
import random
# 0.0 ~ 1.0 사이의 값
print(random.random())
print(random.random())
# 2.0 ~ 5.0 사이의 값
print(random.uniform(2.0, 5.0))
# 임의의 정수 만들기
print([random.randrange(20) for i in range(10)])
print([random.randrange(20) for i in range(10)])
# 유일한 값이 생성
print(random.sample(range(20),10))
print(random.sample(range(20),10))
# 로또 번호
lotto = list(range(1,46))
# 섞여있지 않음
print(lotto)
# 랜덤하게 섞기
random.shuffle(lotto)
print(lotto)
for item in range(5):
print(lotto.pop()) |
b2a293e3a4b70d46473c03a43ded1996257eee03 | kononeddiesto/Skillbox-work | /Module27/02_slowdown/main.py | 587 | 3.515625 | 4 | import time
from typing import Callable
def decorator(func: Callable) -> Callable:
"""
Декоратор, ожидание в 2 секунды
:param func:
:return:
"""
def wrapped() -> None:
start = time.time()
time.sleep(2)
result = func()
end = time.time()
timing = round(end - start, 4)
print('Время выполнения функции: {} секунд(ы) '.format(timing))
print(result)
return wrapped
@decorator
def function() -> str:
return 'Код функции!'
function()
|
0ce725d322499a7fb81f409cb3b2c40c9e34fb3e | aanchal1234/Assignment1 | /assignment7.py | 1,679 | 4.0625 | 4 | # Write a function"perfect"() that determines if parameter number is a perfect number.use this function in a program determines and print all the perfect numbers between 1 and 1000.
p = []
def perfect():
for x in range(1, 1000):
li = []
sum = 0
for y in range(1, x):
if (x % y == 0):
li.append(y)
for a in li:
sum = sum + a
if (sum == x):
p.append(x)
perfect()
print(p)
# print multiplication table of 12 using recursion.
print("Print multiplication table of 12 using recursion\n")
n = 12
i = 1
def table(n, i):
if i > 10:
return
else:
print(n * i)
table(n, i + 1)
table(12, i)
print("\n...........")
# Write a function to find factorial of a number but also store the factorials calc ulated in a dictionary.
print("Write a function to find factorial of a number but also store the factorials calc ulated in a dictionary")
x = int(input("enter the number whose factorial you want to calculate"))
dict = {}
def fact(a):
if a == 1 or a == 0:
return 1
else:
ans = a * fact(a - 1)
return ans
ans = fact(x)
dict[x] = ans
print(dict)
# Write a function to calculate power of a number raised to other(a^b) using recursion
print("Write a function to calculate power of a number raised to other(a^b) using recursion")
x = int(input("enter any number whose power you want to calculate "))
y = int(input("enter the number you want to use the power"))
def power(x, y):
ans = 1
if y == 1:
return x
else:
ans = x * power(x, y - 1)
return ans
print(power(x, y))
print("\n................")
|
098816a9a74846cc3dde4d7c5537cf98907eb8ed | AKDavis96/Data22python | /Classes/Class.py | 544 | 3.703125 | 4 | class Dog:
animal_kind = "Dolphin" # class variable
def bark(self): # method (a function in a class)
return "woof"
# print(Dog().animal_kind)
# print(Dog().bark()) with brackets you have instantiated it
# print(Dog())
# print(Dog.bark) prints memory location
Myles = Dog()
Oscar = Dog()
print(type(Myles))
print(type(Oscar))
print(Oscar.animal_kind)
print(Myles.animal_kind)
print(Myles.bark())
print(Oscar.bark())
Oscar.animal_kind = "Big Dog"
print(Oscar.animal_kind)
print(Myles.animal_kind)
|
1a1d7f1acc562a40541c0d2babbbfa4b0ad33349 | Cosdaman/BSYS2065-Lab | /Lab7/LAB7Q9-8.py | 511 | 4.125 | 4 | # Write a function that removes all occurrences of a given letter from a string.
def removeletter(stringthing,letterthing):
x = int(len(stringthing))
newstring = ""
for i in range(x):
if letterthing != stringthing[i]:
newstring = newstring + stringthing[i]
else:
pass
return newstring
stringitem = str(input("Enter a string: "))
lettertoremove = str(input("Enter a letter to remove from the string: "))
print(removeletter(stringitem, lettertoremove))
|
b070e6d6cb3bc52234d2638b13e4c40ac3fee566 | ryanjmack/MITx-6.00.1x | /week2/exercises/guess_my_number.py | 1,103 | 4.4375 | 4 | """
Created on Wed Jun 7 09:36:06 2017
@author: ryanjmack
In this problem, you'll create a program that guesses a secret number!
The program works as follows: you (the user) thinks of an integer between 0 (inclusive)
and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess\
too high or too low? Using bisection search, the computer will guess the user's secret number!
Illustrates the 'Bisection Search' Algorithm
"""
high = 0
low = 100
middle = int((high + low) / 2)
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number {}?".format(middle))
check = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess \
is too low. Enter 'c' to indicate I guessed correctly. ")
if check == "h":
low = middle
elif check == "l":
high = middle
elif check == "c":
print("Game over. Your secret number was: {}".format(middle))
break;
else:
print("Sorry, I did not understand your input.")
middle = int((high + low) / 2)
|
1a87aee981ea8ac587d87db4247cb54f3d92109d | TogrulAga/Numeric-Matrix-Processor | /Topics/Custom generators/Fibonacci sequence/main.py | 272 | 4 | 4 | def fibonacci(n):
previous = 0
before_previous = 0
for i in range(n):
next_element = previous + before_previous
yield next_element
before_previous = previous if i != 1 else 0
previous = next_element if next_element != 0 else 1
|
81639399eb83541e3c4e653d0a11c5d8455d1600 | julesdesplenter/1NMCT2-LaboBasicProgramming-julesdesplenter | /week4_lijsten/week1_intro/oefening9.py | 269 | 3.59375 | 4 |
# a = int(input("geef mij een nummer "))
#
# uitkomst = ((a * 10) + a) + ((a*100)+(a*10)+a) + a
#
# print("{0}".format(uitkomst))
a = int(input("geef mij een nummer "))
nummer = str(a)
n1 = nummer + nummer
n2 = nummer + nummer + nummer
print(a + int(n1) + int(n2))
|
7b83d4397930fa6873a82b8311d294f9e490d369 | sylviadoce/HCS_Chess_Lab_08 | /SylviaCopyButton.py | 2,748 | 4 | 4 | # HCS Lab 04
# Name: Sahil Agrawal
#
# This module creates the Button class.
from graphics import *
class Button:
"""A button is a labeled rectangle in a window. It is activated or deactivated with the activate()
and deactivate() methods. The clicked(p) method returns true if the button is active and p is inside it."""
#creating a button object parameters
def __init__(self,win,center,width,height,label):
"""creates a rectangular button, eg:
qb=Button(myWin,centerPoint, width, height, 'Quit')"""
w,h=width/2.0,height/2.0
x,y=center.getX(), center.getY()
self.xmax, self.xmin = x+w, x-w
self.ymax, self.ymin = y+h, y-h
p1=Point(self.xmin, self.ymin)
p2=Point(self.xmax, self.ymax)
self.rect=Rectangle(p1,p2)
self.rect.setFill('lightgray')
self.rect.draw(win)
self.label=Text(center,label)
self.label.draw(win)
self.deactivate()
self.click = False
#activate a button
def activate(self):
"""sets this button to 'active'."""
self.label.setFill('black')
self.rect.setWidth(2)
self.active=True
#deactivate the button
def deactivate(self):
"""Sets this button to 'inactive'."""
self.label.setFill('darkgrey')
self.rect.setWidth(1)
self.active=False
#accessor - returns the text of self.label
def getLabel(self):
"""Returns true if button active and p is inside"""
return self.label.getText()
#registers if the button was clicked
def clicked(self,pt):
"""Returns true if pt is inside"""
if (self.xmin <= pt.getX() <= self.xmax and
self.ymin <= pt.getY() <= self.ymax):
self.click = True
return True
else:
return False
def checkClicked(self) -> bool:
return self.click
def setClicked(self) -> bool:
self.click = True
return self.click
def resetClicked(self) -> bool:
self.click = False
return self.click
#sets the text of self.label
def setLabel(self,newText):
"""Sets the text of the button"""
self.label.setText()
def undraw(self):
"""undraws the button from the window"""
self.rect.undraw()
self.label.undraw()
# Changes:
# 1. deleted self.active and so that the clicked method returns True if
# the square's area has a mouse click (doesn't need to be active)
# 2. added the instance var self.clicked that saves whether the square
# has been clicked - added function checkClicked() to return the bool
# 3. added the resetClicked function
# 4. added setClicked function
|
91562f36b088a9ad356222414b95860e12eb0329 | lbuchli/telan | /interpreter.py | 9,561 | 3.5625 | 4 | #!/usr/bin/env python3
import lexer
import parser
###############################################################################
# Command Representation #
###############################################################################
def print_err(position, message):
print("Line " + str(position.line) +
" Chr " + str(position.char) +
": " + message)
class Command:
def __init__(self, action, minargs=0, maxargs=0, types=[]):
self.minargs = minargs # the min number of arguments (e.g. 1)
self.maxargs = maxargs # the max number of arguments (e.g. 2)
self.types = types # the types of arguments (e.g. ["NUMBER", "ANY", "AST"])
self.action = action # what to do when the command is called (gets passed the arguments)
# call the command if arguments match the commands constraints
def call(self, arguments, local):
# check argument count
if len(arguments) < self.minargs:
return self._err(arguments[-1], "Expected at least " + str(self.minargs) + " arguments")
if self.maxargs != -1 and len(arguments) > self.maxargs:
return self._err(arguments[self.maxargs], "Expected at most " + str(self.maxargs) + " arguments")
# check argument type
arg_index = 0
for t in self.types:
if not self._checktype(arguments[arg_index], t):
return self._err(arguments[arg_index], "Expected argument of type " + t)
arg_index += 1
for arg in arguments[arg_index:]:
if not self._checktype(arg, self.types[-1]):
return self._err(arguments[arg_index], "Expected argument of type " + self.types[-1])
# all tests passed, let's call the command
result = self.action(arguments, local)
return lexer.Token("OTHER", "NULL", arguments[0].position) if result == None else result
# prints an error to the screen and returns an error token
def _err(self, token, message):
print_err(token.position, message)
return lexer.Token("OTHER", "ERROR", token.position)
# checks the type of an argument.
# Available types: "ANY", "AST", "ANY/AST", or any of the lexer types
def _checktype(self, arg, atype):
if atype == "ANY/AST":
return True
elif isinstance(arg, lexer.Token):
return atype == "ANY" or atype == arg.ttype
elif isinstance(arg, parser.ASTNode):
return atype == "AST"
return False
###############################################################################
# Interpreter #
###############################################################################
variables = {}
def interpret(root, local):
command = interpret(root.children[0], local) if isinstance(root.children[0], parser.ASTNode) else root.children[0]
arguments = []
leave_next = False
for x in root.children[1:]:
if isinstance(x, lexer.Token):
if x.ttype == "OTHER" and x.value == "'":
leave_next = True
elif x.ttype != "WHITE": # ignore whitespace
arguments.append(x)
leave_next = False
elif isinstance(x, parser.ASTNode):
if leave_next:
arguments.append(x)
else:
arguments.append(interpret(x, local))
else:
print("PARSER: " + x)
return null
# predefined functions
if command.value in COMMANDS:
return COMMANDS[command.value].call(arguments, local)
# userdefined functions
elif command.value in variables and isinstance(variables[command.value], parser.ASTNode):
func = variables[command.value].children
minargs = int(func[0].value)
maxargs = int(func[1].value)
# filter out whitespace
rawtypes = filter(lambda elem: elem.ttype != "WHITE", func[2].children)
types = [token.value for token in rawtypes]
def code(arguments, local):
return interpret(func[3], arguments)
return Command(code, minargs, maxargs, types).call(arguments, local)
# no function
else:
print_err(command.position, "Unknown command: " + command.value)
return lexer.Token("OTHER", "ERROR", command.position)
###############################################################################
# Reusable Tokens #
###############################################################################
def true(pos):
return lexer.Token("BOOL", "true", pos)
def false(pos):
return lexer.Token("BOOL", "false", pos)
def null(pos):
return lexer.Token("OTHER", "NULL", pos)
###############################################################################
# Commands #
###############################################################################
def add(args, _):
result = 0.0
for arg in args:
result += float(arg.value)
return lexer.Token("NUMBER", str(result), args[0].position)
def sub(args, _):
result = float(args[0].value)
for arg in args[1:]:
result -= float(arg.value)
return lexer.Token("NUMBER", str(result), args[0].position)
def mul(args, _):
result = 1.0
for arg in args:
result *= float(arg.value)
return lexer.Token("NUMBER", str(result), args[0].position)
def div(args, _):
result = float(args[0].value)
for arg in args[1:]:
result /= float(arg.value)
return lexer.Token("NUMBER", str(result), args[0].position)
def ifelse(args, _):
if args[0].value == "true":
return args[1]
else:
return args[2]
def last(args, _):
return args[-1]
def eq(args, _):
if args[0].ttype == args[1].ttype:
if args[0].ttype == "NUMBER":
if float(args[0].value) == float(args[1].value):
return true(args[0].position)
else:
return false(args[0].position)
else:
if args[0].value == args[1].value:
return true(args[0].position)
else:
return false(args[0].position)
else:
return false(args[0].position)
def gt(args, _):
if float(args[0].value) > float(args[1].value):
return true(args[0].position)
else:
return false(args[0].position)
def lt(args, _):
if float(args[0].value) < float(args[1].value):
return true(args[0].position)
else:
return false(args[0].position)
def lnot(args, _):
return false(args[0].position) if args[0].value == "true" else true(args[0].position)
def land(args, _):
for arg in args:
if arg.value != "true":
return false(arg.position)
return true(args[0].position)
def lor(args, _):
for arg in args:
if arg.value == "true":
return true(arg.position)
return false(args[0].position)
def io_input(args, _):
return lexer.Token(args[0].value, input(args[1].value if len(args) > 1 else ""), args[0].position)
def io_print(args, _):
for arg in args:
print(arg.value, end='')
print()
def v_set(args, _):
variables[args[0].value] = args[1]
def v_setf(args, _):
variables[args[0].value] = parser.ASTNode(args[1:], args[0].position)
def v_load(args, _):
if args[0].value in variables:
return variables[args[0].value]
def v_get(args, local):
index = int(args[0].value)
if len(local) > index:
return local[index]
else:
return null(args[0].position)
def c_while(args, local):
while True:
result = interpret(args[0], local)
if result.ttype == "BOOL" and result.value != "true":
break
for arg in args[1:]:
interpret(arg, local)
def c_exec(args, _):
for arg in args[:-1]:
interpret(arg)
return interpret(args[-1])
def concat(args, _):
result = ""
for arg in args:
result += arg.value
return lexer.Token("STRING", result, args[0].position)
###############################################################################
# Command Dictionary #
###############################################################################
COMMANDS = {
"+": Command(add, 2, -1, ["NUMBER"]),
"-": Command(sub, 2, -1, ["NUMBER"]),
"*": Command(mul, 2, -1, ["NUMBER"]),
"/": Command(div, 2, -1, ["NUMBER"]),
"ifelse": Command(ifelse, 3, 3, ["BOOL", "ANY/AST", "ANY/AST"]),
"last": Command(last, 1, -1, ["ANY/AST"]),
"eq": Command(eq, 2, 2, ["ANY"]),
"gt": Command(gt, 2, 2, ["NUMBER"]),
"lt": Command(lt, 2, 2, ["NUMBER"]),
"not": Command(lnot, 1, 1, ["BOOL"]),
"and": Command(land, 2, -1, ["BOOL"]),
"or": Command(lor, 2, -1, ["BOOL"]),
"input": Command(io_input, 1, 2, ["STRING"]),
"print": Command(io_print, 1, -1, ["ANY"]),
"set": Command(v_set, 2, 2, ["ANY", "ANY/AST"]),
"setf": Command(v_setf, 5, 5, ["ANY", "NUMBER", "NUMBER", "AST", "AST"]),
"get": Command(v_get, 1, 1, ["NUMBER"]),
"load": Command(v_load, 1, 1, ["ANY"]),
"while": Command(c_while, 2, -1, ["AST"]),
"exec": Command(c_exec, 1, -1, ["AST"]),
"concat": Command(concat, 1, -1, ["ANY"])
}
|
6a1c9e49189c4a742fbf7120b2e3ecd400cd1635 | jeremiedecock/snippets | /science/physics_python/kinematics/finite_difference_method.py | 710 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org)
from common.state import State
name = 'Finite difference method'
class Kinematics:
def __init__(self):
pass
def compute_new_state(self, state, acceleration, delta_time):
"Compute the forward kinematics with finite difference method."
new_state = State(state.ndim)
# Velocity (m/s) at time_n+1
new_state.velocity = state.velocity + acceleration * delta_time
# Position (m) at time_n+1
new_state.position = state.position + state.velocity * delta_time
#new_state.position = state.position + new_state.velocity * delta_time
return new_state
|
3fd1e061e643125303aec25b7b681a8590457d5c | lanners-marshall/Graphs | /projects/graph/src/no_bokeh/adventure/item.py | 676 | 3.578125 | 4 | class Item:
def __init__(self, name, description):
self.name = name
self.description = description
def on_drop(self):
print(f'player has dropped {self.name}')
def __str__(self):
return str(f"{self.name}")
class Treasure(Item):
def __init__(self, name, description, score_amount):
super().__init__(name, description)
self.score_amount = score_amount
self.has_scored = False
def check_scored(self):
if self.has_scored == False:
self.has_scored = True
return False
else:
return True
def __str__(self):
return str(f"\n treasure: {self.name}, description: {self.description}, score amount: {self.score_amount}") |
becf1767f745bade0404dd299210dbd74c34cb71 | ksm0207/Python_study | /Hello.py | 1,283 | 4 | 4 | def plus(x, y):
return x + y
def minus(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
saved_value = 0
while 1:
select_number = int(input("숫자 입력 "))
saved_value = plus(saved_value, select_number)
print("저장된 값 = ", saved_value)
from random import *
print("숫자 랜덤 게임")
print("아무 숫자를 3개 입력하세요 (최대 31까지)")
a = randint(0, 9)
b = randint(0, 9)
c = randint(0, 9)
print(a, b, c)
random1 = a
random2 = b
random3 = c
while 1:
isTrue = 0
a = int(input("첫번째 숫자 입력 : "))
b = int(input("두번째 숫자 입력 : "))
c = int(input("세번째 숫자 입력 : "))
if a == random1:
print("첫번째 숫자를 맞췄습니다")
else:
isTrue = 1
print("다시 입력하세요")
if b == random2:
print("두번째 숫자를 맞췄습니다")
else:
isTrue = 1
print("다시 입력하세요")
if c == random3:
print("세번째 숫자를 맞췄습니다")
else:
isTrue = 1
print("다시 입력하세요")
if isTrue == 1:
continue
else:
break
|
6ccbbb304a2c90e6583861b687b1c497e4f5f154 | dodonmountain/algorithm | /2019_late/adv/playground/카드2.py | 187 | 3.578125 | 4 | from collections import deque
N = int(input())
cards = deque(range(1, N+1))
while True:
a = cards.popleft()
if not cards:
break
cards.append(cards.popleft())
print(a) |
01c3fa214321a7487ef4e1f3e83e2214f8382193 | TobiahRex/python-learn | /tutorial_lists/main.py | 808 | 4.09375 | 4 |
def main():
l = [1,2,3,4]
l.append('toby')
print(f'l: {l}', '\n')
l.clear()
print('clear(): ', l, '\n')
target = ['im the target']
l = target.copy()
print(f"""
target = ['im the target']
l = target.copy()
l: {l}
""")
l.extend([1, 2, 3])
print('l.extend([1, 2, 3]): ', l, '\n')
l = [3,2,6,4,1]
print('l: ', l)
print('l.index(6, 0, 3): ', l.index(6, 0, 3), '\n')
print('pop(): ', l.pop(1))
print('l: ', l, '\n')
l.remove(6)
print('l.remove(): ', l, '\n')
l.reverse()
print(f'l.reverse(): {l}', '\n')
l.sort()
print(f'l.sort(): {l}', '\n')
print(f'l[-1] (ith item): {l[-1]}', '\n')
l = [1,2,3,4,5,6,7,8,9,10]
print(f'l[1::2] (start @ 1 index & increment by 2): {l[1::2]}', '\n')
print('l * 3', l * 3, '\n')
if __name__ == "__main__":
main()
|
24d88d4945ebdb0f13d04cac9ffa13f8ba51ed69 | rajanmanojyadav/Tathastu_Week_of_code | /Day1/Program4.py | 504 | 4.25 | 4 | #Take 2 inputs, CostPrice,SellingPrice of a product for user and return following:
#1.profit from sell
#2.what should be the selling price if we increased th profit by 5%
costprice=int(input("Enter the cost price of the product: "))
sellingprice=int(input("Enter the sell price of the product: "))
profit=sellingprice - costprice
incrasedsellingprice=1.05* profit + costprice
print("Profit from this sell :-", profit)
print("Selling price should be increase for profit of 5% :-",incrasedsellingprice)
|
44b30f1b165021bf6730c4e80a126e12163dfb5f | Scorch116/DeckofCards | /Deck.py | 464 | 4.375 | 4 | Importing modules tools
#random - used to select random in the data
# itertools , used to work with iterable in data sets
import random , itertools
#First the deck is made
deck = list(itertools.product(range(1,14),['Heart','Diamond','Club','Spade']))
#Use the random.shuffle to reorganise the order of item in deck
random.shuffle(deck)
print('Your cards....')
for i in range(3): # will print out 3 cards and will display
print(deck[i][0], 'of', deck[i][1]) |
1cd9eba7b0b78c0f3d029c4e262210b02c007be9 | donnell74/CSC-450-Scheduler | /gui/flow.py | 1,810 | 3.75 | 4 | def main():
subject = raw_input("Which type of constraint? [instructor / course] ").lower() #button
while (1):
if subject in ["instructor", "course"]:
break
else:
subject = raw_input("Invalid input. [instructor / course] ").lower()
if subject == "instructor":
instructor = raw_input("Which instructor? ").lower()
elif subject == "course":
course = "CSC" # not sure if this should be assumed or an option?
num = int(raw_input("Which course number (e.g. 450)? "))
const_type = raw_input("Which type of constraint [time / location / lab]? ").lower() #button
while (1):
if const_type in ["time", "location", "lab"]:
break
else:
const_type = raw_input("Invalid input. [time / location / lab] ").lower()
if const_type == "time":
time_type = raw_input("Before or after? ").lower() #dropdown
while (1):
if time_type in ["before", "after"]:
break
else:
time_type = raw_input("Invalid input. [before / after] ").lower()
time = raw_input("What time in military time (e.g. 13:00)? ")
elif const_type == "location":
building = raw_input("Which building code (e.g. CHK)? ") #dropdown
room = int(raw_input("Which room (e.g. 204)? ")) #dropdown
elif const_type == "lab":
lab = raw_input("Should the course / instructor be in a lab [yes / no]? ").lower() #dropdown
while (1):
if lab in ["yes", "y"]:
lab = True
break
elif lab in ["no", "n"]:
lab = False
break
else:
lab = raw_input("Invalid input. [yes / no] ").lower()
if __name__ == "__main__":
main() |
b17fef7e7e5a7cf94f58820426558aee5cbdfa6a | kaumnen/codewars | /[7 kyu] Find the capitals.py | 90 | 3.859375 | 4 | def capitals(word):
return sorted([x for x in range(len(word)) if word[x].isupper()])
|
adfc2ab73d65a3b8c2113d55d52f60497d42c2e4 | HOTKWIN/Algorithm-diagram | /快速排序.py | 1,657 | 3.578125 | 4 | #分而治之,D&C
class parctice(object):
def sum_DC(self,arr):
if len(arr) == 0:
return 0
elif len(arr) == 1:
return arr[0]
else:
tmp = arr.pop(0)
return tmp+self.sum_DC(arr)
def numOfList_DC(self,arr):
if len(arr) == 0:
return 0
else:
arr.pop(0)
return 1+self.numOfList_DC(arr)
def maxOfList_DC(self,arr):
if len(arr) == 0:
return 0
elif len(arr) == 1:
return arr[0]
else:
if arr.pop(0) < self.maxOfList_DC(arr):
return self.maxOfList_DC(arr)
def binary_search(self,arr,item):
if len(arr) == 0:
return None
elif len(arr) == 1:
return 0
else:
if arr[len(arr)//2] == item:
return len(arr)//2
elif arr[len(arr)//2] < item:
arr = arr[len(arr)//2+1:]
return self.binary_search(arr,item)
else:
arr = arr[:len(arr)//2]
return self.binary_search(arr,item)
#快速排序
def quicksort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array if i <pivot]
greater = [i for i in array if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
if __name__ == '__main__':
test = parctice()
print(test.sum_DC([1,5,8,19]))
print(test.numOfList_DC(([1,5,8,19])))
print(test.maxOfList_DC([1,5,8,19]))
print(test.binary_search([1,5,8,19],8))
print(quicksort([7,1,6,78])) |
fb6a7d8ff81309dcfaa28f701b23c112154a12ef | Icetalon21/Python_Projects | /random_list/list.py | 429 | 3.96875 | 4 | import random
tenRandom = random.sample(range(0, 100), 10)
print ("Every element: ", tenRandom)
print ("Even Index: ", tenRandom[0::2])
myList = list()
for i in tenRandom:
if i % 2 == 0:
myList.append(i)
print("Every even: ", myList)
reverseList = list(reversed(tenRandom)) #non-destructive
print("Reverse Order: ", reverseList)
firstAndLast = [tenRandom[0], tenRandom[-1]]
print("First and Last: ", firstAndLast)
|
fc3960c0b69cc3adfb64e71ae760fc9088a12464 | saurabhkmr707/Word_Game | /test.py | 1,399 | 3.625 | 4 | import tkinter as tk
class Example():
def __init__(self):
self.root = tk.Tk()
# self.table = tk.Frame(self.root)
# self.table.pack(fill="both", expand=True)
self.entry_vals = [[0 for i in range(4)] for i in range(10)]
self.rows = []
for row in range(10):
row_entries = []
self.rows.append(row_entries)
for column in range(4):
entry = tk.Entry(self.root)
entry.grid(row=row, column=column)
row_entries.append(entry)
entry.bind("<Return>", self.handle_enter)
def handle_enter(self, event):
# get the row and column of the entry that got the event
entry = event.widget
row = int(entry.grid_info()['row'])
column = int(entry.grid_info()['column'])
self.entry_vals[row][column] = entry.get()
entry = self.rows[row][column]
entry.config(state = 'disabled')
# compute the new row; either the next row or circle
# back around to the first row
new_row = row+1 if row+1 < len(self.rows) else 0
# get the entry for the new row, and set focus to it
entry = self.rows[new_row][column]
entry.focus_set()
example = Example()
tk.mainloop()
list = example.entry_vals
for row in list:
for val in row:
print (val, end = " ")
print ("") |
5b043ebf41b031775ca7d4279580f6d189c2d112 | treuille/multiplication-battleship | /streamlit_app.py | 5,479 | 3.84375 | 4 | import streamlit as st
import random
from typing import Set, Tuple
from streamlit.session_state import SessionState
Point = Tuple[int, int]
Points = Set[Point]
# What I'm trying to do here is have the state reset if either the board
# size of number of ships changed. In order to do so, I've added this
# initialized flag to the state which feels awkward.
# It feels awkward to me that I
def reinitialize_state(*_):
"""Callback when board_size or num_ships has changed."""
# Reset the state to
state.initialized = False
def guess_is_correct(product_guess):
"""Returns true if the guessed product is correct."""
return (product_guess ==
str(state.current_guess[0] * state.current_guess[1]))
def product_guessed(product_guess):
"""Callback when the user makes a guess as to the product."""
if guess_is_correct(product_guess):
if state.current_guess in state.ships:
st.balloons()
state.guesses.add(state.current_guess)
state.current_guess = None
def initialize_state(board_size: int, num_ships: int) -> None:
"""Setup a clean state of the board."""
state.board_size: int = board_size
state.num_ships: int = num_ships
state.guesses: Points = set()
state.current_guess: Optional[Point] = None
create_new_random_board()
state.initialized = True
def create_new_random_board() -> None:
"""Adds a new random board to the state."""
ships = set()
for ship_len in range(1, state.num_ships + 1):
ships = add_ship(ship_len, ships, state.board_size)
state.ships = ships
state = st.beta_session_state(initialized=False)
def get_settings() -> Tuple[int, int]:
"""Gets some settings for the board."""
return board_size, num_ships
def add_ship(ship_len: int, ships: Points, board_size) -> Points:
"""Adds a ship of the specified length to the board."""
MAX_ITER = 100
# Stop trying to add the ship if it takes more than
# MAX_ITER attempts to find a valid location
for _ in range(MAX_ITER):
pos_1 = random.randrange(1, board_size - ship_len + 1)
pos_2 = random.randrange(1, board_size + 1)
horizontal = bool(random.randint(0, 1))
if horizontal:
new_ship = {(pos_1 + i, pos_2) for i in range(ship_len)}
else:
new_ship = {(pos_2, pos_1 + i) for i in range(ship_len)}
if ships.isdisjoint(new_ship):
return ships.union(new_ship)
raise RuntimeError(f"Unable to place ship after {MAX_ITER} iterations.")
def write_board(ships: Points, board_size: int) -> None:
"""Writes out the board to the Streamlit console."""
st.sidebar.text("\n".join(
" ".join("X" if (x, y) in ships else "."
for x in range(1, board_size + 1))
for y in range(1, board_size + 1)))
def click_cell(point: Point) -> None:
"""Returns a callback for when the specified cell is clicked."""
def cell_clicked():
state.current_guess = point
return cell_clicked
def write_remaining_points() -> None:
"""Write down the number of ships remining."""
# if hasattr(state, "ships") and hasattr(state, "guesses"):
st.sidebar.write(f"{len(state.ships - state.guesses)} remaining")
def draw_board() -> None:
"""Writes out the board to the Streamlit console."""
# First see if the whole board has been guesesed
guessed_everything = state.ships <= state.guesses
if guessed_everything:
# Reveal every point on the board
revealed = {(i, j) for i in range(1, state.board_size + 1)
for j in range(1, state.board_size + 1)}
else:
revealed = state.guesses
for y in range(1, state.board_size + 1):
row = st.beta_columns(state.board_size)
for x, cell in zip(range(1, state.board_size + 1), row):
point = (x, y)
if point not in revealed:
cell.button(f"{x}x{y}", on_click=click_cell(point))
elif point in state.ships:
cell.write("🔥")
else:
cell.write("🌊")
if guessed_everything:
st.success("Great job!")
def ask_for_answer() -> None:
"""Prompt the user for the answer to the multiplication problem."""
if state.current_guess == None:
return
product_str = f"{state.current_guess[0]}X{state.current_guess[1]}"
st.sidebar.warning(f"❓ What is {product_str}?")
product_guess = st.sidebar.text_input(product_str,
on_change=product_guessed)
if product_guess and not guess_is_correct(product_guess):
st.sidebar.error(f"🥺 {product_guess} is not correct")
def main():
"""Execution starts here."""
# Title
st.write("# Battleship")
# Control parameters
board_size = st.sidebar.number_input("Board size", 5, 20, 9,
on_change=reinitialize_state)
num_ships = st.sidebar.number_input("Number of ships", 1, 10, 5,
on_change=reinitialize_state)
# Intializing the state here. I find doing this here very awkward.
if not state.initialized:
initialize_state(board_size, num_ships)
# Write the number of points remaining
write_remaining_points()
# Reset button. The logic is all screwy here!
st.sidebar.button("Reset", on_click=reinitialize_state)
# This is just for debug purposes.
# write_board(state.ships, state.board_size)
# Now draw the main UI
draw_board()
ask_for_answer()
if __name__ == "__main__":
main()
|
64237b744bfd8c3b27af56f759db5d8e4123059c | dashayudabao/practise_jianzhioffer | /jianzhi_offer/day1_二维数组中的查找.py | 1,191 | 3.703125 | 4 | # Author: Baozi
#-*- codeing:utf-8 -*-
"""题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
"""
import random
array = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
target = random.randint(1,20)
# target = 14
print("array :",array)
print("target :",target)
# 二维行列式的行
row_index = len(array)
# 二维行列式的列
col_index = len(array[0])
if target > array[row_index - 1][col_index - 1]:
print("Out of the array range!")
exit(0)
def search_array(array,target):
result = False
row = 0;col = col_index-1
tmp = array[row][col]
while(row < row_index-1 and col >= 0):
if(tmp == target):
result = True
break
elif tmp > target:
col -= 1
tmp = array[row][col]
else:
row += 1
tmp = array[row][col]
return result
if __name__ == '__main__':
result = search_array(array,target)
print("result :",result)
|
4babd09df7470dfde4b4993f095cc78bdb04e66a | MthwBrwn/owasp_research_demo | /build_db.sh | 500 | 3.5625 | 4 | #!/usr/bin/python3
import sqlite3
db = "./students.db"
conn = sqlite3.connect(db)
c = conn.cursor()
cmd = "CREATE TABLE students (Name TEXT, Last TEXT)"
c.execute(cmd)
conn.commit()
data = [
("Robert", "Tables"), ("Toby", "Huang"), ("Hannah", "Sindorf"),
("Daniel", "Frey"), ("Ray", "Ruazol"), ("Roger", "Huba"),
("Joyce", "Liao"), ("Scott", "Curie"), ("Vince", "Masten"),
("Matthew", "Brown")
]
c.executemany("INSERT INTO students VALUES (?,?)", data)
conn.commit()
conn.close()
|
d4f2c07738e084c013018d62b6ca173364530420 | mindovermiles262/projecteuler | /001.py | 514 | 4.15625 | 4 | """"
Project Euler Problem 1
@author: mindovermiles262
@date: 2018.01.18
Problem:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multiple35(max):
total = 0
for i in range(1,max):
if (i % 3 == 0 or i % 5 == 0):
total += i
return total
print(multiple35(1000))
# returns "233168"
|
de5046c3c097aa3d4113f44fb92654c9c4a67e9a | tzhou2018/LeetCode | /doubleHand/345reverseVowels.py | 1,813 | 3.59375 | 4 | '''
@Time : 2020/3/15 16:19
@FileName: 345reverseVowels.py
@Author : Solarzhou
@Email : t-zhou@foxmail.com
'''
"""
使用双指针,一个指针从头向尾遍历,一个指针从尾到头遍历,当两个指针都遍历到元音字符时,交换这两个元音字符。
为了快速判断一个字符是不是元音字符,我们将全部元音字符添加到集合 HashSet 中,从而以 O(1) 的时间复杂度进行该操作。
时间复杂度为 O(N):只需要遍历所有元素一次
空间复杂度 O(1):只需要使用两个额外变量
"""
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
left = 0
s = list(s)
right = len(s) - 1
while left < right:
if s[left] in vowerls:
if s[right] in vowerls:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
else:
right -= 1
else:
left += 1
return ''.join(s)
# 思路同上述方法
def reverseVowels1(self, s):
"""
:type s: str
:rtype: str
"""
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
left = 0
s = list(s)
right = len(s) - 1
while left < right:
while left < right and s[left] not in vowerls:
left += 1
while left < right and s[right] not in vowerls:
right -= 1
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return ''.join(s)
if __name__ == '__main__':
print(Solution().reverseVowels("hello"))
|
80034cd7c74a44311efc584a0f8a384bbb62f148 | jmctsm/Python_03_Deep_Dive_Part_04_OOP | /Section_06_Single_Inheritance/05 - Delegating to Parent.py | 6,133 | 3.75 | 4 | def line_break():
x = 0
print("\n\n")
while x < 20:
print("*", end="")
x += 1
print("\n\n")
line_break()
class Person:
def work(self):
return 'Person works...'
class Student(Person):
def work(self):
result = super().work()
return f'Student works... and {result}'
s = Student()
print(f"s.work(): {s.work()}")
line_break()
class Person:
def work(self):
return 'Person works...'
class Student(Person):
pass
class PythonStudent(Student):
def work(self):
result = super().work()
return f'PythonStudent codes... and {result}'
ps = PythonStudent()
print(f"ps.work(): {ps.work()}")
line_break()
class Person:
def work(self):
return 'Person works...'
class Student(Person):
def work(self):
result = super().work()
return f'Student studies... and {result}'
class PythonStudent(Student):
def work(self):
result = super().work()
return f'PythonStudent codes... and {result}'
ps = PythonStudent()
print(f"ps.work(): {ps.work()}")
line_break()
class Person:
def work(self):
return 'Person works...'
class Student(Person):
def study(self):
return 'Student studies...'
class PythonStudent(Student):
def code(self):
result_1 = self.work()
result_2 = self.study()
return f'{result_1} and {result_2} and PythonStudent codes...'
ps = PythonStudent()
print(f"ps.code(): {ps.code()}")
line_break()
class Person:
def work(self):
return f'{self} works...'
class Student(Person):
def work(self):
result = super().work()
return f'{self} studies... and {result}'
class PythonStudent(Student):
def work(self):
result = super().work()
return f'{self} codes... and {result}'
ps = PythonStudent()
print(f'hex(id(ps)) = {hex(id(ps))}')
print(f'ps.work(): {ps.work()}')
line_break()
class Person:
def set_name(self, value):
print('Setting name using Person set_name method...')
self.name = value
class Student(Person):
def set_name(self, value):
print('Student class delegating back to parent...')
super().set_name(value)
s = Student()
print(f's.__dict__: {s.__dict__}')
s.set_name('Eric')
print(f's.__dict__: {s.__dict__}')
line_break()
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, student_number):
super().__init__(name)
self.student_number = student_number
s = Student('Python', 30)
print(f's.__dict__: {s.__dict__}')
line_break()
class Person:
def __init__(self):
print('Person __init__')
class Student(Person):
pass
s = Student()
line_break()
class Person:
def __init__(self, name):
print('Person __init__')
self.name = name
class Student(Person):
pass
try:
s = Student()
except TypeError as ex:
print(ex)
s = Student('Alex')
print(f's.__dict__ = {s.__dict__}')
line_break()
class Person:
def __init__(self):
print('Person __init__ called...')
class Student(Person):
def __init__(self):
print('Student __init__ called...')
s = Student()
line_break()
class Person:
def __init__(self):
print('Person __init__ called...')
class Student(Person):
def __init__(self):
super().__init__()
print('Student __init__ called...')
s = Student()
line_break()
from math import pi
from numbers import Real
class Circle:
def __init__(self, r):
self._r = r
self._area = None
self._perimeter = None
@property
def radius(self):
return self._r
@radius.setter
def radius(self, r):
if isinstance(r, Real) and r > 0:
self._r = r
self._area = None
self._perimeter = None
else:
raise ValueError('Radius must be a positive number.')
@property
def area(self):
if self._area is None:
self._area = pi * self.radius ** 2
return self._area
@property
def perimeter(self):
if self._perimeter is None:
self._perimeter = 2 * pi * self.radius
return self._perimeter
class UnitCircle(Circle):
def __init__(self):
super().__init__(1)
u = UnitCircle()
print(f'u.radius, u.area, u.perimeter = {u.radius}, {u.area}, {u.perimeter}')
line_break()
class Circle:
def __init__(self, r):
self._r = r
self._area = None
self._perimeter = None
@property
def radius(self):
return self._r
@radius.setter
def radius(self, r):
if isinstance(r, Real) and r > 0:
self._r = r
self._area = None
self._perimeter = None
else:
raise ValueError('Radius must be a positive number.')
@property
def area(self):
if self._area is None:
self._area = pi * self.radius ** 2
return self._area
@property
def perimeter(self):
if self._perimeter is None:
self._perimeter = 2 * pi * self.radius
return self._perimeter
class UnitCircle(Circle):
def __init__(self):
super().__init__(1)
@property
def radius(self):
return super().radius
u = UnitCircle()
print(f'u.radius, u.area, u.perimeter = {u.radius}, {u.area}, {u.perimeter}')
try:
u.radius = 10
except AttributeError as ex:
print(ex)
line_break()
class Person:
def method_1(self):
print('Person.method_1')
self.method_2()
def method_2(self):
print('Person.method_2')
class Student(Person):
def method_1(self):
print('Student.method_1')
super().method_1()
s = Student()
s.method_1()
line_break()
class Person:
def method_1(self):
print('Person.method_1')
self.method_2()
def method_2(self):
print('Person.method_2')
class Student(Person):
def method_1(self):
print('Student.method_1')
super().method_1()
def method_2(self):
print('Student.method_2')
s = Student()
s.method_1()
|
916cb5435053cac29dc738bdf6d10e6e58a67afc | nithesh712/python-programs | /med.py | 3,331 | 4.15625 | 4 | num = float(input('Enter a Number: '))
if(num > 0):
print('Even Number it is', num)
elif(num == 0):
print('Its a Zero')
else:
print('Negative number it is', num)
num = float(input('Enter a Number: '))
if(num % 2 == 0 and num != 0):
print(f'It is Even number {num}')
elif(num == 0):
print('It is Zero')
else:
print(f'It is odd number {num}')
# Leap Year
year = int(input('Enter a year to check it is leap: '))
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
print(f'It is leap year {year}')
else:
print(f'{year}, it is not leap year')
else:
print(f'{year} is a leap year')
else:
print(f'{year} is not leap year')
num = int(input('Enter Number: '))
if num > 1:
for i in range(2, num):
if(num % i == 0):
print('It is not prime number')
print(i, 'times', num//i, 'is', num)
break
else:
print(num, 'is prime')
else:
print(num, 'is not prime')
num = int(input('Enter a number: '))
if(num > 1):
for i in range(2, num):
if(num % i == 0):
print('It is not a prime')
break
else:
print('It is a prime')
else:
print('Not Prime')
# Finding Prime between sequence
lower = int(input('Enter first number: '))
upper = int(input('Enter second number: '))
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if(num % i == 0):
break
else:
print(num)
# Factoral Program
num = int(input('Enter number: '))
factorial = 1
if (num < 0):
print('Not factorial number')
elif (num == 0):
print('Factorial is 1')
else:
for i in range(1, num + 1):
print(i)
factorial = factorial * i
print(factorial)
# Table Program
num = int(input('Table Number: '))
for i in range(1, 11):
print(num, 'x', i, '=', num*i )
num = int(input('Enter Number: '))
n1 = 0
n2 = 1
count = 2
if num <= 0:
print('Enter positive value')
elif num == 1:
print('Febonacci number is: ', n1)
else:
print('Febonacci sequence is:')
print(n1,' , ',n2, end=',')
while count < num:
nth = n1 + n2
print(nth, end=' , ')
n1 = n2
n2 = nth
count += 1
# Fibonacci Number
num = int(input('Enter a number: '))
n1 = 0
n2 = 1
count = 2
if(num<=0):
print('Enter a positive value')
elif(num==1):
print(n1)
else:
print(n1,',', n2, end =', ')
while count < num:
next_num = n1 + n2
print(next_num, end=', ')
n1 = n2
n2 = next_num
count += 1
num = int(input('Enter a number: '))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum = sum + digit**3
temp = temp//10
print(temp)
if num == sum:
print(num, 'It is Amstrong')
else:
print(num, 'Not an Amstrong number')
lower = int(input('Enter lower value: '))
upper = int(input('Enter upper value: '))
for num in range(lower, upper+1):
sum = 0
temp = num
while temp > 0:
digit = temp%10
sum += digit**3
temp //= 10
if num == sum:
print(num)
num = int(input('Enter a number: '))
if num<0:
print('Enter positive number')
else:
sum = 0
while num > 0:
sum += num
num -= 1
print(sum) |
66d5f7f6a18cf06d1a47e04d45359831116a8145 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day18/exercise02.py | 1,379 | 3.53125 | 4 | '''
1.获取可迭代对象中长度最大的元素(列表)
([1,1],[2,2,2,2],[3,3])
2.在技能列表中,获取所有技能的名称与持续时间与攻击力
3.在技能列表中,获取攻击力最小的技能
4.对技能列表根据持续时间进行降序排列
要求:使用两种方式实现ListHelper.py
内置高阶函数
'''
from common.list_helper import ListHelper
class Skill:
def __init__(self, id, name=None, atk=None, duration=None):
self.id = id
self.name = name
self.atk = atk
self.duration = duration
# 对象----> 字符串
def __str__(self):
return self.name
list01 = [
Skill(101, '乾坤大挪移', 8000, 30),
Skill(102, '九阳神功', 9000, 50),
Skill(103, '黑虎掏心', 9800, 10),
Skill(104, '葵花宝典', 6000, 2)
]
# 1.
tuple01 = ([1, 1], [2, 2, 2, 2], [3, 3])
print(ListHelper.get_max(tuple01, lambda item: len(item)))
print(max(tuple01, key=lambda item: len(item)))
# 2.
for item in ListHelper.select(list01, lambda item: (item.name, item.duration, item.atk)):
print(item)
for item in map(lambda item: (item.name, item.duration, item.atk), list01):
print(item)
# 3.
print(min(list01, key=lambda item: item.atk))
# 4.
for item in sorted(list01, key=lambda item: item.duration, reverse=True):
print(item)
|
15aaf2930cbef513453dc6238ff3b6ba93baa307 | alecs396/Jumper-Game | /Jumper.py | 2,930 | 4.0625 | 4 | class Jumper:
"""A jumper is a person who jumps from aircraft. The responsibility of Jumper is to keep track of their parachute."""
def __init__(self):
self.chute = []
self.chute.append(r" ___ ")
self.chute.append(r" /___\ ")
self.chute.append(r" \ / ")
self.chute.append(r" \ / ")
self.chute.append(r" 0 ")
self.chute.append(r" /|\ ")
self.chute.append(r" / \ ")
self.chute.append(r" ")
self.chute.append(r"^^^^^^^")
#if guess does not match a letter this will delete a portion of the chute.
def cut_line(self):
self.chute.pop(0)
# 0 is still found then the game will continue
def is_alive(self):
if ' \ / ' in self.chute:
return True
else:
print(
"\n X ",
"\n /|\ ",
"\n / \ ",
"\n ",
"\n^^^^^^^",
"\nYou Lose"
)
return False
#displays chute
def get_chute(self):
print()
for lines in self.chute:
print(lines)
class Target:
"""A target is a word the jumper is trying to guess. The responsibility of Target is to keep track of the letters in the word and those that have been guessed."""
#Create the target word.
def __init__(self):
self.letters = ['w', 'u', 't', 'a', 'n', 'g']#put the deisired word in seperate letters
self.guesses = ['-', '-', '-', '-', '-', '-'] #put the same abount of underscores or dashes as letters in the word
#create string variable
self.word = ""
self.blanks = ""
#for char in self.letters:
#self.word += char
#for dash in self.guesses:
#self.blanks += dash
def has_letter(self, guess):
for index, letter in enumerate(self.letters):
if guess == letter:
self.guesses[index] = guess
return guess in self.letters
def is_found(self):
if self.guesses == self.letters:
print("\nYou Win!!")
return True
def get_guesses(self):
print(' '.join(self.guesses))
class Trainer:
"""A trainer is a person who trains jumpers. The responsibility of Trainer is to control the sequence of the jump."""
def start_jump(self):
jumper = Jumper()
target = Target()
while jumper.is_alive() and not target.is_found():
guess = input("\n Guess a letter: ")
if target.has_letter(guess) != True:
jumper.cut_line()
target.get_guesses()
jumper.get_chute()
if __name__ == "__main__":
trainer = Trainer()
trainer.start_jump()
|
e2bee9cec8148f2ee0c65aac3d56cda32707f403 | igorpsf/Stanford-cs57 | /2 Lecture.py | 1,893 | 3.9375 | 4 | from pip._vendor.distlib.compat import raw_input
# a = [0,1,2,3,4]
# a[0]=8
# print(a[0]) # 8
# print(a[0:2]) # [8, 1]
# print(a[:2]) # [8, 1]
# print(a[2:4]) # [2, 3]
print(list(range(4))) # [0, 1, 2, 3]
print(list(range(4,8))) # [4, 5, 6, 7]
print(list(range(1,13,2))) # [1, 3, 5, 7, 9, 11]
# count = 10
# while (count != 0):
# print(count)
# count-=1
# print("Blastoff!")
# for x in [0,1,2,3]:
# print(x)
#
# print()
# for x in range(4):
# print(x)
# x = (int(raw_input("What is 2+2?: ")))
# if x == 4:
# print("Nice work!")
# elif (x ==3) or (x == 5):
# print("So close!")
# else:
# print("Try again!")
# in in Strings
print("test" in "testing") # True
print("boss" in "boston") # False
# in in Lists
print(3 in [1,2,3]) # True
print("a" in ['a', 'b', 'c']) # True
studentList = ["Bob", "Charlie", "Jessica", "Sally"]
student = "Allison"
if student in studentList:
print(student + " is in the calss!")
else:
print(student + " is NOT in the calss!")
total = 0 #instantiates total variable and assigns value
number = 0 #instantiates number variable and assigns value
while (number < 5): #condition stays true as long as number < 5
number += 1 #increments number by 1
total += number #adds number to sum to give updated subtotal value
print("The sum of numbers from 1 to 5 is ", total)
total = 0 #instantiates total variable and assigns value
for number in range(51): #for each number until 50
total += number #adds number to total to give updated subtotal value
print("The sum of numbers from 1 to 50 is " + str(total))
# score = (int(raw_input('Enter a score: ')))
# if score >= 90 and score <= 100:
# print ('Score is: A')
# elif score >= 80:
# print ('Score is: B')
# elif score >= 70:
# print ('Score is: C')
#
# if 'bos' in 'bols':
# print (True)
# else:
# print (False) |
611a2f811b6dac9c70ed5de7834362b397b5c9ea | codeartisanacademy/caapygame | /platformer/jumping/player.py | 1,433 | 3.703125 | 4 | import pygame
RED = (255, 0, 0)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Player(pygame.sprite.Sprite):
def __init__(self):
""" Constructor function """
# Call the parent's constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
width = 40
height = 60
self.image = pygame.Surface([width, height])
self.image.fill(RED)
# Set a referance to the image rect.
self.rect = self.image.get_rect()
# Set speed vector of player
self.velocity_y = 0
def update(self):
""" Move the player. """
# Gravity
self.calc_grav()
# Move up/down
self.rect.y += self.velocity_y
def calc_grav(self):
""" Calculate effect of gravity. """
if self.velocity_y == 0:
self.velocity_y = 1
else:
self.velocity_y += .35
# See if we are on the ground.
if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.velocity_y >= 0:
self.velocity_y = 0
self.rect.y = SCREEN_HEIGHT - self.rect.height
def jump(self):
self.velocity_y = -10
def go_left(self):
if self.rect.x > 0:
self.rect.x += -6
def go_right(self):
if self.rect.x < 760:
self.rect.x += 6
|
d736b315ca0e391f07046128196c94ea79ff3fb5 | quisitor/CMIT-135-40D_WEEK-3 | /voting_test.py | 926 | 4.40625 | 4 | """
:Student: Craig Smith
:Week-3: Conditional Logic Programs
:Module: voting_test
:Course: CMIT-135-40D (Champlain College)
:Professor: Steve Giles
Purpose
-------
This module takes in a potential voter's age and determines if they are 18 or
older and able to legally vote.
Constraints
-----------
1. Prompt the user to enter their age
2. Output uses the one of the following
a. 'You must be 18 to vote.'
b. 'You are of voting age.'
Parameters
----------
:param age: user input - integer
:returns: answer if age qualifies person to vote - string
"""
if __name__ == '__main__':
age_input = input("Please enter your age in years: ")
while True:
try:
age = int(age_input)
break;
except ValueError:
age_input = input("Please enter your age in years: ")
if age >= 18:
print("You are of voting age.")
else:
print("You must be 18 to vote.")
|
ab5d362fdf8ba636277b2414e30499ea6a64c949 | ajinkyavn1/hacking-Scripts | /PortScanenr.py | 292 | 3.546875 | 4 | # !/user/bin/python
import socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host='192.168.1.100'
port=135
def Scanner(port):
if sock.connect_ex((host,port)):
print("port %d is closed{port} ")
else:
print("Port %d is Open {port}")
Scanner(port) |
3c0efadd1ffb7dc5b856376b90abf790ef0d942f | Wim4rk/BTH-oopython | /kmom01/lab1/classes.py | 1,994 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Contains classes for lab1
"""
# from datetime import datetime
# import time
class Cat():
"""
Lab1
"""
_lives_left = 9
nr_of_paws = 4
def __init__(self):
""" Awaken the c-c-cat... """
self.eye_color = ''
self.name = ''
self._lives_left = -1
def set_lives_left(self, num):
""" Boost yout kitten """
self._lives_left = num
def get_lives_left(self):
""" Before the kitty gets it! """
return self._lives_left
def description(self):
""" How adorable! """
return ("My cats name is " + self.name +
", has " + self.eye_color + " eyes and " +
str(self._lives_left) + " lives left to live.")
class Duration():
"""
Or durata
"""
def __init__(self, H, m, s):
""" Constructor """
self.hours = H
self.minutes = m
self.seconds = s
def __add__(self, other):
""" Overloading (+) """
s = (self.duration_to_sec(self.display()) +
other.duration_to_sec(other.display()))
return s
def __iadd__(self, other):
""" Overloading (+=) """
self.hours += other.hours
self.minutes += other.minutes
self.seconds += other.seconds
return self
def display(self):
""" Display duration as formatted string """
t = []
t.append(str(self.hours).zfill(2))
t.append(str(self.minutes).zfill(2))
t.append(str(self.seconds).zfill(2))
return "-".join(t)
@staticmethod
def duration_to_sec(in_time):
""" Converts given time into seconds """
hours, minutes, seconds = map(int, in_time.split("-"))
s = hours * 3600
s += minutes * 60
s += seconds
return s
if __name__ == "__main__":
# t = Duration(12, 14, 26)
# print(t.display())
print(Duration.duration_to_sec("40-40-40"))
|
4528ccc368d986e51c2d5c20460be8255b450881 | dona126/Python-Programming | /Basics/loop.py | 199 | 3.84375 | 4 | #for loop
myList=[1,2,3,"meera"]
for x in myList:
print(x)
#while loop
i=0
while(i<4):
print(myList[i])
i=i+1
#break : exit from the loop
#continue : flow goes to beginning of loop
|
0a134dec034fa6f40e2039826911ce134292f8bf | xynicole/Python-Course-Work | /W12/ex7frameDemo.py | 1,862 | 4.3125 | 4 | import tkinter
'''
Creates labels in two different frames
'''
class MyGUI:
def __init__(self):
# Create main window
self.__main_window = tkinter.Tk()
# Create two frames, for top and bottom of window
self.__top_frame = tkinter.Frame(self.__main_window)
self.__bottom_frame = tkinter.Frame(self.__main_window)
# Create three labels that live in the top frame
self.__label1 = tkinter.Label(self.__top_frame, \
text='Omne')
self.__label2 = tkinter.Label(self.__top_frame, \
text='Trium')
self.__label3 = tkinter.Label(self.__top_frame, \
text='Perfectum')
# Pack the labels into the top frame so they are stacked
# Note that this is the default behavior
# (They would do this anyway)
self.__label1.pack(side='top')
self.__label2.pack(side='top')
self.__label3.pack(side='top')
## self.label1.pack()#side='top')
## self.label2.pack()#side='top')
## self.label3.pack()#side='top')
# Create three labels that live in the bottom frame
self.__label4 = tkinter.Label(self.__bottom_frame, \
text='Omne')
self.__label5 = tkinter.Label(self.__bottom_frame, \
text='Trium')
self.__label6 = tkinter.Label(self.__bottom_frame, \
text='Perfectum')
# Pack the labels into the bottom frame so they are
# arranged horizontally from left to right
self.__label4.pack(side='left')
self.__label5.pack(side='left')
self.__label6.pack(side='left')
# Then pack the frames into the main window
self.__top_frame.pack()
self.__bottom_frame.pack()
# Start the listener
tkinter.mainloop()
MyGUI()
|
567cbcc2a5bc59fabf57e326e30e02c9055c2b2b | hamza-yusuff/Python_prac | /Inter advanced threading python stuff/metaclasses.py | 935 | 3.65625 | 4 |
#using __new__
class players(object):
_number=0
def __new__(cls, *args,**kwargs):
instance=object.__new__(players)
if cls._number==2:
return None
else:
cls._number+=1
return instance
def __init__(self,fname,lname,score):
self.fname=fname
self.lname=lname
self.score=score
def __str__(self):
return f"{self.fname} {self.lname}"
class Foo:
def show(self):
print('hi')
def add_attribute(self):
self.z=9
print(self.z+1)
Test=type('Test',(Foo,),{'x':5,'add_attribute':add_attribute})
t=Test()
t.wy="hello"
t.add_attribute()
print(Test.x)
class foo:
def __new__(cls, *args, **kwargs):
instance = super(foo, cls).__new__(cls)
print(instance)
return instance
def __init__(self, a, b):
self.a = a
self.b = b
def bar(self):
pass
|
2b504c510c635a472121bba4a6636ec64d96c80b | Ramaraj2020/100 | /Kadane's Algorithm/max-product-subarray.py | 709 | 3.671875 | 4 | def maxProductSubArray(arr, N):
globalMax = 1
localMax = 1
start = end = 0
localStart = localEnd = 0
for i in range(len(arr)):
if arr[i] > 0:
localMax *= arr[i]
if localMax > globalMax:
globalMax = localMax
start = localStart
end = i
else:
localMax = 1
i += 1
localStart = i
return globalMax, start, end
if __name__ == '__main__':
arr = list(map(int, input().strip().split()))
maxProduct, start, end = maxProductSubArray(arr, len(arr))
print(arr)
print('Max Product :', maxProduct)
print('Start :', start)
print('End :', end) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.