blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
cd96d65248913b4b3238fac25f462e53c463ad85 | Byhako/python | /scripts/metodos/interpolacion_newton.py | 1,423 | 4.03125 | 4 | print("------- Interpolacion Polinomica (Newton) -------")
n = int(input("Ingrese el grado del polinomio a evaluar: ")) + 1
matriz = [0.0] * n
for i in range(n):
matriz[i] = [0.0] * n
vector = [0.0] * n
print(matriz)
print(vector)
for i in range(n):
x = input("Ingrese el valor de x: ")
y = input("Ingrese el valor de f("+x+"): ")
vector[i] = float(x)
matriz[i][0] = float(y)
print(vector)
print(matriz)
punto_a_evaluar = float(input("Ingrese el punto a evaluar: "))
print ("\n------- Calculando ... -------\n")
for i in range(1,n):
for j in range(i,n):
# print("i=",i," j=",j)
# print("(",matriz[j][i-1],"-",matriz[j-1][i-1],")/(",vector[j],"-",vector[j-i],")")
matriz[j][i] = ( (matriz[j][i-1]-matriz[j-1][i-1]) / (vector[j]-vector[j-i]))
# print("matriz[",j,"][",i,"] = ",(matriz[j][i-1]-matriz[j-1][i-1])/(vector[j]-vector[j-i]))
# print("------------------------------")
# for i in range(n):
# print(matriz[i])
# print("------------------------------")
aprx = 0
mul = 1.0
for i in range(n):
# print("matriz[",i,"][",i,"]","=",matriz[i][i])
mul = matriz[i][i];
# print("mul antes del ciclo j=",mul)
for j in range(1,i+1):
mul = mul * (punto_a_evaluar - vector[j-1])
# print("mul en el ciclo j=",mul)
# print aprx
aprx = aprx + mul
print("------------------------------")
print("El valor aproximado de f(",punto_a_evaluar,") es: ", aprx) |
9075401f4a353f91e1fe7b65a115e3b82e4e83f0 | Byhako/python | /poo/morral.py | 491 | 3.71875 | 4 | def morral(size, pesos, valores, n):
if n == 0 or size ==0 :
return 0
if pesos[n-1] > size:
return morral(size, pesos, valores, n-1)
return max(valores[n-1]+morral(size-pesos[n-1], pesos, valores, n-1),
morral(size, pesos, valores, n-1))
if __name__ == "__main__":
valores = [60, 100, 120]
pesos = [10, 20, 30]
size = 50
n = len(valores)
resultado = morral(size, pesos, valores, n)
print(resultado) |
42498a2bff950906b9c2cbbd13c4c5cbf89fb327 | Byhako/python | /scripts/estimar_pi.py | 1,417 | 3.625 | 4 | import random
print('ESTIMAR PI EN UN CIRCULO UNIDAD')
print('')
#MUESTREO SIMPLE
n=0
m=10000
c=0
c1=0
while c<m:
c1=c1+1
x=random.random()
y=random.random()
if x**2+y**2<1:
n=n+1
else:
c=c+1
print('Muestreo simple = %3.4f' %(4*n/c1 ))
#MARKOV
n=0 #asiertos
m=10000 #intentos
x=0
y=0
c=0
c1=0
p=0.3 #paso
while c<m:
c1=c1+1
dx=random.uniform(-p,p)
dy=random.uniform(-p,p)
if (abs(x+dx)<1 and abs(y+dy)<1):
x=x+dx
y=y+dy
else:
if x**2+y**2<1:
n=n+1
else:
c=c+1
print('Marcov = %3.4f' %(4*n/m))
"""
El algoritmo comienza a partir de una posición dada en el espacio a ser muestreados [aquí (0, 0)] y genera la posición del nuevo punto desde la posición de la anterior. Si la nueva posición se encuentra fuera de la plaza, se rechaza (línea 38). Una selección cuidadosa del tamaño de paso p utiliza para generar números aleatorios en el intervalo [-p, p] es de importancia: cuando p es demasiado pequeño, la convergencia es lenta, mientras que si p es demasiado grande muchos movimientos son rechazados porque la simulación menudo dejar el cuadrado unitario. Por lo tanto, un valor de p tiene que ser seleccionado de tal manera que se aceptan movimientos consecutivos aproximadamente el 50% del tiempo.
"""
|
37660afa5ef0d3c689e590713f622ba465bfd038 | glc12125/Algo | /lintcode/Time to flower tree.py | 1,827 | 3.796875 | 4 | '''
There is a tree of nn nodes with Num.00 to n-1n−1, where node 00 is the root node and the parent node of node ii is father[i]father[i]. Now to water the tree, sprinkle water on the root node, the water will flow down every edge, from the father of node ii to node ii costs time[i]time[i], how long will it take to flow water to all nodes?
'''
from typing import (
List, Dict, Set
)
class Solution:
"""
@param father: the father of every node
@param time: the time from father[i] to node i
@return: time to flower tree
"""
def time_to_flower_tree(self, father: List[int], time: List[int]) -> int:
# write your code here
max_time = 0
cache = {}
for i in range(1, len(father)):
this_time = self.search(father, time, cache, i)
max_time = max(max_time, this_time)
return max_time
def search(self, father: List[int], time: List[int], cache: Dict, node: int):
if node == 0:
return 0
if node in cache:
return cache[node]
cache[node] = time[node] + self.search(father, time, cache, father[node])
return cache[node]
def time_to_flower_tree(self, father: List[int], time: List[int]) -> int:
# write your code here
graph = self.build_graph(father)
queue = collections.deque([(0, 0)])
max_time = 0
while queue:
node, current_time = queue.popleft()
max_time = max(max_time, current_time)
for son in graph[node]:
queue.append((son, current_time + time[son]))
return max_time
def build_graph(self, father: List[int]) -> Dict:
graph = collections.defaultdict(set)
for i in range(len(father)):
graph[father[i]].add(i)
return graph |
c8998af521723e52952d0cd1d0916d039a6ce736 | Jerome4914/for_loop_basicI | /for_loop_basicI.py | 550 | 3.65625 | 4 | #1
# for x in range(0, 151, 1):
# print(x)
#2
# for x in range(0, 1001, 5):
# print(x)
#3
# for x in range(0, 101, 1):
# if (x) % 5 == 0:
# print("Coding")
# else:
# print(x)
# if (x) % 10 == 0:
# print("Coding Dojo")
#4
# sum=0
# for x in range(1, 5000, 2):
# if (x) % 2 == 1:
# sum = sum + x
# print(sum)
#5
# for x in range(2018, 0, -4):
# print(x)
#6
lownum = int(10)
highnum = int(100)
mult = int(10)
for x in range(lownum, highnum + 1,):
if (x % mult == 0):
print(x)
|
7d87a377afbf254405c33b1ed03cac858144bca9 | shivarajmishra/jupyter-book-demo | /_build/jupyter_execute/basics1.py | 23,480 | 3.953125 | 4 | # Python Basics I
<img align="left" src="https://ithaka-labs.s3.amazonaws.com/static-files/images/tdm/tdmdocs/CC_BY.png"><br />
Created by [Nathan Kelber](http://nkelber.com) and Ted Lawless for [JSTOR Labs](https://labs.jstor.org/) under [Creative Commons CC BY License](https://creativecommons.org/licenses/by/4.0/)<br />
For questions/comments/improvements, email nathan.kelber@ithaka.org.<br />
___
**Python Basics I**
**Description:** This lesson describes [operators](https://docs.tdm-pilot.org/key-terms/#operator), [expressions](https://docs.tdm-pilot.org/key-terms/#expression), data types, [variables](https://docs.tdm-pilot.org/key-terms/#variable), and basic [functions](https://docs.tdm-pilot.org/key-terms/#function). Complete this lesson if you are familiar with [Jupyter notebooks](https://docs.tdm-pilot.org/key-terms/#jupyter-notebook) or have completed *Getting Started with Jupyter Notebooks*, but do not have any experience with [Python](https://docs.tdm-pilot.org/key-terms/#python) programming. This is part 1 of 3 in the series *Python Basics* that will prepare you to do text analysis using the [Python](https://docs.tdm-pilot.org/key-terms/#python) programming language.
**Use Case:** For Learners (Detailed explanation, not ideal for researchers)
**Difficulty:** Beginner
**Completion Time:** 75 minutes
**Knowledge Required:**
* [Getting Started with Jupyter Notebooks](./getting-started-with-jupyter.ipynb)
**Knowledge Recommended:** None
**Data Format:** None
**Libraries Used:** None
**Research Pipeline:** None
___
[](https://www.youtube.com/watch?v=90wFLSjlFL8)
## Introduction
[Python](https://docs.tdm-pilot.org/key-terms/#python) is the fastest-growing language in computer programming. Learning [Python](https://docs.tdm-pilot.org/key-terms/#python) is a great choice because [Python](https://docs.tdm-pilot.org/key-terms/#python) is:
* Widely-adopted in the digital humanities and data science
* Regarded as an easy-to-learn language
* Flexible, having wide support for working with numerical and textual data
* A skill desired by employers in academic, non-profit, and private sectors
The second most-popular language for digital humanities and data science work is [R](https://docs.tdm-pilot.org/key-terms/#r). We plan to create additional support for learning [R](https://docs.tdm-pilot.org/key-terms/#r) soon. If you are interested in helping develop open educational resources for [R](https://docs.tdm-pilot.org/key-terms/#r), please reach out to Nathan Kelber (nathan.kelber@ithaka.org).
The skills you'll learn in *Python Basics* I-III are general-purpose [Python](https://docs.tdm-pilot.org/key-terms/#python) skills, applicable for any of the text analysis notebooks that you may explore later. They are also widely applicable to many other kinds of tasks in [Python](https://docs.tdm-pilot.org/key-terms/#python) beyond text analysis.
**Making Mistakes is Important**
Every programmer at every skill level gets errors in their code. Making mistakes is how we all learn to program. Programming is a little like solving a puzzle where the goal is to get the desired outcome through a series of attempts. You won't solve the puzzle if you're afraid to test if the pieces match. An error message will not break your computer. Remember, you can always reload a notebook if it stops working properly or you misplace an important piece of code. Under the edit menu, there is an option to undo changes. (Alternatively, you can use **command z** on Mac and **control z** on Windows.) To learn any skill, you need to be willing to play and experiment. Programming is no different.
# Expressions and Operators
The simplest form of Python programming is an [expression](https://docs.tdm-pilot.org/key-terms/#expression) using an [operator](https://docs.tdm-pilot.org/key-terms/#operator). An [expression](https://docs.tdm-pilot.org/key-terms/#expression) is a simple mathematical statement like:
> 1 + 1
The [operator](https://docs.tdm-pilot.org/key-terms/#operator) in this case is `+`, sometimes called "plus" or "addition". Try this operation in the code box below. Remember to click the "Run" button or press Ctrl + Enter (Windows) or shift + return (OS X) on your keyboard to run the code.
# Type the expression in this code block. Then run it.
Python can handle a large variety of [expressions](https://docs.tdm-pilot.org/key-terms/#expression). Let's try subtraction in the next [code cell](https://docs.tdm-pilot.org/key-terms/#code-cell).
# Type an expression that uses subtraction in this cell. Then run it.
We can also do multiplication (\*) and division (/). While you may have used an "×" to represent multiplication in grade school, [Python](https://docs.tdm-pilot.org/key-terms/#python) uses an asterisk (\*). In [Python](https://docs.tdm-pilot.org/key-terms/#python),
> 2 × 2
is written as
> 2 * 2
Try a multiplication and a division in the next [code cell](https://docs.tdm-pilot.org/key-terms/#code-cell).
# Try a multiplication in this cell. Then try a division.
# What happens if you combine them? What if you combine them with addition and/or subtraction?
When you run, or **evaluate**, an [expression](https://docs.tdm-pilot.org/key-terms/#expression) in [Python](https://docs.tdm-pilot.org/key-terms/#python), the order of operations is followed. (In grade school, you may remember learning the shorthand "PEMDAS".) This means that [expressions](https://docs.tdm-pilot.org/key-terms/#expression) are evaluated in this order:
1. Parentheses
2. Exponents
3. Multiplication and Division (from left to right)
4. Addition and Subtraction (from left to right)
[Python](https://docs.tdm-pilot.org/key-terms/#python) can evaluate parentheses and exponents, as well as a number of additional [operators](https://docs.tdm-pilot.org/key-terms/#operator) you may not have learned in grade school. Here are the main [operators](https://docs.tdm-pilot.org/key-terms/#operator) that you might use presented in the order they are evaluated:
|Operator| Operation| Example | Evaluation |
|---|----|---|---|
|\*\*| Exponent/Power| 3 ** 3 | 27 |
|%| Modulus/Remainder| 34 % 6 | 4 |
|/| Division | 30 / 6 | 5|
|\*| Multiplication | 7 * 8 | 56 |
|-| Subtraction | 18 - 4| 14|
|+| Addition | 4 + 3 | 7 |
# Try operations in this code cell.
# What happens when you add in parentheses?
# Data Types (Integers, Floats, and Strings)
All [expressions](https://docs.tdm-pilot.org/key-terms/#expression) evaluate to a single value. In the above examples, our [expressions](https://docs.tdm-pilot.org/key-terms/#expression) evaluated to single numerical value. Numerical values come in two basic forms:
* [integer](https://docs.tdm-pilot.org/key-terms/#integer)
* [float](https://docs.tdm-pilot.org/key-terms/#float) (or floating-point number)
An [integer](https://docs.tdm-pilot.org/key-terms/#integer), what we sometimes call a "whole number", is a number without a decimal point that can be positive or negative. When a value uses a decimal, it is called a [float](https://docs.tdm-pilot.org/key-terms/#float) or floating-point number. Two numbers that are mathematically equivalent could be in two different data types. For example, mathematically 5 is equal to 5.0, yet the former is an [integer](https://docs.tdm-pilot.org/key-terms/#integer) while the latter is a [float](https://docs.tdm-pilot.org/key-terms/#float).
Of course, [Python](https://docs.tdm-pilot.org/key-terms/#python) can also help us manipulate text. A snippet of text in Python is called a [string](https://docs.tdm-pilot.org/key-terms/#string). A [string](https://docs.tdm-pilot.org/key-terms/#string) can be written with single or double quotes. A [string](https://docs.tdm-pilot.org/key-terms/#string) can use letters, spaces, line breaks, and numbers. So 5 is an [integer](https://docs.tdm-pilot.org/key-terms/#integer), 5.0 is a [float](https://docs.tdm-pilot.org/key-terms/#float), but '5' and '5.0' are [strings](https://docs.tdm-pilot.org/key-terms/#string). A [string](https://docs.tdm-pilot.org/key-terms/#string) can also be blank, such as ''.
|Familiar Name | Programming name | Examples |
|---|---|---|
|Whole number|integer| -3, 0, 2, 534|
|Decimal|float | 6.3, -19.23, 5.0, 0.01|
|Text|string| 'Hello world', '1700 butterflies', '', '1823'|
The distinction between each of these data types may seem unimportant, but [Python](https://docs.tdm-pilot.org/key-terms/#python) treats each one differently. For example, we can ask [Python](https://docs.tdm-pilot.org/key-terms/#python) whether an [integer](https://docs.tdm-pilot.org/key-terms/#integer) is equal to a [float](https://docs.tdm-pilot.org/key-terms/#float), but we cannot ask whether a [string](https://docs.tdm-pilot.org/key-terms/#string) is equal to an [integer](https://docs.tdm-pilot.org/key-terms/#integer) or a [float](https://docs.tdm-pilot.org/key-terms/#float).
To evaluate whether two values are equal, we can use two equals signs between them. The expression will evaluate to either `True` or `False`.
# Run this code cell to determine whether the values are equal
42 == 42.0
# Run this code cell to compare an integer with a string
15 == 'fifteen'
# Run this code cell to compare an integer with a string
15 == '15'
When we use the addition [operator](https://docs.tdm-pilot.org/key-terms/#operator) on [integers](https://docs.tdm-pilot.org/key-terms/#integer) or [floats](https://docs.tdm-pilot.org/key-terms/#float), they are added to create a sum. When we use the addition [operator](https://docs.tdm-pilot.org/key-terms/#operator) on [strings](https://docs.tdm-pilot.org/key-terms/#string), they are combined into a single, longer [string](https://docs.tdm-pilot.org/key-terms/#string). This is called [concatenation](https://docs.tdm-pilot.org/key-terms/#concatenation).
# Combine the strings 'Hello' and 'World'
'Hello' + 'World'
Notice that the [strings](https://docs.tdm-pilot.org/key-terms/#string) are combined exactly as they are written. There is no space between the [strings](https://docs.tdm-pilot.org/key-terms/#string). If we want to include a space, we need to add the space to the end of 'Hello' or the beginning of 'World'. We can also concatenate multiple [strings](https://docs.tdm-pilot.org/key-terms/#string).
# Combine three strings
'Hello ' + 'World' + '!'
When we use addition [operator](https://docs.tdm-pilot.org/key-terms/#operator), the values must be all numbers or all [strings](https://docs.tdm-pilot.org/key-terms/#string). Combining them will create an error.
# Try adding a string to an integer
'55' + 23
Here, we receive the error `can only concatenate str (not "int") to str`. [Python](https://docs.tdm-pilot.org/key-terms/#python) assumes we would like to join two [strings](https://docs.tdm-pilot.org/key-terms/#string) together, but it does not know how to join a [string](https://docs.tdm-pilot.org/key-terms/#string) to an [integer](https://docs.tdm-pilot.org/key-terms/#integer). Put another way, [Python](https://docs.tdm-pilot.org/key-terms/#python) is unsure if we want:
>'55' + 23
to become
>'5523'
or
>78
We *can* multiply a [string](https://docs.tdm-pilot.org/key-terms/#string) by an [integer](https://docs.tdm-pilot.org/key-terms/#integer). The result is simply the [string](https://docs.tdm-pilot.org/key-terms/#string) repeated the appropriate number of times.
# Multiply a string by an integer
'Hello World!' * 5
# Variables
A [variable](https://docs.tdm-pilot.org/key-terms/#variable) is like a container that stores information. There are many kinds of information that can be stored in a [variable](https://docs.tdm-pilot.org/key-terms/#variable), including the data types we have already discussed ([integers](https://docs.tdm-pilot.org/key-terms/#integer), [floats](https://docs.tdm-pilot.org/key-terms/#float), and [string](https://docs.tdm-pilot.org/key-terms/#string)). We create (or *initialize*) a [variable](https://docs.tdm-pilot.org/key-terms/#variable) with an [assignment statement](https://docs.tdm-pilot.org/key-terms/#assignment-statement). The [assignment statement](https://docs.tdm-pilot.org/key-terms/#assignment-statement) gives the variable an initial value.
# Initialize an integer variable and add 22
new_integer_variable = 5
new_integer_variable + 22
The value of a [variable](https://docs.tdm-pilot.org/key-terms/#variable) can be overwritten with a new value.
# Overwrite the value of my_favorite_number when the commented out line of code is executed.
# Remove the # in the line "#my_favorite_number = 9" to turn the line into executable code.
my_favorite_number = 7
my_favorite_number = 9
my_favorite_number
# Overwriting the value of a variable using its original value
cats_in_house = 1
cats_in_house = cats_in_house + 2
cats_in_house
# Initialize a string variable and concatenate another string
new_string_variable = 'Hello '
new_string_variable + 'World!'
You can create a [variable](https://docs.tdm-pilot.org/key-terms/#variable) with almost any name, but there are a few guidelines that are recommended.
## Variable Names Should be Descriptive
If we create a [variable](https://docs.tdm-pilot.org/key-terms/#variable) that stores the day of the month, it is helpful to give it a name that makes the value stored inside it clear like `day_of_month`. From a logical perspective, we could call the [variable](https://docs.tdm-pilot.org/key-terms/#variable) almost anything (`hotdog`, `rabbit`, `flat_tire`). As long as we are consistent, the code will execute the same. When it comes time to read, modify, and understand the code, however, it will be confusing to you and others. Consider this simple program that lets us change the `days` [variable](https://docs.tdm-pilot.org/key-terms/#variable) to compute the number of seconds in that many days.
# Compute the number of seconds in 3 days
days = 3
hours_in_day = 24
minutes_in_hour = 60
seconds_in_minute = 60
days * hours_in_day * minutes_in_hour * seconds_in_minute
We could write a program that is logically the same, but uses confusing [variable](https://docs.tdm-pilot.org/key-terms/#variable) names.
hotdogs = 60
sasquatch = 24
example = 3
answer = 60
answer * sasquatch * example * hotdogs
This code gives us the same answer as the first example, but it is confusing. Not only does this code use [variable](https://docs.tdm-pilot.org/key-terms/#variable) names that are confusing, it also does not include any comments to explain what the code does. It is not clear that we would change `example` to set a different number of days. It is not even clear what the purpose of the code is. As code gets longer and more complex, having clear [variable](https://docs.tdm-pilot.org/key-terms/#variable) names and explanatory comments is very important.
## Variable Naming Rules
In addition to being descriptive, [variable](https://docs.tdm-pilot.org/key-terms/#variable) names must follow 3 basic rules:
1. Must be one word (no spaces allowed)
2. Only letters, numbers and the underscore character (\_)
3. Cannot begin with a number
# Which of these variable names are acceptable?
# Comment out the variables that are not allowed in Python and run this cell to check if the variable assignment works.
# If you get an error, the variable name is not allowed in Python.
$variable = 1
a variable = 2
a_variable = 3
4variable = 4
variable5 = 5
variable-6 = 6
variAble = 7
Avariable = 8
## Variable Naming Style Guidelines
The three rules above describe absolute rules of [Python](https://docs.tdm-pilot.org/key-terms/#python) [variable](https://docs.tdm-pilot.org/key-terms/#variable) naming. If you break those rules, your code will create an error and fail to execute properly. There are also style *guidelines* that, while they won't break your code, are generally advised for making your code readable and understandable. These style guidelines are written in the [Python Enhancement Proposals (PEP) Style Guide](https://www.python.org/dev/peps/pep-0008/).
The current version of the style guide advises that [variable](https://docs.tdm-pilot.org/key-terms/#variable) names should be written:
>lowercase, with words separated by underscores as necessary to improve readability.
If you have written code before, you may be familiar with other styles, but these notebooks will attempt to follow the PEP guidelines for style. Ultimately, the most important thing is that your [variable](https://docs.tdm-pilot.org/key-terms/#variable) names are consistent so that someone who reads your code can follow what it is doing. As your code becomes more complicated, writing detailed comments with `#` will also become more important.
snake_case_variable
kebab-case-variable
CamelCaseVariable
# Functions
Many different kinds of programs often need to do very similar operations. Instead of writing the same code over again, you can use a [function](https://docs.tdm-pilot.org/key-terms/#function). Essentially, a [function](https://docs.tdm-pilot.org/key-terms/#function) is a small snippet of code that can be quickly referenced. There are three kinds of [functions](https://docs.tdm-pilot.org/key-terms/#function):
* Native [functions](https://docs.tdm-pilot.org/key-terms/#function) built into [Python](https://docs.tdm-pilot.org/key-terms/#python)
* [Functions](https://docs.tdm-pilot.org/key-terms/#function) others have written that you can import
* [Functions](https://docs.tdm-pilot.org/key-terms/#function) you write yourself
We'll address [functions](https://docs.tdm-pilot.org/key-terms/#function) you write yourself in *Python Basics* II. For now, let's look at a few of the native [functions](https://docs.tdm-pilot.org/key-terms/#function). One of the most common [functions](https://docs.tdm-pilot.org/key-terms/#function) used in [Python](https://docs.tdm-pilot.org/key-terms/#python) is the `print()` [function](https://docs.tdm-pilot.org/key-terms/#function) which simply prints a [string](https://docs.tdm-pilot.org/key-terms/#string).
# A print function that prints: Hello World!
print('Hello World!')
We could also define a [variable](https://docs.tdm-pilot.org/key-terms/#variable) with our [string](https://docs.tdm-pilot.org/key-terms/#string) ```'Hello World!'``` and then pass that [variable](https://docs.tdm-pilot.org/key-terms/#variable) into the `print()` function. It is common for functions to take an input, called an [argument](https://docs.tdm-pilot.org/key-terms/#argument), that is placed inside the parentheses ().
# Define a string and then print it
our_string = 'Hello World!'
print(our_string)
There is also an `input()` [function](https://docs.tdm-pilot.org/key-terms/#function) for taking user input.
# A program to greet the user by name
print('Hi. What is your name?') # Ask the user for their name
user_name = input() # Take the user's input and put it into the variable user_name
print('Pleased to meet you, ' + user_name) # Print a greeting with the user's name
We defined a [string](https://docs.tdm-pilot.org/key-terms/#string) [variable](https://docs.tdm-pilot.org/key-terms/#variable) ```user_name``` to hold the user's input. We then called the `print()` [function](https://docs.tdm-pilot.org/key-terms/#function) to print the [concatenation](https://docs.tdm-pilot.org/key-terms/#concatenate) of 'Pleased to meet you, ' and the user's input that was captured in the [variable](https://docs.tdm-pilot.org/key-terms/#variable) ```user_name```. Remember that we can use a ```+``` to [concatenate](https://docs.tdm-pilot.org/key-terms/#concatenate), meaning join these [strings](https://docs.tdm-pilot.org/key-terms/#string) together.
We could also use an `f string` to print a variable name within a larger string.
# Placing an f before a string, allows us to reference variables in brackets {}
print(f'Hello {user_name}, pleased to meet you!')
We can [concatenate](https://docs.tdm-pilot.org/key-terms/#concatenate) many [strings](https://docs.tdm-pilot.org/key-terms/#string) together, but we cannot [concatenate](https://docs.tdm-pilot.org/key-terms/#concatenate) [strings](https://docs.tdm-pilot.org/key-terms/#string) with [integers](https://docs.tdm-pilot.org/key-terms/#integer) or [floats](https://docs.tdm-pilot.org/key-terms/#float).
# Concatenating many strings within a print function
print('Hello, ' + 'all ' + 'these ' + 'strings ' + 'are ' + 'being ' + 'connected ' + 'together.')
# Trying to concatenate a string with an integer causes an error
print('There are ' + 7 + 'continents.')
We can transform one [variable](https://docs.tdm-pilot.org/key-terms/#variable) type into another [variable](https://docs.tdm-pilot.org/key-terms/#variable) type with the `str()`, `int()`, and `float()` [functions](https://docs.tdm-pilot.org/key-terms/#function). Let's convert the [integer](https://docs.tdm-pilot.org/key-terms/#integer) above into a [string](https://docs.tdm-pilot.org/key-terms/#string) so we can [concatenate](https://docs.tdm-pilot.org/key-terms/#concatenate) it.
print('There are ' + str(7) + ' continents.')
Mixing [strings](https://docs.tdm-pilot.org/key-terms/#string) with [floats](https://docs.tdm-pilot.org/key-terms/#float) and [integers](https://docs.tdm-pilot.org/key-terms/#integer) can have unexpected results. See if you can spot the problem with the program below.
# A program to tell a user how many months old they are
print('How old are you?') # Ask the user their age
user_age = input() # Take the user input and put it into the variable user_age
number_of_months = int(user_age) * 12 # Define a new variable number_of_months that multiplies the user's age by 12
print('That is more than ' + str(number_of_months) + ' months old!' ) # Print a response that tells the user they are at least number_of_months old
In order to compute the [variable](https://docs.tdm-pilot.org/key-terms/#variable) ```number_of_months```, we multiply ```user_age``` by 12. The problem is that ```user_age``` is a [string](https://docs.tdm-pilot.org/key-terms/#string). Multiplying a [string](https://docs.tdm-pilot.org/key-terms/#string) by 12 simply makes the string repeat 12 times. After the user gives us their age, we need that input to be converted to an [integer](https://docs.tdm-pilot.org/key-terms/#integer). At the same time, we have to convert the [integer](https://docs.tdm-pilot.org/key-terms/#integer) ```number_of_months``` back to a [string](https://docs.tdm-pilot.org/key-terms/#string) for our final `print()` function.
# A program to tell a user how many months old they are
print('How old are you?') # Ask the user their age
user_age = input() # Take the user input and put it into the variable user_age
number_of_months = int(user_age) * 12 # Define a new variable number_of_months that multiplies the user's age by 12
print('That is more than ' + str(number_of_months) + ' months old!' ) # Print a response that tells the user they are at least number_of_months old
___
# Lesson Complete
Congratulations! You have completed *Python Basics* I. There are two more lessons in *Python Basics*:
* *Python Basics* II
* *Python Basics* III
## Python Basics I Quiz
If you would like to check your understading of this lesson, you can [take this quick quiz](https://docs.google.com/forms/d/e/1FAIpQLSdTPq_BotRY_eqJIfIXT2OoWkv9MwgOKngWcTYJfilwbQ6eAQ/viewform?usp=sf_link).
## Start Next Lesson: [Python Basics II](./python-basics-2.ipynb)
|
7de7efb40b5db9a3e34dccd9b3e106e6f159dfff | vamshi99k/python-programs | /stringvalidators.py | 267 | 3.65625 | 4 | s=input()
res=['False','False','False','False','False']
for i in s:
if i.isalnum():
res[0]='True'
if i.isalpha():
res[1]='True'
if i.isdigit():
res[2]='True'
if i.islower():
res[3]='True'
if i.isupper():
res[4]='True'
print(*res, sep='\n') |
5ae6d412a388802c9b4811d8d4a209ce5925b80d | vamshi99k/python-programs | /count_letters_digits - Copy.py | 307 | 3.9375 | 4 | def count_letters_digits(sentence):
letter_count=0
digit_count=0
for letter in sentence:
if letter.isdigit():
digit_count+=1
if letter.isalpha():
letter_count+=1
result=[letter_count,digit_count]
return result
sentence='hi bro how are 9999'
print(count_letters_digits(sentence))
|
a7b8d7ba2901fd0417800f51e4f9f81af05f21ad | SeonMoon-Lee/pythonStudy | /dict_comprehension.py | 597 | 3.828125 | 4 | '''
dictonary comprehension
딕셔너리를 생성과 동시에 값을 할당하는 문법
dict = { 키:값 for 키,값 in 반복돌릴것}
'''
students = ["태연","진우","정현","하늘","성진"]
for number , name in enumerate(students):
print ("{}번의 이름은 {}입니다.".format(number,name))
students_dict = {"{}번".format(number+1): name for number, name in enumerate(students)}
print(students_dict)
scores = [85,92,78,90,100]
for x,y in zip(students, scores):
print(x,y)
score_dict = {student:score for student, score in zip(students,scores)}
print(score_dict) |
aaabeeca1e8964ce74aa230c70a085f97bb74c15 | SeonMoon-Lee/pythonStudy | /raise.py | 778 | 3.765625 | 4 | def rsp(mine,yours):
allowed = ["가위","바위","보"]
if mine not in allowed:
raise ValueError
if yours not in allowed:
raise ValueError
#가위바위보 승패를 판단하는 코드
try:
rsp('가위','바')
except ValueError:
print("잘못된 값을 입력한 것 같습니다")
school = {"1반":[172,185,198,177,165,199], "2반":[165,177,167,180,191]}
try:
for class_number, students in school.items():
for student in students:
if student > 190:
print(class_number,"반에 190을 넘는 학생이 있습니다")
raise StopIteration
except StopIteration:
print("정상종료")
'''
raise 사용자가 직접 에러를 발생시키는 명령어
''' |
5cd17480ee4a097b2d437e305ffddadab596d7ea | SeonMoon-Lee/pythonStudy | /class_method.py | 1,040 | 3.625 | 4 | '''
메소드 : 클래스 내부 함수
특수 메소드
__init__() : 인스턴스를 만들 때 실행되는 함수 (생성자)
__str__() : 인스턴스 자체를 출력할 때의 문자열 형식을 지정해 주는 함수
'''
class Human():
'''인간'''
def __init__(self,name,weight):
#초기화 함수
print("__init_실행")
print("이름은 {},몸무게는 {}".format(name,weight))
self.name = name
self.weight = weight
def __str__(self):
#문자열화 함수
return "{}(몸무게 {}kg)".format(self.name,self.weight)
def eat(self):
self.weight+=0.1
print("{}가 먹어서 {}kg이 되었습니다.".format(person.name,person.weight))
def walk(self):
self.weight-=0.1
print("{}가 걸어서 {}kg이 되었습니다.".format(person.name,person.weight))
def speak(self, message):
print(message)
person = Human("철수",60.5)
person.walk()
person.eat()
person.speak("안녕하세요")
print(person) |
97b2a81aaf57fb021ca6b2c49b7bc925d98ba193 | SeonMoon-Lee/pythonStudy | /class.py | 1,049 | 4.25 | 4 | class Human():
'''인간'''
#person = Human()
#person.name = '철수'
#person.weight = 60.5
def create_human(name,weight):
person = Human()
person.name = name
person.weight = weight
return person
Human.create = create_human
person = Human.create("철수",60.5)
def eat(person):
person.weight+=0.1
print("{}가 먹어서 {}kg이 되었습니다.".format(person.name,person.weight))
def walk(person):
person.weight-=0.1
print("{}가 걸어서 {}kg이 되었습니다.".format(person.name,person.weight))
Human.eat = eat
Human.walk = walk
person.walk()
person.eat()
'''
class Human():
"""사람"""
person1 = Human()
person2 = Human()
person1.language = '한국어'
person2.language = 'English'
print(person1.language)
print(person2.language)
person1.name = "서울시민"
person2.name = "인도인"
def speak(person):
print("{}이 {}로 말을 합니다.".format(person.name,person.language))
speak(person1)
speak(person2)
Human.speak = speak
person1.speak()
person2.speak()
'''
|
4c3e7cbbf2e78c3734ee56147a9c83ab33ffa5c5 | Gaminhbirol/BEDU_Python | /Reto_01.2.py | 322 | 4.03125 | 4 |
alumnos = ['Diego', 'Paco', 'Ricky', 'Barbara', 'Canelo']
alumnos.sort()
print('En esta clase de Python los alumnos son: ', alumnos)
nuevo_alum = 'Perengano'
print('El nuevo alumno es: ', nuevo_alum)
alumnos.append(nuevo_alum)
print('Total de alumnos: ', alumnos)
alumnos.sort()
print('Alumnos ordenados: ', alumnos)
|
6d65f634ae17e8ea902799358a0b1fa4b1436219 | parthdoshi/seniordesign | /src/line-db-maker/scrubber.py | 1,983 | 3.5625 | 4 | #! /usr/bin/env/python3
"""
map.py accesses the SEPTA website and outputs
an xml file containing in an xml file containing a list
of station elements with name and url subelements.
The output file is called "results.xml"
usage: $ python map.py
"""
import xml.etree.ElementTree as ET
import urllib.request
import re
import sys
from xml.etree.ElementTree import ElementTree
def get_HTML():
url = "http://www.septa.org/maps/system/index.html"
# UTF-8 encoded checked by hand on a couple of urls
return urllib.request.urlopen(url).read().decode('utf8')
def get_element(text):
stationlist = []
for line in text:
if re.match("(.*)coords(.*)", line):
try:
idxCoord = line.index("coords")
firstCoord = line.index("\"", idxCoord) + 1
secondCoord = line.index("\"", firstCoord)
foundCoord = line[firstCoord:secondCoord]
idxHref = line.index("href")
firstHref = line.index("\"", idxHref) + 1
secondHref = line.index("\"", firstHref)
foundHref = line[firstHref:secondHref]
idxAlt = line.index("alt")
firstAlt = line.index("\"", idxAlt) + 1
secondAlt = line.index("\"", firstAlt)
foundAlt = line[firstAlt:secondAlt]
station = ET.Element('station')
name = ET.SubElement(station, 'name')
coord = ET.SubElement(station, 'coordinates')
url = ET.SubElement(station, 'url')
name.text = foundAlt
coord.text = foundCoord
url.text = "http://www.septa.org/" + foundHref[12:]
stationlist.append(station)
except ValueError:
print("Could not parse " + line)
return stationlist
if __name__ == "__main__":
outfile = "results.xml"
# delete outfile if it exists
import os
if (os.path.exists(outfile)):
os.unlink(outfile)
if len(sys.argv) > 1:
print(__doc__)
sys.exit(1)
text = get_HTML()
children = get_element(text.split("\n"))
tree = ElementTree()
root = ET.Element('septa-stations')
tree._setroot(root)
for child in children:
root.append(child)
tree.write(outfile)
|
143523ac0974d17f3644fa70676956a5f7ae3c1b | Granteur/50_States | /main.py | 1,675 | 3.875 | 4 | import turtle
import pandas
BACKGROUND = "blank_states_img.gif"
screen = turtle.Screen()
#gives game a title
screen.title("United States Game")
#sets the background
screen.bgpic(BACKGROUND)
#Alternative way of setting the background
"""screen.addshape(BACKGROUND)
turtle.shape(BACKGROUND)"""
data = pandas.read_csv("50_states.csv")
list_of_states = data.state.to_list()
correct_guesses = []
state_count = len(correct_guesses)
#1 - Convert guess to Title Case
#2 - Check if guess is among the 50 States
while len(correct_guesses) < 50:
answer_state = screen.textinput(title=f"{len(correct_guesses)}/50 Correct States", prompt="What is a state's name?").title()
if answer_state == "Exit":
states_to_learn = [state for state in list_of_states if state not in correct_guesses]
new_data = pandas.DataFrame(states_to_learn)
new_data.to_csv("States to Learn.csv")
break
if answer_state in list_of_states:
correct_guesses.append(answer_state)
ganke = turtle.Turtle()
ganke.hideturtle()
ganke.penup()
state_data = data[data.state == answer_state]
ganke.goto(int(state_data.x), int(state_data.y))
ganke.write(answer_state)
#alternative - ganke.write(data.state.item()) - not necessary because we already checked the answer
state_count += 1
#print(correct_guesses)
#3 - Write correct guesses on map
#4 - Write a loop to allow user to keep guessing
#5 - Record correct guesses in a list
#6 - Keep track of score
#7 ** Not really a bonus, but update screen.title dynamically with the correct number of guesses
#8 ** Bonus - add a "give up" button
|
69a27f23c239060d45714fe27813cbb18a502dbb | kmanc/cryptopals | /cryptopals/attacks/aes.py | 397 | 3.609375 | 4 | def detect_ecb(input_bytes: bytes):
"""Takes in a byte string. Determines whether or not it is likely to be an AEC-ECB-encrypted ciphertext"""
number_original_chunks = len(input_bytes) // 16
dedupe_chunks = {input_bytes[i: i + 16] for i in range(0, len(input_bytes), 16)}
result = False
if len(dedupe_chunks) < number_original_chunks:
result = True
return result
|
15450e86511ccb6b4ba180ed0966b35a9a86ce7c | Arpita2327/regresspy | /test/model.py | 584 | 3.5 | 4 | from numpy.lib.npyio import load
import numpy as np
from sklearn.linear_model import SGDRegressor
from sklearn.datasets import load_iris
from regresspy.regression import Regression
from regresspy.loss import rmse
iris = load_iris()
# We will use sepal length to predict sepal width
X = iris.data[:, 0].reshape(-1, 1)
Y = iris.data[:, 1].reshape(-1, 1)
#TODO Perform a linear regression using sklearn and calculate training rmse.
# Use the SGDRegressor and only select set learning rate and epochs.
#TODO Perform a linear regression using your code and calculate training rmse.
|
b4b769475ec048c52b79b49130f7c798ed2c5d1f | InertiaElectric-IE/InertiaElectric-IE.github.io | /InertiaElectric/TestRun.py | 140 | 3.578125 | 4 | firstname = input("Print First Name Here: ")
Lastname = input( "Print Last Name Here: ")
print("Your full name is ", firstname, Lastname)
|
34c606463f5d699e2b44b6d27b0c2263f9a8928f | Tydroneous/Rock-Paper-Scissors | /Problems/Letter-spacing/task.py | 68 | 3.578125 | 4 | word = list(input())
num = int(input())
print(*word, sep=' ' * num)
|
0c324fda23710ad69fa3f42bb6096d681a238b13 | 1160287301/python_study | /坑/test2.py | 890 | 3.859375 | 4 | # -*- coding:utf-8 -*-
import operator
#-----------------------------------------------------------------------------------
# print(operator.sub(1, 2))
#-----------------------------------------------------------------------------------
# from collections import namedtuple
# Employee = namedtuple('Employee', 'name, age, salary')
# rows = [('lily', 20, 2000), ('lucy', 19, 2500)]
# for row in rows:
# employee = Employee._make(row)
# print('{}`age is {}, salary is {} '.format(employee.name, employee.age, employee.salary))
#-----------------------------------------------------------------------------------
def get_size(some_object):
if isinstance(some_object, (list, dict, str, tuple)):
return len(some_object)
elif isinstance(some_object, (bool, type(None))):
return 1
elif isinstance(some_object, (int, float)):
return int(some_object)
|
8c1a7803c34d24734ea3bb858fa60796ed378b34 | 1160287301/python_study | /高级编程/多线程/python_thread.py | 1,123 | 3.65625 | 4 | # -*- coding:utf-8 -*-
# 对于io操作来说, 多进程和多线程性能差别不大
# 1.通过thread类实例化
import time
import threading
def get_detail_html(url):
print("get detail html started")
time.sleep(2)
print("get detail html end")
def get_detail_url(url):
print("get detail url started")
time.sleep(2)
print("get detail url end")
class GetDetailhtml(threading.Thread):
def run(self):
print("get detail html started")
time.sleep(2)
print("get detail html end")
class GetDetailUrl(threading.Thread):
def run(self):
print("get detail url started")
time.sleep(2)
print("get detail url end")
if __name__ == '__main__':
start_time = time.time()
# thread1 = threading.Thread(target=get_detail_html, args=("", ))
# thread2 = threading.Thread(target=get_detail_url, args=("", ))
thread1 = GetDetailhtml()
thread2 = GetDetailUrl()
thread1.start()
thread2.start()
thread1.join()
thread2.join()
# thread1.setDaemon(True)
# thread2 .setDaemon(True)
print(time.time() - start_time)
|
b790ee0d7bd99110f1f9bd16abf428a85529e7b1 | 1160287301/python_study | /高级编程/自定义序列类/bisect_test.py | 545 | 3.671875 | 4 | # -*- coding:utf-8 -*-
import bisect
# 用来处理已排序的序列,用来维持已排序的序列,升序
# 二分查找
inter_list = []
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 4)
bisect.insort(inter_list, 6)
bisect.insort(inter_list, 7)
bisect.insort(inter_list, 5)
print(inter_list) # [1, 2, 3, 4, 4, 5, 6]
# 返回相同元素的后一个索引
print(bisect.bisect(inter_list, 3))
print(bisect.bisect_left(inter_list, 3))
print(bisect.bisect_right(inter_list, 3)) |
0ed7f1501241934e31b9c17722c6c24d842edeb9 | anirudhkm/data-mining-course | /hw3/3/frequent.py | 1,302 | 3.875 | 4 | from collections import OrderedDict
def maximal_freq_itemsets(freq_item_dict):
"""
This function helps to find the maximal
frequent items in the dataset and returns
them as a sequence.
"""
maximal_freq_count = 0
# initial value
for i in freq_item_dict:
# iterate through each item
flag = True
for j in freq_item_dict:
# iterate again
if len(i) + 1 == len(j) and set(i).issubset(set(j)):
flag = False
elif len(i) + 2 == len(j):
break
if flag:
maximal_freq_count += 1
return maximal_freq_count
def closed_freq_itemset(freq_item_dict, all_item):
"""
Compute closed frequency itemsets
"""
closed_item_count = 0
# initial value
for i in freq_item_dict:
# iterate through each items
flag = True
for j in all_item:
# iterate through all items
if len(i) + 1 == len(j) and set(i).issubset(set(j)):
# check for immediate super set
if freq_item_dict[i] == all_item[j]:
flag = False
break
if flag:
closed_item_count += 1
return closed_item_count
|
a69b12f8e90567c48a6803fbe531bed77f413dbb | anirudhkm/data-mining-course | /hw3/3/sets.py | 471 | 3.640625 | 4 | import numpy as np
def intersection(*args):
"""
This function performs the
intersection operation for the input data
given and returns them as a numpy array
"""
return tuple(sorted(set(args[0]).intersection(*args[1:])))
def union(*args):
"""
This function performs the union
operation for the input data given and
returns them as a numpy array
"""
return tuple(sorted(set(args[0]).union(*args[1:])))
|
32ec075565ae8d7304f540db2a9fc5bfda0d6ef6 | anirudhkm/data-mining-course | /hw1/5/5_b/recommender_system.py | 3,783 | 3.578125 | 4 | """
Name: Anirudh Kamalapuram Muralidhar
Indiana University
Date: 31th January, 2016
Objective: To build a recommender system
"""
from distance import *
from data_process import *
import numpy as np
def find_top_k_sim_users(similarity_list, k):
"""
This function returns the top "k" most
similar users of the similar_user_dict
and returns them
"""
top_k_list = sorted(similarity_list, reverse = True)[:k]
# get the top
return zip(*top_k_list)
def predict_user_rating(user_rating_dict, movie_dict, users_similarity_dict,
user_id, predicted_rating_dict, k = 1500):
"""
This function helps in calculating the
predicting of the user based on their
similarity
"""
for movie in movie_dict.iterkeys():
# iterate through each movies
total_similarity = 0
weighted_similarity = 0
similarity_list = []
# similarity list
users_who_saw_movie = movie_dict[movie]
# Get the users who saw the movie
for seen_user in users_who_saw_movie.iterkeys():
# iterate through each user who saw the movie
if user_id != seen_user:
#similarity_list.append((distance_to_similarity(users_similarity_dict[frozenset((user_id,seen_user))]), users_who_saw_movie[seen_user]))
similarity = users_similarity_dict[frozenset((user_id,seen_user))]
total_similarity += similarity
weighted_similarity += similarity*users_who_saw_movie[seen_user]
else:
pass
#similar_user_list = find_top_k_sim_users(similarity_list, k)
try:
predicted_rating = sum(np.array(similar_user_list[0])*np.array(similar_user_list[1]))/sum(similar_user_list[0])
if not isnan(predicted_rating):
# get the prediction value
if user_id in predicted_rating_dict:
# check if user is already predicted
predicted_rating_dict[user_id][movie] = predicted_rating
# update the predicted rating dictionary
else:
predicted_rating_dict[user_id] = {movie:predicted_rating}
# add new user predicting rating
except Exception, e:
pass
if __name__ == '__main__':
# start of the program
training = ['u1.base','u2.base','u3.base','u4.base','u5.base']
test = ['u1.test','u2.test','u3.test','u4.test','u5.test']
mad_final = 0
for i in xrange(len(training)):
user_rating_dict, movie_dict = get_input_data(training[i])
# get the user rating for each movie and also movie rating by users
attribute_dict = get_attribute_dict()
# get the various attributes to be used
user_information_dict = get_user_information('u.user', attribute_dict)
# get the information of users stored in a dict
users_similarity_dict = calcuate_similarity(user_rating_dict, user_information_dict)
# get the similarity between users
predicted_rating_dict = {}
# empty dictionary
for user_id in user_rating_dict.iterkeys():
predict_user_rating(user_rating_dict, movie_dict, users_similarity_dict,
user_id, predicted_rating_dict)
# function call
user_rating_dict, movie_dict = get_input_data(test[i])
mad = mean_absolute_difference(user_rating_dict, predicted_rating_dict)
# function call
write_to_file(training[i], test[i], mad, "user_attr_recommend_sys.txt")
mad_final += mad
write_to_file("Average of training set", "Average of testing set", mad, "user_attr_recommend_sys.txt") |
1841100ecfd18b421ab148333f47575c33f5e02c | s19009/python | /kansuu/fail3.py | 91 | 3.5 | 4 | def f(a, b, c=3, d=2, e=4):
return a + b + c * d - e
result = f(5, 3)
print(result)
|
fdf4ed2891138253932f361aa9e18a820b53f4d2 | DjavidHesenov/Bank-ATM-CRUD-system | /admin/admin.py | 334 | 3.546875 | 4 | def control():
username = input("Username: ").lower()
password = input("Password: ").lower()
if username == "admin":
if password == "admin":
print("Success")
else:
print("Password Sehvdir")
control()
else:
print("Username Sehvdir")
control()
|
894323730ff8fa9a603ad4d284178d9011af7790 | mariafoo/COMP1730_assignment2 | /assign2_u5021276.py | 9,463 | 4.03125 | 4 | ## u5021276
## Implementing this function is task 1:
def read_graph_from_file(filename):
'''This function reads a graph from a file and returns a tuple of
two lists: (neighbours, positions): neighbours is the neighbour
list representation of the graph; positions is the list of node
positions (this is used only for displaying the graph on screen).
For a detailed description of the neighbour list data structure
and graph file format, see the assignment specification page in
wattle.'''
graph_file = open(filename,"r")
positions_list = []
neighbour_dict = {}
line_num = 0
node_num = 0
# files always start with 3 column lines representing nodes
col_count = (3,)
# parse the graph file
while True:
# read a line
line = graph_file.readline()
# end of file, break loop
if not line: break
# increment the line count
line_num = line_num + 1
# remove newlines, split the line via commas
columns = line.rstrip().split(',')
# convert elements to integers
try:
columns = [int(n) for n in columns]
except ValueError:
raise FileFormatError(filename, line_num, "Incorrect elements! All elements must be integers.")
# get the length count for the columns
length = len(columns)
# check if the number of columns in the file are valid
if length in col_count:
if length == 3:
# expects the next line to be 3 columns or 2 columns
col_count = (3, 2)
# N case (nodes)
# columns[0] => node
# columns[1] => posx
# columns[2] => posy
# check that the node numbers are incremental
if not node_num == columns[0]:
raise FileFormatError(filename, line_num, "Incorrect node number! Nodes must increment from 0 to N-1 where N is the number of Node lines.")
positions_list.append((columns[1], columns[2]))
# increment the node number
node_num = node_num + 1
elif length == 2:
# expects the next line to be 2 columns only
col_count = (2,)
# M case (links)
# columns[0] => node1
# columns[1] => node2
# check that the nodes are between 0 and N-1 where N is the number of nodes
if columns[0] < 0 or columns[0] > node_num or columns[1] < 0 or columns[1] > node_num:
raise FileFormatError(filename, line_num, "Incorrect link node number! Nodes must be between 0 and N-1 where N is the number of nodes.")
# create a key for a new node
if not columns[0] in neighbour_dict:
neighbour_dict[columns[0]] = []
if not columns[1] in neighbour_dict:
neighbour_dict[columns[1]] = []
# add values to key
neighbour_dict[columns[0]].append(columns[1])
neighbour_dict[columns[1]].append(columns[0])
else:
# check that the file starts with nodes with 3 columns, then with links with 3 columns
raise FileFormatError(filename, line_num, "Incorrect file format! File needs to start with nodes with 3 columns, then with links with 2 columns.")
# close the file!
graph_file.close()
# find nodes that have no neighbours! And mark them as an empty list in the neighbours dictionary
list_of_nodes_from_positions = list(range(0, len(positions_list)))
list_of_nodes_from_neighbours = neighbour_dict.keys()
difference_list = list(set(list_of_nodes_from_positions) - set(list_of_nodes_from_neighbours))
for node in difference_list:
neighbour_dict[node] = []
# converting our neighbour_dict into a neighbour_list while sorting it in order of node index
neighbour_list = [value for (key, value) in sorted(neighbour_dict.items())]
# sorting the neighbours in ascending order
for index, neighbours in enumerate(neighbour_list):
neighbour_list[index] = sorted(neighbours)
# debugging code left here
# with open("log_neighbour.txt", "w") as log:
# log.write(repr(neighbour_list))
# with open("log_positions.txt", "w") as log:
# log.write(repr(positions_list))
return (neighbour_list, positions_list)
## Implementing this function is task 2:
def label_graph_components(neighbour_list):
'''This function takes as input the neighbour list representation of
a graph and returns a list with the component number for each node in
the graph. Components must be numbered consecutively, starting from
zero.'''
# Depth First Search (adapted from Mann, E 2014, 'Depth-First Search and Breadth-First Search in Python', Eddmann blog, web log post, 5 March, viewed 6 October 2014, http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/)
def depth_first_search(neigbour_list, root_node):
visited_nodes = set()
stack = [root_node]
# parse the stack
while stack:
# get the element at the end of the list and return the element
node = stack.pop()
# check if node is not in visited_nodes set
if node not in visited_nodes:
# add node to visited_nodes set
visited_nodes.add(node)
# find the unvisited neighbours of the node and add to the stack
stack.extend(set(neighbour_list[node]) - visited_nodes)
return list(visited_nodes)
# subgraph label is from 0 to C-1 where C is the number of components
component_counter = 0
# create a list of nodes using the neighbour_list
node_list = [index for index, neighbour in enumerate(neighbour_list)]
# create a label_list initialised to None for each node
label_list = [None for node in node_list]
# loop through the label_list checking for None
while None in label_list:
# get a reference node for the first None in label_list
root_node = label_list.index(None)
# apply depth_first_search to the node
visited_list = depth_first_search(neighbour_list, root_node)
# label nodes according to their subgraph
for value in visited_list:
label_list[value] = component_counter
# increment the component count
component_counter = component_counter + 1
return label_list
## Implementing this function is task 3:
def get_component_density(label, neighbour_list, label_list):
'''This function takes a component label, the neighbour list
representation of a graph and a list of component labels
(one for each node in the graph), and should calculate and return
the link density in the component with the given label. The link
density is defined as the number of links (in that component)
divided by the number of nodes (in that component). If there
are no nodes with the given component label, the function
should raise an error.'''
# Depth First Search
def depth_first_search(neighbour_list, root_node):
visited_nodes = set()
stack = [root_node]
# create a path count
path_count = 0
while stack:
node = stack.pop()
if node not in visited_nodes:
visited_nodes.add(node)
# find the unvisited neighbours of the rood node
resultant_neighbours = set(neighbour_list[node]) - visited_nodes
# increment the path count by the number of jumps between node and neighbours
path_count = path_count + len(resultant_neighbours)
stack.extend(resultant_neighbours)
# return the path_count variable
return path_count
# find the first node in the label_list for the required label
root_node = label_list.index(label)
# determine the number of paths in the subgraph
paths = depth_first_search(neighbour_list, root_node)
# determine the number of nodes in the subgraph
nodes = label_list.count(label)
return paths/nodes
# we can also get the full number of paths in the supergraph by collpasing the duplicates in the label_list and then iterating this function on the collapsed label_list
## The code below defines a custom exception type for format errors in
## the graph file. Catching format errors in the input file is one
## important part of task 1. When you detect an error in the input file,
## you should raise a file format error. This is done as follows:
##
## raise FileFormatError(filename, line_number, message)
##
## where filename is the name of the incorrect file, line_number the
## line in the file where the error occurred, and message is a string
## that describes the error. You are free to make up your own error
## messages, but keep in mind that they should be helpful to the user.
class FileFormatError (Exception):
def __init__(self, filename, line_num, message):
super(Exception, self).__init__()
self.filename = filename
self.line_num = line_num
self.message = message
def __str__(self):
return self.filename + ", line " + str(self.line_num) + ": " + self.message |
38037db7be034fbf05d6392ee36b1dd9c33f795d | Mamithi/open-katis-challenges | /carrots.py | 83 | 3.5625 | 4 | x, y = input().split()
x = int(x)
for i in range(x):
desc = input()
print(y)
|
c3efa20414a7e147b9ad5c50cd56ab9cbecb2496 | Mamithi/open-katis-challenges | /kemija.py | 237 | 3.75 | 4 | encoded = input()
decoded = ''
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
while count < len(encoded):
decoded += encoded[count]
if encoded[count] in vowels:
count += 3
else:
count += 1
print(decoded)
|
8c06cb688c09a2c340f34586b54b1b39c682e008 | Mamithi/open-katis-challenges | /nodup.py | 156 | 3.671875 | 4 | words = input().split()
duplicates = [x for i, x in enumerate(words) if x in words[:i]]
if len(duplicates) > 0:
print('no')
else:
print('yes')
|
89c01a8e28117e7b921e01a672f3ce45e39baf27 | Mamithi/open-katis-challenges | /avion.py | 210 | 3.59375 | 4 | found_at = []
for i in range(5):
blimp = input()
if 'FBI' in blimp:
found_at.append(i+1)
if len(found_at) < 1:
print('HE GOT AWAY!')
else:
print(' '.join([str(x) for x in found_at]) ) |
a7390a0db2829dce65dd83ed11733f7dddc8aa22 | MaxDiMassimo/final401 | /smoking classifier.py | 4,179 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 13 21:57:52 2021
@author: 19145
"""
#drinking classifier
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('final project - smoking ready.csv')
X = dataset.iloc[:,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]].values
y = dataset.iloc[:,[-1]].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.19, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Training the Naive Bayes model on the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix, accuracy_score
ac = accuracy_score(y_test,y_pred)
cm = confusion_matrix(y_test, y_pred)
print("")
print("Smoking test")
print ("accuracy score" , "{0:.0%}".format(ac))
print (cm)
#user input
print("Please answer the follow questions. All values must be integers.")
smoking = input("1/19 : do you drink? \nNever = 0, Socially = 1, A lot = 2\n")
reliability = input("2/19 : I am reliable at work and always complete all tasks given to me.: \nStrongly disagree 1-2-3-4-5 Strongly agree\n")
promises = input("3/19 : I always keep my promises.: \n Strongly disagree 1-2-3-4-5 Strongly agree\n")
thinkinga = input("4/19 : I look at things from all different angles before I go ahead.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
work = input("5/19 : I often study or work even in my spare time.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
criticism = input("6/19 : I will find a fault in myself if people don't like me.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
empathy = input("7/19 : I am empathetic person.:\n Strongly disagree 1-2-3-4-5 Strongly agree \n")
eattosur = input("8/19 : I eat because I have to. I don't enjoy food and eat as fast as I can.:\n Strongly disagree 1-2-3-4-5 Strongly agree \n")
borrow = input("9/19 : I look after things I have borrowed from others.:\n Strongly disagree 1-2-3-4-5 Strongly agree \n")
health = input("10/19 : I worry about my health.:\n Strongly disagree 1-2-3-4-5 Strongly agree \n")
changepast = input("11/19 : I wish I could change the past because of the things I have done.:\n Strongly disagree 1-2-3-4-5 Strongly agree \n")
dreams = input("12/19 : I always have good dreams.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
punc = input("13/19 : Timekeeping.:\n I am often early. = 5 - I am always on time. = 3 - I am often running late. =1 \n")
moodswings = input("14/19 : My moods change quickly.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
anger = input("15/19 : I can get angry very easily.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
happy = input("16/19 : I am 100% happy with my life.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
elvl = input("17/19 : I am always full of life and energy.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
personality = input("18/19 : I believe all my personality traits are positive.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
gup = input("19/19 : I find it very difficult to get up in the morning.:\n Strongly disagree 1-2-3-4-5 Strongly agree\n")
enterData= [[smoking,reliability,promises,thinkinga,work,criticism,empathy,eattosur,borrow,health,changepast,dreams,punc,moodswings,anger,happy,elvl,personality,gup]]
enterDataTransformed = sc.transform(enterData)
entered_prediction = classifier.predict(enterDataTransformed)
if entered_prediction == 0:
print("Answer: You've never smoked.")
if entered_prediction == 1:
print("Answer: You've tried smoking.")
if entered_prediction == 2:
print("Answer: You currently smoke.")
if entered_prediction == 3:
print("Answer: You are a former smoker.") |
5a5bb8dcac7f140f2c84efd8c5419da858cf54d0 | bazzscript/SputnikLab | /VulnPortScanner/vulnportscanner.py | 1,512 | 3.546875 | 4 | import portscanner
targets_ip = input('[~] Enter Target(s) To Scan (Split Multiple Targets with comma(,)): ')
while True:
try:
port_number = int(Input('[~] Enter Amount of Ports you want to Scan(500 means first 500 ports) : '))
break
except ValueError:
print(' We dont understand what you typed \nTry Again...\nPlease A number')
#vul_soft_list = input("[~] Enter Path To the list of vulnerble softwares : ")
#target = portscabber.PortScan(targets_ip, port_number)
#target.scan()
#targets = input(f '[~] Enter Target(s) To Scan (Split Multiple Targets with comma(,)): ')
if ',' in targets_ip:
for ip_add in targets_ip.split(','):
target = portscanner.PortScan(ip_add.strip(), port_number)
target.scan()
else:
target = portscanner.PortScan(targets_ip, port_number)
target.scan()
while True:
try:
vul_soft_list = input("[~] Enter Path To the txt list of names vulnerable softwares : ")
with open(vul_soft_list, 'r') as file:
count = 0
for banner in target.banners:
file.seek(0)
for line in file.readlines():
if line.strip() in banner:
print('\n\n')
print('[!!!] VULNERABLE SOFTWARE "', banner, '"DETECTED ON PORT: ', str(target.open_ports[count]))
count += 1
break
except FileNotFoundError as e:
print('[!!] That File/Path doesnt\'t exists ')
print('Try Again') |
da9a3fc22cfc7f56769188bd64a2586e5249e9e7 | scausey/matzobot | /scrape.py | 3,216 | 3.59375 | 4 | from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import requests
from collections import defaultdict
import pprint
# TODO: Check for errors when loading php.
url = "https://www.smith.edu/diningservices/menu_poc/cbord_menus.php"
response = requests.get(url)
bsObj = BeautifulSoup(response.content, "html.parser")
#Check if a menu is empty. Returns true or false.
def isEmpty(block):
childList = block.contents
print("List of block's children: " +str(childList))
for child in childList:
print("current child in childList: " +str(child))
print("child type: " +str(type(child)))
#Check for empty dining hall menus. Make sure element has class attribute.
if child.get("class") != None:
childClasses = child.get("class")
print("childClasses list: " +str(childClasses))
for childClass in childClasses:
print("childClass's class: " +str(childClass))
if childClass == 'smith-menu-empty' or childClass == 'row':
print("childClass has a div with value smith-menu-empty or row. Returning true.")
return True
else:
print("childClass does not have a div with value smith-menu-empty or row.")
return False
print("Checking if child type is navigablestring.")
if str(type(child)) == "<class 'bs4.element.NavigableString'>":
continue
#Returns the dininghall.
def getDiningHall(block):
print("getDiningHall function called.")
diningHallBlock = block.find("div", {"class" : "col-md-12"})
print("diningHallBlock list of col-md-12s: " +str(diningHallBlock))
print("Length of diningHallBlock list of col-md-12s: " +str(len(diningHallBlock)))
print("isEmpty function called for getDiningHall function.")
if isEmpty(diningHallBlock):
return
else:
print("Passed isEmpty test. Getting location.")
location = diningHallBlock.find("span").get_text().lower().strip()
print("Location: " +location)
return location
#Returns a meal.
def getMeal(block, foodDict, location):
print("getMeal function called.")
mealBlocks = block.findAll("div", {"class" : "col-xs-4"})
mealsLs = []
for mealBlock in mealBlocks:
#Locate the meal.
meal = mealBlock.find("h4")
if isEmpty(mealBlock):
continue
if str(type(meal)) == "<class 'NoneType'>":
continue
else:
meal = meal.get_text().lower().strip()
#Join meal with location.
s = '-'
seq = (location, meal)
locationAndMeal = s.join(seq)
#Find the foods for that meal.
foodItems = mealBlock.findAll("td")
for foodItem in foodItems:
food = foodItem.get_text().lower().strip()
#Add the food item to the dictionary, along with where and when.
if food in foodDict:
foodDict[food].append(locationAndMeal)
else:
foodDict.setdefault(food, [])
foodDict[food] = [locationAndMeal]
#Main method.
foodDict = defaultdict(list)
blocks = bsObj.find_all("div", {"class" : "smith-menu-wrapper"})
#Get information.
# count = 0
# for block in blocks:
# count+=1
# location = getDiningHall(block)
# getMeal(block, foodDict, location)
# if count == 1:
# break
for block in blocks:
location = getDiningHall(block)
getMeal(block, foodDict, location)
pp = pprint.PrettyPrinter(compact=True)
pp.pprint(foodDict)
|
d5d73cfa1635c255ea26e4b49ad71e72951c27f5 | wavestoweather/enstools-compression | /enstools/compression/emulators/emulator_class.py | 1,176 | 3.71875 | 4 | """
Abstract class which defines the methods that the emulators need to have.
"""
from abc import ABC, abstractmethod
import numpy as np
from enstools.encoding.api import Encoding
class Emulator(ABC):
"""
This class provides an emulator.
The emulator is initialized with a compression specification (compressor_name, mode and parameter)
and has a method to compress_and_decompress the data.
Its is useful to evaluate the errors that are introduced by the compression.
"""
@abstractmethod
def __init__(self, specification: Encoding, uncompressed_data: np.ndarray):
"""Init method requires certain parameters"""
@abstractmethod
def compress_and_decompress(self, uncompressed_data: np.array) -> np.array:
"""
Gets a numpy array and returns the same array after compression and deflation .
Parameters
----------
uncompressed_data: numpy array
Returns
-------
decompressed_data: numpy array
"""
@abstractmethod
def compression_ratio(self) -> float:
"""compression_ratio method returns the compression ratio achieved during compression"""
|
aa815e48fda770f3d33d50265dd9ce5d87028d1a | wavestoweather/enstools-compression | /enstools/compression/slicing.py | 8,244 | 4.09375 | 4 | """
This file contains classes and methods to divide a multi dimensional slice in different parts, via selecting a
chunk size or the number of desired parts.
"""
import logging
from typing import List, Tuple
from itertools import product
import numpy as np
def split_array(array: np.ndarray, parts: int):
"""
Splits the given array into a specified number of parts.
The function returns a list of chunks, where each chunk is a numpy array.
:param array: A numpy array to be split
:param parts: An int, the number of parts to split the array into
:return: A list of numpy arrays representing the chunks
"""
if parts == -1:
parts = array.size
shape = array.shape
possible_chunk_sizes = []
# Generate all possible chunk sizes for the given array shape
for chunk_size in product(*[range(1, shape[i] + 1) for i in range(len(shape))]):
# Check if the number of chunks generated by the current chunk size is equal to the desired number of parts
if np.prod(
[shape[i] // chunk_size[i] + int(shape[i] % chunk_size[i] != 0) for i in range(len(shape))]) == parts:
possible_chunk_sizes.append(chunk_size)
# Sort the possible chunk sizes in ascending order of the sum of the squares of their dimensions
possible_chunk_sizes.sort(key=lambda x: np.sum(np.array(x) ** 2)) # type: ignore
if not possible_chunk_sizes:
logging.warning("Could not divide the domain in %d parts. Trying with parts=%d.", parts, parts - 1)
return split_array(array=array, parts=parts - 1)
selected_chunk_size = possible_chunk_sizes[0]
chunks = []
# Get the number of chunks for the first possible chunk size
num_chunks = [shape[i] // selected_chunk_size[i] + int(shape[i] % selected_chunk_size[i] != 0) for i in
range(len(shape))]
indexes = [range(num_chunks[i]) for i in range(len(shape))]
# Iterate over the chunks and append the corresponding slice of the array to the chunks list
for indx in product(*indexes):
current_slice = tuple(
slice(selected_chunk_size[i] * indx[i], min(selected_chunk_size[i] * (indx[i] + 1), shape[i])) for i in
range(len(shape)))
chunks.append(array[current_slice])
return chunks
class MultiDimensionalSlice:
"""
A class representing a multi-dimensional slice.
"""
def __init__(self, indices: Tuple[int, ...], slices: Tuple[slice, ...] = (slice(0, 0, 0),)):
"""
Initialize the MultiDimensionalSlice object with indices and slice
:param indices: Tuple of indices
:param slices: Tuple of slice objects representing the slice indices
"""
self.indices = indices
self.slices = slices
def __repr__(self) -> str:
"""
Return the string representation of the MultiDimensionalSlice object
"""
return f"{self.__class__.__name__}({self.indices})"
@property
def size(self):
"""
Return the size of the slice
"""
size = 1
for current_slice in self.slices:
size *= current_slice.stop - current_slice.start
return size
class MultiDimensionalSliceCollection:
"""
A class representing a collection of multi-dimensional slices.
"""
def __init__(self, *, objects_array: np.ndarray = None, shape: Tuple[int, ...] = None,
chunk_sizes: Tuple[int, ...] = None):
"""
Initializes the MultiDimensionalSliceCollection class.
Args:
objects_array (np.ndarray): an array of MultiDimensionalSlice objects
shape (Tuple[int,...]): the shape of the array to be divided into chunks
chunk_sizes (Tuple[int,...]): the size of the chunks in each dimension
Raises:
AssertionError: if objects_array is not provided and shape and chunk_sizes are not provided
"""
if objects_array is not None:
assert shape is None and chunk_sizes is None
self.__initialize_from_array(objects_array=objects_array)
elif shape:
assert chunk_sizes is not None
self.__initialize_from_shape_and_chunk_size(shape, chunk_sizes)
else:
raise AssertionError("objects_array or shape and chunksize should be provided")
def __initialize_from_array(self, objects_array: np.ndarray):
"""
Create a MultiDimensionalSliceCollection given an array of MultiDimensionalSlice
Parameters
----------
objects_array: numpy array of MultiDimensionalSlice
Returns
-------
MultiDimensionalSliceCollection
"""
self.objects = objects_array
self.collection_shape = self.objects.shape
def __initialize_from_shape_and_chunk_size(self, shape: Tuple[int, ...], chunk_size: Tuple[int, ...]):
"""
Create a MultiDimensionalSliceCollection given a shape and a chunk size
Parameters
----------
shape
chunk_size
Returns
-------
MultiDimensionalSliceCollection
"""
collection_shape = tuple(
shape[i] // chunk_size[i] + int(shape[i] % chunk_size[i] != 0) for i in range(len(shape)))
objects = np.empty(collection_shape, dtype=MultiDimensionalSlice)
num_chunks = [shape[i] // chunk_size[i] + int(shape[i] % chunk_size[i] != 0) for i in range(len(shape))]
indexes = [range(num_chunks[i]) for i in range(len(shape))]
for indx in product(*indexes):
current_slice = tuple(
slice(chunk_size[i] * indx[i], min(chunk_size[i] * (indx[i] + 1), shape[i])) for i in range(len(shape)))
objects[indx] = MultiDimensionalSlice(indices=indx, slices=current_slice)
self.__initialize_from_array(objects_array=objects)
def __getitem__(self, args):
return self.objects[args]
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.collection_shape})"
@property
def slice(self) -> Tuple[slice, ...]:
"""
Calculate the total slice that covers all the MultiDimensionalSlice objects in the collection.
Returns:
Tuple[slice, ...]: A tuple of slice objects representing the total slice.
"""
total_slice = tuple(slice(None) for _ in self.collection_shape)
for obj in self.objects.flat:
for i, current_slice in enumerate(obj.slices):
if total_slice[i].start is None:
total_slice = total_slice[:i] + (current_slice,) + total_slice[i + 1:]
else:
if current_slice.start < total_slice[i].start:
total_slice = total_slice[:i] + (
slice(current_slice.start, total_slice[i].stop, total_slice[i].step),) + total_slice[i + 1:]
if current_slice.stop > total_slice[i].stop:
total_slice = total_slice[:i] + (
slice(total_slice[i].start, current_slice.stop, total_slice[i].step),) + total_slice[i + 1:]
return total_slice
def split(self, parts: int) -> List['MultiDimensionalSliceCollection']:
"""
Divide the MultiDimensionalSliceCollection into different parts of similar size.
Args:
parts (int): Number of parts to divide the group.
Returns:
list: A list of MultiDimensionalSliceCollection objects representing the divided parts.
"""
array_parts = split_array(self.objects, parts)
return [MultiDimensionalSliceCollection(objects_array=p) for p in array_parts]
@property
def size(self) -> int:
"""
Calculate the total size of the MultiDimensionalSliceCollection.
Returns:
int: The total size of the collection.
"""
return sum(ob.size for ob in self.objects.ravel())
def __len__(self) -> int:
"""
Calculate the total number of objects in the MultiDimensionalSliceCollection.
Returns:
int: The total number of objects in the collection.
"""
return self.objects.size
|
78af189107537a996ae22edb3cf39d27d775a219 | wesenu/LearnOpenSource | /Kshitij/Coffee Machine/coffee machine/mainwithoutfunctions.py | 5,803 | 4.1875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
# TODO 1.Reuccuring prompt
# TODO 2. Print Report
# TODO 3. Check Resources
# TODO 4. Process Coins
# TODO 5.Check Transaction
# TODO 6.makecoffee
money = 0
while True:
user_input = input("What would you like? (espresso/latte/cappuccino): ")
if(user_input == "OFF" or user_input == "off"):
break
if(user_input == "report"):
for key, value in resources.items():
print(f'{key}:{value}')
print(f'Money:${money}')
if(user_input == "espresso"):
if(MENU["espresso"]["ingredients"]["water"] > resources["water"]):
print("“Sorry there is not enough water.")
if (MENU["espresso"]["ingredients"]["coffee"] > resources["coffee"]):
print("“Sorry there is not enough coffee.")
else:
# resources["coffee"] = resources["coffee"]-MENU["espresso"]["ingredients"]["coffee"]
# resources["water"]=resources["water"]-MENU["espresso"]["ingredients"]["water"]
#! we have checked resources and we will update them if coins are right
print("Please insert Coins")
quaters = int(input("How many Quaters? : "))
dimes = int(input("How many Dimes? : "))
nickels = int(input("How many Nickels? : "))
pennies = int(input("How many Pennies? : "))
user_coin = quaters*0.25+dimes*0.10+nickels*0.05+pennies*0.01
if(user_coin < MENU["espresso"]["cost"]):
print("“Sorry that's not enough money. Money refunded")
user_coin = 0
else:
money = money+MENU["espresso"]["cost"]
resources["coffee"] = resources["coffee"] - \
MENU["espresso"]["ingredients"]["coffee"]
resources["water"] = resources["water"] - \
MENU["espresso"]["ingredients"]["water"]
money_return = user_coin-MENU["espresso"]["cost"]
print(f'Here is ${money_return} in change,')
print("Here is your espresso ☕. Enjoy!")
if(user_input == "latte"):
if(MENU["latte"]["ingredients"]["water"] > resources["water"]):
print("“Sorry there is not enough water.")
if (MENU["latte"]["ingredients"]["coffee"] > resources["coffee"]):
print("“Sorry there is not enough coffee.")
if (MENU["latte"]["ingredients"]["milk"] > resources["milk"]):
print("“Sorry there is not enough milk.")
else:
#! we have checked resources and we will update them if coins are right
print("Please insert Coins")
quaters = int(input("How many Quaters? : "))
dimes = int(input("How many Dimes? : "))
nickels = int(input("How many Nickels? : "))
pennies = int(input("How many Pennies? : "))
user_coin = quaters*0.25+dimes*0.10+nickels*0.05+pennies*0.01
if(user_coin < MENU["latte"]["cost"]):
print("“Sorry that's not enough money. Money refunded")
user_coin = 0
else:
money = money+MENU["latte"]["cost"]
resources["coffee"] = resources["coffee"] - MENU["latte"]["ingredients"]["coffee"]
resources["water"] = resources["water"] - MENU["latte"]["ingredients"]["water"]
resources["milk"] = resources["milk"] - MENU["latte"]["ingredients"]["milk"]
money_return = user_coin-MENU["latte"]["cost"]
print(f'Here is ${money_return} in change,')
print("Here is your latte ☕. Enjoy!")
if(user_input == "cappuccino"):
if(MENU["cappuccino"]["ingredients"]["water"] > resources["water"]):
print("“Sorry there is not enough water.")
if (MENU["cappuccino"]["ingredients"]["coffee"] > resources["coffee"]):
print("“Sorry there is not enough coffee.")
if (MENU["cappuccino"]["ingredients"]["milk"] > resources["milk"]):
print("“Sorry there is not enough milk.")
else:
#! we have checked resources and we will update them if coins are right
print("Please insert Coins")
quaters = int(input("How many Quaters? : "))
dimes = int(input("How many Dimes? : "))
nickels = int(input("How many Nickels? : "))
pennies = int(input("How many Pennies? : "))
user_coin = quaters*0.25+dimes*0.10+nickels*0.05+pennies*0.01
if(user_coin < MENU["cappuccino"]["cost"]):
print("“Sorry that's not enough money. Money refunded")
user_coin = 0
else:
money = money+MENU["cappuccino"]["cost"]
resources["coffee"] = resources["coffee"] - MENU["cappuccino"]["ingredients"]["coffee"]
resources["water"] = resources["water"] - MENU["cappuccino"]["ingredients"]["water"]
resources["milk"] = resources["milk"] - MENU["cappuccino"]["ingredients"]["milk"]
money_return = user_coin-MENU["cappuccino"]["cost"]
print(f'Here is ${money_return} in change,')
print("Here is your cappuccino ☕. Enjoy!")
|
bbfe0baa969fee9ac2d8dae86345bd3b9ecb6a7d | JohnStevensonWSU/Ranking | /IndexList.py | 3,855 | 4.09375 | 4 | import IndexNode
# indexList is a linked list representing a term index
# for a document corpus.
class indexList(object):
# Constructor creates an indexList whose
# head points to an indexNode for the
# given term.
def __init__(self):
self.head = None
# Adds a term/docID tuple to the indexList
def add(self, term, docID):
# Find the node that either corresponds
# with the given term or is right before
# where the term should go in the index.
node = self.search(self.head, term)
# Add term to the beginning of the index
if node is None:
self.head = IndexNode.indexNode(term, docID, None)
return
# Replace head of list
if node == -1:
self.head = IndexNode.indexNode(term, docID, self.head)
return
# Add term to existing indexNode
if node.term == term:
node.add(term, docID)
return
nextTemp = node.nextIndexNode
node.nextIndexNode = IndexNode.indexNode(term, docID, nextTemp)
return
# Searches for indexNode whose term is the
# given term. It returns either the indexNode
# whose term is the given term or the node
# whose term is just before the given term
# alphabetically.
def search(self, indexNode, term):
# Create a node pointer.
node = indexNode
# Return None if the list is empty.
if node is None:
return node
# While there is node after the current node,
while node.nextIndexNode is not None:
# Return current node if it has the search term.
if node.term == term:
return node
# Return current node if the next node's term comes
# after the search term in the alphabet.
elif node.nextIndexNode.term > term:
return node
node= node.nextIndexNode
return node
# Prints the index list who calls the method
def print(self):
indexNode = self.head
count = 0
while indexNode is not None:
count += 1
print(indexNode.term)
docNode = indexNode.docList.head
while docNode is not None:
print("(" + str(docNode.docID) + "," + str(docNode.freq) + ")")
docNode = docNode.nextDocNode
indexNode = indexNode.nextIndexNode
# Returns the DocList associated with a term.
# If no term exists in the index, returns None.
def getIndexNode(self, term):
indexNode = self.search(self.head, term)
if indexNode is None:
return None
elif indexNode == -1:
return None
elif indexNode.term != term:
return None
return indexNode
# Returns the frequency of a term in a document.
def termFreq(self, term, docID):
node = self.search(self.head, term)
if node is None:
return 0
elif node == -1:
return 0
elif node.term != term:
return 0
return node.docList.getFreq(docID)
# Returns the number of documents that contain
# a given term.
def getDocNumber(self, term):
node = self.search(self.head, term)
if node is None:
return 0
elif node == -1:
return 0
elif node.term != term:
return 0
return node.docList.count()
# Returns the documents that contain a given term.
def getDocs(self, term):
node = self.search(self.head, term)
if node is None:
return None
elif node == -1:
return None
elif node.term != term:
return None
return node.docList.getDocs()
|
0964f1d92b02db0e9f25664c7049d657c3be4549 | yy02/test | /Python/Python学习笔记/字符串操作.py | 703 | 4.15625 | 4 | str = 'hello world'
# 转换大小写
# print(str.lower())
# print(str.upper())
# 切片操作
# slice[start:end:step] 左闭右开原则,start < value < end
# print(str[2:5])
# print(str[2:])
# print(str[:5])
# print(str[::-1])
# 共有方法
# 相加操作,对字符串列表和元组都可以使用
strA = '人生苦短'
strB = '我用Python'
listA = list(range(10))
listB = list(range(11,20))
# print(strA+strB)
# print(listA+listB)
# 复制操作 *
# print(strA*3)
# print(listA*3)
# in操作,检测对象是否存在
print('生' in strA)
print(9 in listA)
dictA = {'name':'zhangsan'} #对于字典判断的是key是否在字典中
print('name' in dictA)
print('zhangsan' in dictA)
|
4e0ce47617641b67aec51055403941a1862ef175 | Tharunsai-0512/Coursera | /Assignments/Python-Data-Structures/assignment7_2.py | 547 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 7 18:57:44 2019
@author: VIGNESHWAR REDDY
"""
# Use the file name mbox-short.txt as the file name
count = 0
addOfValues = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
colon = line.find(':')
floatingValue = line[colon + 1 : ]
floatingValue = float(floatingValue)
addOfValues = addOfValues + floatingValue
count = count + 1
average = addOfValues/count
print('Average spam confidence:',average) |
64ba459b0b322274f900e1716496e7643d90bde1 | shermansjliu/Python-Projects | /Ceasar Cipher/Ceaser Cipher.py | 1,888 | 4.21875 | 4 | def ReturnEncryptedString():
code = input("Enter in the code you would like to encrypt")
code = code.upper()
newString = ""
tempArr = list(code)
for oldChar in tempArr:
newString += EncryptKey(oldChar)
print(newString)
def ReturnDecryptedString():
code = input("Enter in the code you would like to decipher")
code = code.upper()
newString = ""
tempArr = list(code)
for oldChar in tempArr:
newString += DecodeKey(oldChar)
print(newString)
def DecodeKey(char):
#Create temp array for word
#take i element in word array and shift it the ascii number back 5 letters
asciiInt = ord(char)
tempInt = ord(char)
tempInt += 13
#If ascii value is greater than 90 shift the original ascii value back by 26
if(char == "!"):
return char
elif(char == " "):
return char
elif(tempInt > 90 ):
asciiInt -=13
else:
asciiInt += 13
#convert the ascii value to a character using the function chr()
char = chr(asciiInt)
#Append character to a new string
return char
def EncryptKey(char):
asciiInt = ord(char)
tempInt = ord(char)
tempInt -= 13
if(char == "!"):
return char
elif(char == " "):
return char
elif(tempInt < 64 ):
asciiInt +=13
else:
asciiInt -= 13
#convert the ascii value to a character using the function chr()
char = chr(asciiInt)
#Append character to a new string
return char
def PromptUser():
answer = input("Do you want to decode or encrypt your message?")
answer = answer.lower()
if(answer == "encrypt"):
ReturnEncryptedString()
if(answer == "decode"):
ReturnDecryptedString()
print("This is Ceaser's Cipher")
PromptUser()
#TODO Convert letter from alphabet 13 spaces or 13 spaces up in Ascii table
#Take user's input
#Convert
|
5d9e6975568ece0a55a827ba8b30080307b4ae86 | YiLisa/DSCI560-hw2 | /visualization.py | 405 | 3.546875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
def main():
input = pd.read_csv('random_x.csv', header=None)
x = input[0].tolist()
output = pd.read_csv('output_y.csv', header=None)
y=output[0].tolist()
plt.plot(x, y)
plt.grid(True)
plt.title('y = 3x + 6')
plt.savefig('plot_x_y.png')
plt.show()
if __name__ == '__main__':
main()
print('plotting graph...') |
874a49dc92c5a328f4d728a2b93f85782a39668d | sweeeeeet/python | /lesson2-function.py | 1,134 | 3.921875 | 4 | #定义函数
def add(x,y):
#函数体
ret=x+y
return ret
#函数调用
ret=add(2,4)
print(ret)
#在定义函数时赋值默认参数
def mius(x,y=0):
return x-y
print(mius(4))
#一个函数可以返回多个值
def get_point():
x=10
y=20
return x,y
#解包 unpack
x,y=get_point()
print(x,y)
#高阶函数:在参数中允许传入函数
def addPlus(x,y,f):
return f(x)+f(y)
print(addPlus(2,3,abs))
#函数返回函数
def sum(x):
m=0
def f():
for i in range(10):
m=i+x
return m
return f
r=sum(3)
#对函数的调用结果是一个函数
print(r)
#对r调用才能得到结果
print(r())
print('=='*10)
#关键字参数
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)
#拼接两个列表
a=[1,2]
b=[3,4]
#将b拼接到a上,并不会创建新的对象
print(a.extend(b))
#字符串拼接
a=["sd","sd","ddd"]
#join前面的字符串对象代表拼接的分割符是什么
result=";".join(a)
print(a*3) |
364bfdd2cd3357abc93bc6762dbcf25b8b72588b | EddyCSE/CSE | /Eduardo Sanchez - Game - Backup.py | 16,464 | 3.59375 | 4 | class Item(object):
def __init__(self, name):
self.name = name
class Player(object):
def __init__(self, starting_location, health, shield, name, weapon):
self.name = name
self.current_location = starting_location
self.inventory = []
self.health = health
self.shield = shield
self.weapon = weapon
def move(self, new_location):
self.current_location = new_location
def find_next_room(self, direction):
name_of_room = getattr(self.current_location, direction)
return globals()[name_of_room]
def take_damage(self, damage: int):
if self.shield.defense > damage:
print("But no damage is done because of armor overpowering the weak weapon.")
elif self.health <= 0:
print("You have died")
return
else:
self.health -= damage - self.shield.defense
print("%s has %d health left." % (self.name, self.health))
def attack(self, target):
print("%s attacks %s for %d damage." % (self.name, target.name, self.weapon.damage))
target.take_damage(self.weapon.damage)
class Room(object):
def __init__(self, name, north=None, east=None, south=None, west=None, description=(), items=None, enemy=None):
if items is None:
items = []
if enemy is None:
enemy = []
self.character = Enemy
self.name = name
self.north = north
self.east = east
self.south = south
self.west = west
self.description = description
self.items = items
self.enemy = enemy
class Weapon(Item):
def __init__(self, name, damage, durability):
super(Weapon, self).__init__(name)
self.damage = damage
self.durability = durability
def attack(self, durability):
self.durability = durability
print("You attack with your weapon.")
self.durability -= 5
print("You %s had %s durability left" % (durability, Weapon))
class Rock(Weapon):
def __init__(self):
super(Rock, self).__init__("Rock", 5, 10)
class MetalBeam(Weapon):
def __init__(self):
super(MetalBeam, self).__init__("Metal Beam", 20, 50)
class Dagger(Weapon):
def __init__(self):
super(Dagger, self).__init__("Small Dagger", 25, 30)
class MakeshiftSword(Weapon):
def __init__(self):
super(MakeshiftSword, self).__init__("Makeshift Sword", 40, 10)
class Fists(Weapon):
def __init__(self):
super(Fists, self).__init__("Fists", 1, 100000000)
class LegendaryPistol(Weapon):
def __init__(self):
super(LegendaryPistol, self).__init__("Legendary Pistol", 150, 10)
class EnemyFists(Weapon):
def __init__(self):
super(EnemyFists, self).__init__("Fists", 10, 100000000)
class WardenSword(Weapon):
def __init__(self):
super(WardenSword, self).__init__("Warden's Sword", 50, 100000000)
class EnemySword(Weapon):
def __init__(self):
super(EnemySword, self).__init__("Enemy Sword", 25, 100000000)
class Potion(Item):
def __init__(self, name, heal, shield, amount):
super(Potion, self).__init__(name)
self.heal = heal
self.shield = shield
self.amount = amount
class HealthPotion(Potion):
def __init__(self):
super(HealthPotion, self).__init__("Health Potion", 50, 0, 3)
def drink_health_potion(self):
self.amount -= 1
print("You drink a health potion and feel regenerated.")
class ShieldPotion(Potion):
def __init__(self):
super(ShieldPotion, self).__init__("Shield Potion", 0, 50, 3)
def drink_shield_potion(self):
self.amount -= 1
self.shield += 50
print("You drink a defense potion and feel protected.")
class LifePotion(Potion):
def __init__(self):
super(LifePotion, self).__init__("Life Potion", 50, 50, 3)
def drink_life_potion(self):
self.amount -= 1
self.shield += 50
print("You drink a life potion and feel revived.")
class Armor(Item):
def __init__(self, name, defense):
super(Armor, self).__init__(name)
self.defense = defense
class Helmet(Armor):
def __init__(self):
super(Helmet, self).__init__("Helmet", 50)
class Chestpiece(Armor):
def __init__(self):
super(Chestpiece, self).__init__("Chestpiece", 100)
class Leggings(Armor):
def __init__(self):
super(Leggings, self).__init__("Leggings", 50)
class Boots(Armor):
def __init__(self):
super(Boots, self).__init__("Boots", 25)
class ArmShield(Armor):
def __init__(self):
super(ArmShield, self).__init__("An Arm Shield", 100)
class Tool(Item):
def __init__(self, name):
super(Tool, self).__init__(name)
class Pickaxe(Tool):
def __init__(self):
super(Pickaxe, self).__init__("Pickaxe")
class Crowbar(Tool):
def __init__(self):
super(Crowbar, self).__init__("Crowbar")
class Screwdriver(Tool):
def __init__(self):
super(Screwdriver, self).__init__("Screwdriver")
class Enemy(object):
def __init__(self, name: str, health: int, weapon, armor):
self.name = name
self.health = health
self.weapon = weapon
self.armor = armor
def take_damage(self, damage: int):
if self.armor.defense > damage:
print("But no damage is done because of armor overpowering the weak weapon.")
elif self.health <= 0:
print("%s boi died" % self.name)
return
else:
self.health -= damage - self.armor.defense
print("%s has %d health left." % (self.name, self.health))
def attack(self, target):
print("%s attacks %s for %d damage." % (self.name, target.name, self.weapon.damage))
target.take_damage(self.weapon.damage)
# Weapons
rock = Weapon("A Rock", 5, 15) # Added
metalbeam = Weapon("A Metal Beam", 20, 50) # Added
dagger = Weapon("A Dagger", 25, 30) # Added
makeshiftsword = Weapon("MakeshiftSword", 40, 10) # Added
legendary_pistol = Weapon("Golden Pistol", 150, 10) # Added
fists = Weapon("Fists", 1, 100000000) # Added
enemy_fists = Weapon("Fists", 10, 100000000) # Added
warden_sword = Weapon("Warden's sword", 50, 100000000) # Added
enemy_sword = Weapon("Sword", 25, 100000000) # Added
# Armor
chestpiece = Armor("A Metal Chestpiece", 100) # Added
helmet = Armor("A Metal Helmet", 50) # Added
leggings = Armor("Metal Leggings", 100) # Added
boots = Armor("Metal Boots", 50) # Added
arm_shield = Armor("A Metal Arm Shield", 25) # Added
# Potions
healthpotion = Potion("Health Potion", 50, 0, 3) # Added
shieldpotion = Potion("Shield Potion", 0, 50, 3) # Added
lifepotion = Potion("Life Potion", 50, 50, 3) # Added
# Tools
pickaxe = Tool("A Sturdy Pickaxe") # Added
crowbar = Tool("A Crowbar") # Added
screwdriver = Tool("A Screwdriver") # Added
# Characters
Demon = Enemy("Demon", 50, enemy_sword, helmet) # Added
Demon1 = Enemy("Demon", 50, enemy_sword, helmet) # Added
Demon2 = Enemy("Demon", 50, enemy_sword, helmet) # Added
Demon3 = Enemy("Demon", 50, enemy_sword, helmet) # Added
Demon4 = Enemy("Demon", 50, enemy_sword, helmet) # Added
Slug = Enemy("Slug", 10, enemy_fists, None) # Added
Slug1 = Enemy("Slug", 10, enemy_fists, None) # Added
Slug2 = Enemy("Slug", 10, enemy_fists, None) # Added
Slug3 = Enemy("Slug", 10, enemy_fists, None) # Added
Slug4 = Enemy("Slug", 10, enemy_fists, None) # Added
Warden = Enemy("Warden", 300, warden_sword, Chestpiece) # Added
OUT = Room("-=-OUT-=-", None, None, None, None, "- You've made it out through skill and intelligence."
" You now just need to find civilization and get your way back home. "
"Congrats, you beat the game.", None, None)
YOUR_CELL = Room("-Your Cell-", "HALLWAY1", None, None, None, "- For command list, type 'commands', An abandoned cell"
"... you don't know how you got here,"
" but you need to escape."
" Your cell door is on the north wall."
"", Rock(), Slug)
UNKNOWN_CELL = Room("- /= --uNkNown cEll- /=-", "OUT", None, "HALLWAY2", None, "- You managed to get in and there's an "
"escape hole."
"", Chestpiece(), Demon)
HALLWAY1 = Room("-East Hallway-", "SHOWER_ROOM", "SECURITY_ROOM2", "YOUR_CELL", "HALLWAY2", "- There is a long hallway,"
" breezes coming left and "
"right with a door north "
"of you."
"", Dagger(), Slug)
SHOWER_ROOM = Room("-Shower Room-", None, None, "HALLWAY1", None, "- A shower room, none of the water is working."
"", MetalBeam(), Slug1)
HALLWAY2 = Room("-West Hallway-", "UNKNOWN_CELL", "HALLWAY1", "WOMENS_CELL", "SECURITY_ROOM", "- There is a long"
" hallway,there's more"
" cells north and south"
" of you. "
"It looks like there "
"were stairs, but it's"
" all destroyed."
"", None, Slug2)
WOMENS_CELL = Room("-Women's Cell", "HALLWAY2", None, None, None, "- A cell with nothing or no"
" one in here..."
"", LegendaryPistol(), Warden)
SECURITY_ROOM = Room("-West Security Office-", "WARDENS_OFFICE", "HALLWAY2", "NURSERY", "ENTRANCE", "- Seems like"
" nothing"
" works in here. "
"Doors north, "
"south, and west."
"", None, Demon2)
NURSERY = Room("-Nursery-", "SECURITY_ROOM", None, None, None, "- The area the nurse would be, "
"kinda scary like always. "
"", ArmShield(), Slug3)
WARDENS_OFFICE = Room("-Warden's Office-", None, None, "SECURITY_ROOM", None, "- The Warden's "
"room, looks like a strong entity"
" lived here. "
"", MakeshiftSword(), Demon1)
ENTRANCE = Room("-Entrance-", None, "SECURITY_ROOM", None, None, "- The exit/entrance, it's all boarded up, can't"
" seem to ever get through. "
"", Screwdriver(), Slug)
SECURITY_ROOM2 = Room("-East Security Room-", None, "CAFETERIA", None, "HALLWAY1", "- A contraband area, nothing is "
"working. A cafeteria is seen"
" east. "
"Helmet nearby.", Helmet(), None)
CAFETERIA = Room("-Cafeteria-", "COURT_YARD", "KITCHEN", "LIBRARY", "SECURITY_ROOM2", "- Lots of spoiled food is here. "
"Open areas north, east,"
" and south.", None, Slug4)
COURT_YARD = Room("-Court Yard-", None, None, "CAFETERIA", None, "- Basketball, weights, "
"and barbed wire located here."
"", Pickaxe(), Demon3)
KITCHEN = Room("-Kitchen-", None, None, None, "CAFETERIA", "- Utensils here and a horrible smell. "
"", Leggings(), None)
LIBRARY = Room("-Library-", "CAFETERIA", None, None, "PHONE_ROOM", "- Books and 'knowledge here. One of the books have "
"been written on it. It reads 'Open the locked"
" cell...'", Boots(), None)
PHONE_ROOM = Room("-Phone Room-", None, "LIBRARY", None, None, "- This is where you call your family, "
"none of the phones are working. :/ "
"", Crowbar(), Demon4)
playing = True
directions = ['north', 'east', 'south', 'west']
inventory = ['inventory', 'i']
pick_up = ['pick up', 'grab']
attack = ['attack', 'hit', 'slash']
player = Player(YOUR_CELL, 100, 0, "You", Fists())
while playing:
print("---------------------------")
print(player.current_location.name)
print("You have %s health" % player.health)
print("You have %s shields" % player.shield)
print("You have %s equipped" % player.weapon.name)
print(player.current_location.description)
print("---------------------------")
try:
print("There is a %s nearby." % player.current_location.items.name)
except AttributeError:
pass
if player.current_location.enemy is not None:
print("There is a %s wanting to fight." % player.current_location.enemy.name)
command = input(">_")
if command.lower() in ['q', 'quit', 'exit']:
playing = False
elif command.lower() in ['commands']:
print("Commands")
print("---------------------------")
print("Moving= North, East, South, West")
print("Actions= Pick up, Grab, attack, hit, slash, inventory, i ")
elif command.lower() in directions:
try:
next_room = player.find_next_room(command)
player.move(next_room)
except KeyError:
print("I can't go that way")
elif command.lower() in inventory:
print("---------------------------")
print("Your inventory:")
print(list(player.inventory))
print("---------------------------")
elif command.lower() in pick_up:
if player.current_location.items is None:
print("---------------------------")
print("There is nothing to pick up here.")
print("---------------------------")
pass
else:
print("---------------------------")
print("You picked up %s" % player.current_location.items.name)
player.inventory.append(player.current_location.items.name)
print(list(player.inventory))
print("---------------------------")
player.current_location.items = None
else:
print("Command Not Found")
|
f71d4c4e64b7ec540c4342520303b95f1fc29579 | EddyCSE/CSE | /notes/hello world.py | 5,109 | 4.3125 | 4 | import random
print("hello world")
# This is a comment. This has no effect on the code
# but this does allow me to do things. I can:
# 1. Make notes to myself.
# 2. Comment pieces of code that do not work.
# 3. Make by my code easier to read.
print("Look at what happens here. Is there any space?")
print()
print()
print("There should be a couple of blank lines here.")
# Math
print(3 + 5)
print(5 - 2)
print(3 + 4)
print(6 / 2)
print("Figure this out...")
print(6 // 2)
print(5 // 2)
print(9 // 4)
print("Here is another one...")
print(6 % 2)
print(5 % 2)
print(11 % 4) # Modulus (Remainder)
# powers
# What is 2^20?
print(2 * 20)
# Taking input
name = input("What is your name?")
print("Hello %s." % name)
age = input("How old are you? >_")
print("%s?!? You belong in a museum." % age)
print()
print("%s is really old. They are %s years old." % (name, age))
# Variable assignments
car_name = "Wiebe Mobile"
car_type = "Tesla"
car_cylinders = 16
car_miles_per_gallon = 0.01
# Make it print "I have a car called Wiebe Mobile. It is a Tesla.
print("I have a car called %s. It is a %s." % (car_name, car_type))
# Recasting
real_age = int(input("How old are you again?"))
hidden_age = real_age + 5
print("This is your real age: %d" % hidden_age)
# (''' ''') <-- That is a multi-line comment. Anything between the "s is not a run.#
# Functions
def say_it():
print("Hello World!")
say_it()
say_it()
say_it()
# f(x) = 2x + 3
def f(x):
print(2*x + 3)
f(1)
f(5)
f(5000)
# Distance Formula
def distance(x1, y1, x2, y2):
dist = ((x2-x1)**2 + (y2-y1)**2)**(1/2)
print(dist)
distance(0, 0, 3, 4)
distance(0, 0, 5, 12)
# For Loops
for i in range(5): # This gives the numbers 0 through 4
say_it()
for i in range(10):
print(i + 1)
for i in range(5):
f(i)
# While loops
a = 1
while a < 10:
print(a)
a += 2 # This is the same as saying a = a + 1
"""
At the moment you START the loop:
For loops - Use when you know EXACTLY how many iterations
While loops - Use when you DON'T know how many iterations
"""
# Control Structures (If statements)
sunny = False
if sunny:
print("Go outside")
def grade_calc(percentage):
if percentage >= 90:
return "A"
elif percentage >= 80:
return "B"
elif percentage >= 70:
return "C"
elif percentage >= 60:
return "D"
else:
return"F"
your_grade = grade_calc(82)
print(your_grade)
# "Random" Notes
# import random <-- This should be on line 1
print(random.randint(0, 100))
# Equality Statements
print(5 > 3)
print(5 >= 3)
print(3 == 3)
print(3 != 4)
"""
a = 3 # A is set to 3
a == 3 # Is A equal to 3?
"""
# Creating a list # USE SQUARED BRACKETS
colors = ["blue", "turquoise", "pink", "orange", "black", "red", "yellow", "green", "white", "brown"]
print(colors)
print(colors[0])
print(colors[1])
# Length of the list
print("There are %d things in the list." % len(colors))
# Changing Elements in a list
colors[1] = "purple"
print(colors)
# Looping through lists
for blahblahblah in colors:
print(blahblahblah)
'''
1. Make a list with 7 items
2. Change the 3rd thing in the list
3. Print the item
4. Print the full list
'''
food1 = ["hamburger", "cupcake", "fries", "cake", "sandwich", "cookie", "rice"]
food1[2] = "french fries"
print(food1[2])
print(food1)
print("The last thing in the list is %s" % food1[len(food1) - 1])
# Slicing a list
print(food1[1:3])
print(food1[1:4])
print(food1[1:])
print(food1[:4])
food2 = ["hamburger", "cupcake", "salad", "cake", "sandwich", "cookie", "rice", "burrito", "sushi", "Chicken", "pizza",
"flan", "noodles", "pie", "chips", "fish", "milk", "spaghetti", "soup", "apples"]
print(len(food2))
# Adding stuff to a list
food2.append("bacon")
food2.append("eggs")
# Notice that everything is object.method(parameters)
print(food2)
food2.insert(1, "eggo waffles")
print(food2)
# Remove things from a list
food2.remove("salad")
print(food2)
'''
1. make a new list with 3 items
2. add a 4th item to the list
3. remove one of the first 3 items from the list
'''
states = ["cali", "arizona", "oregon"]
print(states)
states.append("Washington")
states.remove("oregon")
print(states)
# Tuples
brands = ("apple", "samsung", "htc") # Notice the parenthesis, you cannot change a tuple.
# Also removing stuff from a list
print(food2)
food2.pop(0)
print(food2)
# Find the index of an item
print(food2.index("Chicken"))
# Changing things into a list
string1 = "turquoise"
list1 = list(string1)
print(list1)
# Hangman hints
for i in range(len(list1)): # i goes through all indicies
if list1[1] == "u": # if we find a U
list1.pop(1) # remove the i-th index
list1.insert(i, "*") # put a * there instead
'''
for character in list1:
if character == "u":
# replace with a *
current_index = list1.index(character)
list1.pop(current_index)
list1.insert(current_index, "*")
'''
# Turn a list into a string
print("".join(list1))
# Function Notes
# a**2 + b**2 = c**2
def pythagorean(a, b):
return (a**2 + b**2)**(1/2)
print(pythagorean(3, 4))
|
b6dae1eb5340cbd79237c3184ec88987643499c1 | EddyCSE/CSE | /notes/Eduardo Sanchez - Hangman.py | 1,689 | 4 | 4 | import random
import string
AllLetters = string.ascii_letters
words = ["thigh", "computer", "mouse", "chair", "shirt", "o'clock", "concatenation", "pajama", "soccer", "sweater",
"goldfish", "human", "haphazard", "wildebeest", "pixel", "Wiebe"]
guesses = 6
output = []
randword = (random.choice(words))
wordlist = list(randword)
length = len(randword)
print("".join(output))
# Takes the randword into blanks
for i in range(length):
output.append("_ ")
print("".join(output))
# Takes the guess and checks it in the word list
# The "\n" is a full line space
while guesses > 0 and len(wordlist) > 0:
guess = input("Guess out my word, letter = ")
print("\n" * 20)
if guess in randword:
print("Nice, that's a letter.")
print(guesses)
for i in range(length):
if guess in wordlist:
wordlist.pop(i)
for i in range(length):
if randword[i] == guess:
output.pop(i)
output.insert(i, guess)
print("".join(output))
if len(wordlist) == 0: # Checks if you won
print("\n" * 10)
print("Congrats, you won!")
print("The word was %s" % randword)
quit()
else:
print("Wrong, guess again.")
guesses = (guesses - 1)
print(guesses)
print("".join(output))
if guesses <= 0:
print("\n" * 10)
print("You ran out of guesses, you failed, he's dead, shame on you")
if len(wordlist) == 0: # Checks if you won
print("\n" * 10)
print("Congrats, you won!")
print("The word was %s" % randword)
# quit()
|
0561cf0ce7ea015818af70852c72a91afb105c59 | kenpos/LearnPython | /正規表現とか色々/BigSmallMatch.py | 606 | 3.625 | 4 | #大文字,小文字を無視したマッチング
#compileオプション「re.I」をつける
import re
#1つ以上の数字の次に空白文字があり,一つ以上文字,数字,下線
robocop_regex = re.compile(r'RoboCop',re.I)
mo = robocop_regex.search('RoboCop is part man,part machine,all cop.').group()
print(mo)
#検索し,パターンマッチした奴を全部抽出する
mo1 = robocop_regex.search('ROBOCOP is part man,part machine,all cop.').group()
print(mo1)
mo2 = robocop_regex.search('Al,whiy does your programming book talk about robocop so much????').group()
print(mo2)
|
74d738e09d72eb4d08091a3a18b68929de0baa5e | rbetik12/ai-lab2 | /astar_search.py | 2,041 | 3.515625 | 4 | from cities import cities
from distances import distances
from greedy_search import Node
class ANode(Node):
def __init__(self, name, parent):
super().__init__(name, parent)
self.h = 0
self.g = 0
self.f = 0
def __str__(self):
if self.parent:
return "Name: " + str(self.name) + " " + "Parent: " + self.parent.name + " Cost: " + str(self.g)
return "Name: " + str(self.name) + " " + "Parent: " + " None" + " Cost: " + str(self.g)
def checked_opened(opened, node):
for el in opened:
if node == el and node.g >= el.g:
return False
return True
def a_star(start, finish):
start_node = ANode(start, None)
start_node.g = start_node.f = start_node.h = 0
finish_node = ANode(finish, None)
finish_node.g = finish_node.f = finish_node.h = 0
opened = list()
closed = list()
graph = list()
opened.append(start_node)
while opened:
opened.sort()
current_node = opened.pop(0)
closed.append(current_node)
if current_node == finish_node:
path = list()
sum = current_node.g
while current_node != start_node:
path.append(current_node)
current_node = current_node.parent
return graph, path, sum
children = list()
for child in cities[current_node.name]:
children.append(ANode(child["name"], current_node))
for child in children:
if child in closed:
continue
child_parent_dist = 0
for city in cities[current_node.name]:
if child.name == city["name"]:
child_parent_dist = city["dist"]
child.g = child.parent.g + child_parent_dist
child.h = distances[child.name]
child.f = child.g + child.h
if checked_opened(opened, child):
opened.append(child)
graph.append(current_node.name + " --> " + child.name)
|
68dc5c4931436e5b83c619401a48beefc9b69088 | davidvargaspuga/CurbsideRecycling | /blob_detection.py | 500 | 3.546875 | 4 | import cv2
import numpy as np
# Read in an image in grayscale
img = cv2.imread('updated_300.png', cv2.IMREAD_GRAYSCALE)
detector = cv2.SimpleBlobDetector_create()
# Detects the blobs in the image
keypoints = detector.detect(img)
# Draw detected keypoints as red circles
imgKeyPoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# Display found keypoints
cv2.imshow("Keypoints", imgKeyPoints)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
48def1c3190fb8e4463f68dd478055621b12e4b6 | yooshxyz/ITP | /Feb19.py | 1,702 | 4.125 | 4 | import random
# answer = answer.strip()[0].lower()
def main():
while True:
user_choice_input = int(input("What Function do you want to Use?\nPlease type 1 for the No vowels function, type 2 for the random vowels function, and 3 for the even or odd calculator.\n"))
if user_choice_input == 1:
vowelLessCommand()
elif user_choice_input == 2:
randomWords()
elif user_choice_input ==3:
evenOdd()
else:
print("Please choose one of those numbers!")
user_quit_option = input("If you wise to exit please press X")
if user_quit_option.lower() == "x":
print("Exiting....")
break
else:
return
return
def vowelLessCommand():
vowels = ["a","e","i","o","u"]
user_input = input("Please input your sentence: ")
vowelless = ""
for i in user_input:
if i not in vowels:
if i != vowels:
vowelless = vowelless + i
print(vowelless)
def randomWords():
x = 0
vowels = ["a","e","i","o","u"]
user_input2 = input("Please input your sentence: ")
randomvalues = ""
for i in user_input2:
if i in vowels:
i = random.choice(vowels)
randomvalues += i
else:
randomvalues += i
print(randomvalues)
def evenOdd():
user3_input = float(input("Please pick a number."))
if user3_input % 2 == 0:
print("The number is even!")
else:
print("The number is odd!")
def addUp():
x = 0
user_number_input = int(input("Pick a number!"))
main()
|
38dfab114e3fb05038bbef3e959c7da0de87b1c2 | yooshxyz/ITP | /fileIO.py | 864 | 3.859375 | 4 | import random
nouns_file = open("nouns.txt")
# names = open()
adj_file = open("adj.txt")
# print(nouns_file)
# for line in nouns_file:
# word = line.strip()
# nouns.append(word)
nouns = [line.strip() for line in nouns_file if line.strip()!=""]
adjectives = [line.strip() for line in adj_file if line.strip() !=""]
adjused = random.choice(adjectives).capitalize() # could also do noun_index = random.randrange(len(nouns)) then use noun = nouns[noun_index]
nounsused = random.choice(nouns).capitalize()
print(f"The band name is: {adjused} {nounsused}")
gennumber = int(input("How many bad names do yo wish to generate?"))
f = open("bandNames.txt", "a+")
f.write("Here are some more band names:")
for x in range(gennumber):
f.write(f"The band name is: {random.choice(adjectives).capitalize()} {random.choice(nouns).capitalize()} \n")
|
ecf358b69a9eccda46fe310e7989346fb7001be2 | BelongtoU/nguyentienanh-labs-C4E26 | /lab2/homework/5_te.py | 210 | 3.578125 | 4 | from turtle import*
def draw_star (x, y, lenght):
penup()
setpos(x, y)
pendown()
left(144)
forward(lenght)
for _ in range(4):
right(144)
forward(lenght)
mainloop() |
fe1f445c91e1949579163cd0545c019966d83095 | BelongtoU/nguyentienanh-labs-C4E26 | /lab2/homework/6_te.py | 405 | 3.90625 | 4 | from turtle import*
def draw_star (x, y, lenght):
penup()
setpos(x, y)
pendown()
left(144)
forward(lenght)
for _ in range(4):
right(144)
forward(lenght)
speed(0)
color('blue')
for i in range(100):
import random
x = random.randint(-300, 300)
y = random.randint(-300, 300)
length = random.randint(3, 10)
draw_star(x, y, length)
mainloop() |
e01def81ca1637d220670aae48dae515193b743f | Saptarshi-prog/LeetCode-problems-code | /3. Longest Substring.py | 280 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 22:46:33 2020
@author: 91842
"""
s = input()
m = 0
d = []
for char in s:
if char in d:
d = d[d.index(char)+1:]
d.append(char)
print(d)
m = max(m, len(d))
print(m) |
a09d239c09374761d9c78ae4cfd872eec416a71c | NishadKumar/leetcode-30-day-challenge | /construct-bst-preorder-traversal.py | 1,585 | 4.15625 | 4 | # Return the root node of a binary search tree that matches the given preorder traversal.
# (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
# It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root = TreeNode(preorder[0])
current = root
stack = [root]
i = 1
while i < len(preorder):
if preorder[i] < current.val:
current.left = TreeNode(preorder[i])
current = current.left
else:
while True:
if not stack or stack[-1].val > preorder[i]:
break
current = stack.pop()
current.right = TreeNode(preorder[i])
current = current.right
stack.append(current)
i += 1
return root |
12ce47dd742dc5e152b21eb815a5bf33e6436a41 | NishadKumar/leetcode-30-day-challenge | /binary-tree-valid-sequence.py | 1,200 | 4.03125 | 4 | # Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.
# We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidSequence(self, root, arr):
"""
:type root: TreeNode
:type arr: List[int]
:rtype: bool
"""
return self.isValid(root, arr, 0)
def isValid(self, node, arr, index):
if node.val != arr[index]:
return False
if index == len(arr) - 1:
return not node.left and not node.right
if node.left and self.isValid(node.left, arr, index + 1):
return True
if node.right and self.isValid(node.right, arr, index + 1):
return True
return False |
02b3cdcf689007b5cf1224ab3cb87d30a0dfadcc | DarynaZlochevska/Practic | /1 день/1.py | 627 | 3.96875 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
a = float(input("Введіть об'єм вашого контейнера: "))
b = int(input("Введіть кількість ваших контейнерів: "))
if a < 1:
c = b * 0.10
template = '{:.' + str(2) + 'f}'
print(template.format(c), "$")
elif a > 1:
c = b * 0.25
template = '{:.' + str(2) + 'f}'
print(template.format(c), "$")
else:
print(error)
printTimeStamp("Злочевська Д. С.")
|
af95e3682c89276ddc707bed79e14ee7e36a1add | DarynaZlochevska/Practic | /3 день/12.py | 380 | 3.5625 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
def GCD(a, b):
if a == b:
return a
elif a > b:
return GCD(a - b, b)
elif a < b:
return GCD(a, b - a)
print(GCD(500, 150))
printTimeStamp("Злочевська Д. С. Притула В. О.")
|
b1d83a286acfa0d779945d7ab5f0cfbb608f735e | nandanabhishek/C-programs | /Checking Even or Odd/even_odd.py | 249 | 4.21875 | 4 | a = int(input(" Enter any number to check whether it is even or odd : "))
if (a%2 == 0) :
print(a, "is Even !")
# this syntax inside print statement, automatically adds a space between data separated by comma
else :
print(a, "is Odd !")
|
652167ca3f075156a408e474ba047a8d204b093f | Atifmoin19/Sig-Python | /Module 2/q2.py | 437 | 3.921875 | 4 | print("Atif moin\n")
print("1900300100051\n")
print("Q.2=>Write a Python program to check a triangle is equilateral, isosceles or scalene.\n")
s1=int(input('length of side 1 : '))
s2=int(input('length of side 2 : '))
s3=int(input('length of side 3 : '))
if s1==s2==s3:
print(' This is Equiletral triangle\n')
elif(s1==s2 or s2==s3 or s3==s1):
print("This is isosceles triangle\n")
else:
print("This is scalene triangle\n") |
6041b3112f596d67d1e95eca6953cbfe698be278 | Atifmoin19/Sig-Python | /Module 5/question2.py | 487 | 3.921875 | 4 | print("Atif Moin")
print("19003000100051")
list1=[]
list2=[]
n=int(input('Enter Number of element in list : '))
for i in range(0,n):
ele=str(input('Enter element : '))
list1.append(ele)
print("List name is : ",list1)
for j in range(0,n):
list2.append(len(list1[j]))
print("List length is : ",list2)
maximum=max(list2)
print("Length of longest element is : ",maximum)
for k in range(0,n):
if (len(list1[k])==maximum):
print("Longest element is : ",list1[k])
|
a4ba4a598a77283a303e5cbc97fec434ff007df0 | ankuagar/leetcode | /pythoncode/all_rectangles_2d_array.py | 4,767 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Imagine we have an image. We'll represent this image as a simple 2D array where every pixel is a 1 or a 0.
The image you get is known to have potentially many distinct rectangles of 0s on a background of 1's. Write a function that takes in the image and returns the coordinates of all the 0 rectangles -- top-left and bottom-right; or top-left, width and height.
image1 = [
[0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 1, 1],
[1, 1, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 0],
]
Sample output variations (only one is necessary):
findRectangles(image1) =>
// (using top-left-row-column and bottom-right):
[
[[0,0],[0,0]],
[[2,0],[2,0]],
[[2,3],[3,5]],
[[3,1],[5,1]],
[[5,3],[6,4]],
[[7,6],[7,6]],
]
// (using top-left-row-column and width/height):
[
[[0,0],[1,1]],
[[2,0],[1,1]],
[[2,3],[3,2]],
[[3,1],[1,3]],
[[5,3],[2,2]],
[[7,6],[1,1]],
]
Other test cases:
image2 = [
[0],
]
findRectangles(image2) =>
// (using top-left-row-column and bottom-right):
[
[[0,0],[0,0]],
]
// (using top-left-row-column and width/height):
[
[[0,0],[1,1]],
]
image3 = [
[1],
]
findRectangles(image3) => []
image4 = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
]
findRectangles(image4) =>
// (using top-left-row-column, and bottom-right or width/height):
[
[[1,1],[3,3]],
]
n: number of rows in the input image
m: number of columns in the input image
"""
image1 = [
[0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 1, 1],
[1, 1, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 0],
]
image2 = [
[0],
]
image3 = [
[1],
]
image4 = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
]
import unittest
import copy
def findRectangle(image):
"""
Assumptions:
1. There is 0 or 1 rectangle only
"""
imageCopy = copy.deepcopy(image)
topLeft, width, height = [], -1, -1
for rowNum, row in enumerate(imageCopy):
if all(row):
continue
else:
if len(topLeft) == 0:
width, height = row.count(0), 1
topLeft = [rowNum, row.index(0)]
else:
height += 1
if len(topLeft) == 0:
return topLeft
else:
return [[topLeft, [width, height]]]
t = unittest.TestCase()
t.assertEqual([[[0, 0], [1, 1]]], findRectangle(image2))
t.assertEqual([], findRectangle(image3))
t.assertEqual([[[1, 1], [3, 3]]], findRectangle(image4))
def findRectangles(image):
"""
Assumptions:
1. There are multiple rectangles
2. Rectangles do not overlap
"""
imageCopy = copy.deepcopy(image)
ans = []
for rownum, row in enumerate(imageCopy):
while not all(row):
# print(f"""[
# [0, 1, 1, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 1, 1],
# [0, 1, 1, 0, 0, 0, 1],
# [1, 0, 1, 0, 0, 0, 1],
# [1, 0, 1, 1, 1, 1, 1],
# [1, 0, 1, 0, 0, 1, 1],
# [1, 1, 1, 0, 0, 1, 1],
# [1, 1, 1, 1, 1, 1, 0],
# ]""")
# print(f"rownum = {rownum}, row = {row}")
colnum0 = row.index(0) #get col number that has a 0
topLeft = [rownum, colnum0] # store top left coordinates for the rectangle
width, height = 0, 1
while colnum0 < len(row) and row[colnum0] == 0: # compute width of this rectangle
width += 1
colnum0 += 1
# print(f"colnum0 - width = {colnum0 - width}, width = {width}")
row[colnum0-width:colnum0] = [1] * width # slice assignment of all 0s to 1s in current row
# print(f"After assignment of 1s: rownum = {rownum}, row = {row}")
rownum0 = rownum + 1 # row number of next row
# print(rownum0, colnum0 - width, width)
while rownum0 < len(imageCopy) and imageCopy[rownum0][colnum0 - width] == 0:
height += 1
imageCopy[rownum0][colnum0 - width:colnum0] = [1] * width # slice assignment of all 0s to 1s in row below which are part of current rectangle
rownum0 += 1
ans.append([topLeft, [width, height]])
# print("--")
return ans
t = unittest.TestCase()
t.assertEqual([
[[0,0],[1,1]],
[[2,0],[1,1]],
[[2,3],[3,2]],
[[3,1],[1,3]],
[[5,3],[2,2]],
[[7,6],[1,1]],
], findRectangles(image1))
t.assertEqual([
[[0,0],[1,1]],
], findRectangles(image2))
t.assertEqual([], findRectangles(image3))
t.assertEqual( [
[[1,1],[3,3]],
], findRectangles(image4)) |
9f790dbf9f80207fe4c8e5102ef0e5a862b72819 | ankuagar/leetcode | /pythoncode/heap.py | 4,271 | 4.03125 | 4 | #!/usr/bin/env python3
import unittest
class Heap(object):
'''
Min Heap. Every root node is <= child nodes
Uses 1 based indexing
'''
def __init__(self, capacity):
self.capacity = capacity
self.arr = []
def size(self):
return len(self.arr)
def push(self, ele):
if self.size() < self.capacity:
self.arr.append(ele) # append new element to the end
if self.size() > 1:
self._heap_up() # and heap up
else:
raise Exception("Heap is full cannot push")
def pop(self):
if self.size() == 0:
raise Exception("Heap is empty cannot pop")
self.arr[0], self.arr[-1] = self.arr[-1], self.arr[0] # swap the root with the last element
ele = self.arr.pop() # pop the last element to get root
if self.size() > 1:
self._heap_down() # and heap down
return ele
def _heap_down(self):
def _find_min_child_idx(parentidx):
childidx0 = 2*parentidx
childidx1 = 2*parentidx + 1
if childidx1 > self.size():
if childidx0 > self.size():
return None
else:
return childidx0
elif self.arr[childidx0 - 1] > self.arr[childidx1 - 1]:
return childidx1
else:
return childidx0
parentidx = 1
min_child_idx = _find_min_child_idx(parentidx)
while True:
if self.arr[parentidx - 1] > self.arr[min_child_idx - 1]:
self.arr[parentidx - 1], self.arr[min_child_idx - 1] = self.arr[min_child_idx - 1], self.arr[parentidx - 1]
parentidx = min_child_idx
min_child_idx = _find_min_child_idx(parentidx)
if min_child_idx is None:
return
else:
return
def _heap_up(self):
childidx = self.size()
parentidx = childidx//2
while True:
if self.arr[parentidx - 1] > self.arr[childidx - 1]: # if parent > child, then swap
self.arr[childidx - 1], self.arr[parentidx - 1] = self.arr[parentidx - 1], self.arr[childidx - 1]
if parentidx == 1: # if already at root
return
childidx = parentidx
parentidx = childidx // 2
def print_heap(self):
'''
Not so ugly level order traversal of the heap
'''
if not self.size() > 0:
return
parent = [1] # contains indexes
temp = []
while len(parent) > 0:
temp.clear()
for idx in parent:
print(self.arr[idx-1], end=' ')
temp.append(2*idx)
temp.append(2*idx+1)
parent = list(filter(lambda x: x <= self.size(),temp))
print()
t = unittest.TestCase()
obj = Heap(4) # capacity is 4
t.assertEqual(0, obj.size())
t.assertEqual([], obj.arr)
obj.push(8)
t.assertEqual(1, obj.size())
t.assertEqual([8], obj.arr)
obj.push(4)
t.assertEqual(2, obj.size())
t.assertEqual([4,8], obj.arr)
obj.push(3)
t.assertEqual(3, obj.size())
t.assertEqual([3,8,4], obj.arr)
obj.push(5)
t.assertEqual(4, obj.size())
t.assertEqual([3,5,4,8], obj.arr)
with t.assertRaises(Exception): # push() to a heap that exceeds capacity should raise an exception
obj.push(10)
t.assertEqual(obj.pop(), 3)
t.assertEqual(3, obj.size())
t.assertEqual([4,5,8], obj.arr)
t.assertEqual(obj.pop(), 4)
t.assertEqual(2, obj.size())
t.assertEqual([5,8], obj.arr)
t.assertEqual(obj.pop(), 5)
t.assertEqual(1, obj.size())
t.assertEqual([8], obj.arr)
t.assertEqual(obj.pop(), 8)
t.assertEqual(0, obj.size())
t.assertEqual([], obj.arr)
with t.assertRaises(Exception): # pop() from an empty heap should raise an exception
obj.pop()
obj.push(5)
t.assertEqual(1, obj.size())
t.assertEqual([5], obj.arr)
obj.push(5)
t.assertEqual(2, obj.size())
t.assertEqual([5,5], obj.arr)
obj.push(5)
t.assertEqual(3, obj.size())
t.assertEqual([5,5,5], obj.arr)
obj.push(5)
t.assertEqual(4, obj.size())
t.assertEqual([5,5,5,5], obj.arr)
with t.assertRaises(Exception): # push() to a heap that exceeds capacity should raise an exception
obj.push(5) |
3507349ce69a165ef1b4165843a3ba72e09e4a12 | Rishab-kulkarni/caesar-cipher | /caesar_cipher.py | 1,861 | 4.40625 | 4 | import string
# Enter only alphabets
input_text = input("Enter text to encrypt:").lower()
shift_value = int(input("Enter a shift value:"))
alphabet = string.ascii_lowercase
alphabet = list(alphabet)
def encrypt(input_text,shift_value):
"""
Shifts all the characters present in the input text by a fixed value(encrypting) and returns the encrypted text.
"""
encrypted_text = ""
for ch in input_text:
index = alphabet.index(ch)
if index + shift_value >=26:
encrypted_text+="".join(alphabet[index + shift_value - 26])
else:
encrypted_text +="".join(alphabet[index + shift_value])
return encrypted_text
encrypted_text = encrypt(input_text, shift_value)
print("Encrypted text:",encrypted_text)
def decrypt(encrypted_text):
"""
Brute forces through all the shift values and decrypts the given encrypted text.
Uses the method encrypt() but the shift value passed is negative, inorder to decrypt.
"""
print("All possible messages:")
for shift in range(1,27):
decrypted_text = encrypt(encrypted_text,-shift)
print(decrypted_text, shift)
decrypt(encrypted_text)
def text_to_morse(encrypted_text):
"""
Converts the encrpyted text into morse code.
"""
morse_codes = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--'
,'-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..'
]
morse_alphabet_codes = dict(zip(list(alphabet),morse_codes))
print(morse_alphabet_codes)
encrypted_morse = ""
for ch in encrypted_text:
encrypted_morse += morse_alphabet_codes.get(ch)
return encrypted_morse
print(text_to_morse(encrypted_text))
|
ebe5f04f9ae3e7572d6595ea85caeb0833cfa352 | Sipoufo/Python_realisation | /Ex-5/high_score.py | 329 | 3.84375 | 4 | student_score = input("Input a list of student score\n").split()
high_score = 0
for n in range(0, len(student_score)):
student_score[n] = int(student_score[n])
print(student_score)
for score in student_score:
if score > high_score:
high_score = score
print(f"The highest score in the class is : {high_score}") |
0e8366c415dd5b7ba4812b30d1a97dd5b4bf7763 | Sipoufo/Python_realisation | /Ex-12/guess_number.py | 1,389 | 4.125 | 4 | from art import logo
import random
print("Welcome to the Number Guessing Game")
# init
live = 0
run = True
# function
def add_live(difficulty):
if difficulty.lower() == 'easy':
return 10
elif difficulty.lower() == 'hard':
return 5
def compare(user, rand):
if user < rand:
print("Too low")
elif user > rand:
print("Too high")
else:
print(f"You got it! the answere was {guess}")
# running the app
while run:
print(logo)
print("I'm thinking of a number between 1 and 100: ")
answere = random.randint(1, 101)
print(f"Pssf {answere}")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
live = add_live(difficulty)
guess = 0
while guess != answere:
if live == 0:
print(compare(guess, answere))
print("You've run out of guesses, you lose")
run = False
break
elif guess == answere:
compare(guess, answere)
run = False
else:
print(f"You have {live} attempts remaning to guess the number")
guess = int(input("Make a guess: "))
live -= 1
compare(guess, answere)
print("Guess again")
again = input("Try again? 'Yes' or 'No': ")
if again == 'No':
run = False
else:
run = True
|
91c61dec3ac0cac535dabcc6f543bd1f95fb4955 | ingdanielmichel/estudio0todatascientist | /prueba.py | 420 | 3.859375 | 4 | def complejidad(lista):
for x in lista:
if x == 33:
print('Esto es lo que buscamos!')
return(x)
print('No esta lo que buscamos')
def simplicidad(lista):
if len(lista)>0:
print('Tenemos datos!')
return
print('No tenemos datos!')
return
lista = [1,21,23,321,43,245,431,534,33,231,23,123,21]
complejidad(lista)
simplicidad(lista)
|
eefef27fae7d18c378b4abfec6d3c543209a04e4 | Kevnien/Lambda-Technical | /Search in Sorted Matrix/solution.py | 731 | 3.734375 | 4 | def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while col >= 0 and row < len(matrix):
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return [row, col]
return [-1, -1]
matrix = [
[1, 4, 7, 12, 15, 997, 999],
[2, 5, 19, 32, 35, 1001, 1007],
[4, 8, 24, 34, 36, 1008, 1015],
[40, 41, 42, 44, 45, 1018, 1020],
[98, 99, 101, 104, 190, 1021, 1025],
]
print(search_in_sorted_matrix(matrix, 33))
print(search_in_sorted_matrix(matrix, 34))
print(search_in_sorted_matrix(matrix, 1025))
print(search_in_sorted_matrix(matrix, 997))
print(search_in_sorted_matrix(matrix, 1))
print(search_in_sorted_matrix(matrix, 5)) |
fc3b3ba9561dd23a4ec7442043683b28aab0e31f | RulasLalo/HackerRank | /Python3/FRUPS.py | 276 | 3.875 | 4 | #Find the Runner-Up Score! program
n=int(input())
lista=[]
unico=[]
datos=input()
lista= [int(d) for d in datos.split()]
lista.sort()
for i in lista:
if i not in unico:
unico.append(i)
#print(unico)
unico[-2:-1]
for i in unico[-2:-1]:
print(i)
|
f55819c8e653d6b4d94ad5f74cffd6a8121ddda2 | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Dictionaries_23.py | 2,317 | 4.375 | 4 | # in with dictionaries
grades = {"John": 97.6,
"Randall": 80.45,
"Kim": 67.5,
"Linda": 50.2,
"Sarah": 99.2}
## check if the student is in there
name = input("Who's grade do you want? ")
print(name in grades)
## if not there, add them
name = input("Who's grade do you want? ").capitalize()
if name in grades:
print(grades[name])
else:
print("This student does not have a grade for this assignment")
g = input("Please enter a grade now: ")
try:
g = float(g)
except:
print("Invalid grade, assigning grade of 0 for now")
g = 0
finally:
grades[name] = g
print(grades)
# sets
my_set = {"February", "January", "April"}
print(my_set)
my_set2 = {1,1,1,1,1,1,3,5,9,11}
print(my_set2)
# creating sets
my_list = [10,5,5,9,3,4,9,1,2,6,8,9,4,2,5,7]
my_list_to_set = set(my_list)
print(my_list_to_set)
## can't put mutable objects inside a set
my_mutables = {(1,2,3,4), (5,6,7,8)}
## but you can mix types
my_mixed_set = {1, "ant", "blue", (1,2)}
print(my_mixed_set)
# set methods
my_set.add("June")
print(my_set)
my_set.add("February")
print(my_set)
my_set.remove("January")
print(my_set)
## union, intersection, difference
odds = {1,3,5,7,9}
evens = {2,4,6,8,10}
pos_ints = {1,2,3,4,5,6,7,8,9,10}
primes = {2,3,5,7}
# union
print(odds | evens)
print(odds.union(evens))
# intersection
print(odds & pos_ints)
print(odds.intersection(pos_ints))
# difference
print(odds - primes)
print(odds.difference(primes))
print(primes - odds)
print(primes.difference(odds))
# symmetric difference
print(odds^primes)
print(odds.symmetric_difference(primes))
print(primes^odds)
# if i switched the order, would the answer be different?
'''
Let's write some code to ask two friends their favorite music artists,
and then print out a message telling them which artists they both said they like!
'''
songs = {}
for friend in range(0,2):
f = "friend" + str(friend)
print("Welcome " + f)
songs[f] = set()
artist = input("Name an artist you like, enter a blank string to end: ").lower()
while artist != "":
songs[f].add(artist)
artist = input("Name an artist you like, enter a blank string to end: ").lower()
print("GREAT JOB!")
print("The artists you have in common are: ", ",".join(list(songs["friend0"] & songs["friend1"])))
|
ad45fe4fddbfc734955ab84e434975e7bea7aa6d | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Conditionals_6_BLANK.py | 452 | 4.0625 | 4 | # if elif else
# baggage check
# bank rewards
# and or
# friends
# maybe you're not so picky....
# and/or with comparisons
# conditional expressions
# name check
name = "Chelsea"
if name == "Chelsea":
print("You're the professor.")
else:
print("You're a student.")
# Daniel Craig
day = "Sunday"
if day == "Sunday" or day == "Saturday":
print("Ladies and Gentlemen...The Weekend.")
else:
print("Work work work work work.")
|
9aba99649efeda7100d760f8464fe9697075d923 | cmparlettpelleriti/CPSC230ParlettPelleriti | /Classwork/Conditionals_6.py | 3,573 | 4.375 | 4 | # Class Activities + Review (Class 6)
# Together------------------------------------------------
# 0. Questions?
# 1. If/Elif/Else
# 2. And/Or
# 3. Conditional Expressions
# Classwork-----------------------------------------------
'''
1. Help me figure out where to go on campus! On MW I tech in Keck.
On TTh I teach in the Library. And on Friday I work in my office in
Swenson Hall. On the weekend I am at home.
Write a python script that asks me (the user) to input
the day of the week and use ifs/elifs/elses to print out where I should
be based on what day it is (either Keck, Library, Swenson, or Home).
'''
'''
2. Create some code that checks whether a number is even.
If it is, print "even", otherwise print "odd". If the number
is 0, print "this is neither even, nor odd".
'''
'''
3. Pretend you're writing some code for a convience store. Ask the user to
input the name of an item (such as diapers, milk, lipgloss, moisturizer...etc).
Check if the item is either "cigarettes" or "alcohol". If it is, ask the user
how old they are and make sure they're old enough to buy the item (18 for
cigarettes and 21 for alcohol). If they're not old enough, print "Sorry I can't
sell you that.", If they are old enough, OR they're buying something else, print
"Thank you for your purchase".
'''
'''
4. Ask a user to input an integer, then check if that integer is even and
greater than 17. If it is print "yes!".
'''
'''
5. Translate the following if statements into conditional expressions.
'''
# if 1
x = 10
# ------------------------------------------
if x == 7:
print("That's a lucky Number!")
else:
print("okay.")
# ------------------------------------------
# if 2
late_days = int(input("How many late days do you get?"))
# ------------------------------------------
if late_days == 3:
print("Correct!")
else:
print("WRONG.")
# ------------------------------------------
# if 3
string = "kayak"
# ------------------------------------------
if string == string[::-1]: # using [::-1] reverses a string
print("palindrome")
else:
print("boring old word.")
# ------------------------------------------
# if 4
x = 12
# check if number is divisible by 2 and 3.
# ------------------------------------------
if x%2 == 0 and x%3 == 0:
print("yes")
else:
print("no")
'''
6. Pretend you run a movie theatre. Using if/elif/else statements as needed, write some
code that asks the user to input their age. If customers are under 11, ask if
they have an adult with them (yes/no), if they do, then ask them how many tickets
they want. Tickets are $11.50 each (they get a student discount on all tickets).
Print out their total cost. If they do not have an adult with them, print out a
message saying they cannot buy any tickets. If the customer is older than 11,
ask them how many tickets they want, and print out the price (Adults pay
$13 per ticket).
HINT: before you write out code, diagram this problem or write out the steps first.
'''
'''
7. Ask the user to input 3 integers which represent the lengths of the sides of
a triangle. Write some code to check if the triangle is equilateral (all sides
the same length), isosceles (two sides are equal), or obtuse (no sides are equal).
Print out the result for the user to see.
'''
'''
8. Use if/elif/else to check whether a variable, x, is negative, zero, or positive.
'''
'''
9. Use if/elif/else statements to ask the user to input their grade as a percentage
(0-100%), and print out whether they have an A, B, C, D or F. (Use 90,80,70,60,
and < 60 as your grade cutoffs.)
'''
|
a47c6e062100a927376d78bb6a292fe8b76b3e4c | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Dictionaries_23_BLANK.py | 707 | 3.796875 | 4 | # in with dictionaries
grades = {"John": 97.6,
"Randall": 80.45,
"Kim": 67.5,
"Linda": 50.2,
"Sarah": 99.2}
## check if the student is in there
## if not there, add them
# sets
# creating sets
## can't put mutable objects inside a set
## but you can mix types
# set methods
## union, intersection, difference
odds = {1,3,5,7,9}
evens = {2,4,6,8,10}
pos_ints = {1,2,3,4,5,6,7,8,9,10}
primes = {2,3,5,7}
# union
# intersection
# difference
# symmetric difference
# if i switched the order, would the answer be different?
'''
Let's write some code to ask two friends their favorite music artists,
and then print out a message telling them which artists they both said they like!
'''
|
d56bfae8d6f3ed3c39ce1464c95c056f8c31d4ac | cmparlettpelleriti/CPSC230ParlettPelleriti | /Classwork/ListsAndTuples_16.py | 4,496 | 4.125 | 4 | # Class Activities + Review (Class 16)
# Together------------------------------------------------
# 0. Questions?
# 1. modifying vs. nonmodifying
'''
Modify your bridge_crosser() function *again* (from the last classwork),
so that it returns a list with two things:
at index 0, it returns the # of successful steps,
and at index 1, it returns a list of the successful steps made
(e.g. ["l", "r", "l", "l"]).
So the output of the function could look something like this if the player made
4 successful steps:
# output
[4, ['l', 'r', 'r', 'r']]
'''
# let's talk about how we formed bridge!
import random
def bridge_crosser():
# list of 0's and 1's, 1 means right side is solid,
# 0 means left side is solid
bridge = [random.randint(0,1) for i in range(0,10)]
print(bridge)
# your code here #
safe_steps = 0
for pane in bridge:
choice = input("Would you like to go left or right?").lower()
if choice == "r" and pane == 1:
print("PHEW, safe")
safe_steps += 1
elif choice == "l" and pane == 0:
print("PHEW, safe")
safe_steps += 1
else:
print("Oh no, you fell")
break
else:
print("CONGRATUALTIONS! You Made it Out.")
return(safe_steps)
# Classwork-----------------------------------------------
'''
1. Let’s continue our work from Classwork 13 (Functions) and help our adventure
hero carry items.
- Make an empty list called backpack
- Make an empty list called pockets
- Create a maximum number of items for pockets and backpack (pocket max is
4 items, backpack max is 20 items) and store them in the variables
pocket_max and backpack_max.
- Create a function, storage_check() that takes in the pocket list, the backpack
list, and an item as a string. The function should check whether the pocket is
full (use len()), if it is, put item in backpack, if backpack is full, print
out the items in the backpack and ask user to choose item to remove. Once they
choose a valid item (check if they did using in), remove it and insert the new
item in its place.
- Using append, add 20 items to your backpack list.
'''
'''
2. Using the code from #1, let's have our adventurer find an apple, decide whether
to pick it up, and then eat it.
First, print out apple_message using the adventure_mess() function from Lecture 13.
Next, ask the user to input a "yes" or "no" about whether or not to pick up the apple.
Then, if they say yes, use the storage_check function to help them add the apple. If
they say no, then print out "moving on".
'''
apple_message = "You've found an apple on the ground. It looks delicious."
'''
3. Write a function, cursed_backpack() which takes in the backpack list and
performs a curse on it! The curse takes the name of each item in the backpack,
and scambles it so that it's an anagram of the item name. Return the new cursed
backpack list.
'''
'''
4. Write a function, drop_it_all() which takes in the backpack list and removes
all the items from the backpack using .pop() and prints out a message telling
the user what was removed at each iteration.
'''
'''
5. Modifying the bridge_crosser() function we made at the beginning of class
(also in the previous classwork), modify the function yet *again* so that it takes
in two arguments, known_steps, which is a list of steps the player KNOWS to be safe
(because they saw the previous player take them), and bridge, which is a list of 0's
and 1's that represent whether the right (1) or left (0) pane is the solid one.
(note: we previously created this list INSIDE the function, so remove that code. We
will now take in bridge as an argument.)
The default for this list should be [].
If the list contains any steps (e.g. it's not empty), use those steps first
and THEN ask the player to choose left or right ('l' or 'r') once that list runs out.
For example, if the playe knows the first 3 steps are ['l', 'r', 'l'], have them take
those steps, and then on the 4th step (when we don't know which is safe) ask them to choose 'l' or 'r'.
'''
'''
6. Turn the following for loops into list comprehensions
'''
l = []
for i in range(0,10):
l.append(i**2)
for person in people:
print(person + " is silly")
def perfect(n):
factors = 1
for i in range(1,n):
if n%i == 0:
factors *= i
if factors == n:
return(True)
else:
return(False)
is_perf = []
for j in range(1,26):
is_perf.append(perfect(j))
|
998e19b6bd3fd6f73471a13fd3e08a177c499e5e | cmparlettpelleriti/CPSC230ParlettPelleriti | /Classwork/Dictionaries_24.py | 3,697 | 4.21875 | 4 | # Class Activities + Review (Class 24)
# Together------------------------------------------------
# 0. Questions?
# 1. dicts are mutable like lists, what does that mean about changing it in a function?
'''
1. Using the Book dictionary below, write the following functions that do things
with the Book dictionary.
- update_read_perc() which takes in the book dictionary, and an integer, pages_read
as arguments. The function should calculate and update the percent_read.
- rate() which takes in the book dictionary, and a float (between 0 and 5), stars,
as arguments. The function should update the star_rating key/value.
Call these functions on Book.
'''
Book = {"title": "A Short History of Nearly Everything",
"author": "Bill Bryson",
"num_pages": 452,
"star_rating": 4.5,
"percent_read": 0}
'''
2. Using the dictionary below, write the following functions that do things with
the soccer_player dictionary.
- trade() which takes in the soccer player dictionary, and new_team (a string
representing the new team they'll be on) as arguments. Set the player's team
to be the new team and print a message welcoming them to the new team.
- goal() which takes in the player's dictionary and increments the player's goals
for the season by 1, and prints out "GOAAAAAAAAAAL".
- add_minutes() which takes in the player's dictionary and an int, mins, as arguments
and increments the player's minutes played by mins.
- end_game() which takes in the player's dictionary, an int, mins, and an int, goals,
as arguments and calls the goal() and add_minutes() functions for that game.
- bmi() which takes in the player's dictionary and returns their bmi.
- change_teams() which takes in the player's dictionary, their new team name as a string,
their player number (an int), and their new position (a string) as arguments. The function
should then change the dictionarie's team argument (using trade), update their jersey number,
and update their position. If their position and number are different from before, print
out a message telling them so.
Call all of these functions to test them out on the soccer_player dictionary.
'''
soccer_player = {"name": "Zlatan Ibrahimovic", "number": 11,
"team": "Galaxy", "height_cm": 195, "goals_season": 5,
"minutes_played_season": 466, "age": 40, "position": "FW",
"instagram": "@iamzlatanibrahimovic",
"weight_kg": 95}
'''
3. Using the Car dictionary below, write the following functions that do things
with the Car dictionary.
- calc_miles_left() which takes in the dictionary as an argument, and returns an
estimate of how many miles the car has left based on it's average mpg, and the
current number of gallons in the tank (tank_fill_current).
- calc_gas_cost() which takes in the dictionary, and a float, gas_price, which
is the cost of gas per gallon (e.g. 4.56) as arguments and returns the estimated
cost to fill up the tank *completely*.
- fill_tank() which takes in the dictionary, a float, gas_price, which
is the cost of gas per gallon (e.g. 4.56, and an int, num_gallons, as arguments
and prints out the cost to add num_gallons gallons of gas to the car, and then
changes tank_fill_current to reflect the refueling.
- drive() which takes in the dictionary, and a float, trip_miles, which tells you
how long the trip is in miles as arguments. The function should: use the average mpg
(mpg) to calculate how much gas will be used, and subtract it from tank_fill_current
(i know that's not exactly how cars work, but we're simplifying...). It should also
increase the odometer by the requisite number of miles.
'''
Car = {"make": "Honda",
"model": "Accord",
"year": 2006,
"mpg": 27,
"tank_vol_gallons": 15,
"tank_fill_current": 10,
"odometer": 79482.25}
|
5ace467fb1083c7a5a15a0fab41026c737172902 | taiharry108/captcha_recognition | /captcha_generation.py | 3,197 | 3.5 | 4 | from captcha.image import ImageCaptcha
from shutil import copyfile
from os.path import join
import numpy as np
import os
from config import CAP_LEN, CHARACTERS, RESULT_FILE_NAME, NO_TRAIN_CAP, NO_TEST_CAP, DES_PATH, OUT_FILENAME
from collections import defaultdict
import pandas as pd
def gen_str(size, characters):
'''
A generator to generate random string as captcha
Args:
size (int): The length of the captcha string
characters (str): A string with unique characters
Yields:
str: Generated captcha
'''
while True:
positions = np.random.randint(len(characters), size=size)
yield ''.join(map(lambda x: characters[x], positions))
def generate_captcha(captcha, out_dir, no_of_img=10000, size=CAP_LEN, characters=CHARACTERS):
'''
A function to generate a number of captcha images and write them to an output directory
Args:
captcha (ImageCaptcha): An ImageCaptcha object for the generation of captcha from the module captcha
out_dir (str): Output directory for the captcha images
no_of_img (int): Number of images to be generated
size (int): The length of the captcha string
characters (str): A string with unique characters
Returns;
bool: True for success, False otherwise.
'''
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
str_gen = gen_str(size, characters)
img_dict = defaultdict(int)
for i in range(no_of_img):
text = next(str_gen)
if i % 10000 == 0:
print("Generating image {} of {}".format(i, no_of_img))
img_name = f'{text}_{img_dict[text]}.png'
img_dict[text] += 1
captcha.write(text, join(out_dir, img_name))
return True
def generate_feather(train_dir, valid_dir, out_filename):
'''
A function to generate a feather file with the input files and labels
Args:
train_dir (str): A directory containing training images
valid_dir (str): A directory contarining images for validation
Returns;
bool: True for success, False otherwise.
'''
def process_filename(filename):
text = filename.split('_')[0]
return list(map(lambda x: f'{x[1]}{x[0]}', enumerate(text)))
rows = []
for filename in os.listdir(train_dir):
rows.append((os.path.join('train', filename),
process_filename(filename), False))
for filename in os.listdir(valid_dir):
rows.append((os.path.join('valid', filename),
process_filename(filename), True))
df = pd.DataFrame(rows, columns=['name', 'label', 'is_valid'])
df.to_feather(out_filename, index=False)
def main():
ic = ImageCaptcha()
train_dir = join(DES_PATH, RESULT_FILE_NAME, 'train')
valid_dir = join(DES_PATH, RESULT_FILE_NAME, 'valid')
directories = [train_dir, valid_dir]
nos_of_img = [NO_TRAIN_CAP, NO_TEST_CAP]
for directory, no_of_img in zip(directories, nos_of_img):
generate_captcha(captcha=ic, out_dir=directory,
no_of_img=no_of_img, size=CAP_LEN, characters=CHARACTERS)
if __name__ == "__main__":
main()
|
13a40128d38fc83d7494f692c61bf7f8a1935269 | luisfmgoncalves/adventOfCode2020 | /day5/day5.py | 982 | 3.65625 | 4 | import math
def read_input():
file = open('input.txt')
puzzle_input = [line.strip() for line in file]
file.close()
return puzzle_input
def interval(tuple, char):
lower, upper = tuple[0], tuple[1]
middle = (upper - lower) / 2
b = math.floor(upper - middle) if char == 'F' or char == 'L' else upper
a = math.ceil(lower + middle) if char == 'B' or char == 'R' else lower
return a, b
def seat_id(line):
row = (0, 127)
col = (0, 7)
for char in line[:7]: row = interval(row, char)
for char in line[-3:]: col = interval(col, char)
return (row[0] * 8) + col[0]
def find_missing_seat(seat_list):
return [s for s in range(seat_list[0], seat_list[-1] + 1) if s not in seat_list]
def main():
puzzle_input = read_input()
ids = [seat_id(s) for s in puzzle_input]
ids.sort()
print('Part 1: ' + str(ids[-1]))#850
print('Part 2: ' + str(find_missing_seat(ids)[0]))#599
if __name__ == '__main__':
main() |
788b81702a0cafc6a44fcc011447d30f84178680 | luisfmgoncalves/adventOfCode2020 | /day12/day12.py | 3,675 | 3.5625 | 4 | def read_input():
file = open('input.txt')
puzzle_input = [line.replace('\n', '') for line in file]
file.close()
return puzzle_input
NORTH_RIGHT = {90: 'E', 180: 'S', 270: 'W'}
NORTH_LEFT = {90: 'W', 180: 'S', 270: 'E'}
EAST_RIGHT = {90: 'S', 180: 'W', 270: 'N'}
EAST_LEFT = {90: 'N', 180: 'W', 270: 'S'}
SOUTH_RIGHT = {90: 'W', 180: 'N', 270: 'E'}
SOUTH_LEFT = {90: 'E', 180: 'N', 270: 'W'}
WEST_RIGHT = {90: 'N', 180: 'E', 270: 'S'}
WEST_LEFT = {90: 'S', 180: 'E', 270: 'N'}
def move_ship_part_1(action, units, facing, ship):
if action == "N": ship["N"] += units
elif action == "S": ship["N"] -= units
elif action == "E": ship["E"] += units
elif action == "W": ship["E"] -= units
elif action == 'F':
if facing == 'E': ship["E"] += units
if facing == 'S': ship["N"] -= units
if facing == 'W': ship["E"] -= units
if facing == 'N': ship["N"] += units
elif action == 'L':
if facing == 'N': facing = NORTH_LEFT[units]
elif facing == 'E': facing = EAST_LEFT[units]
elif facing == 'S': facing = SOUTH_LEFT[units]
else: facing = WEST_LEFT[units]
elif action == 'R':
if facing == 'N': facing = NORTH_RIGHT[units]
elif facing == 'E': facing = EAST_RIGHT[units]
elif facing == 'S': facing = SOUTH_RIGHT[units]
else: facing = WEST_RIGHT[units]
return facing, ship
def part1(puzzle_input):
ship = {"N": 0, "S": 0, "E": 0, "W": 0}
facing = 'E'
for line in puzzle_input:
action, units = line[0], int(line[1:])
facing, ship = move_ship_part_1(action, units, facing, ship)
return abs(ship['E']) + abs(ship['N'])
def move_ship_part_2(action, units, facing, waypoint, ship):
if action == "N": waypoint["N"] += units
elif action == "S": waypoint["N"] -= units
elif action == "E": waypoint["E"] += units
elif action == "W": waypoint["E"] -= units
elif action == 'F':
for x in range(units):
if facing == 'N':
ship["E"] -= waypoint["N"]
ship["N"] -= waypoint["E"]
if facing == 'S':
ship["E"] += waypoint["N"]
ship["N"] += waypoint["E"]
if facing == 'E':
ship["E"] += waypoint["E"]
ship["N"] += waypoint["N"]
if facing == 'W':
ship["E"] -= waypoint["E"]
ship["N"] -= waypoint["N"]
elif action == 'L':
if units == 90:
waypoint["E"], waypoint["N"] = -waypoint["N"], waypoint["E"]
elif units == 270:
waypoint["E"], waypoint["N"] = waypoint["N"], -waypoint["E"]
elif units == 180:
waypoint["E"] = -waypoint["E"]
waypoint["N"] = -waypoint["N"]
elif action == 'R':
if units == 90:
waypoint["E"], waypoint["N"] = waypoint["N"], -waypoint["E"]
elif units == 270:
waypoint["E"], waypoint["N"] = -waypoint["N"], waypoint["E"]
elif units == 180:
waypoint["E"] = -waypoint["E"]
waypoint["N"] = -waypoint["N"]
return waypoint, ship
def part2(puzzle_input):
ship = {"N": 0, "S": 0, "E": 0, "W": 0}
waypoint = {"N": 1, "S": 0, "E": 10, "W": 0}
facing = 'E'
for line in puzzle_input:
action, units = line[0], int(line[1:])
waypoint, ship = move_ship_part_2(action, units, facing, waypoint, ship)
return abs(ship['E']) + abs(ship['N'])
def main():
puzzle_input = read_input()
print('Part 1: ' + str(part1(puzzle_input))) #441
print('Part 2: ' + str(part2(puzzle_input))) #40014
if __name__ == '__main__':
main()
|
11f9cd49d79abaa09b7a02d18e06af81a20332ff | Muthupriya20/LetsUpgrade_pythonEssentials_B7_assignment | /B7_day8_assignment.py | 745 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Question 1
# In[5]:
def getinput(arg_func):
def wrap_function():
x=int(input("enter:"))
arg_func(x)
return wrap_function
# In[ ]:
@getinput
def fibo(n):
if n<=1:
return n
else:
return(fibo(n-1)+fibo(n-2))
nterms=int(input())
if(nterms<=0):
print("invalid")
else:
for i in range (nterms):
print(fibo(i))
fibo()
# ##Question 2
# In[ ]:
get_ipython().run_cell_magic('writefile', 'test.txt', 'Hi....This is Muthupriya')
# In[ ]:
try:
file=open("test.txt","r")
file.write("i am kaviya")
print("it is in read mode")
except Exception as e:
print("Error")
print("Error message is:",e)
# In[ ]:
|
1afd54bded4dc958e33ae0484aceaaa7658d8a1b | CosmoAndrade/Fic-programador_web | /Hospitalar em Python/hospital.py | 1,685 | 3.828125 | 4 | import sqlite3
from sqlite3 import Error
class Hospital:
def __init__(self,nome,tipo,especialidade,avaliacao):
self.nome = nome
self.tipo = tipo
self.especialidade = especialidade
self.avaliacao = avaliacao
def inserir(self):
try:
conecta = sqlite3.connect('D:/hospitalar.db')
cursor = conecta.cursor()
sair = 'n'
while sair == 'n':
self.nome = input ('Digite o seu nome: --> ')
self.tipo = input ('Digite o tipo do Hospital: --> ')
self.especialidade = input ('Digite a especialidade: --> ')
self.avaliacao = input ('Como você alavia o Hospital?: --> ')
cursor.execute("""INSERT INTO hospital(nome_hosp,tipo_hosp,especialidade_hosp,avalia_hosp) VALUES(?,?,?,?)
""", (self.nome,self.tipo,self.especialidade,self.avaliacao) )
conecta.commit()
sair = input ('Deseja parar digite s para SIM e n para NÂO: --> ')
except Error as e:
print(e)
def mostrar(self):
try:
conecta = sqlite3.connect('D:/hospitalar.db')
cursor = conecta.cursor()
cursor.execute('SELECT * FROM hospital')
for linha in cursor:
print (linha)
except Error as e:
print (e)
class Medico:
def __init__(self,nome,crm):
self.nome = nome
self.crm = crm
def mostrar_medico(self):
print(self.nome,' ',self.crm)
|
34f595312e5ea7350c60fbffc54a1690a35fa8d1 | LuisFros/AdvancedProgramming | /Tareas/T02/estructuras.py | 6,449 | 3.703125 | 4 |
class Nodo:
def __init__(self, valor=None):
self.siguiente = None
self.valor = valor
class ListaLigada:
def __init__(self, *args):
self.cola = None
self.cabeza = None
for arg in args:
self.append(arg)
def __len__(self):
largo = 0
for i in self:
largo += 1
return largo
def __iter__(self):
actual = self.cabeza
while actual is not None:
yield actual.valor
actual = actual.siguiente
def __repr__(self):
nodo = self.cabeza
s = "["
if nodo:
s += str(nodo.valor) + ", "
else:
return "[]"
while nodo.siguiente:
nodo = nodo.siguiente
s += str(nodo.valor) + ", "
return s.strip(", ") + "]"
def __getitem__(self, index):
nodo = self.cabeza
if isinstance(index, slice):
pass
# temp=ListaLigada()
# for i in range(index.start):
# temp.append(self[i])
# return temp
else:
if index < 0: # Condicion para recorrer la lista con indices negativos
# Coincide que el largo mas el indice negativo es su posicion
# de manera positiva!
index = len(self) + index
for i in range(index):
if nodo:
nodo = nodo.siguiente
else:
raise IndexError
if nodo == None:
raise IndexError
else:
return nodo.valor
def __setitem__(self, idx, valor):
Nodo_actual = self.cabeza
if idx >= len(self):
raise IndexError
for i in range(idx):
Nodo_actual = Nodo_actual.siguiente
Nodo_actual.valor = valor
def __gt__(self, other):
return self[1] > other[1]
def __eq__(self, other):
return self.cabeza.valor == other.cabeza.valor
def index(self, valor):
contador = 0
for i in self:
if i == valor:
return contador
contador += 1
def __siguiente__(self):
return self.cabeza.siguiente
def __contains__(self, valor):
for elemento in self:
if elemento == valor:
return True
return False
def append(self, valor):
if not self.cabeza:
self.cabeza = Nodo(valor)
self.cola = self.cabeza
else:
self.cola.siguiente = Nodo(valor)
self.cola = self.cola.siguiente
def clear(self):
self = ListaLigada()
def count(self, valor):
contador = 0
for elemento in self:
if elemento == valor:
contador += 1
return contado
def delete(self, valor):
actual = self.cabeza
anterior = None
encontrado = False
while actual and encontrado is False:
if actual.valor == valor:
encontrado = True
else:
anterior = actual
actual = actual.siguiente
if actual is None:
raise ValueError("valor not in list")
if anterior is None:
self.cabeza = actual.siguiente
else:
anterior.siguiente = actual.siguiente
class ColaPrioridades(ListaLigada):
def __init__(self, *args):
super().__init__(*args)
def crear_cola(self, Pais, paises_conectados, progreso_cura):
total = Pais.poblacion_viva + Pais.poblacion_infectada + Pais.poblacion_muerta
prioridad = Pais.poblacion_infectada / \
(Pais.poblacion_infectada + Pais.poblacion_viva)
if Pais.poblacion_infectada / total >= 0.5 or Pais.poblacion_muerta / total >= 0.25 and Pais.fronteras_abiertas:
self.insert(ListaLigada("Cerrar fronteras", promedio_fronteras(
Pais, paises_conectados) * prioridad)) # Para poder usar la funcion,hay que crear
# MUNDO!!
elif Pais.poblacion_infectada / total >= 0.8 or Pais.poblacion_muerta / total >= 0.2 and Pais.aeropuertos_abiertos:
self.insert(ListaLigada("Cerrar aeropuertos", 0.8 * prioridad))
elif Pais.poblacion_infectada / total < 0.8 and Pais.poblacion_infectada / total < 0.5 and not Pais.aeropuertos_abiertos and not Pais.fronteras_abiertas:
if progreso_cura != 1:
self.insert(ListaLigada("Abrir todo", 0.7 * prioridad))
else:
self.insert(ListaLigada("Abrir todo", 1 * prioridad))
if Pais.poblacion_infectada / total >= 1 / 3:
self.insert(ListaLigada("Entregar mascarillas", 0.5 * prioridad))
# Este retorna las primeras tres prioridades en la cola y se eliminan de
# si mismo
def primeros_tres(self):
if len(self) > 3:
temp1 = self
temp = ListaLigada(self[-1], self[-2], self[-3])
self.delete(self[-1])
self.delete(self[-1])
self.delete(self[-1])
return temp
else:
temp = ListaLigada()
for i in reversed(self):
temp.append(i)
self.clear()
return temp
# Este metodo inserta los valores ordenados en la cola de prioridades!, esto se pueden comparar gracias a un Override
# de __gt__ en ListaLigada(), el cual compara el segundo elemento de cada
# lista insertada (la prioridad) :D
def insert(self, valor):
actual = self.cabeza
if actual == None:
n = Nodo()
n.valor = valor
self.cabeza = n
return
if actual.valor > valor:
n = Nodo()
n.valor = valor
n.siguiente = actual
self.cabeza = n
return
while actual.siguiente != None:
if actual.siguiente.valor > valor:
break
actual = actual.siguiente
n = Nodo()
n.valor = valor
n.siguiente = actual.siguiente
actual.siguiente = n
return
def pop(self):
if len(self) > 0:
ultimo = self[-1]
return ultimo
else:
raise IndexError
def __repr__(self):
s = ""
for i in self:
s += "Accion: {},Prioridad: {}\n".format(i[0], i[1])
return s.rstrip()
|
781947d55ede62f31a47dc2a4c17cd7eef4007db | EduardoHenSil/testes_python3 | /iteraveis/itertools/accumulate.py | 650 | 4.28125 | 4 | #!/usr/bin/python3
# coding: utf-8
import itertools
import operator
summary = """
itertools.accumulate(it, [func])
Produz somas accumuladas; se func for especificada, entrega o resultado da sua aplicação
ao primeiro par de itens de it, em seguida ao primeiro resultado e o próximo item.
Diferente da função functools.reduce, accumulate gera os valores a cada resultado.
"""
print(summary)
sample = [5, 4, 2, 8, 7, 6, 3, 0, 9, 1]
print("sample =", sample)
print("itertools.accumulate(sample) -->", list(itertools.accumulate(sample)))
print("itertools.accumulate(sample, operator.mul) -->", list(itertools.accumulate(sample, operator.mul)))
|
eb8229ed52395f30d81fa3b7e0f36889fee37f65 | srvendrix/hangman | /triangle.py | 239 | 3.71875 | 4 | class Triangle():
def __init__(self, x, y):
self.teihen = x
self.height = y
def calculate_area(self):
return (self.teihen * self.height) / 2
a_triangle = Triangle(5, 8)
print(a_triangle.calculate_area())
|
9e49375a8250aefe77b9aeeb6a8093710a37f4e0 | shira19-meet/meet2017y1lab5 | /fun1.py | 190 | 3.75 | 4 |
def add_numbers(start, end):
c = 0
for number in range (start, end+1,2):
# print(number)
c = c+number
return(c)
answer1 = add_numbers(333 ,777)
print(answer1)
|
1aabb86c880a4bd196d00d4266b6df3533d748ad | adarshadrocks/pyhonActivities | /menubar.py | 2,152 | 3.5 | 4 | #!/usr/bin/python
import time
import os
import webbrowser
import urllib
option='''
press 1 : current date and time
press 2 : To create a file
press 3 : To create a directory
press 4 : To search on google
press 5 : logout your system
press 6 : Shutdown your os
press 7 : To check internet connection in your pc
press 8 : To login watsapp on browser
press 9 : To check all connected IP in your network
'''
print(option)
select = raw_input("kindly press atleat one")
if select == '1' :
time = time.ctime().split()
print "displaying current date&time" +time[3],time[1],time[2]
elif select == '2' :
path = "/home/adarsh/Desktop/"
filename=raw_input("enter the name of file")
os.system('touch ' +path+filename)
print "your file is created in the Desktop"
elif select == '3' :
path = "/home/adarsh/Desktop/"
dirname=raw_input("enter the name of directory")
os.system('mkdir ' +path+dirname)
print "your directory is created"
elif select == '4' :
print "searching on google"
msg = raw_input("type for search")
webbrowser.open_new_tab('https://www.google.com/search?q='+msg)
elif select == '5' :
print "turn off your application your system is going to be off"
time.sleep(2)
msg1 = "again giving you last chance"
os.system('echo '+msg1+' | festival --tts')
time.sleep(2)
os.system("pkill -KILL -u " + os.getlogin())
elif select == '6' :
print "turn off your application your system is going to be off"
time.sleep(2)
msg1 = "fr se bol rha hu last chance"
os.system('echo '+msg1+' | festival --tts')
time.sleep(2)
os.system('poweroff')
elif select == '7' :
print "checking internet connection in your lappi"
try :
urllib.urlopen('https://www.google.com')
print "connected"
except :
print "not connected"
elif select == '8' :
print "opening watsapp app on google"
time.sleep(2)
webbrowser.open_new_tab('https://www.watsapp.com')
elif select == '9' :
print "9"
else :
print "wrong option"
|
872311d701a810ead37b49cd9e37d62707fe6da9 | KR4705/algorithms | /palindrome_recursive.py | 241 | 3.71875 | 4 | # palindrome_recursive.py
from sys import argv
name , string = argv
def pal(arg):
if len(arg) == 1 or len(arg) == 0:
return True
elif arg[0] == arg[len(arg)-1]:
return pal(arg[1:len(arg)-1])
else: return False
print pal(string)
|
7a683f984c9fba0e0c3d2d53fa805e841d2d29dd | KR4705/algorithms | /routeFinder.py | 1,019 | 4.15625 | 4 | # need to implement a simple path finding game in python.
# import pprint
board = [[0]*7 for _ in range(7)]
def print_grid(grid):
for row in grid:
for e in row:
print e,
print
# print print_grid(board)
def set_goal(a,b):
board[a][b] = "g"
# set_goal(3,3)
# print print_grid(board)
def set_block(a,b):
board[a][b] = "b"
set_block(4,2)
set_block(2,2)
set_block(3,2)
set_block(5,2)
set_block(1,0)
set_block(1,2)
set_block(1,1)
print print_grid(board)
def fill(board,a,b):
if a<5 and b<5 and a>1 and b>1:
if not board[a-1][b] == "b" and board[a-1][b] == 0: board[a-1][b] = board[a][b] + 1
if not board[a][b+1] == "b" and board[a][b+1] == 0: board[a][b+1] = board[a][b] + 1
if not board[a+1][b] == "b" and board[a+1][b] == 0: board[a][b+1] = board[a][b] + 1
if not board[a][b-1] == "b" and board[a][b-1] == 0: board[a][b+1] = board[a][b] + 1
fill(board,a-1,b)
fill(board,a,b+1)
fill(board,a+1,b)
fill(board,a,b+1)
return
fill(board,3,3)
print_grid(board)
|
5f9534bfd81e358312cf779081cd7d1fd49bd224 | tied/DevArtifacts | /master/Challenges-master/Challenges-master/level-1/fizzBuzz/fizz_buzz.py | 757 | 3.75 | 4 | import sys
def main(input_file):
with open(input_file, 'r') as data:
for line in data:
# convert str list to int and unpack to variables
x, y, n = map(int, line.split())
print fizzbuzz(x, y, n)
def fizzbuzz(x, y, n):
result = []
for i in xrange(1, n + 1):
if i % x == 0 and i % y == 0:
result.append('FB')
elif i % x == 0:
result.append('F')
elif i % y == 0:
result.append('B')
else:
result.append(str(i))
return " ".join(result)
if __name__ == "__main__":
# first argument must be a text file
try:
main(sys.argv[1])
except Exception:
print 'First argument must be a text file!' |
732af18e55deacb0c0d41224943a551a6831e2de | tied/DevArtifacts | /master/tic-tac-ai-master/tic-tac-ai-master/game.py | 8,882 | 4.125 | 4 | import random
class Player:
"""
Interface class for a player.
"""
printing = False # Whether the player will print its status updates
label = '?' # Will be set to either 'X' or 'O'
scores = [] # A list containing the score
def __init__(self, printing=False):
self.printing = printing
self.scores = []
def make_action(self, my_tiles, opponent_tiles, free_tiles):
"""
Decide which tile (integer 0 (left-top) up to 8 (bottom-right)) to use given the current game state.
:param my_tiles: A list of tiles (integers) owned by you.
:param opponent_tiles: A list of tiles (integers) owned by your opponent.
:param free_tiles: A list of tiles (integers) which are not owned by anyone.
:return: The tile (integer) to play.
"""
raise Exception('Not implemented yet!')
def handle_invalid_move(self, tile, my_tiles, opponent_tiles, free_tiles):
"""
This method is called when the last move was invalid. You can implemented a negative feedback loop here.
:param tile: The tile that was invalid.
:param my_tiles: A list of tiles (integers) owned by you.
:param opponent_tiles: A list of tiles (integers) owned by your opponent.
:param free_tiles: A list of tiles (integers) which are not owned by anyone.
"""
raise Exception('Invalid move %d!' % tile)
def handle_game_end(self, status):
"""
This method is called when the game reached an end.
:param status 0 for tie, 1 for win, 2 for loose
"""
if self.printing:
if status == 0:
print('Player [%s]: It is a tie!' % self.label)
elif status == 1:
print('Player [%s]: I win the game!' % self.label)
else:
print('Player [%s]: I just lost the game!' % self.label)
self.scores.append(status)
def __str__(self):
recent_history = self.scores[-100:]
num_winner = sum([1 if status == 1 else 0 for status in recent_history])
num_loser = sum([1 if status == 2 else 0 for status in recent_history])
num_ties = sum([1 if status == 0 else 0 for status in recent_history])
if num_winner + num_loser == 0:
return 'Player [%s]: Only ties yet!' % self.label
return 'Player [%s]: Winning percentage:\t%.1f%%' % (
self.label, 100. * float(num_winner + num_ties) / float(num_winner + num_loser + num_ties))
class RandomPlayer(Player):
"""
Just playing a random move.
"""
def make_action(self, my_tiles, opponent_tiles, free_tiles):
num_free_tiles = len(free_tiles)
choice = int(random.random() * num_free_tiles)
return free_tiles[choice]
class HumanPlayer(Player):
"""
Human input.
"""
def make_action(self, my_tiles, opponent_tiles, free_tiles):
tile = None
while tile not in free_tiles:
tile = int(input("Choose a number to continue...")) - 1
return tile
def handle_game_end(self, status):
if status == 0:
print('It is a tie!')
elif status == 1:
print('You win!')
else:
print('You lose!')
class SmartPlayer(Player):
"""
A player which blocks all known wins.
"""
def make_action(self, my_tiles, opponent_tiles, free_tiles):
for combo in Game.winning_combinations:
if combo[0] in opponent_tiles and combo[1] in opponent_tiles and combo[2] in free_tiles:
return combo[2]
if combo[1] in opponent_tiles and combo[2] in opponent_tiles and combo[0] in free_tiles:
return combo[0]
if combo[2] in opponent_tiles and combo[0] in opponent_tiles and combo[1] in free_tiles:
return combo[1]
if combo[0] in my_tiles and combo[1] in my_tiles and combo[2] in free_tiles:
return combo[2]
if combo[1] in my_tiles and combo[2] in my_tiles and combo[0] in free_tiles:
return combo[0]
if combo[2] in my_tiles and combo[0] in my_tiles and combo[1] in free_tiles:
return combo[1]
return random.choice(free_tiles)
class Game:
"""
This class holds and maintains the game state.
"""
# The current player (0 for self.players[0], 1 for self.players[1])
current_player = -1
# A list consisting of two players
players = None
# The tiles (0 (left-top), 1, ..., 8 (bottom-right)) where -1 are the free tiles, 0 are the tiles owned by
# self.players[0] and 1 are the tiles owned by self.players[1]
tiles = None
# A list of all winning combinations
winning_combinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
def __init__(self, players, labels=[], starter=None):
"""
Initialize the game state.
:param players: A list consisting of players.
"""
self.tiles = [-1] * 9
# Copy the players
self.players = players
# Do a coinflip to decide on the initial player
if starter is None:
self.current_player = 0 if random.random() > 0.5 else 1
else:
self.current_player = starter
# Set the labels
if len(labels) == 0:
self.players[0].label = 'X'
self.players[1].label = 'O'
else:
self.players[0].label = labels[0]
self.players[1].label = labels[1]
def play(self):
"""
Play one move and return True if the game is not completed yet.
:return: True if the game is not completed, False otherwise.
"""
free_tiles = [tile for tile, owner in enumerate(self.tiles) if owner == -1]
my_tiles = [tile for tile, owner in enumerate(self.tiles) if owner != -1 and owner == self.current_player]
opponent_tiles = [tile for tile, owner in enumerate(self.tiles) if owner != -1 and owner != self.current_player]
player = self.players[self.current_player]
opponent = self.players[1 - self.current_player]
action = player.make_action(my_tiles, opponent_tiles, free_tiles)
if action not in free_tiles:
player.handle_invalid_move(action, my_tiles, opponent_tiles, free_tiles)
return False
# Update the current state
self.tiles[action] = self.current_player
my_tiles.append(action)
free_tiles = [tile for tile in free_tiles if tile != action]
# Check whether the game is done
game_won = self.check_win(my_tiles)
if game_won:
player.handle_game_end(1)
opponent.handle_game_end(2)
return False
else:
# Check a tie
if len(free_tiles) == 0:
player.handle_game_end(0)
opponent.handle_game_end(0)
return False
# Update the current player
self.current_player = (self.current_player + 1) % 2
return True
@staticmethod
def check_win(current_player_tiles):
"""
Check whether a set of tiles contains a winning combination.
:param current_player_tiles: A list of tiles (0 up to and including 8) to check.
:return: True if the list contains a winning combination, False otherwise.
"""
for combination in Game.winning_combinations:
game_won = True
for number in combination:
if number not in current_player_tiles:
game_won = False
break
if game_won:
return True
return False
def __str__(self):
"""
Build the string representation of the current game state.
:return: The string representation of the current game state.
"""
def create_line(boundary_symbol='+', inner_boundary_symbol='-', inner_symbol='-', texts=[]):
output = ''
output += boundary_symbol
for text_index in range(3):
output += inner_symbol
output += texts[text_index] if len(texts) > 0 else inner_symbol * 3
output += inner_symbol
if text_index < 2:
output += inner_boundary_symbol
output += boundary_symbol + '\n'
return output
output = ''
for row in range(3):
output += create_line()
tiles = [' %s ' % self.players[tile].label if tile != -1 else '[%d]' % (row * 3 + index + 1) for index, tile
in
enumerate(self.tiles[row * 3:row * 3 + 3])]
output += create_line('|', '|', ' ', tiles)
output += create_line()
return output
|
5ee79511cb6aad16dbafe72606cbd2b3ad8f89c2 | tied/DevArtifacts | /master/python-snippets-master/python-snippets-master/excel-xlrd.py | 811 | 4 | 4 | # Demonstrates basic xlrd functions for working with Excel files
# (Excel 97-2003)
import xlrd
wb = xlrd.open_workbook('excel-xlrd-sample.xls')
# Print the sheet names
print wb.sheet_names()
# Get the first sheet either by index or by name
sh = wb.sheet_by_index(0)
# Iterate through rows, returning each as a list that you can index:
for rownum in range(sh.nrows):
print sh.row_values(rownum)
# If you just want the first column:
first_column = sh.col_values(0)
print first_column
# Index individual cells:
cell_c4 = sh.cell(3, 2).value
# Or you can use:
#cell_c4 = sh.cell(rowx=3, colx=2).value
print cell_c4
# Let's say you want the same cell from x identical sheets in a workbook:
x = 2
while x >= 0:
sh = wb.sheet_by_index(x)
cell_x = sh.cell(2, 3).value
print cell_x
x = x - 1
|
80e1db6dd3af955ea83c04f7bca48ab0f93709a9 | tied/DevArtifacts | /master/python-snippets-master/python-snippets-master/facebook-api-sqlite.py | 1,422 | 3.5625 | 4 | # Fetch Facebook page metrics via Social Graph API into a SQLite DB
# Grabs the number of likes and "talking about" numbers
import requests
import sqlite3
import os
from datetime import datetime
# These are the accounts for which you will fetch data
names_list = [
'fallingskies',
'usatoday'
]
# API base URL
base_url = 'https://graph.facebook.com/'
# Function to add row to accounts table
def insert_db(handle, likes, talking):
conn = sqlite3.connect('social_data.db')
cur = conn.cursor()
cur.execute('''
INSERT INTO fbaccounts VALUES (?,?,?,?);
''', (datetime.now(), handle, likes, talking))
conn.commit()
conn.close()
# Create the database if it doesn't exist
if not os.path.exists('social_data.db'):
conn = sqlite3.connect('social_data.db')
conn.close()
else:
pass
# Create the table if it's not in the db
conn = sqlite3.connect('social_data.db')
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS fbaccounts
(FetchDate Date, Handle Text, Likes Integer, Talking Integer)
''')
conn.commit()
conn.close()
# Iterate over handles and hit the API with each
for user in names_list:
url = base_url + user
print 'Fetching ' + user
response = requests.get(url)
profile = response.json()
handle = profile['name']
likes = profile['likes']
talking = profile['talking_about_count']
insert_db(handle, likes, talking)
|
890e0daec877b2e427ade34f86cda7f57177d8d5 | isaacroldan/tuentiChallenge4 | /C01/C1.py | 715 | 3.53125 | 4 | ##########################################
#
# #TuentiChallenge4 (2014).
# Challenge 1 (https://contest.tuenti.net/Challenges?id=1)
# Isaac Roldan (@saky)
#
##########################################
import mmap
cases = int(raw_input(""))
for case in range(1,cases+1):
try:
data = raw_input("")
with open("students", "r+b") as f:
mm = mmap.mmap(f.fileno(),0)
found = ""
for line in f.readlines():
student = line.split(",",1)
if student[1] == data+"\n":
if found == "":
found = student[0]
else:
found = found + "," + student[0]
if found != "":
print "Case #" + str(case) + ": " + found
else:
print "Case #" + str(case) + ": NONE"
except EOFError:
break
|
c629fcd473e694c884abc1fb68e7fde47b97f73b | willdoliver/BD1 | /01 - Modelos de dados e XML/ExercicioHerois.py | 5,325 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
#Usando ElementTree para trabalhar com arquivos XML
from xml.etree import ElementTree as et
conteudo = et.parse('campeonato.xml')
lista_equipes = conteudo.findall("equipe")
for equi in lista_equipes:
print ("Nome da equipe: ", equi.find("descricao").text)
'''
#!/usr/bin/python
#Usando xml.dom.minidom para trabalhar com arquivos XML
from xml.dom.minidom import parse
import xml.dom.minidom
import csv
# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse("marvel_simplificado.xml")
universe = DOMTree.documentElement
if universe.hasAttribute("name"):
print ("Root element : %s" % universe.getAttribute("name"))
# Get all the heroes in the universe
heroes = universe.getElementsByTagName("hero")
fileHerois = open('herois.csv', 'w')
herois_bad = open('herois_bad.csv', 'w')
herois_good = open('herois_good.csv', 'w')
#DELIMITER: usar ";" para separar cada celular LINETERMINATOR: usar para pular apenas uma linha
writerFile = csv.writer(fileHerois, delimiter = ";" ,lineterminator = '\r', quoting =csv.QUOTE_MINIMAL)
badFile = csv.writer(herois_bad, delimiter = ';', lineterminator = '\r', quoting = csv.QUOTE_MINIMAL)
goodFile = csv.writer(herois_good, delimiter = ';', lineterminator = '\r', quoting = csv.QUOTE_MINIMAL)
#cabeçalho das 3 planilhas
writerFile.writerow(["Id", "Nome", 'Popularidade', 'Time', 'Genero', 'Altura', 'Peso', 'Localizacao', 'Inteligencia', 'Forca', 'Velocidade',
'Durabilidade', 'Energia', 'Skils' ])
badFile.writerow(["Id", "Nome", 'Popularidade', 'Time', 'Genero', 'Altura', 'Peso', 'Localizacao', 'Inteligencia', 'Forca', 'Velocidade',
'Durabilidade', 'Energia', 'Skils' ])
goodFile.writerow(["Id", "Nome", 'Popularidade', 'Time', 'Genero', 'Altura', 'Peso', 'Localizacao', 'Inteligencia', 'Forca', 'Velocidade',
'Durabilidade', 'Energia', 'Skils' ])
cont = 0
contBad = 0
contGood = 0
contpeso = 0
for hero in heroes:
id = hero.getAttribute('id')
nome = hero.getElementsByTagName('name')[0]
popularidade = hero.getElementsByTagName('popularity')[0]
time = hero.getElementsByTagName('alignment')[0]
genero = hero.getElementsByTagName('gender')[0]
altura = hero.getElementsByTagName('height_m')[0]
peso = hero.getElementsByTagName('weight_kg')[0]
localizacao = hero.getElementsByTagName('hometown')[0]
inteligencia = hero.getElementsByTagName('intelligence')[0]
forca = hero.getElementsByTagName('strength')[0]
velocidade = hero.getElementsByTagName('speed')[0]
durabilidade = hero.getElementsByTagName('durability')[0]
energia = hero.getElementsByTagName('energy_Projection')[0]
Skils = hero.getElementsByTagName('fighting_Skills')[0]
cont +=1
contpeso += int (peso.childNodes[0].data)
#writerFile.writerow(["%s %s %s %s %s %s %s %s %s %s %s %s %s %s" % name.childNodes[0].data], )
writerFile.writerow((id, nome.childNodes[0].data, popularidade.childNodes[0].data, time.childNodes[0].data, genero.childNodes[0].data, altura.childNodes[0].data, peso.childNodes[0].data, localizacao.childNodes[0].data, inteligencia.childNodes[0].data, forca.childNodes[0].data, velocidade.childNodes[0].data, durabilidade.childNodes[0].data, energia.childNodes[0].data, Skils.childNodes[0].data))
if time.childNodes[0].data == 'Bad':
contBad = contBad+1;
badFile.writerow((id, nome.childNodes[0].data, popularidade.childNodes[0].data, time.childNodes[0].data, genero.childNodes[0].data, altura.childNodes[0].data, peso.childNodes[0].data, localizacao.childNodes[0].data, inteligencia.childNodes[0].data, forca.childNodes[0].data, velocidade.childNodes[0].data, durabilidade.childNodes[0].data, energia.childNodes[0].data, Skils.childNodes[0].data))
if time.childNodes[0].data == 'Good':
contGood = contGood+1;
goodFile.writerow((id, nome.childNodes[0].data, popularidade.childNodes[0].data, time.childNodes[0].data, genero.childNodes[0].data, altura.childNodes[0].data, peso.childNodes[0].data, localizacao.childNodes[0].data, inteligencia.childNodes[0].data, forca.childNodes[0].data, velocidade.childNodes[0].data, durabilidade.childNodes[0].data, energia.childNodes[0].data, Skils.childNodes[0].data))
if nome.childNodes[0].data == "Hulk":
imc = int (peso.childNodes[0].data) / int (altura.childNodes[0].data)**2
fileHerois.close()
# Print detail of each hero.
for hero in heroes:
# if hero.hasAttribute("id"):
# print ("Id: %s" % hero.getAttribute("id"))
name = hero.getElementsByTagName('name')[0]
print( "Id: {0} - {1}".format(hero.getAttribute("id"), name.childNodes[0].data))
#Duas formas de printar mais de um uma string na mesma linha: usando .format ou colocando entre "()"
print( "\nBom: %s - Ruim: %s" % (contGood, contBad) )
#5. Calcule, a partir dos dados do arquivo, e imprima na tela a proporção de heróis bons/maus.
print("Proporção de Herois bons: %.1f%%" % ((contGood*100)/cont))
print("Proporção de Herois maus: %.1f%%" % ((contBad*100)/cont))
#6. Calcule, a partir dos dados do arquivo, e imprima na tela a média de peso dos heróis
print("Peso medio: %.1f" % (contpeso/cont))
#7. Calcule, a partir dos dados do arquivo, e imprima na tela o "Índice de massa corporal” do Hulk
print("O IMC do Hulk é: ", imc ) |
39a97c3366248770fba81735c9c4e231b34077b9 | kuwarkapur/Robot-Automation-using-ROS_2021 | /week 1/assignement.py | 2,292 | 4.3125 | 4 | """Week I Assignment
Simulate the trajectory of a robot approximated using a unicycle model given the
following start states, dt, velocity commands and timesteps
State = (x, y, theta);
Velocity = (v, w)
1. Start=(0, 0, 0); dt=0.1; vel=(1, 0.5); timesteps: 25
2. Start=(0, 0, 1.57); dt=0.2; vel=(0.5, 1); timesteps: 10
3. Start(0, 0, 0.77); dt=0.05; vel=(5, 4); timestep: 50
Upload the completed python file and the figures of the three sub parts in classroom
"""
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
class Unicycle:
def __init__(self, x: float, y: float, theta: float, dt: float):
self.x = x
self.y = y
self.theta = theta
self.dt = dt
# Store the points of the trajectory to plot
self.x_points = [self.x]
self.y_points = [self.y]
def step(self, v: float, w: float, n:int):
for i in range(n):
self.theta += w *(self.dt)
self.x += v*np.cos(self.theta)
self.y += v*np.sin(self.theta)
self.x_points.append(self.x)
self.y_points.append(self.y)
return self.x, self.y, self.theta
def plot(self, v: float, w: float,i:int):
plt.title(f"Unicycle Model: {v}, {w}")
plt.title(f"kuwar's graphs {i}")
plt.xlabel("x-Coordinates")
plt.ylabel("y-Coordinates")
plt.plot(self.x_points, self.y_points, color="red", alpha=0.75)
plt.grid()
plt.show()
if __name__ == "__main__":
print("Unicycle Model Assignment")
# make an object of the robot and plot various trajectories
point = [{'x':0,'y': 0,'theta': 0,'dt': 0.1, 'v':1,'w': 0.5,'step': 25},
{'x':0,'y': 0,'theta': 1.57,'dt' :0.2,'v': 0.5, 'w':1,'step': 10},
{'x':0,'y': 0,'theta': 0.77, 'dt':0.05, 'v': 5,'w': 4, 'step': 50},
]
for i in range(len(point)):
x = point[i]['x']
y = point[i]['y']
theta = point[i]['theta']
dt = point[i]['dt']
v = point[i]['v']
w = point[i]['w']
n = point[i]['step']
model=Unicycle(x, y, theta, dt)
position =model.step(v, w, n)
x, y, theta = position
model.plot(v, w, i+1) |
1dec745e6821aaf844d7af3d983f05bfaa0704f7 | NadavOrzech/DL_project | /source/proj-311549455_312168354/src/cs236781/train_results.py | 1,176 | 3.5 | 4 | from typing import NamedTuple, List
class BatchResult(NamedTuple):
"""
Represents the result of training for a single batch: the loss
and number of correct classifications.
"""
loss: float
num_correct: int
class EpochResult(NamedTuple):
"""
Represents the result of training for a single epoch: the loss per batch
and accuracy on the dataset (train or test).
"""
losses: List[float]
accuracy: float
pos_accuracy: float
neg_accuracy: float
class FitResult(NamedTuple):
"""
Represents the result of fitting a model for multiple epochs given a
training and test (or validation) set.
The losses are for each batch and the accuracies are per epoch.
"""
num_epochs: int
train_loss: List[float]
train_acc: List[float]
test_loss: List[float]
test_acc: List[float]
train_pos_acc: List[float]
train_neg_acc: List[float]
test_pos_acc: List[float]
test_neg_acc: List[float]
class EpochHeatMap(NamedTuple):
"""
Represents epoch data for generating Attention Map graph
"""
y_vals: List[int]
attention_map: List[float]
indices_list: List[int] |
b1b91d725b1a9664e9d61be5ebdad1fd8fd85869 | amsrafid/asl-simple-py-accounting | /controller/account.py | 2,373 | 3.640625 | 4 | from library.file import File
from model.user import User
from model.Models import Models
"""
Account Management
"""
class Account(Models):
table = "table/accountTable"
def __init__(self):
super().__init__(self.table, 'Account')
@staticmethod
def all():
return File.read('table/accountTable')
"""
Create new Account
"""
@staticmethod
def create(user):
account = File.read('table/accountTable')
if( (user.getNumber()) in account):
print("\nUser is already exists\n")
return False
else:
account[user.getNumber()] = {
'number' : user.getNumber(),
'name' : user.getName(),
'age' : user.getAge(),
'phone' : user.getPhone(),
'balance' : user.getBalance()
}
File.write('table/accountTable', account)
print("\nNew Account has been created successfully.\n")
return True
# Edit existing account
@staticmethod
def edit(user):
account = File.read('table/accountTable')
if( user.getNumber() in account):
if(user.getName()):
account[user.getNumber()]['name'] = user.getName()
if(user.getAge()):
account[user.getNumber()]['age'] = user.getAge()
if(user.getPhone()):
account[user.getNumber()]['phone'] = user.getPhone()
if(user.getBalance()):
account[user.getNumber()]['balance'] = user.getBalance()
File.write('table/accountTable', account)
print("\nAccount has been updated successfully.\n")
return True
else:
print("\nAccount is not exists.\n")
return False
# Show a single Account
@staticmethod
def show():
accNumber = input("Enter account Number: ")
account = File.read('table/accountTable')
if(accNumber in account):
print("\n")
Account.viewSingle(account[accNumber])
else:
print("\nAccount is not found\n")
"""
Delete an existing account
"""
@staticmethod
def delete(number):
account = File.read('table/accountTable')
if(number in account):
del account[number]
File.write('table/accountTable', account)
print('Account number ' + number + " is deleted successfully.")
return True
else:
print("Account number is not registred.")
return False
# View Single account details
@staticmethod
def viewSingle(acc):
user = User()
for fields in range(len(user.accountFields)):
print("Account " + user.accountFields[fields] + ": " + acc[user.accountFields[fields]])
print("\n")
|
4a5cbe1ed1209b768f36b1bc65e7cf4ee59336a2 | amsrafid/asl-simple-py-accounting | /library/file.py | 552 | 3.578125 | 4 | import json
# File input Output
class File:
# Read a JSON file
# @param string dir FIle directory with file name
# @return dictionary
@staticmethod
def read(dir):
with open('./' + dir + '.json', 'r') as file:
return json.load(file)
# Write a JSON Data into a Json file
# @param string dir FIle directory with file name
# @param dictinary data Dictionary data to write into dir file
# @return dictionary
@staticmethod
def write(dir, data):
with open('./' + dir + '.json', 'w') as file:
json.dump(data, file)
|
a610a07aecfccd0201e9198b1d445066ddd01e70 | MadmanSilver/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 1,932 | 3.515625 | 4 | #!/usr/bin/python3
""" Contains the Base class. """
import json
class Base():
""" I'm the base for everything! """
__nd_objects = 0
def __init__(self, id=None):
""" Initializes the attributes. """
if id is not None:
self.id = id
else:
Base.__nd_objects += 1
self.id = Base.__nd_objects
@staticmethod
def to_json_string(list_dictionaries):
""" Returns the JSON string representation of list_dictionaries. """
if list_dictionaries is None:
return "[]"
return json.dumps(list_dictionaries)
@classmethod
def save_to_file(cls, list_objs):
""" Writes the JSON string representation of list_bjs to a file. """
if list_objs and len(list_objs) > 0:
objs = list_objs.copy()
for i in range(len(objs)):
objs[i] = objs[i].to_dictionary()
else:
objs = []
with open("{}.json".format(cls.__name__), 'w') as f:
f.write(cls.to_json_string(objs))
@staticmethod
def from_json_string(json_string):
""" Returns the list of the JSON string representation. """
if not json_string or len(json_string) < 1:
return []
return json.loads(json_string)
@classmethod
def create(cls, **dictionary):
""" Returns an instance with all attributes already set. """
if cls.__name__ == "Square":
new = cls(1)
else:
new = cls(1, 1)
new.update(**dictionary)
return new
@classmethod
def load_from_file(cls):
""" Returns a list of instances. """
try:
with open("{}.json".format(cls.__name__), 'r') as f:
l = cls.from_json_string(f.read())
for i in range(len(l)):
l[i] = cls.create(**l[i])
except:
return []
return l
|
5e6a0b129f5077b6db4e0583ce83fca398353db8 | MadmanSilver/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 488 | 4.09375 | 4 | #!/usr/bin/python3
""" Contains the append_after function. """
def append_after(filename="", search_string="", new_string=""):
""" Inserts line of text in file after lines containing new_string. """
with open(filename, "r+") as f:
contents = f.readlines()
for line in range(len(contents)):
if search_string in contents[line]:
contents.insert(line + 1, new_string)
f.seek(0)
f.truncate()
f.writelines(contents)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.