blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
81cd4dcee9ef0ceb25c304dbc3f4bd47bec13ffb | DayGitH/Python-Challenges | /DailyProgrammer/DP20150202A.py | 5,356 | 3.71875 | 4 | """
[2015-02-02] Challenge #200 [Easy] Flood-Fill
https://www.reddit.com/r/dailyprogrammer/comments/2ug3hx/20150202_challenge_200_easy_floodfill/
# [](#EasyIcon) _(Easy)_: Flood-Fill
Flood-fill is a tool used in essentially any image editing program that's worth its salt. It allows you to fill in any
contigious region of colour with another colour, like flooding a depression in a board with paint. For example, take
[this beautiful image](http://i.imgur.com/NlCcrKj.png). If I was to flood-fill the colour orange into [this region of
the image](http://i.imgur.com/yCavN08.png), then that region would be [turned completely
orange](http://i.imgur.com/u6626BA.png).
Today, you're going to implement an algorithm to perform a flood-fill on a text ASCII-style image.
# Input and Output Description
## Challenge Input
You will accept two numbers, **w** and **h**, separated by a space. These are to be the width and height of the image
in characters, with the top-left being (0, 0). You will then accept a grid of ASCII characters of size **w**\***h**.
Finally you will accept two more numbers, **x** and **y**, and a character **c**. **x** and **y** are the co-ordinates
on the image where the flood fill should be done, and **c** is the character that will be filled.
Pixels are defined as contigious (touching) when they share at least one edge (pixels that only touch at corners aren't
contigious).
For example:
37 22
.....................................
...#######################...........
...#.....................#...........
...#.....................#...........
...#.....................#...........
...#.....................#...........
...#.....................#...........
...#.....................#######.....
...###.................##......#.....
...#..##.............##........#.....
...#....##.........##..........#.....
...#......##.....##............#.....
...#........#####..............#.....
...#........#..................#.....
...#.......##..................#.....
...#.....##....................#.....
...#...##......................#.....
...#############################.....
.....................................
.....................................
.....................................
.....................................
8 12 @
## Challenge Output
Output the image given, after the specified flood-fill has taken place.
.....................................
...#######################...........
...#.....................#...........
...#.....................#...........
...#.....................#...........
...#.....................#...........
...#.....................#...........
...#.....................#######.....
...###.................##......#.....
...#@@##.............##........#.....
...#@@@@##.........##..........#.....
...#@@@@@@##.....##............#.....
...#@@@@@@@@#####..............#.....
...#@@@@@@@@#..................#.....
...#@@@@@@@##..................#.....
...#@@@@@##....................#.....
...#@@@##......................#.....
...#############################.....
.....................................
.....................................
.....................................
.....................................
# Sample Inputs and Outputs
## Input
16 15
----------------
-++++++++++++++-
-+------------+-
-++++++++++++-+-
-+------------+-
-+-++++++++++++-
-+------------+-
-++++++++++++-+-
-+------------+-
-+-++++++++++++-
-+------------+-
-++++++++++++++-
-+------------+-
-++++++++++++++-
----------------
2 2 @
## Output
----------------
-++++++++++++++-
-+@@@@@@@@@@@@+-
-++++++++++++@+-
-+@@@@@@@@@@@@+-
-+@++++++++++++-
-+@@@@@@@@@@@@+-
-++++++++++++@+-
-+@@@@@@@@@@@@+-
-+@++++++++++++-
-+@@@@@@@@@@@@+-
-++++++++++++++-
-+------------+-
-++++++++++++++-
----------------
## Input
9 9
aaaaaaaaa
aaadefaaa
abcdafgha
abcdafgha
abcdafgha
abcdafgha
aacdafgaa
aaadafaaa
aaaaaaaaa
8 3 ,
## Output
,,,,,,,,,
,,,def,,,
,bcd,fgh,
,bcd,fgh,
,bcd,fgh,
,bcd,fgh,
,,cd,fg,,
,,,d,f,,,
,,,,,,,,,
# Extension (Easy/Intermediate)
Extend your program so that the image 'wraps' around from the bottom to the top, and from the left to the right (and
vice versa). This makes it so that the top and bottom, and left and right edges of the image are touching (like the
surface map of a torus).
## Input
9 9
\/\/\/\.\
/./..././
\.\.\.\.\
/.../.../
\/\/\/\/\
/.../.../
\.\.\.\.\
/./..././
\/\/\/\.\
1 7 #
## Output
\/\/\/\#\
/#/###/#/
\#\#\#\#\
/###/###/
\/\/\/\/\
/###/###/
\#\#\#\#\
/#/###/#/
\/\/\/\#\
# Further Reading
If you need a starting point with recursion, here are some reading resources.
* [Recursive Algorithms](http://www2.its.strath.ac.uk/courses/c/subsection3_9_5.html)
* [Recursive function calls](http://www.cs.cmu.edu/~rwh/introsml/core/recfns.htm)
Consider using list-like data structures in your solution, too.
# Addendum
200! :)
"""
def main():
pass
if __name__ == "__main__":
main()
|
1b32a55dc8a8882f2181e314981c9edb2e42a5f3 | DayGitH/Python-Challenges | /DailyProgrammer/DP20170825C.py | 1,680 | 4.0625 | 4 | """
[2017-08-25] Challenge #328 [Hard] Subset Sum Automata
https://www.reddit.com/r/dailyprogrammer/comments/6vyihu/20170825_challenge_328_hard_subset_sum_automata/
# Description
Earlier this year we did the [subset
sum](https://www.reddit.com/r/dailyprogrammer/comments/68oda5/20170501_challenge_313_easy_subset_sum/) problem wherein
given a sequence of integers, can you find any subset that sums to 0. Today, inspired by [this
post](https://thquinn.github.io/projects/automaton.html) let's play subset sum automata. It marries the subset sum
problem with [Conway's Game of
Life](https://www.reddit.com/r/dailyprogrammer/comments/271xyp/622014_challenge_165_easy_ascii_game_of_life/).
You begin with a board full of random integers in each cell. Cells will increment or decrement based on a simple
application of the subset sum problem: if any subset of the 8 neighboring cells can sum to the target value, you
increment the cell's sum by some value; if not, you decrement the cell by that value. Automata are defined with three
integers `x/y/z`, where `x` is the target value, `y` is the reward value, and `z` is the penalty value.
Your challenge today is to implement the subset automata:
- Create a 2 dimensional board starting with random numbers
- Color the board based on the value of the cell (I suggest some sort of rainbow effect if you can)
- Parse the definition as described above
- Increment or decrement the cell according to the rules described above
- Redraw the board at each iteration
You'll probably want to explore various definitions and see what sorts of interesting patterns emerge.
"""
def main():
pass
if __name__ == "__main__":
main()
|
db322807d137276219ecaab479af539fe4088cb5 | DayGitH/Python-Challenges | /DailyProgrammer/DP20170619A.py | 1,147 | 4.125 | 4 | """
[2017-06-19] Challenge #320 [Easy] Spiral Ascension
https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/
# Description
The user enters a number. Make a spiral that begins with 1 and starts from the top left, going towards the right, and
ends with the square of that number.
# Input description
Let the user enter a number.
# Output description
Note the proper spacing in the below example. You'll need to know the number of digits in the biggest number.
You may go for a CLI version or GUI version.
# Challenge Input
5
4
# Challenge Output
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
# Bonus
As a bonus, the code could take a parameter and make a clockwise or counter-clockwise spiral.
# Credit
This challenge was suggested by /u/MasterAgent47 (with a bonus suggested by /u/JakDrako), many thanks to them both. If
you would like, submit to /r/dailyprogrammer_ideas if you have any challenge ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
|
843cf451a8db485aae96a11dd02ecadb8e890d25 | DayGitH/Python-Challenges | /DailyProgrammer/DP20150102.py | 1,602 | 3.8125 | 4 | """
[2015-01-02] Challenge #195 [All] 2015 Prep Work
https://www.reddit.com/r/dailyprogrammer/comments/2r4wal/20150102_challenge_195_all_2015_prep_work/
#Description:
As we enter a new year it is a good time to get organized and be ready. One thing I have noticed as you use this
subreddit and finish challenges you repeat lots of code in solutions. This is true in the area of reading in data.
One thing I have done is develop some standard code I use in reading and parsing data.
For today's challenge you will be doing some prep work for yourself.
#Tool Development
Develop a tool or several tools you can use in the coming year for completing challenges. The tool is up to you. It can
be anything that you find you repeat in your code.
An example will be shown below that I use. But some basic ideas
* Read input from user
* Input from a file
* Output to user
* Output to a file
Do not limit yourself to these. Look at your previous code and find the pieces of code you repeat a lot and develop
your own library for handling that part of your challenges. Having this for your use will make solutions easier to
develop as you already have that code done.
#Example:
I tend to do a lot of work in C/objective C -- so I have this code I use a lot for getting input from the user and
parsing it. It can be further developed and added on by me which I will.
(https://github.com/coderd00d/standard-objects)
#Solutions:
Can be your code/link to your github/posting of it -- Also can just be ideas of tools you or others can develop.
"""
def main():
pass
if __name__ == "__main__":
main()
|
35ca56b2002c47e738ea6efedc666552b9243b45 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140430.py | 3,670 | 3.671875 | 4 | """
[4/30/2014] Challenge #160 Intermediate Part 2 - Damage Control
https://www.reddit.com/r/dailyprogrammer/comments/24da3f/4302014_challenge_160_intermediate_part_2_damage/
[Part 1](http://www.reddit.com/r/dailyprogrammer/comments/236va2/4162014_challenge_158_intermediate_part_1_the/)
#Introduction
The new building techniques are a massive success, and soon it is adopted all across the far future society. However,
suddenly a great swarm of high-tech termites are predicted to strike - and worse, due to a bug in /u/1337C0D3R's code,
the design of the buildings are shoddy and are prone to being destroyed easily. If the buildings are destroyed by the
army of termites this could lead to a crisis.
The slightly incompetent government of the future has realized that it is incumbent for them to act. They can provide
you with a number of Reinforcement Kits 3000tm that when placed on a building, prevents the building from being
destroyed. However, the Reinforcement Kit 3000tm is expensive to produce, so you decide to design an algorithm to use
the least number of kits, and save the most money.
Description
The threatened buildings are placed in a straight line, numbered from 1 to N. Each building shares a wall with the
buildings next to them - the adjacent buildings are known as 'neighbours'. This is an example of how the buildings
would be set up for N = 12:
----------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
----------------------------------------------------
Each day the termites will start at one building and completely, irreversibly destroy it. After having destroyed the
building, the termites will then spread to, but not destroy yet, all buildings that can be reached from the building
that they started at. They cannot pass through buildings that are already destroyed. In other words, the termites cover
all the area of a flood-fill from the starting building, with destroyed buildings as the boundary.
The termites will destroy the buildings that they have spread to unless a Reinforcement Kittm is placed on the
building. After the termites have spread fully, you may begin placing kits. A Reinforcement Kittm will kill all
termites in the building it is placed in. However, they only have an effect for one day; if on the next day the
building again has termites another Reinforcement Kit must be used.
Given a list of P buildings that will be destroyed in P days, find the minimum number of Reinforcement Kits required,
given that the buildings may be destroyed in any order. (The government has also given you Termite Bait which lets you
choose the order in which the buildings in the list are destroyed).
#Formal Inputs and Outputs
Input Description
Input will be given on STDIN, or read from a file input.txt located in the working directory of the operating system.
There will be exactly 2 lines of input. The first line contains two integers that are space separated, N and P. N is
the number of buildings in the line. P is the number of buildings that will be destroyed in P days.
The second line consists of space-separated integers. The total number of integers will be equal to P. These are the
indexes of the buildings which are to be destroyed.
Output Description
Output will be to STDOUT, or written to a file output.txt in the working directory. Output will contain a single
integer consisting of the minimum number of Reinforcement Kits required.
#Sample Inputs and Outputs
#Sample Input 1
8 1
3
#Sample Output 1
7
#Sample Input 2
20 3
3 6 14
#Sample Output 2
35
#Notes
Thanks again to /u/202halffound
"""
def main():
pass
if __name__ == "__main__":
main()
|
8ae8f2db0a591eb3bec68a906a1881bb40b979ff | DayGitH/Python-Challenges | /DailyProgrammer/DP20140827W.py | 1,143 | 3.96875 | 4 | """
[Weekly #8] Sorting algorithms
https://www.reddit.com/r/dailyprogrammer/comments/2emixb/weekly_8_sorting_algorithms/
#Weekly Topic:
Often times we need to sort the data. A basic foundation in learning programming is to understand how to do this sort
on the data and why to do it. Monday we saw a challenge based on the very popular Quick Sort algorithm.
But let's talk about sorting in more detail. Sorting routines best fit the need. Sometimes we need a quicksort but
sometimes thou a different sorting algorithm should be done.
Where/how/what do you do to sort? Give some examples of some challenges where perhaps a different sorting approach is
used/needed. Why does it work better? How do you determine which sorting algorithm to use?
Also this is a chance to point out some other algorithms perhaps out there but not used much or talked about much.
Maybe you still like bubble sort even if it is not always the optimal choice. Why?
#Previous Week Topic:
[Weekly #7] (http://www.reddit.com/r/dailyprogrammer/comments/2dwc2p/weekly_7_programming_tools_the_editors/)
"""
def main():
pass
if __name__ == "__main__":
main()
|
9cc6c399c85bf0eeb6757e4420468d5f6ff6224e | DayGitH/Python-Challenges | /DailyProgrammer/DP20140813B.py | 1,330 | 4.03125 | 4 | """
[8/13/2014] Challenge #175 [Intermediate] Largest Word from Characters
https://www.reddit.com/r/dailyprogrammer/comments/2dgd5v/8132014_challenge_175_intermediate_largest_word/
#Description:
Given a string of words and a string of letters. Find the largest string(s) that are in the 1st string of words that
can be formed from the letters in the 2nd string.
* Letters can be only used once. So if the string has "a b c" then words like "aaa" and "bbb" do not work because there
is only 1 "a" or "b" to be used.
* If you have tie for the longest strings then output all the possible strings.
* If you find no words at all then output "No Words Found"
#input:
(String of words)
(String of characters)
##example:
abc cca aaaaaa bca
a b c
#output:
List of max size words in the first string of words. If none are found "No Words Found" displayed.
##example (using above input):
abc bca
#Challenge input 1:
hello yyyyyyy yzyzyzyzyzyz mellow well yo kellow lellow abcdefhijkl hi is yellow just here to add strings fellow
lellow llleow
l e l o h m f y z a b w
#Challenge input 2:
sad das day mad den foot ball down touch pass play
z a d f o n
#Got an Idea For a Challenge?
Visit /r/dailyprogrammer_ideas and submit your idea.
"""
def main():
pass
if __name__ == "__main__":
main()
|
dea6624c859356ed196474cbb7f746f5d5b44dd8 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120808C.py | 1,199 | 4.1875 | 4 | """
[8/8/2012] Challenge #86 [difficult] (2-SAT)
https://www.reddit.com/r/dailyprogrammer/comments/xx970/882012_challenge_86_difficult_2sat/
Boolean Satisfiability problems are problems where we wish to find solutions to boolean equations such as
(x_1 or not x_3) and (x_2 or x_3) and (x_1 or not x_2) = true
These problems are notoriously difficult, and k-SAT where k (the number of variables in an or expression) is 3 or
higher is known to be
NP-complete.
However, [2-SAT](http://en.wikipedia.org/wiki/2-satisfiability) instances (like the problem above) are NOT NP-complete
(if P!=NP), and even have linear time solutions.
You can encode an instance of 2-SAT as a list of pairs of integers by letting the integer represent which variable is
in the expression, with a negative integer representing the negation of that variable. For example, the problem above
could be represented in list of pair of ints form as
[(1,-3),(2,3),(1,-2)]
Write a function that can take in an instance of 2-SAT encoded as a list of pairs of integers and return a boolean for
whether or not there are any true solutions to the formula.
"""
def main():
pass
if __name__ == "__main__":
main()
|
51e69b647068cc60de578216e630fc6d6fffe082 | DayGitH/Python-Challenges | /DailyProgrammer/DP20151230B.py | 5,275 | 3.5 | 4 | """
[2015-12-30] Challenge #247 [Intermediate] Moving (diagonally) Up in Life
https://www.reddit.com/r/dailyprogrammer/comments/3ysdm2/20151230_challenge_247_intermediate_moving/
# [](#IntermediateIcon) _(Intermediate)_: Moving (diagonally) Up in Life
Imagine you live on a grid of characters, like the one below. For this example, we'll use a 2\*2 grid for simplicity.
. X
X .
You start at the `X` at the bottom-left, and you want to get to the `X` at the top-right. However, you can only move
up, to the right, and diagonally right and up in one go. This means there are three possible paths to get from one `X`
to the other `X` (with the path represented by `-`, `+` and `|`):
+-X . X . X
| / |
X . X . X-+
What if you're on a 3\*3 grid, such as this one?
. . X
. . .
X . .
Let's enumerate all the possible paths:
+---X . +-X . +-X . +-X . . X . +-X . . X
| / | | / | |
| . . + . . +-+ . . + . . / . . | . +---+
| | | / / | |
X . . X . . X . . X . . X . . X-+ . X . .
. . X . . X . . X . . X . . X . . X
/ | | | | /
. + . . +-+ . . + . . | . +-+ +-+ .
| | / | / |
X-+ . X-+ . X-+ . X---+ X . . X . .
That makes a total of 13 paths through a 3\*3 grid.
However, what if you wanted to pass through 3 `X`s on the grid? Something like this?
. . X
. X .
X . .
Because we can only move up and right, if we're going to pass through the middle `X` then there is no possible way to
reach the top-left and bottom-right space on the grid:
. X
. X .
X .
Hence, this situation is like two 2\*2 grids joined together end-to-end. This means there are 3^(2)=9 possible paths
through the grid, as there are 3 ways to traverse the 2\*2 grid. (Try it yourself!)
Finally, some situations are impossible. Here, you cannot reach all 4 `X`s on the grid - either the top-left or
bottom-right `X` must be missed:
X . X
. . .
X . X
This is because we cannot go left or down, only up or right - so this situation is an invalid one.
Your challenge today is, given a grid with a certain number of Xs on it, determine first whether the situation is valid
(ie. all `X`s can be reached), and if it's valid, the number of possible paths traversing all the `X`s.
# Formal Inputs and Outputs
## Input Specification
You'll be given a tuple **M, N** on one line, followed by **N** further lines (of length **M**) containing a grid of
spaces and `X`s, like this:
5, 4
....X
..X..
.....
X....
Note that the top-right `X` need not be at the very top-right of the grid, same for the bottom-left `X`. Also, unlike
the example grids shown above, there are no spaces between the cells.
## Output Description
Output the number of valid path combinations in the input, or an error message if the input is invalid. For the above
input, the output is:
65
# Sample Inputs and Outputs
## Example 1
### Input
3, 3
..X
.X.
X..
### Output
9
## Example 2
### Input
10, 10
.........X
..........
....X.....
..........
..........
....X.....
..........
.X........
..........
X.........
### Output
7625
## £xample 3
### Input
5, 5
....X
.X...
.....
...X.
X....
### Output
**<invalid input>**
## Example 4
### Input
7, 7
...X..X
.......
.......
.X.X...
.......
.......
XX.....
### Output
1
## Example 5
### Input
29, 19
.............................
........................X....
.............................
.............................
.............................
.........X...................
.............................
.............................
.............................
.............................
.............................
.....X.......................
....X........................
.............................
.............................
.............................
XX...........................
.............................
.............................
### Output
19475329563
## Example 6
### Input
29, 19
.............................
........................X....
.............................
.............................
.............................
.........X...................
.............................
.............................
.............................
.............................
.............................
....XX.......................
....X........................
.............................
.............................
.............................
XX...........................
.............................
.............................
### Output
6491776521
# Finally
Got any cool challenge ideas? Submit them to /r/DailyProgrammer_Ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
|
35a0fdd29e629a3e4bd1e795d6a7de6805243aaa | DayGitH/Python-Challenges | /DailyProgrammer/20120219A.py | 491 | 4.4375 | 4 | '''
The program should take three arguments. The first will be a day, the second will be month, and the third will be year.
Then, your program should compute the day of the week that date will fall on.
'''
import datetime
day_list = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}
year = int(input('Year >> '))
month = int(input('Month >> '))
day = int(input('Day >> '))
print(day_list[datetime.date(year, month, day).weekday()]) |
9d583bc0464ebcbf6876a0bc5ca748e05a4e8cd0 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140924B.py | 5,112 | 4.09375 | 4 | """
[09/24/2014] Challenge #181 [Intermediate] Average Speed Cameras
https://www.reddit.com/r/dailyprogrammer/comments/2hcwzn/09242014_challenge_181_intermediate_average_speed/
# [](#IntermediateIcon) _(Intermediate)_: Average Speed Cameras
In the UK, a common safety measure on motorways is the so-called [average speed
cameras](http://en.wikipedia.org/wiki/SPECS_%28speed_camera%29). These, unlike normal speed cameras which measure a
vehicle's speed instantaneously, have several connected cameras at intervals along a motorway. The speed of a vehicle
can be determined by dividing the distance between two cameras by the time it takes the vehicle to get from one to
another. This can be used to stop vehicles breaking the speed limit over long stretches of roads, rather than allowing
vehicles to speed up after they are out of range. The Home Office has contacted you to replace the aging software
system in the cameras with something more up to date.
In this challenge, you will be given a number of speed cameras and their positions along a road, along with the speed
limit. You will then be given the camera logs for each camera in turn. From this data, you will work out which vehicles
are breaking the speed limit.
# Formal Inputs and Outputs
## Input Description
The first section of the input will contain the speed limit and the position of the speed cameras. The speed limit may
be in miles per hour or kilometres per hour. The lines will be in the format:
Speed limit is <limit> mph.
OR
Speed limit is <limit> km/h.
The lines describing the positions of the speed cameras will look like:
Speed camera <number> is <distance> metres down the motorway.
Speed camera number 1 will always have a distance of 0.
After this, you will get logs for each speed camera, like this:
Start of log for camera <number>:
Vehicle <registration number> passed camera <number> at <time>.
Vehicle <registration number> passed camera <number> at <time>.
...
Example inputs and outputs can be found below.
## Output Description
For each vehicle that breaks the speed limit, print a line like so:
Vehicle <registration number> broke the speed limit by <amount>.
Where `<amount>` is in the local units.
# Sample Inputs and Outputs
## Sample Input
Speed limit is 60.00 mph.
Speed camera number 1 is 0 metres down the motorway.
Speed camera number 2 is 600 metres down the motorway.
Speed camera number 3 is 855 metres down the motorway.
Speed camera number 4 is 1355 metres down the motorway.
Start of log for camera 1.
Vehicle G122 IVL passed camera 1 at 09:36:12.
Vehicle H151 KEE passed camera 1 at 09:36:15.
Vehicle U109 FIJ passed camera 1 at 09:36:20.
Vehicle LO04 CHZ passed camera 1 at 09:36:23.
Vehicle I105 AEV passed camera 1 at 09:36:28.
Vehicle J828 EBC passed camera 1 at 09:36:29.
Vehicle WF EP7 passed camera 1 at 09:36:32.
Vehicle H108 KYL passed camera 1 at 09:36:33.
Vehicle R815 FII passed camera 1 at 09:36:34.
Vehicle QW04 SQU passed camera 1 at 09:36:34.
Start of log for camera 2.
Vehicle G122 IVL passed camera 2 at 09:36:42.
Vehicle LO04 CHZ passed camera 2 at 09:36:46.
Vehicle H151 KEE passed camera 2 at 09:36:51.
Vehicle QW04 SQU passed camera 2 at 09:36:53.
Vehicle J828 EBC passed camera 2 at 09:36:53.
Vehicle R815 FII passed camera 2 at 09:36:55.
Vehicle U109 FIJ passed camera 2 at 09:36:56.
Vehicle H108 KYL passed camera 2 at 09:36:57.
Vehicle I105 AEV passed camera 2 at 09:37:05.
Vehicle WF EP7 passed camera 2 at 09:37:10.
Start of log for camera 3.
Vehicle LO04 CHZ passed camera 3 at 09:36:55.
Vehicle G122 IVL passed camera 3 at 09:36:56.
Vehicle H151 KEE passed camera 3 at 09:37:03.
Vehicle QW04 SQU passed camera 3 at 09:37:03.
Vehicle J828 EBC passed camera 3 at 09:37:04.
Vehicle R815 FII passed camera 3 at 09:37:09.
Vehicle U109 FIJ passed camera 3 at 09:37:11.
Vehicle H108 KYL passed camera 3 at 09:37:12.
Vehicle I105 AEV passed camera 3 at 09:37:20.
Vehicle WF EP7 passed camera 3 at 09:37:23.
Start of log for camera 4.
Vehicle LO04 CHZ passed camera 4 at 09:37:13.
Vehicle QW04 SQU passed camera 4 at 09:37:24.
Vehicle J828 EBC passed camera 4 at 09:37:26.
Vehicle G122 IVL passed camera 4 at 09:37:28.
Vehicle R815 FII passed camera 4 at 09:37:28.
Vehicle H151 KEE passed camera 4 at 09:37:29.
Vehicle H108 KYL passed camera 4 at 09:37:36.
Vehicle I105 AEV passed camera 4 at 09:37:42.
Vehicle WF EP7 passed camera 4 at 09:37:44.
Vehicle U109 FIJ passed camera 4 at 09:37:45.
## Sample Output
Vehicle LO04 CHZ broke the speed limit by 3.4 mph.
Vehicle LO04 CHZ broke the speed limit by 2.1 mph.
Vehicle QW04 SQU broke the speed limit by 10.6 mph.
Vehicle R815 FII broke the speed limit by 3.9 mph.
# Challenge
## Challenge Input
A long pastebin containing a huge data set is [available
here](https://gist.githubusercontent.com/Quackmatic/e75d61c1ecc319f721a2/raw/average-speed-cameras.txt), to stress-test
your input if nothing else.
# Notes
You may want to use regular expressions again for this challenge.
"""
def main():
pass
if __name__ == "__main__":
main()
|
bad24f313366dde14556e9d6f89bdacc4fb2eb7b | DayGitH/Python-Challenges | /DailyProgrammer/DP20121018A.py | 976 | 3.984375 | 4 | """
[10/18/2012] Challenge #104 [Easy] (Powerplant Simulation)
https://www.reddit.com/r/dailyprogrammer/comments/11paok/10182012_challenge_104_easy_powerplant_simulation/
**Description:**
A powerplant for the city of Redmond goes offline every third day because of local demands. Ontop of this, the
powerplant has to go offline for maintenance every 100 days. Keeping things complicated, on every 14th day, the
powerplant is turned off for refueling. Your goal is to write a function which returns the number of days the
powerplant is operational given a number of days to simulate.
**Formal Inputs & Outputs:**
*Input Description:*
Integer days - the number of days we want to simulate the powerplant
*Output Description:*
Return the number of days the powerplant is operational.
**Sample Inputs & Outputs:**
The function, given 10, should return 7 (3 days removed because of maintenance every third day).
"""
def main():
pass
if __name__ == "__main__":
main()
|
7a7ca97a97c90480d88a0a2d1355b07744842b21 | DayGitH/Python-Challenges | /DailyProgrammer/DP20131104A.py | 4,226 | 3.984375 | 4 | """
[11/4/13] Challenge #140 [Easy] Variable Notation
https://www.reddit.com/r/dailyprogrammer/comments/1q6pq5/11413_challenge_140_easy_variable_notation/
# [](#EasyIcon) *(Easy)*: Variable Notation
When writing code, it can be helpful to have a standard ([Identifier naming
convention](http://en.wikipedia.org/wiki/Identifier_naming_convention)) that describes how to define all your variables
and object names. This is to keep code easy to read and maintain. Sometimes the standard can help describe the type
(such as in [Hungarian notation](http://en.wikipedia.org/wiki/Hungarian_notation)) or make the variables visually easy
to read ([CamcelCase notation](http://en.wikipedia.org/wiki/CamelCase) or
[snake_case](http://en.wikipedia.org/wiki/Snake_case)).
Your goal is to implement a program that takes an english-language series of words and converts them to a specific
variable notation format. Your code must support CamcelCase, snake_case, and capitalized snake_case.
# Formal Inputs & Outputs
## Input Description
On standard console input, you will be given an integer one the first line of input, which describes the notation you
want to convert to. If this integer is zero ('0'), then use CamcelCase. If it is one ('1'), use snake_case. If it is
two ('2'), use capitalized snake_case. The line after this will be a space-delimited series of words, which will only
be lower-case alpha-numeric characters (letters and digits).
## Output Description
Simply print the given string in the appropriate notation.
# Sample Inputs & Outputs
## Sample Input
0
hello world
1
user id
2
map controller delegate manager
## Sample Output
0
helloWorld
1
user_id
2
MAP_CONTROLLER_DELEGATE_MANAGER
## Difficulty++
For an extra challenge, try to convert from one notation to another. Expect the first line to be two integers, the
first one being the notation already used, and the second integer being the one you are to convert to. An example of
this is:
Input:
1 0
user_id
Output:
userId
"""
def main():
pass
if __name__ == "__main__":
main()
"""
[11/4/13] Challenge #139 [Easy] Pangrams
https://www.reddit.com/r/dailyprogrammer/comments/1pwl73/11413_challenge_139_easy_pangrams/
# [](#EasyIcon) *(Easy)*: Pangrams
[Wikipedia](http://en.wikipedia.org/wiki/Pangram) has a great definition for Pangrams: "*A pangram or holoalphabetic
sentence for a given alphabet is a sentence using every letter of the alphabet at least once.*" A good example is the
English-language sentence "[The quick brown fox jumps over the lazy
dog](http://en.wikipedia.org/wiki/The_quick_brown_fox_jumps_over_the_lazy_dog)"; note how all 26 English-language
letters are used in the sentence.
Your goal is to implement a program that takes a series of strings (one per line) and prints either True (the given
string is a pangram), or False (it is not).
**Bonus:** On the same line as the "True" or "False" result, print the number of letters used, starting from 'A' to
'Z'. The format should match the following example based on the above sentence:
a: 1, b: 1, c: 1, d: 1, e: 3, f: 1, g: 1, h: 2, i: 1, j: 1, k: 1, l: 1, m: 1, n: 1, o: 4, p: 1, q: 1, r: 2, s: 1,
t: 2, u: 2, v: 1, w: 1, x: 1, y: 1, z: 1
# Formal Inputs & Outputs
## Input Description
On standard console input, you will be given a single integer on the first line of input. This integer represents the
number of lines you will then receive, each being a string of alpha-numeric characters ('a'-'z', 'A'-'Z', '0'-'9') as
well as spaces and [period](http://en.wikipedia.org/wiki/Period_(punctuation\)).
## Output Description
For each line of input, print either "True" if the given line was a pangram, or "False" if not.
# Sample Inputs & Outputs
## Sample Input
3
The quick brown fox jumps over the lazy dog.
Pack my box with five dozen liquor jugs
Saxophones quickly blew over my jazzy hair
## Sample Output
True
True
False
# Authors Note: [Horay, we're back with a queue of new challenges](http://i.imgur.com/chKCAPM.jpg)! Sorry fellow
r/DailyProgrammers for the long time off, but we're back to business as usual.
"""
def main():
pass
if __name__ == "__main__":
main()
|
f4e0f4775698853e23a8cd47e80778a3eb34e6a3 | lingwei-gu/globalEngineeringYouthSummitWorkshop | /webscrapingWithImage.py | 741 | 3.578125 | 4 | from bs4 import BeautifulSoup
import urllib.request
import requests
from PIL import Image
link = "https://www.reddit.com/"
def webscraper():
opensite = urllib.request.urlopen(link)
site_content = opensite.read()
soup = BeautifulSoup(site_content, "lxml")
soup.prettify()
posts = soup.select('div#siteTable div.thing')
print(posts[0].select("p.title a")[0].text)
print(posts[0].select("a.thumbnail img")[0].get("src"))
image_name = "Image.jpg"
img1 = posts[0].select("a.thumbnail img")[0].get("src")
img1 = "http:" + img1
TheImage = requests.get(img1)
with open(image_name, "wb") as f:
f.write(TheImage.content)
image = Image.open(image_name)
image.show()
webscraper()
|
e7a6fc9dc8fcc6d0b9e05a8a1f04bfccf023fba0 | gregglind/Tic-Tac-Toe | /invincitron.py | 8,029 | 3.765625 | 4 | #!/usr/bin/env python
'''
INVINCITRON, an opponent that can win *all games* with 100% certainty [1]
Note [1]: current implementation only plays tic-tac-toe, future versions will expand on this.
LICENSE: BSD, with attribution
AUTHOR: Gregg Lind <gregg.lind@gmail.com>
'''
'''
Intructions:
1. Fork this repo on github.
2. Create an app that can interactively play the game of Tic Tac Toe against another player and never lose.
3. Commit early and often, with good messages.
4. Push your code back to github and send me a pull request.
'''
'''
Strategy (from Wikipedia)
A player can play perfect tic-tac-toe (win or draw) given they move according to the highest possible move from the following table.[4]
Win: If the player has two in a row, play the third to get three in a row.
Block: If the opponent has two in a row, play the third to block them.
Fork: Create an opportunity where you can win in two ways.
Block opponent's fork:
Option 1: Create two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork or winning. For example, if "X" has a corner, "O" has the center, and "X" has the opposite corner as well, "O" must not play a corner in order to win. (Playing a corner in this scenario creates a fork for "X" to win.)
Option 2: If there is a configuration where the opponent can fork, block that fork.
Center: Play the center.
Opposite corner: If the opponent is in the corner, play the opposite corner.
Empty corner: Play in a corner square.
Empty side: Play in a middle square on any of the 4 sides.
The first player, whom we shall designate "X", has 3 possible positions to mark during the first turn. Superficially, it might seem that there are 9 possible positions, corresponding to the 9 squares in the grid. However, by rotating the board, we will find that in the first turn, every corner mark is strategically equivalent to every other corner mark. The same is true of every edge mark. For strategy purposes, there are therefore only three possible first marks: corner, edge, or center. Player X can win or force a draw from any of these starting marks; however, playing the corner gives the opponent the smallest choice of squares which must be played to avoid losing.[5]
The second player, whom we shall designate "O", must respond to X's opening mark in such a way as to avoid the forced win. Player O must always respond to a corner opening with a center mark, and to a center opening with a corner mark. An edge opening must be answered either with a center mark, a corner mark next to the X, or an edge mark opposite the X. Any other responses will allow X to force the win. Once the opening is completed, O's task is to follow the above list of priorities in order to force the draw, or else to gain a win if X makes a weak play.
'''
import itertools
import random
# ttt has small state, so we can throw it around.
triples = [
(0,1,2),
(3,4,5),
(6,7,8),
(0,3,6),
(1,4,7),
(2,5,8),
(0,4,8),
(2,4,6)
]
corners = {0:8,2:6,6:2,8:0}
sides = {1:7,3:5,5:3,7:1}
def opponent(player):
return 'XO'[player=='X']
def won(game):
''' return play who wins the game, or False
>>> print won(['X','X','X'] + [None,]*6)
X
>>> print won([None,]*9)
None
# 2 ways for x to win
>>> print won(['O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X'])
X
'''
winners = set()
for p in (('O','O','O'),('X','X','X')):
for (a,b,c) in triples:
run = (game[a],game[b],game[c])
if run == p:
winners.add(p[0])
else:
pass
#print run, p[0]
l = len(winners)
if l == 0:
return None
elif l == 1:
return list(winners)[0]
else:
raise Exception('more than one winner!? oops!')
def tie(game):
'''
>>> g = ['O', 'X', 'O', 'X', 'O', 'X', 'X', 'O', 'X']
>>> tie(g)
True
'''
return (not won(game)) and None not in game
## all of these are brute force. We could save state along the way.
def can_win(game,player):
''' in some triple, there is a None, and two 'player' tokens.
>>> can_win(['X','X'] + [None,]*7,'X')
2
'''
for t in triples:
run = (game[t[0]],game[t[1]],game[t[2]])
if None in run and sorted([None,player,player]) == sorted(run):
for k in t:
if game[k] is None: return k
return None
def can_block(game,player):
# block the enemy
return can_win(game,opponent(player))
def can_fork(game,player):
return None
def block_fork(game,player):
return None
def center(game,player):
'''
>>> center([None,]*9,'X')
4
>>> w = [None,]*9
>>> w[4] = 'O'
>>> print center(w,'X')
None
'''
if game[4] is None:
return 4
else:
return None
def opposite_corner(game,player):
move = None
for k,v in corners.iteritems():
if game[k] is None and game[v] == opponent(player):
move = k
break
return move
def empty_corner(game,player):
moves = [x for x in corners if game[x] is None]
if moves:
return random.choice(moves)
else:
return None
def empty_side(game,player):
moves = [x for x in sides if game[x] is None]
if moves:
return random.choice(moves)
else:
return None
def random_move(game,player):
moves = [ii for (ii,x) in enumerate(game) if x is None]
#print "NEXT_MOVE:", game, player, moves
return random.choice(moves)
def suggest_optimal_move(game,player):
move = None
move_fns = (can_win,can_block,can_fork,
block_fork,center,
opposite_corner, empty_corner,
empty_side)
for move_fn in move_fns:
move = move_fn(game,player)
#print move, move_fn.__name__
if move is not None:
break
return move
def play_game(player1,player2):
'''
Play an interactive tic-tac-toe game.
Args:
player1, player2: 'players'
that have a 'get_move(game,player)'
method.
Returns:
game, winner, moves
'''
game = [None,]*9
moves = []
players = itertools.cycle([('X',player1),('O',player2)])
while not (won(game) or tie(game)):
s, p = players.next()
move = p.next_move(game,s)
if move is None:
raise Exception, "no move chosen! %r %r %r" % (s,game,moves)
game[move] = s
moves.append(move)
# should have some exceptions here for illegal moves.
if tie(game):
winner = "TIE"
else:
winner = won(game)
return winner,game,moves
class GoodPlayer(object):
def next_move(self,game,player):
return suggest_optimal_move(game,player)
class RandomPlayer(object):
def next_move(self,game,player):
return random_move(game,player)
def format(game):
g = [(x,'_')[x is None] for x in game]
a = ('''%s %s %s 1 2 3 \n'''
'''%s %s %s 4 5 6 \n'''
'''%s %s %s 7 8 9 \n''' %
(g[0],g[1],g[2],g[3],g[4],g[5],g[6],g[7],g[8])
)
return a
class LivePlayer(object):
def next_move(self,game,player):
print format(game)
moves = dict([(str(ii+1),ii) for (ii,x) in enumerate(game) if x is None])
while True:
provisional = raw_input("your move? choose from [%s] " % " ".join(sorted(moves))).strip()
if provisional not in moves:
print "%s: not a valid move, try again" % (provisional)
else:
return moves[provisional]
if __name__ == '__main__':
ans = raw_input("X or 0? ").strip().upper()
X = 'X' in ans
players = (LivePlayer(),GoodPlayer())
if X:
print "you are X"
else:
print "you are O"
players = players[::-1]
winner,game,moves = play_game(*players)
print "winner", winner
print "game board:"
print format(game)
print "move sequeunce:", moves
|
df6df81fd9a4d8f2e5346e593f14a33b1585e8de | renito09/Computer-Science | /operators.py | 487 | 3.78125 | 4 | import time
secret_message = float (input("Enter a 2 factor number between 0 - 1 (0 or 1 doesnt count): "))
if (secret_message == 0.1) or (secret_message == 0.2) or (secret_message == 0.3) or (secret_message == 0.4) or (secret_message == 0.5) or (secret_message == 0.6) or (secret_message == 0.7) or (secret_message == 0.8) or (secret_message == 0.9) :
time.sleep(2)
print("Your answer was correct")
else:
time.sleep(2)
print("Unfortunately your answer was incorrect") |
5bbddcc5b486e2aa4ad57bf681afa1934f1fc485 | donoghuc/code_example_2 | /socket_class.py | 4,063 | 4.03125 | 4 | #! /usr/bin/python3
# Cas Donoghue
# CS372
# Project 2
#
# This is a class for sockets. It is used for the server and client side.
# i got the idea from: https://docs.python.org/3/howto/sockets.html
# basically just followed the docs.
import socket
import sys
class MySocket:
"""class for message app.
"""
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def client_connect(self, host, port):
try:
self.sock.connect((host, port))
except socket.error as e:
print(str(e))
sys.exit()
# listen function.
def server_listen(self, host, port, connections):
try:
self.sock.bind((host, port))
except socket.error as e:
print(str(e))
sys.exit()
self.sock.listen(connections)
# super simple accept function (returns conn, addr)
def server_accept(self):
return self.sock.accept()
# python3 has a sendall so you dont have to worry about writing one yourself
def client_send(self, msg):
self.sock.sendall(str.encode(msg))
# subtle diff between client and server
def server_send(self, conn, msg):
conn.sendall(str.encode(msg))
# use my system of prepending expected message len to ensure you get the whole message.
def server_receive(self, conn):
chunks = []
bytes_expected = ''
bytes_recd = 0
while True:
data = conn.recv(3).decode()
for x in range(len(data)):
if data[x] != 'x':
bytes_expected = bytes_expected + data[x]
if not data:
break
bytes_expected = int(bytes_expected)
while bytes_recd < bytes_expected:
chunk = conn.recv(min(bytes_expected - bytes_recd, 2048)).decode()
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return ''.join(chunks)
# again use the prepend message idea
def client_recv(self):
chunks = []
bytes_expected = ''
bytes_recd = 0
while True:
data = self.sock.recv(3).decode()
for x in range(len(data)):
if data[x] != 'x':
bytes_expected = bytes_expected + data[x]
if not data:
break
bytes_expected = int(bytes_expected)
while bytes_recd < bytes_expected:
chunk = self.sock.recv(min(bytes_expected - bytes_recd, 2048)).decode()
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return ''.join(chunks)
# takes file size name and connection. receives file_size bytes and write to file name
def recieve_and_write_req_file(self, file_size, file_name, conn):
CHUNK_SIZE = 10
bytes_recd = 0
fo = open(file_name, 'w')
while bytes_recd < file_size:
chunk = conn.recv(min(file_size - bytes_recd, CHUNK_SIZE)).decode()
# print(chunk)
fo.write(chunk)
bytes_recd = bytes_recd + len(chunk)
fo.close()
# recieved bytes_expected bytes and print out parsed directory list (from comma sep list)
def recieve_and_print_serv_dir(self, bytes_exp, conn):
CHUNK_SIZE = 10
bytes_recd = 0
chunks = []
while bytes_recd < bytes_exp:
chunk = conn.recv(min(bytes_exp - bytes_recd, CHUNK_SIZE)).decode()
# print(chunk)
bytes_recd = bytes_recd + len(chunk)
chunks.append(chunk)
coma_sep_dir_str = ''.join(chunks)
dir_list = coma_sep_dir_str.split(',')
for i in dir_list:
print(i)
# simply close up connections when done.
def client_close(self):
self.sock.close()
def server_close(self, conn):
conn.close()
|
a01c987f9fe31b9a56f46657ca51612cee5e0d5b | andreigabor21/Python-Games | /OrderAndChaos/Domains.py | 3,018 | 3.515625 | 4 | from texttable import Texttable
import unittest
import random
class Board:
def __init__(self):
self.board = [[" " for j in range(6)] for i in range(6)]
def __str__(self):
t = Texttable()
t.add_rows(self.board, [])
return t.draw()
def ReadFromFile(self, file_name):
f = open(file_name, "r")
lines = f.readlines()
i = 0
for line in lines:
for j in range(6):
if line[j] == "#":
self.board[i][j] = " "
elif line[j] == "X":
self.board[i][j] = "X"
elif line[j] == "O":
self.board[i][j] = "O"
i += 1
def WriteToFile(self, file_name):
f = open(file_name, "w")
for i in range(6):
for j in range(6):
if self.board[i][j] == " ":
f.write("#")
else:
f.write(self.board[i][j])
f.write('\n')
def move(self, piece, i, j):
self.board[i][j] = piece
def isGameWon(self, piece):
#check line
for i in range(6):
for j in range(2):
if self.board[i][j] == self.board[i][j+1] == self.board[i][j+2] == self.board[i][j+3] == self.board[i][j+4] == piece:
return True
#check columns
for j in range(6):
for i in range(2):
if self.board[i][j] == self.board[i+1][j] == self.board[i+2][j] == self.board[i+3][j] == self.board[i+4][j] == piece:
return True
#check diagonals
if self.board[1][0] == self.board[2][1] == self.board[3][2] == self.board[4][3] == self.board[5][4] == piece:
return True
if self.board[0][1] == self.board[1][2] == self.board[2][3] == self.board[3][4] == self.board[4][5] == piece:
return True
if self.board[0][0] == self.board[1][1] == self.board[2][2] == self.board[3][3] == self.board[4][4] == piece:
return True
if self.board[1][1] == self.board[2][2] == self.board[3][3] == self.board[4][4] == self.board[5][5] == piece:
return True
return False
def NoSpacesLeft(self):
for i in range(6):
for j in range(6):
if self.board[i][j] == " ":
return False
return True
class AI:
def checkForConnection(self, piece, board):
pass
def move(self, piece1, piece2, board):
pass
def available_moves(self,board : Board):
l = []
for i in range(6):
for j in range(6):
if board.board[i][j] == " ":
l.append((i,j))
return l
def choose_random(self, board: Board):
symbol = random.choice(["X", "O"])
elem = random.choice(self.available_moves(board))
i = elem[0]
j = elem[1]
board.board[i][j] = symbol
'''
b = Board()
b.ReadFromFile("OAC.txt")
print(b)
''' |
d62891c71fa12b75124713cc57f6da21b2f0c950 | RVPH/import_scripts | /textprocessing_module.py | 5,263 | 3.515625 | 4 | # Text processing functions for
# Russkiy Vrach Publishing House article database
import re
# Individual functions to process text
def remove_linebreaks(value: str) -> str:
"""Remove linebreaks (\n) """
regexp = re.compile(r'\n')
return regexp.sub(' ', value)
def remove_wordwraps(value: str) -> str:
"""Remove wordwraps (-\n) """
regexp = re.compile(r'-\n')
return regexp.sub('', value)
def remove_extra_spaces(value: str) -> str:
"""Remove leading and trailing space characters and replace any
multiple whitespace characters to one space character"""
regexp = re.compile(r'^\s+')
value = regexp.sub('', value)
regexp = re.compile(r'\s+$')
value = regexp.sub('', value)
regexp = re.compile(r'\s+')
return regexp.sub(' ', value)
def remove_trailing_dots(value: str) -> str:
"""Remove trailing dot(s)"""
regexp = re.compile(r'\.+$')
return regexp.sub('', value)
def replace_semicolon_to_comma(value: str) -> str:
"""Remove semicolons to commas"""
regexp = re.compile(r';')
return regexp.sub(',', value)
def arrange_spaces_around_commas(value: str) -> str:
"""Remove unnecessary space before commas and add a single space after"""
regexp = re.compile(r'\s+,')
value = regexp.sub(',', value)
regexp = re.compile(r',\s*')
return regexp.sub(', ', value)
def remove_phrase_before_colon(value: str) -> str:
"""Remove a phrase before colon at the beginning of the given string"""
regexp = re.compile(r'^.*:\s*')
return regexp.sub('', value)
def remove_extra_spaces_in_list(value: str) -> str:
"""Remove spaces in the beginning of a string in a list"""
regexp = re.compile(r'^[ \t]+', re.M)
value = regexp.sub('', value, re.M)
#regexp = re.compile(r'\n\s+', re.M)
#value = regexp.sub('\n', value, re.M)
regexp = re.compile(r'¬')
value = regexp.sub('', value)
regexp = re.compile(r'')
value = regexp.sub('-', value)
regexp = re.compile(r'[ \t][ \t]+', re.M)
return regexp.sub(' ', value, re.M)
# Stack of functions to check critical values
def id_is_valid(cell: 'Excel cell') -> 'Boolean':
"""Check ID field"""
if type(cell.value) is str:
if re.compile(r'........-\d\d\d\d-\d\d-\d\d').fullmatch(cell.value):
return True
return False
def volume_is_valid(cell: 'Excel cell') -> 'Boolean':
"""Check Volume field"""
regexp = re.compile(r'^\d{1,2}$')
if regexp.fullmatch(str(cell.value)):
return True
return False
def month_is_valid(cell: 'Excel cell') -> 'Boolean':
"""Check Month field"""
regexp = re.compile(r'^\d{1,2}$')
if regexp.fullmatch(str(cell.value)):
return True
return False
# Stack of texprocessing functions by Excel columns
def process_title_field(cell: 'Excel cell') -> None:
"""Stack of texprocessing functions for 'Title' field"""
# Check whether cell has the type of 'String'
# to ignore emply cells
if type(cell.value) is str:
cell.value = remove_wordwraps(cell.value)
cell.value = remove_linebreaks(cell.value)
cell.value = remove_extra_spaces(cell.value)
cell.value = remove_trailing_dots(cell.value)
def process_authors_list_field(cell: 'Excel cell') -> None:
"""Stack of texprocessing functions for 'Authors list' field"""
if type(cell.value) is str:
cell.value = remove_wordwraps(cell.value)
cell.value = remove_linebreaks(cell.value)
cell.value = remove_extra_spaces(cell.value)
cell.value = replace_semicolon_to_comma(cell.value)
cell.value = arrange_spaces_around_commas(cell.value)
def process_authors_field(cell: 'Excel cell') -> None:
if type(cell.value) is str:
cell.value = remove_wordwraps(cell.value)
cell.value = remove_linebreaks(cell.value)
cell.value = remove_extra_spaces(cell.value)
def process_abstract_field(cell: 'Excel cell') -> None:
if type(cell.value) is str:
cell.value = remove_wordwraps(cell.value)
cell.value = remove_linebreaks(cell.value)
cell.value = remove_extra_spaces(cell.value)
def process_keywords_field(cell: 'Excel cell') -> None:
if type(cell.value) is str:
cell.value = remove_wordwraps(cell.value)
cell.value = remove_phrase_before_colon(cell.value)
cell.value = remove_linebreaks(cell.value)
cell.value = remove_extra_spaces(cell.value)
cell.value = replace_semicolon_to_comma(cell.value)
cell.value = arrange_spaces_around_commas(cell.value)
cell.value = remove_trailing_dots(cell.value)
def process_rubric_field(cell: 'Excel cell') -> None:
if type(cell.value) is str:
cell.value = remove_wordwraps(cell.value)
cell.value = remove_linebreaks(cell.value)
cell.value = remove_extra_spaces(cell.value)
cell.value = remove_trailing_dots(cell.value)
cell.value = cell.value.upper()
def process_references_field(cell: 'Excel cell') -> None:
if type(cell.value) is str:
cell.value = remove_extra_spaces_in_list(cell.value)
def process_pages_field(cell: 'Excel cell') -> None:
if type(cell.value) is str:
cell.value = remove_extra_spaces(cell.value)
|
639fa03d236ec2f8f9a26f1aa53af7c0d9b4e85a | JaiRaga/FreeCodeCamp-Data-Structures-and-Algorithms-in-Python | /Basic_Algorithm_Scripting/ReverseAString.py | 237 | 4 | 4 | def reverseString(s):
newStr = ''
for i in s:
newStr = i + newStr
return newStr
print(reverseString("hello"))
print(reverseString("Howdy"))
print(reverseString("Greetings from Earth"))
print(reverseString("12345")) |
00901a71600d77818e99872915fb77eb17e1692e | JaiRaga/FreeCodeCamp-Data-Structures-and-Algorithms-in-Python | /Basic_Algorithm_Scripting/SliceAndSplice.py | 302 | 3.609375 | 4 | def frankenSplice(lis1, lis2, n):
lis = lis2[:]
for i in lis1:
lis.insert(n, i)
n += 1
return lis
print(frankenSplice([1, 2, 3], [4, 5, 6], 1))
print(frankenSplice([1, 2], ["a", "b"], 1))
print(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)) |
ea8e85c489477c5736dbbaa83c565228543da9e4 | seesiva/ML | /lpthw/newnumerals.py | 1,169 | 4.65625 | 5 |
"""
Your Informatics teacher at school likes coming up with new ways to help you understand the material.
When you started studying numeral systems, he introduced his own numeral system,
which he's convinced will help clarify things. His numeral system has base 26, and
its digits are represented by English capital letters - A for 0, B for 1, and so on.
The teacher assigned you the following numeral system exercise:
given a one-digit number, you should find all unordered pairs of one-digit numbers whose values add up to the number.
Example
For number = 'G', the output should be
newNumeralSystem(number) = ["A + G", "B + F", "C + E", "D + D"].
Translating this into the decimal numeral system we get: number = 6, so it is ["0 + 6", "1 + 5", "2 + 4", "3 + 3"].
"""
def newNumeralSystem(number):
letter=number.upper()
alphabet = list('abcdefghijklmnopqrstuvwxyz'.upper())
numeral=alphabet.index(letter)
newNumeral=[]
for i in range(0,(numeral/2)+1):
print i
print i+numeral
newNumeral.append(alphabet[i]+" + "+alphabet[numeral-i])
return newNumeral
if __name__=="__main__":
print newNumeralSystem("g")
|
5514cb1b4588c60ba18477693747381d99b2073f | seesiva/ML | /lpthw/ex20.py | 777 | 4.28125 | 4 | """
Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).
Note: is considered to be an even index.
"""
import sys
if __name__=="__main__":
string_list=[]
T=int(raw_input())
for i in range (0,T):
inputstring=raw_input()
string_list.append(inputstring)
for i in range (0,T):
even=""
odd=""
#print i
#print string_list[i]
for j, char in enumerate(string_list[i]):
print j
if j % 2 == 0:
#print char
even=even+char
else:
#print char
odd=odd+char
print even, odd |
5d99fca1cf48a39fce34f6246bf4f02155ba8f07 | seesiva/ML | /lpthw/sortbyheight.py | 238 | 4.03125 | 4 | def sortByHeight(a):
l = sorted([i for i in a if i > 0])
print l
for n,i in enumerate(a):
if i == -1:
l.insert(n,i)
return l
if __name__=="__main__":
print sortByHeight([-1,-1,3,4,10,2,-1,200,4,2]) |
9958b0569eea52042d347d1e977137d3fff8ffc8 | seesiva/ML | /lpthw/euclids.py | 357 | 4.125 | 4 | """
Compute the greatest common divisor of two non-negative integers p and q as follows: If q is 0, the answer is p.
If not, divide p by q and take the remainder r. The answer is the greatest common divisor of q and r.
"""
def gcd(p,q):
if q==0:
return p
else:
r=p % q
return r
if __name__=="__main__":
print gcd(13,2) |
848503c9b6118fa2cd2cdbd860b7aba687f63a9b | seesiva/ML | /lpthw/ex11.py | 342 | 4.09375 | 4 | """
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
"""
def fact(x):
if x==1:
return 1
else:
return x*fact(x-1)
print fact(8)
|
953469d38c6689be6f48986e855b6b3c6881aa56 | seesiva/ML | /lpthw/ex9.py | 698 | 4.21875 | 4 | """
Higher Order Functions
HoF:Function as a return value
"""
def add_two_nums(x,y):
return x+y
def add_three_nums(x,y,z):
return x+y+z
def get_appropriate_function(num_len):
if num_len==3:
return add_three_nums
else:
return add_two_nums
if __name__=="__main__":
args = [1,2,3]
num_len=len(args)
res_function=get_appropriate_function(num_len)
print(res_function) # when length is 3
print (res_function(*args)) # Addition according to 3 params
args = [1,2]
num_len=len(args)
res_function=get_appropriate_function(num_len)
print(res_function) # when length is 2
print (res_function(*args)) # Addition according 2 parameters
|
3c3707fbc7f5f4329dd090ede98ab6dabf987639 | TatianaKudryavtseva/python_algoritm | /lesson 3_3.py | 554 | 3.9375 | 4 | # В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
import random
SIZE = 30
MIN_ITEM = 1
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
index_max, index_min = 0, 0
for i in range(1, len(array)):
if array[i] > array[index_max]:
index_max = i
if array[i] < array[index_min]:
index_min = i
array[index_max], array[index_min] = array[index_min], array[index_max]
print(array) |
61cc20f572aecf4040eb9be3896af7daf5ad2d73 | TatianaKudryavtseva/python_algoritm | /lesson 1_3.py | 556 | 4.09375 | 4 | # По введенным пользователем координатам двух точек
# вывести уравнение прямой вида y = kx + b, проходящей через эти точки.
print('Введите координаты первой точки')
x_1 = float(input())
y_1 = float(input())
print('Введите координаты второй точки')
x_2 = float(input())
y_2 = float(input())
k = (y_1 - y_2) / (x_1 - x_2)
b = y_2 - k * x_2
print(f'уравнение прямой: y = {k:.2f} * x + {b:.2f}') |
db8b5a361d085137634b19777ef97db2ab4db46d | TatianaKudryavtseva/python_algoritm | /lesson 3_2.py | 735 | 4.15625 | 4 | # Во втором массиве сохранить индексы четных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2,
# второй массив надо заполнить значениями 0, 3, 4, 5,
# (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа.
import random
SIZE = 10
MIN_ITEM = 1
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
array_new = []
for i in range(len(array)):
if array[i] % 2 == 0:
array_new.append(i)
print(array_new) |
04e6d1bbb4806b7372a3884fea13ab2be88f63d2 | TatianaKudryavtseva/python_algoritm | /lesson 2_4_1.py | 431 | 3.796875 | 4 | # Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...
# Количество элементов (n) вводится с клавиатуры
n = int(input('Введите количество элементов '))
element = 1
sum_element = 0
for i in range(n):
sum_element += element
element /= -2
i += 1
print(f'Сумма элементов = {sum_element}')
|
e030b7a81514bf60108c9dea4532f16edae4087b | dohun6643/practicepython | /Funtion_tuple.py | 347 | 3.609375 | 4 | # def function_name([formal_args,]*var_args_tuple):
# function_suite
# return [expression]
def print_return_tuple(arg1,*vartuple):
print("inside arg1 is :" , arg1)
for var in vartuple:
print("inside vartuple is : ", var)
return vartuple
print_return_tuple(10)
out_tuple = print_return_tuple(70,60,50)
print(out_tuple) |
344308fa5e539364f66195e44a4f1bc0515e5309 | saileshnankani/Python-Game | /saileshNankani_JoeLin_Game.py | 12,242 | 3.890625 | 4 | # Filename: saileshNankani_JoeLinGame.py
# Author: Sailesh Nankani and Joe Lin
# Date: January 20th, 2015
# Description: This program runs a game called Dash Square where the user controls the square. The objective of the game is to dodge as many as
# triangles as possible. The user gets a score for dodging each triangle. The user only has one life at a time.
# --------1) Import & start pygame -----------------------------------------
import pygame, sys
from pygame.locals import *
from random import randint
import random
pygame.init()
pygame.mixer.init()
# --------2) Definitions: Classes, Constants and Variables --------------------------
# Class(es): MyTriangleClass, PlayerClass and Player
class MyTriangleClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load("image/triangle.png")
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
def move(self):
global points, score_text
self.rect = self.rect.move(self.speed)
if self.rect.left <= -57:
if self.speed[0] == -26: # restricts the speed to maximum of -26
self.speed[0] = random.randrange(-24, -7) # randomly chooses the speed of the triangle once it reaches maximum speed
elif self.speed[0] != -27:
self.speed[0] = self.speed[0]-1 # increases the speed of the triangle after each miss
points = points + 1 # increases the score
class PlayerClass(pygame.sprite.Sprite):
allsprites = pygame.sprite.Group() #to store all the sprites
def __init__(self, x, y, width, height, img_string):
pygame.sprite.Sprite.__init__(self)
PlayerClass.allsprites.add(self)
self.image = pygame.image.load("image/main1.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.width = width
self.height = height
#creating a class called Player which contians the variables for player
class Player(PlayerClass):
List = pygame.sprite.Group() #stroe all sprites in a list
def __init__(self, x, y, width, height, img_string):
PlayerClass.__init__(self, x, y, width, height, img_string)
Player.List.add(self)
self.velx = 0
self.vely = 10
self.jump = False
self.fall = False
#creating a function which stops the player from going outsie of the screen
def motion(self, width, height):
predicted_location = self.rect.x + self.velx
if predicted_location < 0:
self.velx = 0
elif predicted_location + self.width > width:
self.velx = 0
self.rect.x += self.velx
self.__jump(height)
#creating a function which specify the jump
def __jump(self, height):
max_jump = 210
if self.jump:
if self.rect.y < max_jump:
self.fall = True
if self.fall:
self.rect.y += self.vely
predicted_location = self.rect.y + self.vely
if predicted_location + self.height > height - 120:
self.jump = False
self.fall = False
else:
self.rect.y -= self.vely
# Constants:BLACK, WHITE
BLACK = (0,0,0)
WHITE = (255,255,255)
# Variables: clock, FPS, delay, interval, keepGoing, pygame GUI components (screenWidth, screenHeight, screen, background, my_font, arrowKeys,
# title, ruleDisplay1, ruleDisplay2, ruleDisplay3, gameControl1, gameControl2, bg_image)
clock = pygame.time.Clock()
FPS = 40
delay = 100
interval = 50
scoreList=[0]
keepGoing = True
# pygame GUI & sound components
screenWidth = 700
screenHeight = 480
screen = pygame.display.set_mode((screenWidth, screenHeight))
background = pygame.Surface((screenWidth, screenHeight))
my_font = pygame.font.SysFont("arial", 20)
arrowKeys = pygame.image.load("image/ArrowKeys.jpg")
title = my_font.render("WELCOME TO THE SQUARE DASH!", True, BLACK)
ruleDisplay1 = my_font.render("Rules:", True, BLACK)
ruleDisplay2 = my_font.render("1) You are the square. Dodge the triangles to score using the controls specified below.", True, BLACK)
ruleDisplay3 = my_font.render("2) You have only 1 life to play this game.", True, BLACK)
gameControl1 = my_font.render("Game controls:", True, BLACK)
gameControl2 = my_font.render("Use the arrow keys to move around and dodge.", True, BLACK)
start = my_font.render("Press (SPACE) to start.", True, WHITE)
bg_image = pygame.image.load("image/bg_image.jpg")
pygame.key.set_repeat(delay, interval)
# ------------3) Sounds set-up ------------------------------------------------
r = randint(0, 2) #pick random number from 0 to 1
#This is a list that stores different background musics (0 = welcome1, 1 = welcome2) the number
#it selects is random which is to be determined by the upper code.
sounds = [pygame.mixer.Sound("sound/welcome1.wav"), #play if random picked 0
pygame.mixer.Sound("sound/welcome2.wav"), #play if random picked 1
pygame.mixer.Sound("sound/welcome3.wav")] #play if random picked 2
backgroundMusic = sounds[r] #play the song
backgroundMusic.play(-1) #loop that song
d = randint(0, 2)
sounds_inGame = [pygame.mixer.Sound("sound/bgm1.wav"), #play if random picked 0
pygame.mixer.Sound("sound/bgm2.wav"), #play if random picked 1
pygame.mixer.Sound("sound/bgm3.wav")] #play if random picked 2
backgroundMusic_inGame = sounds_inGame[d] #play the song
sound_eff = pygame.mixer.Sound("sound/jump_eff.wav")
# -------------4) Pygame commands ------------------------------------------
# 4a) Set up pygame GUI components (caption, background)
screen = pygame.display.set_mode((700,480))
pygame.display.set_caption("Rules")
background = pygame.Surface(screen.get_size()).convert()
screen.fill(WHITE)
background.fill(WHITE)
# 4b) display the rules screen until user closes it
keepGoingRules = True
while keepGoingRules:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoingRules = False
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # exits the while loop and displays the main game screen
backgroundMusic_inGame.play(-1)
backgroundMusic.fadeout(500)
pygame.time.delay(1000)
background.fill(WHITE)
pygame.display.set_caption("Rules")
keepGoingRules = False
#end of if event.key
#end of if event
#end for event
#display the rules to the screen
screen.blit(background, (0, 0))
screen.blit(ruleDisplay1, (20, 50))
screen.blit(title, (190, 10))
screen.blit(ruleDisplay2, (20, 90))
screen.blit(ruleDisplay3, (20, 120))
screen.blit(gameControl1, (20, 160))
screen.blit(gameControl2, (150, 322))
screen.blit(start, (250, 388))
arrowKeys = arrowKeys.convert() #need to convert it after we have set-up the screen
screen.blit(arrowKeys, (270,200)) #draw img onto temporary buffer that is not displayed
background.blit(bg_image, (0, 0))
pygame.display.flip()
# end of rule screen
# 4c) Set up pygame GUI components (speedTriangle, clock, points, score, width, height, screen, caption, font, score_text, textpos, gameOver) for
# the main game screen
speedTriangle = 7 # initial speed of the triangle
clock = pygame.time.Clock()
points = 0 # for final screen
score = 0 # for main screen
width = 700
height = 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Square Dash - The Game")
font = pygame.font.Font(None, 50)
score_text = font.render(str(points), 1, (0, 0, 0))
textpos = [10, 10]
gameOver = False
# ememyGroup components
myTriangle = MyTriangleClass('image/triangle.png', [(-1*speedTriangle),0], [50, 50]) # defines myTriangle
enemy = pygame.sprite.Group(myTriangle) # groups triangles as enemy
myTriangle.rect.topleft = (700, 310)
# Player
player = Player(20, 310, 50, 50, "image/main1.png")
#4d) displays the game until the user closes it or until the square collides with the triangle
while not gameOver:
screen.fill([255, 255, 255])
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
player.velx = 5 #move the square right
elif keys[pygame.K_LEFT]:
player.velx = -5 #move the square left
else:
player.velx = 0 #if nothings pressed the player will not move
#if the up arrow is pressed the jump function is activated
if keys[pygame.K_UP]:
sound_eff.play() # plays the jump sound everytime the square jumps
sound_eff.set_volume(0.05)
player.jump = True
player.motion(width, height) #set-up the border
screen.fill(WHITE) #fill screen white
pygame.draw.rect(screen, BLACK, (0, 360, 700, 120)) #draws the ground
PlayerClass.allsprites.draw(screen) #draws all the sprites on the screen
highestScore = str(len(scoreList)-1) # gets the last score
highScore = my_font.render(highestScore, True, BLACK)
screen.blit(myTriangle.image, myTriangle.rect.topleft)
screen.blit(highScore, [10, 10]) # blits the score on the top left of the main screen
screen.blit(myTriangle.image, myTriangle.rect.topleft)
pygame.display.flip()
if pygame.sprite.spritecollide(player, enemy, False): # if the square collides with the triangle
gg_image = pygame.image.load("image/gg_image.jpg")
pygame.display.set_caption("Game Over") # sets the caption for final screen
screen.blit(gg_image, (0, 0)) # displays the background for final screen
backgroundMusic_inGame.stop() # stops the background music
final_text1 = "Game Over"
final_text2 = "Your final score is: " + str(points)
final_text3 = "The game will close in 5 seconds."
ft1_font = pygame.font.Font(None, 70)
ft1_surf = font.render(final_text1, 1, (0, 0, 0))
ft2_font = pygame.font.Font(None, 50)
ft2_surf = font.render(final_text2, 1, (0, 0, 0))
ft3_font = pygame.font.Font(None, 50)
ft3_surf = font.render(final_text3, 1, (0, 0, 0))
screen.blit(ft1_surf, [screen.get_width()/2 - \
ft1_surf.get_width()/2, 100]) # displays "Game Over"
screen.blit(ft2_surf, [screen.get_width()/2 - \
ft2_surf.get_width()/2, 200]) # displays the final score
screen.blit(ft3_surf, [screen.get_width()/2 - \
ft3_surf.get_width()/2, 300]) # displays the time it will take to close the game
pygame.display.flip()
gameOver = True # exits the while loop
pygame.time.delay(5000) # waits for 5 seconds
sys.exit() # closes the game
if not gameOver:
pygame.display.flip()
myTriangle.move() # moves the Triangle
if myTriangle.rect.left <= -57:
scoreList.append(score)
myTriangle.rect.topleft = [800, 310] # blits the triangle back to its original position
clock.tick(FPS)
|
1fc3cf2c40325016868eb3b0bae7ef912d4dae9e | musyahid/pythonUnitTest | /src/convert.py | 878 | 3.5 | 4 | def Convert(i):
angka = ['','satu','dua','tiga','empat','lima','enam','tujuh','delapan','sembilan','sepuluh','sebelas']
i = int(i)
result = ''
if i >= 0 and i <=11:
result += f'{angka[i]}'
elif i<20:
result += f'{Convert(i % 10)} belas'
elif i <100:
result += f'{Convert(i / 10)} puluh {Convert(i % 10)}'
elif i<200:
result += f'seratus {Convert(i - 100)}'
elif i < 1000:
result += f'{Convert( i / 100)} ratus {Convert(i %100)}'
elif i < 2000:
result += f'seribu {Convert(i - 1000)}'
elif i<1000000:
result += f'{Convert(i / 1000)} ribu {Convert(i % 1000)}'
elif i<1000000000:
result += f'{Convert(i / 1000000)} juta {Convert(i % 1000000)}'
else:
result += f'{Convert(i / 1000000000)} milyar {Convert(i % 1000000000)}'
return result
# print(Convert(12)) |
ebb9c446e97928e82fbd09e394b7b6d30680e5dd | Benjaminyuan/LeetCode | /python/gennerateParentheses.py | 1,168 | 3.515625 | 4 | class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
#这样会漏情况,if 后面的情况并不是基础情况
def recorsiveFun(n):
if n == 1:
return ["()"]
else:
rlist = []
print("递归"+str(n))
tempList = recorsiveFun(n-1)
for i,item in enumerate(tempList):
if item+'()' not in rlist:
rlist.append(item+"()")
if '('+item+')' not in tempList:
rlist.append('('+item+')')
if "()"+item not in rlist:
rlist.append("()"+item)
return rlist
rlist = recorsiveFun(n)
return rlist
if __name__=="__main__":
count = Solution()
rlist = count.generateParenthesis(4)
print(rlist)
right = ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"]
for item in rlist:
right.remove(item)
print(right) |
e5a9ae0fecb0e9b9878a2e9a702150e7afe0264f | Benjaminyuan/LeetCode | /python/findSubString.py | 1,319 | 3.5 | 4 | class Solution:
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
slen = len(s)
wordsLen = len(words)
possLoc = []
if slen and wordsLen:
possiList=set()
wordLen = len(words[0])
posiStart = 0
possiList = []
i = 0
wordsTemp = words
while i < slen:
if s[i:i+wordLen] in words and s[i:i+wordLen] not in possiList :
possiList.append(s[i:i+wordLen])
posiStart = i
if len(possiList) == wordsLen:
possLoc.append(posiStart-wordLen*(wordsLen-1))
i = posiStart-wordLen*wordsLen+2*wordLen
else:
i+=wordLen
elif s[i:i+wordLen] not in words:
i+=wordLen
possiList=[]
else:
possiList=[]
return possLoc
else:
return
if __name__=="__main__":
Solu = Solution()
s = "barfoofoobarthefoobarman"
words=["bar","foo","the"]
# s= "barfoothefoobarman"
# words=["foo","bar"]
print(Solu.findSubstring(s,words)) |
47a6e7a126dfc1accb2bcdd8f120fc7be23acf0b | Custom-Tech-Enterprize/sportProgrammingSubmissionsOfmoghya | /cforce/785/A/25503070.py | 218 | 3.796875 | 4 | data = {
'Tetrahedron':4,
'Cube':6,
'Octahedron':8,
'Dodecahedron':12,
'Icosahedron':20
}
n = int(input())
ans = 0
for _ in range(0,n):
s = input()
ans = ans + data[s]
print(ans) |
6a1a8294519a15c52d511a7f5b95b2329b76d57a | dnoneill/IS289 | /web_hw#1.py | 2,104 | 4.03125 | 4 | '''base class and sub class, understand inheritance and unit tests that
test methods.
travis to github, create repo.
send link to repo.'''
import unittest
class AudioVisual():
def __init__(self, title, mediatype, genre):
self.title = title
self.mediatype = mediatype
self.genre = genre
def report(self):
return 'Title: {}\nMedia Type: {}\nGenre: {}'.format(self.title, self.mediatype, self.genre)
class TVShow(AudioVisual):
def __init__(self, title, mediatype, genre, seasons, epruntime, rating):
super().__init__(title, mediatype, genre)
self.seasons = seasons
self.epruntime = epruntime
self.rating = rating
def report(self):
return super().report() + "\nNumber of Seasons: {}\nEpisode Length: {}\nRating: {}".format(self.seasons, self.epruntime, self.rating)
class Movie(AudioVisual):
def __init__(self, title, mediatype, genre, runtime, sequels, rating):
super().__init__(title, mediatype, genre)
self.runtime = runtime
self.sequels = sequels
self.rating = rating
def report(self):
return super().report() + "\nRuntime: {}\nSequels: {}\nRating: {}".format(self.runtime, self.sequels, self.rating)
class Music(AudioVisual):
def __init__(self, title, mediatype, genre, length, artist, numbalbums):
super().__init__(title, mediatype, genre)
self.length = length
self.artist = artist
self.numbalbums = numbalbums
def report(self):
return super().report() + "\nAlbum Length: {}\nArtist: {}\nNumber of Albums by {}: {}".format(self.length, self.artist, self.artist, self.numbalbums)
class UnitTest(unittest.TestCase):
def test_audiovisual(self):
result = Movie("The Princess Bride", "DVD", "Fantasy", "98 min", "", "PG").report()
self.assertEqual(result, "Title: The Princess Bride\nMedia Type: DVD\nGenre: Fantasy\nRuntime: 98 min\nSequels: \nRating: PG")
result = TVShow("Parks and Recreation", "Netflix", "Comedy", "7", "42 min", "PG").report()
self.assertEqual(result, "Title: Parks and Recreation\nMedia Type: Netflix\nGenre: Comedy\nNumber of Seasons: 7\nEpisode Length: 42 min\nRating: PG")
if __name__ == "__main__":
unittest.main() |
af93b3f45475abfc980bd53f5af21f5d4ad7c98b | cnovoab/coding-interview | /udemy-11/2.array_common_elements.py | 534 | 3.890625 | 4 | #!/bin/python
def common_items(alist, blist):
common = []
n = 0
m = 0
while(n < len(alist) and m < len(blist)):
if alist[n] == blist[m]:
common.append(alist[n])
m += 1
n += 1
elif alist[n] > blist[m]:
m += 1
else:
n += 1
return common
if __name__ == "__main__":
testa = [1, 3, 7, 34, 35]
testb = [1, 2, 5, 7, 9, 35]
print "Common elements between {} and {} are: {}".format(testa, testb, common_items(testa, testb))
|
e5585a7907884e4fc26f55245f3d317d96cc364f | cnovoab/coding-interview | /udemy-11/7.minesweeper_expand.py | 643 | 3.734375 | 4 | #!/bin/python
def click(board, rows, cols, click_x, click_y):
board = [[0 for col in range(cols)] for row in range(rows)]
for bomb in bombs:
(x, y) = bomb
print "({}, {})".format(x, y)
board[x][y] = -1
for i in range(x -1, x + 2):
for j in range(y - 1, y + 2):
if 0 <= i < rows and 0 <= j < cols and board[i][j] != -1:
board[i][j] += 1
return board
if __name__ == "__main__":
# bombs = [[3, 0], [1, 4]]
bombs = [[3, 0], [3, 1], [4, 1], [1, 4]]
ms = mine_sweeper(bombs, 5, 6)
print "Minesweeper:"
for row in ms:
print row
|
3181d2f1bbd8f21aafc45e9419d43f8d01491126 | cnovoab/coding-interview | /udemy-11/8.rotate_array_aux.py | 606 | 4.03125 | 4 | #!/bin/python
def rotate_array(a, n):
a2 = [[None for i in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
i2 = j
j2 = n - i - 1
a2[i2][j2] = a[i][j]
return a2
if __name__ == "__main__":
test = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
print "Original:"
for row in test:
print row
rotated_array = rotate_array(test, len(test))
print "Rotated:"
for row in rotated_array:
print row
|
9d962bf277fd03145643a05bee7804563309e38b | kd5278fi/UnitTst | /Calculate.py | 404 | 3.96875 | 4 | def is_tens(number):
"""
Return true if the number is a multiple of 10
"""
if number % 10 != 0:
#print ("False")
return False
#print ("True")
return True
def next_tens(number):
"""
Finds the next highest number by ten
"""
index = number
while True:
index += 1
if is_tens(index):
print (index)
break
|
ca138f087a7cdadb84ea054df8fff44596fc265d | AdishiSood/The-Joy-of-Computing-using-Python | /Week 4/Factorial.py | 285 | 4.28125 | 4 | """
Given an integer number n, you have to print the factorial of this number.
Input Format:
A number n.
Output Format:
Print the factorial of n.
Example:
Input:
4
Output:
24
"""
k = int(input())
fac = 1
for i in range(1,k+1):
if(k==0):
break
fac=fac*i
print(fac)
|
76651f9226b584f4a7a0dfe0f1ceeb338ba0e2ae | AdishiSood/The-Joy-of-Computing-using-Python | /Week 12/Sentence.py | 807 | 4.21875 | 4 | """
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalised.
Input Format:
The first line of the input contains a number n which represents the number of line.
From second line there are statements which has to be converted. Each statement comes in a new line.
Output Format:
Print statements with each word in capital letters.
Example:
Input:
2
Hello world
Practice makes perfect
Output:
HELLO WORLD
PRACTICE MAKES PERFECT
"""
n=int(input())
for i in range(n):
print(input().upper(),end="")
if i!=n-1:
print()
or
lines = []
n = int(input())
for i in range(n):
s = input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print(sentence)
|
82401ab5f1d228c0312819a08859994363fdce4f | AdishiSood/The-Joy-of-Computing-using-Python | /Week 9/First and Last.py | 470 | 4.21875 | 4 | """
Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
Input Format:
The first line of the input contains the String S.
Output Format:
The first line of the output contains the modified string.
Sample Input:
Programming
Sample Output:
Prng
"""
s=input()
output=""
if(len(s)<2):
print("",end="")
else:
print(s[0:2]+s[-2:-1]+s[-1],end="")
|
8eb64625c46daa0a9254448f38a67a9a83088d07 | Luv8436/Programming | /python codes/rename_file.py | 498 | 3.625 | 4 | import os
#taking file names and saves into the list
def rename_files():
file_list=os.listdir(r"C:\Users\luvku\CS 2019\prank\prank")
#print(file_list)
saved_path=os.getcwd()
print("Current working directory is =" +saved_path)
os.chdir(r"C:\Users\luvku\CS 2019\prank\prank")
#rename file in the directory one by one
for file_name in file_list:
os.rename(file_name,file_name.translate({ord(c):'' for c in "1234567890"}))
os.chdir(saved_path)
rename_files()
|
da01edc64d3846f6611f60e533704cad8c871441 | Panchofdez/Minigames | /Pong/Pong.py | 2,388 | 3.671875 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
#Score
player_a_score= 0
player_b_score = 0
#Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0) #speed of animation, sets to max speed
paddle_a.shape("square")
paddle_a.penup()
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.goto(-350, 0)
#Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.penup()
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.goto(350, 0)
#Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.penup()
ball.color("white")
ball.goto(0, 0)
ball.dx = 0.3
ball.dy= 0.3
#Pen
pen =turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write(f"PlayerA :{player_a_score} PlayerB:{player_b_score}", align="center", font=("Courier", 24 , "normal"))
#Functions
def paddle_a_up():
y=paddle_a.ycor()
y+=20
paddle_a.sety(y)
def paddle_a_down():
y=paddle_a.ycor()
y-=20
paddle_a.sety(y)
def paddle_b_up():
y=paddle_b.ycor()
y+=20
paddle_b.sety(y)
def paddle_b_down():
y=paddle_b.ycor()
y-=20
paddle_b.sety(y)
#Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
#Main game loop
while True:
wn.update()
#Move the ball
ball.setx(ball.xcor()+ball.dx)
ball.sety(ball.ycor()+ball.dy)
if ball.ycor() >= 290:
ball.sety(290)
ball.dy *=-1
if ball.ycor() <= -290:
ball.sety(-290)
ball.dy *=-1
if ball.xcor()>390:
ball.goto(0,0)
ball.dx *=-1
player_a_score+=1
pen.clear()
pen.write(f"PlayerA :{player_a_score} PlayerB:{player_b_score}", align="center", font=("Courier", 24 , "normal"))
if ball.xcor()<-390:
ball.goto(0,0)
ball.dx *=-1
player_b_score+=1
pen.clear()
pen.write(f"PlayerA :{player_a_score} PlayerB:{player_b_score}", align="center", font=("Courier", 24 , "normal"))
#Paddle and Ball collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor()+50 and ball.ycor() > paddle_b.ycor() -50):
ball.setx(340)
ball.dx*=-1
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor()+50 and ball.ycor() > paddle_a.ycor() -50):
ball.setx(-340)
ball.dx*=-1 |
628cf91b1d6030837b5b4f89aeb06b01f9842fde | SachinDevelopment/AQclone | /Player.py | 2,949 | 3.609375 | 4 | import sys
import pygame
from time import sleep
#Sample class for sample.py
class Player(object):
def __init__(self):
self.image = pygame.image.load("Images\Artixv2.png")
self.x = 10
self.y = 390
self.isJumping = 0
self.velocity = 8
self.mass = 2
self.health = 100
#added due to jump method taking away from velocity stopping player movement while in the air
self.speed = abs(self.velocity)
#hitbox
self.rect = self.image.get_rect()
self.rect.left = self.x
self.rect.top = self.y
def handleInput(self):
#print('trying to move player')
key = pygame.key.get_pressed()
if key[pygame.K_a]:
print('moving left')
self.x-=self.speed
if key[pygame.K_d]:
print('moving right')
self.x+=self.speed
if key[pygame.K_SPACE]:
print('moving up')
self.isJumping = 1
self.updateHitbox()
#check if player is already in a jump
self.playerJump()
def playerJump(self):
#calc force
#print('jump method initiated')
if self.isJumping:
if self.velocity > 0:
force = (.5 * self.mass * self.velocity**2)
else:
force = -(.5 * self.mass * self.velocity**2)
#change pos
self.y-=force
#change velocity
self.velocity-=1
print(self.velocity)
#Checking is ground has been reached
if(self.y >= 390):
self.isJumping = 0
self.velocity = 8
print('jump set to 0')
#print(self.x,self.y)
#update hitbox
def updateHitbox(self):
self.rect.left = self.x
self.rect.top = self.y
def draw(self, surface):
surface.blit(self.image, (self.x,self.y))
self.draw_health()
def takeDamage(self):
self.health-=10
def draw_health(self):
print(self.health)
blue = (0,0,255)
width = int(self.rect.width * (self.health / 100))
self.health_bar = pygame.Rect(0, 0, width, 7)
if self.health == 100:
pygame.draw.rect(self.image, (0,255,0), self.health_bar)
elif (self.health < 100 and self.health > 0):
print('hello')
# self.health_bar = pygame.Rect(self.x, self.y, self.rect.width, 7)
# pygame.draw.rect(self.image,(255,0,0) , self.health_bar)
# self.health_bar = pygame.Rect(0, 0, width, 7)
# pygame.draw.rect(self.image,(0,255,0) , self.health_bar)
else:
self.health_bar = pygame.Rect(self.x, self.y, self.rect.width, 7)
pygame.draw.rect(self.image,(255,0,0) , self.health_bar)
# if self.health < 100:
#pygame.draw.rect(self.image, red, self.health_bar)
|
8ae1fdd34726473c458e248c6cddadbfce0cf585 | biiakovnv/amis_python | /km73/Biiakov _Nikita/3/Task_3.py | 67 | 3.53125 | 4 | print("What is your name?")
name=(input())
print("Hello,",name)
|
30308952b2c2948f42492e1b7389081dad07c29f | nobleator/ims-microservices | /optimizer/cvrp.py | 15,627 | 3.59375 | 4 | """
Route optimizer
Capacitated Vehicle Routing Problem
Route Scheduling Model/Module
Branch and bound for integer optimization
Sub-problems solved using scipy:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html
"""
import numpy as np
from scipy.optimize import linprog
import random as rnd
from typing import Dict
class Delivery:
def __init__(self, delivery_id: str, location: tuple, profit: float = None, size: float = None):
self.id = delivery_id
self.location = location
self.profit = profit
self.size = size
class Truck:
def __init__(self, truck_id: str, capacity: float, per_mile_cost: float, max_dist: float):
self.id = truck_id
self.capacity = capacity
self.per_mile_cost = per_mile_cost
self.max_dist = max_dist
class CVRP:
def __init__(self, depot_location: tuple, trucks: list, deliveries: list):
"""Initializes the model for use with scipy.optimize.linprog and generates text formulation.
Model should follow the format:
min
c @ x
such that
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
d0 represents the depot.
Could add a dummy/slack truck with no profit for skipping deliveries.
"""
self.depot_location = depot_location
self.trucks = trucks
self.deliveries = deliveries
# Map variable name to index in array for translation between text and matrix formats
self.var_to_index = {}
self.index_to_var = {}
index = 0
for t in trucks:
for d1 in deliveries:
var = f"route_{t.id}_d0_{d1.id}"
if var not in self.var_to_index:
self.var_to_index[var] = index
self.index_to_var[index] = var
index += 1
var = f"route_{t.id}_{d1.id}_d0"
if var not in self.var_to_index:
self.var_to_index[var] = index
self.index_to_var[index] = var
index += 1
for d2 in deliveries:
if d1.id == d2.id:
continue
var = f"route_{t.id}_{d1.id}_{d2.id}"
if var not in self.var_to_index:
self.var_to_index[var] = index
self.index_to_var[index] = var
index += 1
var = f"route_{t.id}_{d2.id}_{d1.id}"
if var not in self.var_to_index:
self.var_to_index[var] = index
self.index_to_var[index] = var
index += 1
self.max_index = max(self.index_to_var) + 1
# TODO: Pre-calculate number of constraints to more efficiently initialize arrays?
self.c = np.zeros(self.max_index)
self.A_ub = None
self.A_eq = None
# self.x_0 = np.zeros(self.max_index)
self.b_ub = None
self.b_eq = None
self.bounds = [(0, 1) for _ in range(self.max_index)]
self.result = None
self.mip_result = None
def init_all(self):
"""Initializes all the default constraints and bounds.
Override this with MIP constraints if needed.
"""
self.obj_func()
self.cons_capacity()
self.cons_max_dist()
self.cons_node_balanced_flow()
self.cons_node_arrivals()
self.cons_node_departures()
self.cons_start_at_depot()
self.cons_end_at_depot()
self.vars_bounds()
def solve(self):
"""Solve the MIP CVRP model
Uses a branch-and-bound technique and the Scipy.optimize solver to solve relaxed problems.
15 nodes, 10 test runs:
argmin + BFS: 2.656984043121338s
(current) argmin + DFS: 2.5454505443573s
argmax + BFS: 2.6716614723205567s
argmax + DFS: 2.579980564117432s
Note: BFS may be a better choice if parallelization is possible.
"""
ctr = 0
curr_best = float("inf")
# TODO: Better starting node selection
queue = [{0: 0}, {0: 1}]
while len(queue) > 0:
# Using .append and .pop() makes this LIFO, DFS
# Using .append and .pop(0) makes this FIFO, BFS
node = queue.pop()
self.vars_bounds(node)
self.run_linprog()
ctr += 1
# If a relaxed solution is worse than the current best, skip that branch.
if self.result.success and self.result.status == 0 and self.result.fun < curr_best:
# If feasible and integral and better than curr_best, set new curr_best and enqueue children
if all_integral(self.result.x):
curr_best = self.result.fun
self.mip_result = self.result
# If feasible and non-integer and better than curr_best, enqueue children
next_node = self.get_next_node()
for b in [0, 1]:
node[next_node] = b
queue.append(node)
# TODO: Add verbose mode?
# print(f"{ctr} nodes evaluated. Best solution: {curr_best}")
if self.mip_result is None:
print("No integer solution found")
def get_next_node(self):
"""Heuristic for getting the next node in branch-and-bound algorithm.
If a result exists, select the variable closest to 0.
Could also select closest to 1?
If no result exists yet, randomly select one that isn't already set.
"""
if self.result.x.any():
return np.argmin(self.result.x)
else:
eligible_indices = [k for k, v in enumerate(self.bounds) if v[0] != v[1]]
return rnd.choice(eligible_indices)
def run_linprog(self):
self.result = linprog(c=self.c, A_ub=self.A_ub, b_ub=self.b_ub,
A_eq=self.A_eq, b_eq=self.b_eq, bounds=self.bounds)
def add_to_ub(self, arr, rhs):
"""Add the given array and right-hand-side values to the upper constraints
"""
if self.A_ub is None:
self.A_ub = np.array(arr)
else:
self.A_ub = np.vstack((self.A_ub, arr))
if self.b_ub is None:
self.b_ub = np.array(rhs)
else:
self.b_ub = np.append(self.b_ub, rhs)
def add_to_eq(self, arr, rhs):
"""Add the given array and right-hand-side values to the equality constraints
"""
if self.A_eq is None:
self.A_eq = np.array(arr)
else:
self.A_eq = np.vstack((self.A_eq, arr))
if self.b_eq is None:
self.b_eq = np.array(rhs)
else:
self.b_eq = np.append(self.b_eq, rhs)
def obj_func(self):
"""Generates the objective function and visualization for the model
min route_t_d1_d2 * per_mile_cost_t * dist_d1_d2 - route_t_d0_d * profit_d
"""
# Cost per route
for t in self.trucks:
# Depot-specific routes
for d in self.deliveries:
dist = get_euclidean_dist(self.depot_location, d.location)
var = f"route_{t.id}_d0_{d.id}"
# If the product is loaded at the depot get credit for the delivery?
self.c[self.var_to_index[var]] = (t.per_mile_cost * dist) - d.profit
# Handle returns to the depot
var = f"route_{t.id}_{d.id}_d0"
self.c[self.var_to_index[var]] = t.per_mile_cost * dist
# Site-to-site routes
for d1 in self.deliveries:
for d2 in self.deliveries:
if d1.id == d2.id:
continue
dist = get_euclidean_dist(d1.location, d2.location)
var = f"route_{t.id}_{d1.id}_{d2.id}"
# print(f"var: {var}, d2.profit: {d2.profit}")
self.c[self.var_to_index[var]] = (t.per_mile_cost * dist) - d2.profit
def cons_capacity(self):
"""Capacity constraint
sum_d2(route_t_d1_d2 * size_d2) <= capacity_t, for t in trucks, d1, d2 in deliveries
"""
for t in self.trucks:
arr = np.zeros(self.max_index)
for d2 in self.deliveries:
var = f"route_{t.id}_d0_{d2.id}"
arr[self.var_to_index[var]] = d2.size
for d1 in self.deliveries:
if d1.id == d2.id:
continue
var = f"route_{t.id}_{d1.id}_{d2.id}"
arr[self.var_to_index[var]] = d2.size
self.add_to_ub(arr, t.capacity)
def cons_max_dist(self):
"""Maximum distance constraint
sum_d1_d2(route_t_d1_d2 * dist_d1_d2) <= max_dist_t, for t in trucks
"""
arr = np.zeros(self.max_index)
for t in self.trucks:
for d1 in self.deliveries:
dist = get_euclidean_dist(self.depot_location, d1.location)
var = f"route_{t.id}_d0_{d1.id}"
arr[self.var_to_index[var]] = dist
dist = get_euclidean_dist(d1.location, self.depot_location)
var = f"route_{t.id}_{d1.id}_d0"
arr[self.var_to_index[var]] = dist
for d2 in self.deliveries:
if d1.id == d2.id:
continue
dist = get_euclidean_dist(d1.location, d2.location)
var = f"route_{t.id}_{d1.id}_{d2.id}"
arr[self.var_to_index[var]] = dist
self.add_to_ub(arr, t.max_dist)
def cons_node_balanced_flow(self):
"""Arrivals at a node must have a corresponding departure (but the node can be skipped)
sum_d2(route_t_d2_d) - sum_d2(route_t_d_d2) = 0, for t in trucks, for d in deliveries
Using this in conjunction with arrival and departure specific constraints.
The TSP constraints would be:
Arrivals to a node must come from another node
sum_d2(route_t_d2_d) = 1, for t in trucks, for d in deliveries
Departures from a node must go to another node
sum_d2(route_t_d_d2) = 1, for t in trucks, for d in deliveries
"""
for t in self.trucks:
for d1 in self.deliveries:
arr = np.zeros(self.max_index)
var = f"route_{t.id}_{d1.id}_d0"
arr[self.var_to_index[var]] = 1
for d2 in self.deliveries:
if d1.id == d2.id:
continue
var = f"route_{t.id}_{d1.id}_{d2.id}"
arr[self.var_to_index[var]] = 1
var = f"route_{t.id}_d0_{d1.id}"
arr[self.var_to_index[var]] = -1
for d2 in self.deliveries:
if d1.id == d2.id:
continue
var = f"route_{t.id}_{d2.id}_{d1.id}"
arr[self.var_to_index[var]] = -1
self.add_to_eq(arr, 0)
def cons_node_arrivals(self):
"""Arrivals to a node must come from another node, or the node is skipped
sum_d2(route_t_d2_d) <= 1, for t in trucks, for d in deliveries
"""
for t in self.trucks:
for d1 in self.deliveries:
arr = np.zeros(self.max_index)
var = f"route_{t.id}_d0_{d1.id}"
arr[self.var_to_index[var]] = 1
for d2 in self.deliveries:
if d1.id == d2.id:
continue
var = f"route_{t.id}_{d2.id}_{d1.id}"
arr[self.var_to_index[var]] = 1
self.add_to_ub(arr, 1)
def cons_node_departures(self):
"""Departures from a node must go to another node
sum_d2(route_t_d_d2) <= 1, for t in trucks, for d in deliveries
"""
for t in self.trucks:
for d1 in self.deliveries:
arr = np.zeros(self.max_index)
var = f"route_{t.id}_{d1.id}_d0"
arr[self.var_to_index[var]] = 1
for d2 in self.deliveries:
if d1.id == d2.id:
continue
var = f"route_{t.id}_{d1.id}_{d2.id}"
arr[self.var_to_index[var]] = 1
self.add_to_ub(arr, 1)
def cons_start_at_depot(self):
"""Every route must start at the depot
sum_d(route_t_d0_d) = 1, for t in trucks
"""
arr = np.zeros(self.max_index)
for t in self.trucks:
for d in self.deliveries:
var = f"route_{t.id}_d0_{d.id}"
arr[self.var_to_index[var]] = 1
self.add_to_eq(arr, 1)
def cons_end_at_depot(self):
"""Every route must end at the depot
sum_d(route_t_d_d0) = 1, for t in trucks
"""
arr = np.zeros(self.max_index)
for t in self.trucks:
for d in self.deliveries:
var = f"route_{t.id}_{d.id}_d0"
arr[self.var_to_index[var]] = 1
self.add_to_eq(arr, 1)
def vars_bounds(self, bounds: Dict[int, int] = dict()):
"""Variable bounds
Set default binary bounds if no input is given, just 0 <= route_t_d1_d2 <= 1
Otherwise, set incoming bounds.
bounds parameter keys should be indices of the variable they are setting, and value of 0 or 1 for the new bound
Unset variables use the default (0, 1) bounds.
"""
# Reset default bounds before modifying with incoming dict
self.bounds = [(0, 1) for _ in range(self.max_index)]
for k, v in bounds.items():
self.bounds[k] = (v, v)
def viz_model(self) -> str:
output = ["########## Optimization formulation ##########", "min"]
# Objective function
for col_indx, val in enumerate(self.c):
temp = f" + ({val}) * {self.index_to_var[col_indx]}"
output.append(temp)
output.append("s.t.")
# Upper constraints
for row_indx, row in enumerate(self.A_ub):
temp = ""
for col_indx, val in enumerate(row):
if val == 1:
temp += f" + {self.index_to_var[col_indx]}"
temp += f" <= {self.b_ub[row_indx]}"
output.append(temp)
# Equality constraints
for row_indx, row in enumerate(self.A_eq):
temp = ""
for col_indx, val in enumerate(row):
if val == 1:
temp += f" + {self.index_to_var[col_indx]}"
temp += f" = {self.b_eq[row_indx]}"
output.append(temp)
# Variable bounds
return "\n".join(output)
def get_euclidean_dist(point1: tuple, point2: tuple):
"""Calculates the Euclidean distance between 2 points (tuples)
Eventually will replace this with a street-based distances calculation.
"""
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
def all_integral(result):
return all(x % 1 == 0 for x in result)
if __name__ == "__main__":
print("See main.py for an example of how to run this optimizer") |
c61b0532d7fe7e3ae92bc25a41e9e1ff10cee46b | lplade/lmn | /eventful_data/read_json_file.py | 2,476 | 3.625 | 4 | import json
class Venues():
''' Gets the venues information, from the name to the location or urls'''
def __init__(self, venue_id, venue_name, city_name, state, venue_address, venue_url, performer_name = None):
self.venue_id = venue_id
self.venue_name = venue_name
self.city_name = city_name
self.state = state
self.venue_address = venue_address
self.url = venue_url
self.performer_name = performer_name
def get_venues_data():
# Open the file that hold the json data.
with open('MN_venues_data.json', mode='r') as f:
try:
s = json.load(f)
except Exception as e:
print('Problem loading file', e)
# This line is to pull items on the event list only.
raw_event_list = s['events']
venues_list = []
# This is a good code to get just the name that we want.
for venue in raw_event_list['event']:
# This is to see if name is in the list first.
# if venue['venue_name'] == 'First Avenue':
if venue['performers'] != None:
venue_perfomers = venue['performers']['performer']
if isinstance(venue_perfomers, dict):
# Wrap in a list
venue_perfomers = [venue_perfomers]
# Now loop in the new list format
for inside_performer in venue_perfomers:
# This will store the name on the list of items for Venues.
venues_data = Venues(venue_id = str(venue['venue_id']), venue_name = str(venue['venue_name']), city_name = str(venue['city_name']), state = str(venue['region_name']), venue_address = str(venue['venue_address']), venue_url = str(venue['venue_url']), performer_name = str(inside_performer['name']))
else:
# This is to make sure that dosen't get a duplicate.
venues_data = Venues(venue_id = str(venue['venue_id']), venue_name = str(venue['venue_name']), city_name = str(venue['city_name']), state = str(venue['region_name']), venue_address = str(venue['venue_address']), venue_url = str(venue['venue_url']))
venues_list.append(venues_data)
return venues_list
def main():
# Create an instance to print the list.
venue_list = get_venues_data()
for venue in venue_list: # Run the script to see the results.
print('{} {} performer : {}'.format(venue.venue_name, venue.venue_id, venue.performer_name))
if __name__ == '__main__':
main()
|
96e6ba6a7d2fadfa50c06881f4c30514b1644678 | perchrib/masters_thesis | /preprocessors/language_detection.py | 986 | 3.53125 | 4 | import langdetect as ld
ENGLISH = 'en'
SPANISH = 'es'
GERMAN = 'de'
DUTCH = 'nl'
def detect_language(text, language=SPANISH, ret_conf=False):
"""
Uses langdetect to detect a language in text. Spanish by default
:param text: text to analyze
:param language: language to detect
:param ret_conf: return dict of language confidences or not
:return:
"""
try:
detections = ld.detect_langs(text)
confidences = {lang_obj.lang: lang_obj.prob for lang_obj in detections}
if language in confidences and confidences[language] > 0.9:
# print(text)
if not ret_conf:
return True
elif ret_conf:
return confidences
else:
return False
except Exception:
# print("No language detected - Probably URL")
return False
if __name__ == '__main__':
# Num trials
for i in range(10):
print(detect_language("Ik ben voor", ret_conf=True)) |
eaa288238495b0d4ae55f33571876dcd2c9f774e | don1291/Python | /km.py | 179 | 4.1875 | 4 |
def main():
km = float(input("Enter the distances in km: "))
miles = convert(km)
print(miles)
def convert(km):
miles = km * 0.6214
return miles
main()
|
a4049d840d56402f7482d1ccb64a2f7d35b1b3a6 | don1291/Python | /Land.py | 158 | 3.8125 | 4 | #Land Calculation
#Program calculate square feet to arce
sqft = input("Enter the square feet tract in land:")
land_size = int(sqft) / 43560
print (land_size)
|
65ea608d7f8a1b8f1b5054c9a98b51cd93738d97 | CShariff4/Programming-308 | /Acutal Programs/war2.py | 2,591 | 3.515625 | 4 | import random
from random import shuffle
#deck attributes
SUITS = ['H', 'D', 'S', 'C']
FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
DECK = [f + s for f in FACES for s in SUITS]
VALUE = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))
class WarCardGame:
## start card game War
def __init__(self):
deck = DECK.copy()
shuffle(deck)
self.deck1, self.deck2 = deck[:26], deck[26:]
self.pending = []
def flip(self):
##one card turn
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()
##user input to advance hands
userin = input("Press enter to see next hand:")
if userin.lower() == str(f"h"):
print(f'continue')
self.flip
##quit game early
elif userin.lower() == str(f"quit"):
print(f'Game eneded')
exit()
card1, card2 = self.deck1.pop(0), self.deck2.pop(0)
stregnth1, stregnth2 = VALUE[card1], VALUE[card2]
print("{:10}{:10}".format(card1, card2), end='')
if stregnth1 > stregnth2:
print('Player 1 takes the cards.')
self.deck1.extend([card1, card2])
self.deck1.extend(self.pending)
self.pending = []
account123 = int(len(self.deck1))
print ("Player 1 has ",account123, "cards now" )
elif stregnth1 < stregnth2:
print('The computer takes the cards.')
self.deck2.extend([card2, card1])
self.deck2.extend(self.pending)
self.pending = []
account223 = int(len(self.deck2))
print ("The computer has ",account223, "cards now" )
else: ##if cards are a tie
print('Tie!')
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()
card3, card4 = self.deck1.pop(0), self.deck2.pop(0)
self.pending.extend([card1, card2, card3, card4])
print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='')
return self.flip()
return True
def gameover(self):
##who won/end of game message
if len(self.deck2) == 0:
if len(self.deck1) == 0:
print('\nGame ends as a tie.')
else:
print('\nPlayer 1 wins the game.')
else:
print('\nComputer wins the game.')
return False
if __name__ == '__main__':
CD = WarCardGame()
while CD.flip():
continue |
b3bdc75c4be056248adef5615f3a484624775404 | nayudujahnavi/guvi23 | /four.py | 101 | 3.953125 | 4 | ch=input('')
if((ch >='a' and ch<='z') or (ch >='a' and ch<='z')):
print(alphabet)
else:
print("no")
|
047178a4533d3b9a24cb3b6ed24910cca6b308ed | nayudujahnavi/guvi23 | /21.py | 150 | 3.640625 | 4 | def sumofAP(a,d,n)
sum=0
i=0
while i<n:
sum =sum+a
a=a+d
i=i+1
return sum
n=int(input(" "))
a=int(input(" "))
d=int(input(" "))
print(sumOFAP(a,d,n))
|
16db59ddfa2af4ad84aa8efeec3199aedf0cbba0 | JoyceWill/LearnPython | /coxu/Task15.py | 389 | 3.625 | 4 | from itertools import groupby
lines = '''
This is the
first paragraph.
This is the second.
'''.splitlines() #splitlines break line into list of string
# accourding to the /n line breaker
#Use intertools.groupby and bool to treturn group of
#condecutive lines that either have content or don't.
for has_chars, frags in groupby(lines,bool):
if has_chars:
print ' '.join(frags) |
9ed78163f19835094bc94281b4dbc37e6c015c5c | imapersonman/henri-variables | /henri_2_9_21.py | 2,263 | 3.8125 | 4 | from Question import Question
from Expression import Int, Plus, Equals, Var, Minus
def check_sub_q(a):
return a.interpret() == True
questions = [
Question("If a = 1, what is another way of writing 'b'?", lambda a: a == Var("b")),
Question("If x = 3, what is another way of writing 'x + y?'", lambda a: a == Plus(Int(3), Var("y"))),
Question("Use substitute to make '11 + a = 17' True // copy-paste Equals(Plus(Int(11), Var(\"a\")), Int(17))", check_sub_q),
Question("Use substitute and Minus to make '44 - b = 20' True // copy-paste Equals(Minus(Int(44), Var(\"b\")), Int(20))", check_sub_q),
Question("Use substitute to make '30 + 50 = x' True // copy-paste Equals(Plus(Int(30), Int(50)), Var(\"x\"))", check_sub_q),
Question("Use substitute to make 'y - 7 = 33' True // copy-paste Equals(Minus(Var(\"y\"), Int(7)), Int(33))", check_sub_q),
Question("Use substitute to make 'n + 50 = 140' True // copy-paste Equals(Plus(Var(\"n\"), Int(50)), Int(140))", check_sub_q),
Question("Use substitute to make '11 + m = 31' True // copy-paste Equals(Plus(Int(11), Var(\"m\")), Int(31))", check_sub_q),
Question("Use substitute to make 'p - 7 = 23' True // copy-paste Equals(Minus(Var(\"p\"), Int(7)), Int(23))", check_sub_q),
Question("Use substitute to make '70 - n = 20' True // copy-paste Equals(Minus(Int(70), Var(\"n\")), Int(20))", check_sub_q)
]
class QuestionMachine:
def __init__(self, questions):
self.questions = questions
self.current_index = 0
def ask(self):
if self.current_index >= len(self.questions):
return "You're done! Congratulations!"
return self.questions[self.current_index]
def answer(self, answer):
if self.current_index >= len(self.questions):
print("No more questions!")
question = self.questions[self.current_index]
response_prefix = "Question: {}\nAnswer: {}\n".format(self.questions[self.current_index], answer)
if (question.check_answer(answer)):
self.current_index += 1
print("{}Correct!".format(response_prefix))
print("\nNext Question: {}".format(self.ask()))
else:
print("{}Incorrect. Try again.".format(response_prefix)) |
7f65cc8534cac8140b20dd82ec74c292af35084d | imapersonman/henri-variables | /henri_3_18_21.py | 1,874 | 4.09375 | 4 | from Question import Question
from Expression import Int, Plus, Equals, Var, Minus, Times, Negative
documentation = [
"expr.to_pos_neg(): If expr looks like 'a - b', it is converted to 'a + -b'",
"expr.pos_neg_to_minus(): If expr looks like 'a + -b', it is converted to 'a - b'",
"expr.associate_l_to_r(): If expr looks like '(a + b) + c', it is converted to 'a + (b + c)'. You can replace '+' with '*'.",
"expr.associate_r_to_l(): Converts an expression that looks like 'a + (b + c)' to '(a + b) + c'. You can replace '+' with '*'",
"expr.rw_se(sub_expr, equal_expr): Rewrites every expression equal to subexpr inside of expr to equal_expr, but only if equal_expr means the same thing as sub_expr.",
"expr.commute(): If expr looks like 'a + b', it is converted to 'b + a'. You can replace '+' with '*'"
]
def check_answer(a0):
return lambda a: a == a0
def conv_q(expr1_str, expr2_str, af):
return Question("Convert the expression '{}' to '{}'".format(expr1_str, expr2_str), af)
questions = [
#conv_q("1 + (2 + 3)", "1 + (3 + 2)", check_answer(Plus(Int(1), Plus(Int(3), Int(2))))),
#conv_q("(2 * 3) * a", "(c * b) * a", check_answer(Times(Times(Var("c"), Var("b")), Var("a")))),
conv_q("(1 * 2) + (2 * 3)", "(2 * 1) + (3 * 2)", check_answer(Plus(Times(Int(2), Int(1)), Times(Int(3), Int(2))))),
conv_q("1 + ((2 + 3) + 4)", "1 + ((3 + 4) + 2)", check_answer(Plus(Int(1), Plus(Plus(Int(3), Int(4)), Int(2))))),
conv_q("(1 - 3) - 2", "(1 - 2) - 3", check_answer(Minus(Minus(Int(1), Int(2)), Int(3)))),
conv_q("1 + (2 + 3)", "3 + (2 + 1)", check_answer(Plus(Int(3), Plus(Int(2), Int(1))))),
conv_q("(-3 - 2) - 1", "(-1 - 2) - 3", check_answer(Minus(Minus(Negative(Int(1)), Int(2)), Int(3)))),
conv_q("1 + (2 + (3 + 4))", "4 + (3 + (2 + 1))", check_answer(Plus(Int(4), Plus(Int(3), Plus(Int(2), Int(1))))))
] |
723a42eb6e074fe0aa54a77a9532334c8afb95dd | rohanaggarwal7997/Studies | /Python/loop.py | 699 | 3.875 | 4 | import random
import sys
import os
'''
for x in range(0,10): #end at 9
print(x,' ',end="")
lis=['a','b','c','d']
for y in lis: #browse through entire list
print (y)
num_list=[[1,2,3],[10,20,30],[4,5,6]] #create list of lists
for x in range(0,3):
for y in num_list[x]:#do same indentation at each place
print(y) #browse through list
for x in range(0,3):
for y in range(0,len(num_list[x])):
print(num_list[x][y])
random_num =random.randrange(0,100) #to get a random number
while(random_num!=15):
print(random_num)
random_num=random.randrange(0,100)
i=0;
while(i<=20):
if(i%2==0):
print(i)
elif(i==9):
break #same as c++
else:
i+=1
continue #same as c++
i+=1
...
|
39adbf633463303ae3395d0f67a349497f293c68 | rohanaggarwal7997/Studies | /Python new/finding most frequent words in a list.py | 337 | 4.125 | 4 | from collections import Counter
text='''
dfkjskjefisej tjeistj isejt isejt iseotjeis tiset iesjt iejtes
est isjti esties hesiuhea iurhaur aurhuawh ruahwruawhra u
njra awurhwauirh uawirhuwar huawrh uawrhuaw
ajiawj eiwhaeiaowhe awhewai hiawe
'''
words=text.split()
counter=Counter(words)
print(counter.most_common(3)) #returns tuple |
e916cfd5c36631ca073f6261eca2d863c858124f | rohanaggarwal7997/Studies | /Python new/if for range while and comments Break and Continue.py | 621 | 3.90625 | 4 | name='rohan aggarwal'
if name is 'rohan':
print('You are great')
elif name is 'rohan aggarwal':
print('You are also great')
else:
print('You might be great')
numb=[1,2,3,4,5]
for f in numb[:2]:
print(f)
print('\n')
#:2 is very important
#range --very important
for x in range(5,12): #means 0to 10 if only 1 number start from 0
print('x is right now',x)
for x in range(6,12,2):
print('y is right now',x)
if x==8:
continue
z=1
while z<10:
print('z is right now',z)
z+=1
if z==5:
break
'''
Long range comment
'''
# checking if a number is in a list if n in list_name |
39d722a3749955b2946925e869613350400c2fa0 | thebrutus314/Alarm-clock | /alarm_clock.py | 3,243 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import strftime
from time import sleep
import os
print("Alarm clock")
print("Codet by @thebrutus314")
try:
# Tkinter for Python 2.xx
import Tkinter as tk
except ImportError:
# Tkinter for Python 3.xx
import tkinter as tk
APP_TITLE = "Alarm clock in Python by thebrutus314"
APP_XPOS = 100
APP_YPOS = 100
APP_WIDTH = 300
APP_HEIGHT = 200
LABEL_01_FONT = ('Helevtica', 14, 'bold')
LABEL_BG = 'light blue'
LABEL_ALARM_BG = 'red'
class Application(tk.Frame):
def __init__(self, master):
self.master = master
tk.Frame.__init__(self, master)
self.act_time_var = tk.StringVar()
tk.Label(self, textvariable=self.act_time_var, font=LABEL_01_FONT,
fg='green').pack()
label_frame = tk.Frame(self, bg=LABEL_BG, padx=2, pady=2)
label_frame.pack(pady=4)
self.label_01 = tk.Label(label_frame, text='Enter time:',
font=LABEL_01_FONT, bg=LABEL_BG)
self.label_01.pack()
self.label_02 = tk.Label(label_frame, text='ss:mm(:ss)', bg=LABEL_BG)
self.label_02.pack()
entry_frame = tk.Frame(self)
entry_frame.pack(pady=4)
self.entry_std = tk.Entry(entry_frame, width=2)
self.entry_std.pack(side='left')
self.entry_min = tk.Entry(entry_frame, width=2)
self.entry_min.pack(side='left')
self.entry_sec = tk.Entry(entry_frame, width=2)
self.entry_sec.pack(side='left')
self.alarm_set_var = tk.IntVar()
self.checkbox = tk.Checkbutton(self, text='On', onvalue=1, offvalue=0,
variable=self.alarm_set_var)
self.checkbox.pack(expand=True)
self.alarm_flag = False
self.label_frame = label_frame
self.update_time()
def update_time(self):
act_time = strftime('%H:%M:%S')
self.act_time_var.set(act_time)
alarm_time = "{}:{}:{}".format(
self.entry_std.get(),
self.entry_min.get(),
self.entry_sec.get())
if self.alarm_set_var.get():
if alarm_time == act_time:
self.alarm_display(True)
else:
if self.alarm_flag:
self.alarm_display(False)
self.after(100, self.update_time)
def alarm_display(self, alarm=False):
self.alarm_flag = alarm
if alarm:
self.label_frame['bg'] = LABEL_ALARM_BG
self.label_01['bg'] = LABEL_ALARM_BG
self.label_02['bg'] = LABEL_ALARM_BG
for i in range(10):
os.system("echo -ne '\007'")
else:
self.label_frame['bg'] = LABEL_BG
self.label_01['bg'] = LABEL_BG
self.label_02['bg'] = LABEL_BG
def main():
app_win = tk.Tk()
app_win.title(APP_TITLE)
app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS))
app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT))
app = Application(app_win).pack(expand=True)
app_win.mainloop()
if __name__ == '__main__':
main()
|
9af31f0b9f40d78ee48de71218a11b98e6d4450a | 2Gdivirasalsabiil/algpython- | /Ceknilaimahasiswa5d.py | 393 | 3.671875 | 4 | #7. D. Penilaian mahasiswa mendapatkan huruf x
#@author: Divira Salsabiil Susanto - 20083000178 - 2G
print('===================')
print('PENILAIAN NILAI MAHASISWA')
print('===================')
x = input (">> Masukkan nilai = ")
#cek nilai mahasiswa
if int(x)>=91:
sts="A"
elif int(x)>=81:
sts="B"
elif int(x)>=71:
sts="C"
elif int(x)<71:
sts="D"
else:
sts="ulang"
print(sts)
|
4c984a05dabfef887ae4b827de02545b74299a6a | Wolfhan99/LeetCode-Javascript-Solution | /leetcode/116.填充每个节点的下一个右侧节点指针.py | 2,364 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=116 lang=python3
#
# [116] 填充每个节点的下一个右侧节点指针
#
# https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/description/
#
# algorithms
# Medium (70.11%)
# Likes: 529
# Dislikes: 0
# Total Accepted: 146.9K
# Total Submissions: 209.2K
# Testcase Example: '[1,2,3,4,5,6,7]'
#
# 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
#
#
# struct Node {
# int val;
# Node *left;
# Node *right;
# Node *next;
# }
#
# 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
#
# 初始状态下,所有 next 指针都被设置为 NULL。
#
#
#
# 进阶:
#
#
# 你只能使用常量级额外空间。
# 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
#
#
#
#
# 示例:
#
#
#
#
# 输入:root = [1,2,3,4,5,6,7]
# 输出:[1,#,2,3,#,4,5,6,7,#]
# 解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由
# next 指针连接,'#' 标志着每一层的结束。
#
#
#
#
# 提示:
#
#
# 树中节点的数量少于 4096
# -1000
#
#
#
# @lc code=start
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
def connectTwoNodes(node1, node2):
if node1 is None or node2 is None:
return
node1.next = node2
connectTwoNodes(node1.left, node1.right)
connectTwoNodes(node2.left, node2.right)
connectTwoNodes(node1.right, node2.left)
if root is None:
return None
connectTwoNodes(root.left, root.right)
return root
# @lc code=end
|
176a210da966c2548f576443d74aed98c87db607 | Wolfhan99/LeetCode-Javascript-Solution | /leetcode/447.回旋镖的数量.py | 1,873 | 3.59375 | 4 | # @before-stub-for-debug-begin
from python3problem447 import *
from typing import *
# @before-stub-for-debug-end
#
# @lc app=leetcode.cn id=447 lang=python3
#
# [447] 回旋镖的数量
#
# https://leetcode-cn.com/problems/number-of-boomerangs/description/
#
# algorithms
# Medium (60.42%)
# Likes: 166
# Dislikes: 0
# Total Accepted: 26.8K
# Total Submissions: 42.8K
# Testcase Example: '[[0,0],[1,0],[2,0]]'
#
# 给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组
# ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。
#
# 返回平面上所有回旋镖的数量。
#
#
# 示例 1:
#
#
# 输入:points = [[0,0],[1,0],[2,0]]
# 输出:2
# 解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
#
#
# 示例 2:
#
#
# 输入:points = [[1,1],[2,2],[3,3]]
# 输出:2
#
#
# 示例 3:
#
#
# 输入:points = [[1,1]]
# 输出:0
#
#
#
#
# 提示:
#
#
# n == points.length
# 1
# points[i].length == 2
# -10^4 i, yi
# 所有点都 互不相同
#
#
#
# @lc code=start
import collections
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
n = len(points)
if n <= 2:
return 0
ans = 0
points.sort(key=lambda a: (a[0], a[1]))
cnt = collections.defaultdict(int)
for i in range(n):
cnt.clear()
for j in range(n):
if i != j:
dis = (points[i][0] - points[j][0]) ** 2 + \
(points[i][1] - points[j][1]) ** 2
cnt[dis] += 1
for m in cnt.values():
ans += m*(m-1)
return ans
# @lc code=end
|
e308c99dab47e48ccee9042abf7d51030db58b89 | Wolfhan99/LeetCode-Javascript-Solution | /leetcode/92.反转链表-ii.py | 2,198 | 3.953125 | 4 | #
# @lc app=leetcode.cn id=92 lang=python3
#
# [92] 反转链表 II
#
# https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
#
# algorithms
# Medium (54.60%)
# Likes: 989
# Dislikes: 0
# Total Accepted: 196.7K
# Total Submissions: 359.9K
# Testcase Example: '[1,2,3,4,5]\n2\n4'
#
# 给你单链表的头指针 head 和两个整数 left 和 rightNode ,其中 left 。请你反转从位置 left 到位置 rightNode 的链表节点,返回
# 反转后的链表 。
#
#
# 示例 1:
#
#
# 输入:head = [1,2,3,4,5], left = 2, rightNode = 4
# 输出:[1,4,3,2,5]
#
#
# 示例 2:
#
#
# 输入:head = [5], left = 1, rightNode = 1
# 输出:[5]
#
#
#
#
# 提示:
#
#
# 链表中节点数目为 n
# 1
# -500
# 1
#
#
#
#
# 进阶: 你可以使用一趟扫描完成反转吗?
#
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
def reverseLinkedList(head):
pre = None
cur = head
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
# 因为头结点有坑呢发生变化,使用dummy节点
dummy = ListNode(-1)
dummy.next = head
pre = dummy
# 从dummy节点走left - 1步, 来到left节点的前一个节点
for _ in range(left - 1):
pre = pre.next
# 从pre再走rightNode - left + 1步,来到rightNode节点
rightNode = pre
for _ in range(right - left + 1):
rightNode = rightNode.next
# 切断一个子链表
leftNode = pre.next
cur = rightNode.next
# 切断连接
pre.next = None
rightNode.next = None
reverseLinkedList(leftNode)
pre.next = rightNode
leftNode.next = cur
return dummy.next
# @lc code=end
|
473bbd84ec28a21dad96c8207709f5981b2edb16 | Wolfhan99/LeetCode-Javascript-Solution | /常考代码/sort-python/merge.py | 1,006 | 3.796875 | 4 | # def merge(left, right):
# l, r= 0, 0
# res = []
# while l < len(left) and r < len(right):
# if left[l] < right[r]:
# res.append(left[l])
# l+=1
# else:
# res.append(right[r])
# r+=1
# res.append(left[l:])
# res.append(right[r:])
# return res
def merge(left, right):
l, r = 0, 0
result = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result.append(left[l:])
result.append(right[r:])
return result
def merge_sort(alist):
if len(alist) <= 1:
return
num = len(alist) / 2
# 划分
left = merge_sort(alist[:num])
right = merge_sort(alist[num:])
# 合并
return merge(left, right)
import random
data = [random.randint(-100, 100) for _ in range(10)]
merge_sort(data) |
c4e082d8c4f62c428d77a8f667f8f619acfd8c32 | Wolfhan99/LeetCode-Javascript-Solution | /leetcode/70.爬楼梯.py | 1,090 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#
# https://leetcode-cn.com/problems/climbing-stairs/description/
#
# algorithms
# Easy (52.59%)
# Likes: 1813
# Dislikes: 0
# Total Accepted: 533.2K
# Total Submissions: 1M
# Testcase Example: '2'
#
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
#
# 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
#
# 注意:给定 n 是一个正整数。
#
# 示例 1:
#
# 输入: 2
# 输出: 2
# 解释: 有两种方法可以爬到楼顶。
# 1. 1 阶 + 1 阶
# 2. 2 阶
#
# 示例 2:
#
# 输入: 3
# 输出: 3
# 解释: 有三种方法可以爬到楼顶。
# 1. 1 阶 + 1 阶 + 1 阶
# 2. 1 阶 + 2 阶
# 3. 2 阶 + 1 阶
#
#
#
# @lc code=start
class Solution:
def climbStairs(self, n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2,n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[-1]
# @lc code=end
|
a4975ee06f14f6a973cf076d2c8cf7cd38a10540 | Wolfhan99/LeetCode-Javascript-Solution | /leetcode/1.两数之和.py | 1,769 | 3.65625 | 4 | #
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# https://leetcode-cn.com/problems/two-sum/description/
#
# algorithms
# Easy (51.75%)
# Likes: 11862
# Dislikes: 0
# Total Accepted: 2.4M
# Total Submissions: 4.6M
# Testcase Example: '[2,7,11,15]\n9'
#
# 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
#
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
#
# 你可以按任意顺序返回答案。
#
#
#
# 示例 1:
#
#
# 输入:nums = [2,7,11,15], target = 9
# 输出:[0,1]
# 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
#
#
# 示例 2:
#
#
# 输入:nums = [3,2,4], target = 6
# 输出:[1,2]
#
#
# 示例 3:
#
#
# 输入:nums = [3,3], target = 6
# 输出:[0,1]
#
#
#
#
# 提示:
#
#
# 2
# -10^9
# -10^9
# 只会存在一个有效答案
#
#
# 进阶:你可以想出一个时间复杂度小于 O(n^2) 的算法吗?
#
#
# @lc code=start
from typing import Hashable
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[num[i]] = i
return []
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
# @lc code=end
|
0909853dc00f03e259e991a4c6ea4fa6cae6db06 | raianyrufino/URI-OnlineJudge | /1043.py | 199 | 3.5625 | 4 | A, B, C = map(float,raw_input().split())
if (A+B > C) and (B+C > A) and (C+A >B):
perimetro = A+B+C
print("Perimetro: %.1f" %(perimetro))
else:
area = (A+B)*C/2
print("Area: %.1f" %(area))
|
2de9ef41e6bef06e07a7b20f5271e261213124a8 | raianyrufino/URI-OnlineJudge | /1164.py | 248 | 3.546875 | 4 | n = int(raw_input())
soma = 0
for i in range(1,n+1):
x = int(raw_input())
soma = 0
for j in range(1, x):
if x % j == 0:
soma += j
if soma == x:
print "%d eh perfeito" %(x)
else:
print "%d nao eh perfeito" %(x)
|
d65f2347f9e73a045e5b05728c497f91b3bfb714 | raianyrufino/URI-OnlineJudge | /1066.py | 385 | 3.53125 | 4 | contpar = 0
contim = 0
contpos = 0
contneg = 0
for i in range(5):
i = int(raw_input())
if i % 2 == 0:
contpar += 1
else:
contim += 1
if i > 0:
contpos += 1
elif i < 0:
contneg += 1
print "%d valor(es) par(es)" %(contpar)
print "%d valor(es) impar(es)" %(contim)
print "%d valor(es) positivo(s)" %(contpos)
print "%d valor(es) negativo(s)" %(contneg)
|
9511bbb743d46583c05723c663929e940d8614ec | raianyrufino/URI-OnlineJudge | /1180.py | 284 | 3.578125 | 4 | n = int(raw_input())
vetor = []
pos = 0
vetor = map(int,raw_input().split())
for i in range(len(vetor)):
if i == 0:
menor = vetor[i]
pos = i
else:
if vetor[i] < menor:
menor=vetor[i]
pos=i
print "Menor valor:", menor
print "Posicao: %i" %(pos)
|
22c87e695fe8c460a0ca95b13d7e9afb80a89314 | amutava/Machine_learning_algorithmns | /decision_tree.py | 596 | 3.703125 | 4 | # Import Library
# Import other necessary libraries like pandas, numpy...
from sklearn import tree
# Assumed you have, X (predictor) and Y (target) for training data set and x_test(predictor) of test_dataset
# Create tree object
# for classification, here you can change the algorithm as gini or entropy (information gain) by default it is gini
model = tree.DecisionTreeClassifier(criterion='gini')
# model = tree.DecisionTreeRegressor() for regression
# Train the model using the training sets and check score
model.fit(X, y)
model.score(X, y)
# Predict Output
predicted = model.predict(x_test)
|
e588bbb9899fa27aa4ee92fc9825a38ee626259e | kildarejoe1/CourseWork_Lotery_App | /app.py | 1,859 | 4.15625 | 4 | #Udemy Course Work - Lottery App
#Import the random class
import random
def menu():
"""Controlling method that
1. Ask players for numbers
2. Calculate the lottery numbers
3. Print out the winnings
"""
players_numbers = get_players_numbers()
lottery_numbers = create_lottery_numbers()
if len(players_numbers.intersection(lottery_numbers)) == 1:
print("Congratulations, you have won 10 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 2:
print("Congratulations, you have won 20 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 3:
print("Congratulations, you have won 30 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 4:
print("Congratulations, you have won 40 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 5:
print("Congratulations, you have won 50 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 6:
print("Congratulations, you have won it all!!!")
else:
print("Sorry, you have won nothing!!!")
#Get the Lottery numbers
def get_players_numbers():
numbers = str( raw_input("Enter the numbers separated by commas: "))
#Now split the string into a list using the string split method
numbers_in_list=numbers.split(",")
#Now get a set of numbers instead of list of string by using set comprehension, same as list just returns a set.
numbers_in_set={int(x) for x in numbers_in_list}
#Now return a set from the invoking call
return numbers_in_set
#Lottery calaculates 6 random nubers
def create_lottery_numbers():
lottery_num=set()
for x in range(6):
lottery_num.add(random.randint(1,100)) #Prints a random number between 1 and 100
return lottery_num
if __name__ == "__main__":
menu()
|
5d462e58a2b3cbfcbb59f6128a2c3724ea0f407c | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao08.py | 332 | 3.96875 | 4 | '''Faça um programa que leia 5 números e informe a soma e a média dos números.'''
lista = list()
for i in range(5):
num = float(input(f'Informe o {i + 1}º numero: '))
lista.append(num)
soma = sum(lista)
media = soma / len(lista)
print(f'''A soma dos valores é: {soma}
A media entre os valores é: {media:.2f}''')
|
9688e61269b53f9ac4de4d9652f1f42f22a2242b | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao22.py | 669 | 4.09375 | 4 | '''Altere o programa de cálculo dos números primos, informando, caso o número não seja primo, por quais número ele é
divisível.'''
number = int(input('Enter a integer number: '))
list_ = list()
divisible_list = list()
not_divisible_list = list()
cont_np = 0
cont_yp = 0
for i in range(number):
list_.append(i)
for i in list_:
if number % (i+1) == 0:
cont_yp += 1
divisible_list.append(i + 1)
if cont_yp == 2:
print(f'The number {number} is prime')
print(f'The number is divisible by {divisible_list}')
elif cont_yp > 2:
print(f'The number {number} is not prime.')
print(f'The number is divisible by {divisible_list}')
|
d35658055b36c894a01b375bb333ae11236ffbfa | fabricio24530/ListaPythonBrasil | /EstruturaDeDecisao08.py | 411 | 4.1875 | 4 | '''Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a
decisão é sempre pelo mais barato.'''
lista = list()
for i in range(3):
produto = float(input(f'Informe o preço do {i + 1}º produto: '))
lista.append(produto)
menor = min(lista)
posicao = lista.index(menor)
print(f'O {posicao + 1}º produto possui o menor preço: R$ {menor}')
|
4b4295d6a734eec6c5b8d4467c9036dc04ade8a4 | fabricio24530/ListaPythonBrasil | /EstruturaSequencial03.py | 216 | 3.890625 | 4 | '''Faça um Programa que peça dois números e imprima a soma.'''
n1, n2 = int(input('Informe o primeiro numero: ), int(input('informe o segundo numero: '))
soma = n1 + n2
print(f'A soma de {n1} e {n2} é {soma}')
|
97c75844f36a3ad08ef63b982cee4d7a41f431de | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao27.py | 512 | 3.921875 | 4 | '''Faça um programa que calcule o número médio de alunos por turma. Para isto, peça a quantidade de turmas e a
quantidade de alunos para cada turma. As turmas não podem ter mais de 40 alunos.'''
qtd_turmar = int(input('Informe a quantidade de turmas: '))
lista = list()
for i in range(qtd_turmar):
qtd_alunos = int(input(f'Informe a quantidade de alunos da {i + 1}º turma: '))
lista.append(qtd_alunos)
media = sum(lista)/qtd_turmar
print(f'O numero medio de alunos por turma é de {media:.2f}') |
8d4ede1972573ed6ea89c68ec89ee4ec7e928f55 | fabricio24530/ListaPythonBrasil | /EstruturaSequencial09.py | 306 | 4.1875 | 4 | '''Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius.
C = (5 * (F-32) / 9).'''
temp_f = float(input('Informe a temperatura em graus Farenheit: '))
temp_c = (5 * (temp_f-32) / 9)
print(f'A temperatura {temp_f}°F equivale a {temp_c:.2f}°C')
|
6f96e9df955a926865d9dcdbc2e4231762536507 | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao07.py | 234 | 4.3125 | 4 | '''Faça um programa que leia 5 números e informe o maior número.'''
lista = list()
for i in range(5):
num = float(input(f'Informe o {i+1}º numero: '))
lista.append(num)
print(f'O maior valor digitado foi: {max(lista)}') |
3c28e8d63db49785131ea8cf92bf16b751a078b4 | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao35.py | 600 | 3.9375 | 4 | '''Encontrar números primos é uma tarefa difícil. Faça um programa que gera uma lista dos números primos existentes entre
1 e um número inteiro informado pelo usuário.'''
num = int(input('Informe um numero: '))
lista = []
lista2 = []
for i in range(num, 0, -1):
for j in range(num, 0, -1):
if i % j == 0:
lista.append(i) # Os numeros primos se repetem duas vezes
for k in lista:
if lista.count(k) == 2 and k not in lista2: # Deixa so os primos e tira sua duplicidade
lista2.append(k)
print(f'O numeros primos entre 1 e {num} são: \n{lista2[::-1]}')
|
c767b4be16594d0381b03df7a0d6499b8d970825 | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao26.py | 770 | 3.9375 | 4 | '''
Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor
votar e ao final mostrar o número de votos de cada candidato.
'''
eleitores = int(input('Total de eleitores: '))
votos1, votos2, votos3 = 0, 0, 0
for i in range(eleitores):
candidato = input('Informe em qual candidato quer votar: 1, 2 ou 3 ').strip()
if candidato.isdecimal():
if candidato == '1':
votos1 += 1
elif candidato == '2':
votos2 += 1
elif candidato == '3':
votos3 += 1
else:
print('Valor errado')
print(f'Total de votos do candidato 1: {votos1}')
print(f'Total de votos do candidato 2: {votos2}')
print(f'Total de votos do candidato 3: {votos3}')
|
ffef4b470cfb1aea38fde6d66b22d1f2c3fc70b7 | Rasadell09/LeetCode | /intersection_of_two_arrays.py | 530 | 3.984375 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
if nums1 == [] or nums2 == []:
return []
for x in nums1:
if x in nums2:
if x not in res:
res.append(x)
return res
# nums1=set(nums1)
# nums2=set(nums2)
# return list(nums1&nums2)
s = Solution()
print s.intersection([1], [1])
|
564f481e560af6591880e93f0da1e6d61e9abf37 | Rasadell09/LeetCode | /maximum_depth_of_binary_tree.py | 995 | 3.765625 | 4 | # 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 maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
depth = []
q = []
q.append(root)
depth.append(1)
max_d = 0
while len(q) != 0:
if max_d < max(depth):
max_d = max(depth)
n = q.pop()
lv = depth.pop()
if n.right:
q.append(n.right)
depth.append(lv + 1)
if n.left:
q.append(n.left)
depth.append(lv + 1)
return max_d
s = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.left.right = TreeNode(5)
root.right.left = TreeNode(6)
print s.maxDepth(root)
|
cae5015830450552672f8abcfb4f0c96d855d15d | Rasadell09/LeetCode | /relative_ranks.py | 696 | 3.578125 | 4 | class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
t = []
for e in nums:
t.append(e)
t.sort()
t.reverse()
res = []
for e in nums:
if t.index(e) >= 3:
res.append(str(t.index(e) + 1))
elif t.index(e) == 2:
res.append("Bronze Medal")
elif t.index(e) == 1:
res.append("Silver Medal")
elif t.index(e) == 0:
res.append("Gold Medal")
return res
s = Solution()
print s.findRelativeRanks([3, 6, 89, 23, 123, 45, 112, 54, 1, 2, 0])
|
8466213692c72aa5f721c08853eb41a5bbca6a98 | ozgurkaracam/instapy | /test.py | 532 | 3.53125 | 4 |
class Test:
def __init__(self):
self.a = ["a", "b"]
self.b = ["a","c"]
print(self.Diff(self.a,self.b))
def Diff(self,li1, li2):
li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return li_dif
if __name__ == '__main__':
# f=open('notfollowers.txt')
# w=0
# for i in f:
# w=w+1
# print(w)
testt=["özgür","karaçam","www"]
f=open('notfollowers.txt',"w")
for i in testt:
f.write(i+"\n")
f.close()
|
89bcba596bf9a599b8d1c5a916f46d224c7db11d | Rosebotics/PythonGameDesign2019 | /camp/Nidha/Day 1 - The Game Loop, Colors, Drawing and Animation/06-InteractingWithAPlayer.py | 1,153 | 3.609375 | 4 | # My first Pygame program.
# Authors: Many people and Nidha Rajoli
import pygame
import sys
import time
backgroundColor = (100, 34, 188)
white = (255, 255, 0)
circlelocation = (300, 150)
circleRadius = 180
rectX = 96
rectY = 196
rectWidth = 176
rectHeight = 186
pygame.display.set_mode((640, 480))
pygame.init()
screen = pygame.display.set_mode((640, 480))
green = (0, 255, 0)
x = 300
y = 280
while True:
time.sleep(0.01)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_RIGHT]:
x = x + 1
if pressed_keys[pygame.K_LEFT]:
x = x - 1
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_DOWN]:
y = y + 1
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_RIGHT]:
screen.fill(backgroundColor)
pygame.draw.circle(screen, green, (x, y), 30)
circleRadius = circleRadius + 1
#pygame.draw.circle(screen, white, circlelocation, circleRadius)
pygame.draw.rect(screen, white, (rectX, rectY, rectWidth, rectHeight))
pygame.display.update()
|
48a513a18aad8577cfb5bb634bdb0e6705a2b764 | Rosebotics/PythonGameDesign2019 | /camp/Marika/Day 1 - The Game Loop, Colors, Drawing and Animation/06-InteractingWithAPlayer.py | 1,112 | 3.515625 | 4 | # My first Pygame program.
# Authors: Many people and Marika
import pygame
import sys
from pygame.locals import *
screenSize = (640, 480)
backgroundColor = (0, 0, 0)
circleColor = (140, 100, 255)
rectColor1 = (255, 100, 120)
rectColor2 = (100, 120, 255)
circleRadius = 20
rectY1 = 100
rectY2 = 100
rectSpeed = 5
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get() :
if event.type == pygame.QUIT:
sys.exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_UP]:
rectY1 = rectY1 - 5
if pressed_keys[K_DOWN]:
rectY1 = rectY1 + 5
if pressed_keys[K_w]:
rectY2 = rectY2 - 5
if pressed_keys[K_s]:
rectY2 = rectY2 + 5
screen.fill((backgroundColor))
pygame.draw.circle(screen, (circleColor), (320, 150), circleRadius)
pygame.draw.rect(screen, (rectColor1), (600, rectY1, 20, 75))
pygame.draw.rect(screen, (rectColor2), (30, rectY2, 20, 75))
pygame.display.update()
|
8711ed470f9f0a02ff337099e757a761b4de096b | Rosebotics/PythonGameDesign2019 | /camp/Aidan/Day 1 - The Game Loop, Colors, Drawing and Animation/04-Drawing.py | 639 | 3.5625 | 4 |
# My first Pygame program.
# Authors: Many people and Aidan
import pygame
import sys
backgroundColor = (50, 60, 123.456789)
white = (255, 255, 255)
circleLocation = (300, 150)
circleRaidous = 200
circleLocation = (300, 150)
circleRaidous = 35
red = (255, 255, 255)
pygame.init()
screen = pygame.display.set_mode((640, 480))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(backgroundColor)
pygame.draw.circle(screen, white, circleLocation, circleRaidous)
pygame.draw.circle(screen, white, circleLocation, circleRaidous)
pygame.display.update()
|
546d41138df9078ee41dcae8da40bb79c798c200 | agarithm/2019_AOC | /04.py | 1,763 | 3.5625 | 4 |
passwords = 0;
for pwd in range(359282,820402,1):
repeats = False;
sequential = False;
pwd = f"{pwd}"
if "00" in pwd:
repeats = True;
elif "11" in pwd:
repeats = True;
elif "22" in pwd:
repeats = True;
elif "33" in pwd:
repeats = True;
elif "44" in pwd:
repeats = True;
elif "55" in pwd:
repeats = True;
elif "66" in pwd:
repeats = True;
elif "77" in pwd:
repeats = True;
elif "88" in pwd:
repeats = True;
elif "99" in pwd:
repeats = True;
tmp = [char for char in pwd]
tmp.sort()
tmp = "".join(tmp)
sequential = tmp == pwd;
if(sequential & repeats):
passwords+=1
print(f"Valid Passwords = {passwords}")
passwords = 0;
for pwd in range(359282,820402,1):
repeats = False;
sequential = False;
pwd = f"{pwd}"
if "00" in pwd and not "000" in pwd:
repeats = True;
elif "11" in pwd and not "111" in pwd:
repeats = True;
elif "22" in pwd and not "222" in pwd:
repeats = True;
elif "33" in pwd and not "333" in pwd:
repeats = True;
elif "44" in pwd and not "444" in pwd:
repeats = True;
elif "55" in pwd and not "555" in pwd:
repeats = True;
elif "66" in pwd and not "666" in pwd:
repeats = True;
elif "77" in pwd and not "777" in pwd:
repeats = True;
elif "88" in pwd and not "888" in pwd:
repeats = True;
elif "99" in pwd and not "999" in pwd:
repeats = True;
tmp = [char for char in pwd]
tmp.sort()
tmp = "".join(tmp)
sequential = tmp == pwd;
if(sequential & repeats):
passwords+=1
print(f"Valid Passwords = {passwords}")
|
30c6005ca4fd8c122c8e5cf14e09734b59d2347c | allentv/DataScienceMachineLearning | /DataMunging/DataMunging.py | 4,607 | 3.84375 | 4 | """
Created for Dublin Data Science Beginners Meetup session on 11-Aug-2015
This is an example to showcase the results of Data Munging in Python
with Pandas using wxPython GUI toolkit. The results are shown in a
Grid for easy visualization of data.
@author: Allen Thomas Varghese
@email: allentv4u@gmail.com
"""
import wx
import wx.grid as wg
import os
import pandas as pd
class DataMungingUI(wx.Frame):
""" Class to create the GUI """
def __init__(self):
super(DataMungingUI, self).__init__(
None, -1, "Data Munging UI", wx.DefaultPosition, wx.Size(800, 600)
)
# Constants for positioning controls
LEFT_MARGIN = 30
TOP_MARGIN = 30
DEFAULT_SPACING = 20
# Parameters: Parent, ID
panel = wx.Panel(self, -1)
# Parameters: Parent, ID, title, position
wx.StaticText(panel, -1, 'Choose CSV file to process:', (LEFT_MARGIN, TOP_MARGIN))
# Parameters: Parent, ID, placeholder text, position, (width, height)
self.file_path_ctrl = wx.TextCtrl(panel, -1, '', (LEFT_MARGIN, TOP_MARGIN + DEFAULT_SPACING), (500, -1))
# Parameters: Parent, ID, label, position
wx.Button(panel, 9, 'Choose', (LEFT_MARGIN + 520, TOP_MARGIN + DEFAULT_SPACING))
# Attaching event handler to the 'Choose' button
# Parameters: Type of event, event handler function, ID of the control
self.Bind(wx.EVT_BUTTON, self.get_file_path, id=9)
wx.Button(panel, 10, 'Process File', (LEFT_MARGIN, TOP_MARGIN + 3 * DEFAULT_SPACING))
# Attaching event handler to the 'Process File' button
self.Bind(wx.EVT_BUTTON, self.process_csv_file, id=10)
# Creating the Grid to display information from the CSV file
self.data_grid = wg.Grid(panel, -1, (LEFT_MARGIN, TOP_MARGIN + 5 * DEFAULT_SPACING), (500, 150))
# Parameters: rows, columns
self.data_grid.CreateGrid(5, 5)
# Disable editing of values in the Grid
self.data_grid.EnableEditing(False)
# Set default alignment for all cells
# Parameters: Horizontal alignment, Vertical alignment
self.data_grid.SetDefaultCellAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
self.status_bar = self.CreateStatusBar()
self.Centre()
self.Show(True)
def get_file_path(self, event):
""" Show the File Dialog """
wcd = 'All files (*)|*|CSV files (*.csv)|*.csv|Text files (*.txt)|*.txt'
dir = os.getcwd()
open_dlg = wx.FileDialog(
self, message='Choose a file', defaultDir=dir, defaultFile='',
wildcard=wcd, style=wx.OPEN|wx.CHANGE_DIR
)
path = ""
if open_dlg.ShowModal() == wx.ID_OK:
path = open_dlg.GetPath()
open_dlg.Destroy()
self.file_path_ctrl.SetValue(path)
self.status_bar.SetStatusText('CSV file path loaded')
def perform_data_munging(self):
""" Data Munging happens here. Return a Pandas DataFrame. """
# TODO: Add file loading code here
data = {
'col1': [1, 2, 3, 4, 5],
'col2': ['v1', 'v2', 'v3', 'v4', 'v5'],
'col3': [0.01, 0.25, 1.23, 25.03, 100.00]
}
# TODO:
# Add file processing code here
# ...
# ...
# ...
# Return only the top 1,000 records to avoid memory problems
df = pd.DataFrame(data).head(1000)
return df # Change the return value based on above code
def process_csv_file(self, event):
""" Processing the selected CSV file """
self.status_bar.SetStatusText('CSV file processing started...')
df = self.perform_data_munging()
no_of_rows = len(df)
no_of_columns = len(df.columns)
self.data_grid.ClearGrid() # Clear existing data in the grid
self.data_grid.DeleteCols(0, self.data_grid.GetNumberCols()) # Delete all the columns
self.data_grid.DeleteRows(0, self.data_grid.GetNumberRows()) # Delete all the rows
self.data_grid.InsertCols(0, no_of_columns) # Add new columns
self.data_grid.InsertRows(0, no_of_rows) # Add new rows
for col_index, col in enumerate(df.columns):
# Set the column label to match the value for the column in the CSV file
self.data_grid.SetColLabelValue(col_index, col)
for row_index, value in enumerate(df[col]):
self.data_grid.SetCellValue(row_index, col_index, str(value))
self.status_bar.SetStatusText('CSV file processing completed!')
# Display the GUI
app = wx.App()
DataMungingUI()
app.MainLoop()
|
fd1d5b77f2f3a1095340a82f2af4fcf685934a33 | widnerlr/isat252 | /lab6.py | 1,076 | 3.640625 | 4 | """
lab 6 5/27
"""
#3.1
#for num in range(6):
# if num != 3:
# print(num)
#3.2
#result_32 = 1
#for num in range(1,6):
# result_32= result_32 * num
#print(result_32)
#3.3
#result_33 = 0
# num in range(1,6):
# result_33=result_33 + num
#print(result_33)
#3.4
#result_34 = 1
#for num in range(3,9):
# result_34=result_34 * num
#print(result_34)
#3.5
#result_351=1
#for num in range(1,9):
# result_351=result_351 * num
#result_352=1
#for num in range(1,4):
# result_352=result_352* num
#print(result_351/result_352)
#3.6
result= 0
for word in 'this is my 6th string'.split():
result=result+1
print(result)
#3.7
my_tweet = {
'favorite_count': '1138',
'lan':'eng',
'coordinates':(-75,40),
'entities':
{
"hashtags":[ "Preds ", "Pens", " SingIntoSpring "]
}
}
result=0
for hastag in my_tweet['entities']['hashtags']:
result=result+1
print(result)
|
1e6686d27e2f119426aa0cf1271151d2594fa2b0 | xxxfly/PythonStudy | /ProjectBaseTest1/python核心编程/07-正则表达式/03-re模块的高级用法.py | 989 | 3.578125 | 4 | # coding=utf-8
import re
# search方法
def test1():
"""
re.search() 匹配第一个结束
"""
print(re.search(r'python','<html><h1>python</h1></html>'))
print(re.search(r'python','<html><h1>python</h1><h2>python</h2></html>').group())
print(re.search(r'python','<html><h1>python</h1></html>').group())
def test2():
"""
re.findall() 匹配所有的
"""
print(re.findall(r'python','<html><h1>python</h1><h2>python</h2></html>'))
def add(result):
strNum=result.group()
num=int(strNum)+10
return str(num)
def test3():
"""
re.sub() 将匹配到的数据进行替换
"""
print(re.sub(r'php','python','c++ c python php cpp python php'))
print(re.sub(r'\d+',add,'python=88,php=75'))
def test4():
"""
re.split() 根据匹配进行切割字符串,并返回一个列表
"""
print(re.split(r':|,','project:python,javascript,html'))
def main():
test4()
if __name__ == '__main__':
main() |
30b8c8d8977ed91502d51f36c4d6695a9c3cb961 | xxxfly/PythonStudy | /ProjectBaseTest1/Python基础/名片管理系统-文件版.py | 3,819 | 3.59375 | 4 | #-*- coding: utf-8 -*-
#定义全局变量 数组用来存储名片信息
card_infos=[]
#新增一个名片
def add_new_card_info():
'''完成新增一个名片'''
new_name=input("请输入新的名字:")
new_qq=input("请输入新的QQ:")
new_weixin=input("请输入新的微信:")
new_addr=input("请输入新的住址:")
#定义一个字典,用来存储一个新的名片
new_info={}
new_info['name']=new_name
new_info['qq']=new_qq
new_info['weixin']=new_weixin
new_info['addr']=new_addr
#讲一个字典添加到列表中
global card_infos
card_infos.append(new_info)
#删除名片信息
def remove_card_info():
'''删除名片信息'''
remove_name=input('请输入要删除的姓名:')
remove_falg=False #删除的标识
for temp in card_infos:
if(temp['name']==remove_name):
card_infos.remove(temp)
remove_falg=True
print('成功删除%s'%remove_name)
break
if not remove_falg:
print('查不此人')
#修改名片信息
def update_card_info():
'''修改名片信息'''
update_name=input('请输入要修改的姓名:')
new_name=input('请输入修改后的姓名:')
update_flag=False #修改成功的标识,默认不成功
for i in range(len(card_infos)):
if card_infos[i]['name']==update_name:
card_infos[i]['name']=new_name
update_flag=True
print('修改成功')
break
if not update_flag:
print('查无此人')
#查找名片信息
def find_card_info():
'''查找名片信息'''
find_name=input('请输入要查找的姓名:')
find_flag=False #找到的标识,默认没有找到
for temp in card_infos:
if temp['name']==find_name:
print('%s找到了'%find_name)
print('%s\t%s\t%s\t%s'%(temp['name'],temp['qq'],temp['weixin'],temp['addr']))
find_flag=True
break
if not find_flag:
print('查无此人')
#展示名片信息
def show_all_info():
'''展示所有名片信息'''
print('姓名\tQQ\t微信\t地址\t')
for temp in card_infos:
print('%s\t%s\t%s\t%s'%(temp['name'],temp['qq'],temp['weixin'],temp['addr']))
def save_2_file():
'''把已经添加的名片信息保存在文件中'''
f=open('card_backup.data','w',encoding='utf-8')
f.write(str(card_infos))
f.close()
def load_file():
global card_infos
try:
f=open('card_backup.data',encoding='utf-8')
card_infos=eval(f.read())
except Exception:
pass
finally:
f.close()
#打印功能菜单
def print_menu():
'''打印功能菜单'''
print('*'*50)
print("名片管理系统 v1.0")
print("1.添加一个新名片")
print("2.修改一个名片")
print("3.删除一个名片")
print("4.查找一个名片")
print("5.查看所有名片")
print("6.存入文件")
print("7.退出")
print('*'*50)
def main():
'''完成对整个程序的控制'''
#将文件数据加载到程序中
load_file()
#1.打印菜单
print_menu()
while True:
#2.获取用户的输入
num=int(input('请输入操作序号:'))
#3.根据用户的数据执行相应的功能
if num==1:
add_new_card_info()
elif num==2:
remove_card_info()
elif num==3:
update_card_info()
elif num==4:
find_card_info()
elif num==5:
show_all_info()
elif num==6:
save_2_file()
elif num==7:
print("再见")
break
else:
print('输入有误,请重新输入')
print('')
if __name__ == '__main__':
main() |
fe5f6811834273336c8afe8c526cc9d5973d659e | xxxfly/PythonStudy | /ProjectBaseTest1/算法与数据结构/03-排序/02-选择排序.py | 604 | 3.84375 | 4 | #coding:utf-8
def selectSort(orgList):
"""选择排序"""
# for i in range(0,len(orgList)):
# for j in range(i+1,len(orgList)):
# if orgList[i]>orgList[j]:
# orgList[i],orgList[j]=orgList[j],orgList[i]
n=len(orgList)
for j in range(0,n-1): # j:0~n-2
min_index=j
for i in range(j+1,n):
if orgList[min_index]>orgList[i]:
min_index=i
orgList[j],orgList[min_index]=orgList[min_index],orgList[j]
if __name__=='__main__':
a=[22,1,223,43,23,567,334,38,34]
print(a)
selectSort(a)
print(a) |
5b6b1da23f3ce3c77688148546276ca171cb0300 | xxxfly/PythonStudy | /ProjectBaseTest1/python核心编程/02-高级3-元类/02-元类.py | 769 | 4.34375 | 4 | #-*- coding:utf-8 -*-
#元类
# # --类也是对象,就是一组用来描述如何生成一个对象的代码段
# class Person(object):
# num=0
# print('--person--test--') #会直接被执行,说明此时python解释器已经创建了这个类
# def __init__(self):
# self.name='a'
# print(100)
# print('hello')
# print(Person)
# class Person():
# pass
# p1=Person()
# print(type(p1))
#---------------------------------------
# #type 创建类type(类名,集成,方法和属性)
# Test2=type('Test2',(),{'name':'a'})
# t2=Test2()
# print(t2.name)
# print(type(t2))
# def printNum(self):
# print('--num:%d'%self.num)
# Test3=type('Test3',(),{'printNum':printNum,'num':100})
# t3=Test3()
# t3.printNum()
#__metaclass__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.