blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
304031c43b782e87103ef0ac275e6d2fa550a1f8 | Calvin98/Iowa_PythonProjects | /Flower Real.py | 1,241 | 3.625 | 4 | import turtle
def draw_arc(t):
t.right(18)
for count in range(10):
t.forward(10)
t.left(4)
t.right(4)
t.right(18)
def draw_squiggle(t):
t.right(90)
for count in range(10):
t.forward(10)
t.left(4)
t.right(4)
t.right(18)
t.left(10)
for count in range(10):
t.forward(10)
t.right(4)
t.left(4)
t.left(18)
t.penup()
t.right(90)
for count in range(10):
t.backward(10)
t.left(4)
t.right(4)
t.right(18)
t.left(10)
for count in range(10):
t.backward(10)
t.right(4)
t.left(4)
t.left(18)
t.pendown()
def draw_petal(t):
t.begin_fill()
draw_arc(t)
t.left(180)
draw_arc(t)
t.left(180)
t.end_fill()
wn = turtle.Screen()
alex = turtle.Turtle()
alex.color('red')
alex.fillcolor('yellow')
alex.speed(0)
n = 10
size = 30
interior_angle = 180 * (n - 2) / n
turn_angle = 180 - interior_angle
for count in range(n):
alex.forward(size)
petal_turn = interior_angle / 2
alex.right(petal_turn)
draw_squiggle(alex)
draw_petal(alex)
alex.left(petal_turn)
alex.left(turn_angle)
wn.exitonclick()
|
760ab7c54cae4c13ae6b43d6bfe1e2fa0cd300eb | svaccaro/codeeval | /overlapping_rectangles.py | 511 | 3.9375 | 4 | #!/usr/bin/env python
from sys import argv
input = open(argv[1])
def overlap(a1,a2,b1,b2):
if a1 > b2 or a2 < b1:
return False
else:
return True
for line in input:
line = line.rstrip()
coords = map(int,line.split(','))
x_overlap = True
y_overlap = True
x_overlap = overlap(coords[0],coords[2],coords[4],coords[6])
y_overlap = overlap(coords[7],coords[5],coords[3],coords[1])
if x_overlap and y_overlap:
print 'True'
else:
print 'False'
|
b56f6a2c017da7a95241a857d224c8cec50c1a63 | AnimeshSinha1309/terminal-joyride | /firebeam.py | 2,249 | 3.53125 | 4 | """
Implements the obstacles (beams of fire) hanging in the air
"""
import numpy as np
import colorama as cl
import container
from spawnable import Spawnable
class FireBeam(Spawnable):
"""
The FireBeam obstacles that destroy the player if colliding
"""
def __init__(self):
self._type = np.random.choice(
['Vertical', 'Horizontal', 'LeftDiagonal', 'RightDiagonal'])
self._bgcolor = cl.Back.YELLOW
self._fgcolor = cl.Fore.BLACK
if self._type == 'Vertical':
self._sprite = [
"X",
"X",
"X",
"X"
]
self._position = (np.random.randint(
container.FRAME_ROWS + 1 - 4), container.FRAME_COLS)
elif self._type == 'Horizontal':
self._sprite = [
"XXXX"
]
self._position = (np.random.randint(
container.FRAME_ROWS + 1 - 1), container.FRAME_COLS)
elif self._type == 'LeftDiagonal':
self._sprite = [
"X ",
" X ",
" X ",
" X"
]
self._position = (np.random.randint(
container.FRAME_ROWS + 1 - 4), container.FRAME_COLS)
elif self._type == 'RightDiagonal':
self._sprite = [
" X",
" X ",
" X ",
"X "
]
self._position = (np.random.randint(
container.FRAME_ROWS + 1 - 4), container.FRAME_COLS)
def __str__(self):
return "\n".join(self._sprite)
def update_on_timestep(self):
"""
Move the obstacle to the right in every frame
:return: False if it's supposed to be deleted, True otherwise
"""
if self._delete_me:
return
self._position = (
self._position[0], self._position[1] - container.SCROLL_SPEED)
if self._position[0] < -4:
self._delete_me = True
@staticmethod
def spawn(prob: float = 1/50):
to_spawn = np.random.choice([False, True], p=[1 - prob, prob])
if to_spawn:
return FireBeam()
return False
|
505d55c4b03b3cbfc56fccf1e126ab28930e34c2 | patnev/GM1_G3 | /read_serial.py | 1,242 | 3.65625 | 4 | """
Class to read sensor data from serial port (via USB)
"""
import serial
from constants import *
class SerialReader:
"""
SerialReader: class to read sensor data
Methods: readline, readline_multi, isButtonPressed
"""
def __init__(self):
"""
Initialise serial reader from serial port and baud set in constants file
Parameters: None
"""
self.reader = serial.Serial(SERIAL_PORT, SERIAL_BAUD)
def readline(self):
"""
Reads a single line from serial and convert to int
Parameters: None
Returns: int : reading in grams
"""
strl = str(self.reader.readline())
if strl == "-1":
return -1
return int(strl[2:][:-5])
def readline_multi(self):
"""
Reads a single line of 3 comma separated values from serial and convert to list of ints
Parameters: None
Returns: list : 3 readings in grams representing individual sensors and sum
"""
strl = str(self.reader.readline())[2:][:-5]
print(strl)
if strl == "-1":
return -1
return [int(i) for i in strl.split(',')]
def isButtonPressed(self, r):
return r == -1 |
e7c4151acf27d25e1cd1afb7affa86ccec6cedb4 | cynthia8863/test | /ex/ex25_sample.py | 1,017 | 3.609375 | 4 | import ex25
sentence = "All good things come to those who wait"
words = ex25.break_words(sentence)
print words
print "-"*30
sorted_words = ex25.sort_words(words)
print sorted_words
print "-"*30
print ex25.print_first_word(words)
print ex25.print_last_word(words)
print "-"*30
print ex25.print_first_word(sorted_words)
print ex25.print_last_word(sorted_words)
print "-"*30
sorted_words2 = ex25.sort_sentence(sentence)
print sorted_words2
print "-"*30
print ex25.print_first_and_last(sentence)
print "-"*30
print ex25.print_first_and_last_sorted(sentence)
'''
Result:
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
------------------------------
['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
------------------------------
All
None
wait
None
------------------------------
All
None
who
None
------------------------------
['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
------------------------------
All
wait
None
------------------------------
All
None
''' |
e3da65a2517a2fccbf79fbfc0ecd0b208efb3a1b | jgingh7/Problem-Solving-Python | /Inter/MinimumHeightTrees.py | 1,354 | 3.6875 | 4 | # https://leetcode.com/problems/minimum-height-trees/
# Time: O(V)
# Space: O(V) - edges + leaves
from collections import defaultdict
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
# base cases
if n <= 2:
return [i for i in range(n)]
# make adjacency list of tree edges
tree = defaultdict(set)
for edge in edges:
tree[edge[0]].add(edge[1])
tree[edge[1]].add(edge[0])
# check for leaves
leaves = []
for key in tree:
if len(tree[key]) == 1:
leaves.append(key)
while True:
newLeaves = []
for leaf in leaves:
fixNeededNode = tree[leaf].pop()
tree[fixNeededNode].remove(leaf) # remove leaf from the nodes that connect the leaf
if len(tree[fixNeededNode]) == 1: # if the connecting node becomes a leaf, set it as newLeaf
newLeaves.append(fixNeededNode)
tree.pop(leaf) # remove leaf from the tree
if len(tree) <= 2: # there are at most 2 roots possible for a MHT
return tree.keys()
leaves = newLeaves #set next leaves as newLeaves
|
dad078e3463e155e5ac368b2de398ee2d57497be | clarkwalcott/CSPractice | /Easy/checkNums.py | 425 | 4.125 | 4 | # Have the function CheckNums(num1,num2) take both parameters being passed and return the string "true"
# if num2 is greater than num1, otherwise return the string "false". If the parameter values are equal
# to each other then return the string "-1".
# Problem Credit: Coderbyte.com
def CheckNums(num1,num2):
if num2==num1: return "-1"
return "true" if num2 > num1 else "false"
print CheckNums(raw_input()) |
5cebbbd34f6d67c25c69ba9eac50a44836a9ea64 | DevproxMeetup/TicTacToe-Python | /board.py | 1,011 | 3.578125 | 4 | # Our Game Class
class GameBoard:
def __init__(self, cols, rows=None):
if rows is None:
rows = cols
self.cols = cols
self.rows = rows
self._matrix = [None] * (rows*cols)
def _convert_to_pos(self, key):
if isinstance(key, int):
return key
if isinstance(key, str):
c = ord(key[0]) - ord('A')
r = int(key[1]) - 1
return r * self.cols + c
def __str__(self):
row = '|'.join([' {} ' for _ in range(self.cols)])
line = '\n' + '+'.join(['---' for _ in range(self.cols)]) + '\n'
layout = line.join(row for _ in range(self.rows))
markers = [i or ' ' for i in self._matrix]
return layout.format(*markers)
def __setitem__(self, key, value):
pos = self._convert_to_pos(key)
self._matrix[pos] = value
def __getitem__(self, key):
pos = self._convert_to_pos(key)
return self._matrix[pos]
|
4331adac75ddea1b1dc88ea2aa21d89e5ce2db39 | harrifeng/Python-Study | /Leetcode/ZigZag_Conversion.py | 1,211 | 4.375 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
```
P A H N
A P L S I I G
Y I R
```
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
"""
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1: # Be careful about nRows ==1
return s
size = 2 * nRows - 2
n = len(s) / size + 1
res = []
for i in range(size):
if i == 0 or i == size / 2:
for j in range(n):
if j * size + i < len(s):
res.append(s[j*size+i])
if i == size/2:
return ''.join(res)
else:
for j in range(n):
if j * size + i < len(s):
res.append(s[j*size+i])
if (j+1) * size - i < len(s):
res.append(s[(j+1) * size - i])
|
c0e31502d9694c5220f0ca0e899f9b8e3137b853 | SillyHatsOnly/Python-Education-Experiments | /Homework files/Homework_4_test_2.py | 739 | 3.84375 | 4 | '''
Написать функцию moar(a, b, n) от трёх параметров — целочисленных
последовательностей a и b, и натурального числа n. Функция возвращает
True, если в a больше чисел, кратных n, чем в b, и False в противном
случае.
Input: print(moar((25,0,-115,976,100500,7),(32,5,78,98,10,9,42),5))
Output: True
'''
def moar(a, b, n):
count_a, count_b = 0, 0
for i in a:
if i % n == 0: count_a += 1
for i in b:
if i % n == 0: count_b += 1
if count_a > count_b:
return True
else:
return False
print(moar((25,0,-110,975,100500,7),(32,5,78,98,10,9,42),5))
|
ed468f962989c19655c152748b4a443f8d574917 | ManullangJihan/Linear_Algebra_Courses | /CH 1/CH 1 Sec 7 Part 1/part55.py | 208 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 18:52:55 2020
@author: hanjiya
"""
import numpy as np
r = np.array([[2,1,0]])
A = np.array([[1,2,-3],[-2,1,1],[3,1,4]])
print(r@A)
|
59427c6db6e5fc4e674371eea1f58834591878c2 | yckfowa/codewars_python | /7KYU/Reverse words.py | 84 | 3.640625 | 4 | def reverse_words(text):
return ' '.join(text[::-1] for text in text.split(" "))
|
9c61d83ff1568391796df9bb3dfeea09f9bd6a43 | profarav/python101 | /002_kmtomiles.py | 204 | 4.34375 | 4 | print("This program converts kilometers into miles. You get to choose the number for the kilomter.")
km = float(input ("Please enter your number for the kilometer:") )
print(km, "km =", km/1.6, "miles")
|
092909badd9beeb0a2a2d12baf6aa411a695d722 | n8hanwilliams/pdsnd_github | /bikeshare.py | 7,532 | 4.21875 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_DATA = {'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6,
'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4}
DAY_DATA = {'monday': 0,
'tuesday': 1,
'wednesday': 2,
'thursday': 3,
'friday': 4,
'saturday': 5,
'sunday': 6,
'mon': 0,
'tue': 1,
'wed': 2,
'thu': 3,
'fri': 4,
'sat': 5,
'sun': 6}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = input('Please input city name. Options are "chicago", "new york city", or "washington": ').lower()
while city not in ['chicago', 'new york city', 'washington']:
city = input('City is invalid! Options are "chicago", "new york city", or "washington": ').lower()
# get user input for month (all, january, february, ... , june)
month = input('Please input month name. Options are "all", "january", "february", "march", "april", "may", "june": ').lower()
while month not in ['all', 'january', 'february', 'march', 'april', 'may', 'june', 'jan', 'feb', 'mar', 'apr']:
month = input('Month is invalid! Options are "all", "january", "february", "march", "april", "may", "june": ').lower()
# get user input for day of week (all, monday, tuesday, ... sunday)
day = input('Please input day of week. Options are "all", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday": ').lower()
while day not in ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']:
day = input('Day is invalid! Options are "all", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday": ').lower()
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
# Convert the Start and End Time columns to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['End Time'] = pd.to_datetime(df['End Time'])
# Create day_of_week and month columns
df['day_of_week'] = df['Start Time'].dt.dayofweek
df['month'] = df['Start Time'].dt.month
# filter by month if applicable
if month != 'all':
df = df[df['month'] == MONTH_DATA[month]]
# filter by day of week if applicable
if day != 'all':
df = df[df['day_of_week'] == DAY_DATA[day]]
return df
#gets the name of the month or day
def get_name(dictionary,val):
for key, value in dictionary.items():
if val == value:
return key
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
print("The most common month is: {}".format(get_name(MONTH_DATA,df['month'].mode().values[0]).capitalize()))
# display the most common day of week
print("The most common day of the week: {}".format(get_name(DAY_DATA,df['day_of_week'].mode().values[0]).capitalize()))
# display the most common start hour
df['start_hour'] = df['Start Time'].dt.hour
print("The most common start hour: {}".format(str(df['start_hour'].mode().values[0])))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
print("The most common start station is: {} ".format(df['Start Station'].mode().values[0]))
# display most commonly used end station
print("The most common end station is: {}".format(df['End Station'].mode().values[0]))
# display most frequent combination of start station and end station trip
df['routes'] = df['Start Station']+ " ==> " + df['End Station']
print("The most common start and end station combo is: {}".format(df['routes'].mode().values[0]))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
df['duration'] = df['End Time'] - df['Start Time']
# display total travel time
print("The total travel time is: {}".format(str(df['duration'].sum())))
# display mean travel time
print("The mean travel time is: {}".format(str(df['duration'].mean())))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df, city):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
print("Here are the counts of various user types:")
print(df['User Type'].value_counts())
if city != 'washington':
# Display counts of gender
print("Here are the genders:")
print(df['Gender'].value_counts())
# Display earliest, most recent, and most common year of birth
print("The earliest birth year is: {}".format(str(int(df['Birth Year'].min()))))
print("The latest birth year is: {}".format(str(int(df['Birth Year'].max()))))
print("The most common birth year is: {}".format(str(int(df['Birth Year'].mode().values[0]))))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def raw_data(df):
"""Displays raw data"""
start = 0
end = 5
display_raw = input("Do you want to see the raw data? (yes/no): ")
while display_raw == "yes" or display_raw == "y":
print(df.iloc[start:end])
start += 5
end += 5
display_raw = input("Would you like to see more raw data? Enter yes or no.\n")
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df, city)
raw_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
8bad99423f390221a6eab31195669e9ce9a08d6b | Olga2344/pythonProject | /2 ex.py | 567 | 3.84375 | 4 | # 2. Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
sec = int(input('введите количество секунд: '))
hour = ((sec // 3600)) % 24
minuets = (sec // 60) % 60
seconds = sec % 60
print(f"вы ввели количество секунд {sec}, время в формате чч:мм:сс {hour:02}:{minuets:02}:{seconds:02}")
|
2d99ebfdce4345f44ee622cab045193ecd5ba2a4 | coryplusplus/PythonMusicConverter | /convertABC.py | 866 | 3.578125 | 4 | from music21 import *
songName = raw_input("Please enter the name of the song: ")
musicFile = open("textfiles\\" + songName + ".txt", 'w+')
abcScore = converter.parse("abcfiles\\" + songName + ".abc")
flat = abcScore.flat
measures = abcScore.getElementsByClass(stream.Part)[0].getElementsByClass(stream.Measure)
if(len(measures) != 0):
print("We have measures")
for measure in measures:
measureNotes = ""
for note in measure.notes:
measureNotes = measureNotes + str(note.name) + str(note.octave) + " "
musicFile.write(measureNotes + "\n")
else:#we will just use the chords
print("No measures")
flat = abcScore.flat
chords = abcScore.getElementsByClass(stream.Part)[0].getElementsByClass(chord.Chord)
for chord in chords:
musicFile.write(str(chord)[21:len(str(chord))-1] + "\n")
musicFile.close();
|
086cca562bfe70cd29bb9b594b9afdc8113df06f | nielsbijl/ML | /Perceptron/PerceptronNetwork.py | 1,308 | 4.21875 | 4 | class PerceptronNetwork:
"""
The PerceptronNetwork class is a network of perceptrons, this contains layers which contains perceptrons
"""
def __init__(self, layers: list):
"""
This function initializes the PerceptronNetwork object
:param perceptrons: The list of layer(s) for the network
"""
self.layers = layers
self.networkInput = []
self.output = []
def setInput(self, networkInput: list):
"""
This function sets the input for the network
:param networkInput: The list of integers or floats as input for the network
"""
self.networkInput = networkInput
def feedForward(self):
"""
This functions runs the network. A layer gets his input and his output will be the next input for the next layer
This wil generate the final output of the perceptron network
"""
if self.networkInput:
layerInput = self.networkInput
for layer in self.layers:
layer.setInput(layerInput)
layer.run()
layerInput = layer.output
self.output = layerInput
else:
raise Exception("The perceptron network has no input, please set the input with the setInput function!")
|
a06757353abe4cec3149868402f4b04fdfa385eb | yeghia-korkejian/Aca_python | /Week2/Homework_2/problem2.py | 569 | 4.28125 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("text",
help="Add text which is 7 or more characters long and has an odd number of characters", type=str)
args = parser.parse_args()
if len(args.text) % 2 == 0 or len(args.text) < 7 :
print ("Add text which is 7 or more characters long and has an odd number of characters")
else:
print("The old string: " + args.text)
a = args.text[(len(args.text) // 2)-1 : (len(args.text) // 2)+2]
print("Middle 3 characters: " + a)
print("The new string: " + args.text.replace(a ,a.upper())) |
bad58f65ab58881e92dccf862475200c3c5c5e60 | kindlychung/pyQCDH | /build/lib/pyQCDH/BimFamReader.py | 2,557 | 3.8125 | 4 | import pandas
def count_lines(filename):
"""
Count the number of lines in a file.
:param filename:
:type filename: str
:return:
:rtype: int
"""
n = 0
with open(filename, "rb") as fh:
for line in fh:
n += 1
return n
# a mix-in class for reading bim and fam files
class BimFamReader:
def __init__(self, *args, **kwargs):
"""
The cols and full_idx field must exist in the other class that uses this one as a mix-in.
:return:
:rtype:
"""
#:type: pandas.core.frame.DataFrame
self._data = None # family and individual id, lazily evaluated
@property
def data(self):
if self._data is not None:
self._data = self.read(usecols="all")
return self._data
def read(self, **kwargs):
"""
Read bim or fam file. All the **kwargs are passed to pandas.read_csv,
the usecols option is given special care, you can pass an numbered index list,
or a list of column names that you wish to select.
When usecols is set to "all", all columns are read.
:param kwargs:
:type kwargs:
:return:
:rtype: pandas.core.frame.DataFrame
"""
# pdb.set_trace()
#:type: list[str]
cols_res = self.cols[:]
if "usecols" in kwargs:
# read all if usecols is set to "all"
if kwargs["usecols"] == "all":
kwargs["usecols"] = self.full_idx
# if usecols is a list of integers, use it as an index for colnames
elif isinstance(kwargs["usecols"][0], int):
idx = [x for x in self.full_idx if x in kwargs["usecols"]]
cols_res = [self.cols[x] for x in idx]
# if usecols is a list of strings, then we need to calculate the index to be passed to read_csv
elif isinstance(kwargs["usecols"][0], str):
idx = [self.cols.index(x) for x in kwargs["usecols"]]
cols_res = [i for i in self.cols if i in kwargs["usecols"]]
kwargs["usecols"] = idx
else:
raise ValueError("usecols must be a list of str or int or None")
data = pandas.read_csv(self.filename, delim_whitespace=True, header=None, **kwargs)
data.columns = cols_res
return data
def count_lines(self):
"""
Count the number of lines in the bim or fam file.
:return:
:rtype: int
"""
return count_lines(self.filename)
|
ba15ab403bcdb2ad7972758ece7f0afa9e5ee7f3 | gwendalp/Machine_Learning | /Week_7/aralsea_main.py | 2,575 | 3.5 | 4 | #%% Machine Learning Class - Exercise Aral Sea Surface Estimation
# package
import numpy as np
import matplotlib.pyplot as plt
plt.ioff() # to see figure avant input
# ------------------------------------------------
# YOUR CODE HERE
from preprocessing import preprocessing
# ------------------------------------------------
# ------------------------------------------------
#%% Examen des données, prétraitements et extraction des descripteurs
# Chargement des données et prétraitements
featLearn,img73,img87 = preprocessing()
print(featLearn[0].shape)
print(featLearn[1] * featLearn[2])
print(img73.shape)
plt.subplot(121)
plt.title("Aral 1973")
plt.imshow(img73)
plt.subplot(122)
plt.title("Aral 1987")
plt.imshow(img87)
plt.show()
#%% Apprentissage / Learning / Training
# Apprentissage de la fonction de classement
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
# prediction des labels sur la base d'apprentissage
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
# Visualisation des resultats
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
#%% Classement et estimation de la diminution de surface
# Classifying / Predicting / Testing
# mise en forme de l'image de 1973 et 1987 en matrice Num Pixels / Val Pixels
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
# Classement des deux jeux de données et visualisation des résultats en image
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
#%% Estimation de la surface perdue
answer = input('Numero de la classe de la mer ? ')
cl_mer = int(answer)
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
|
2642537498d52d98390e8b1b82bf4d314ec5e81f | hazamp01/Algorithms | /Array_with_duplicates.py | 805 | 3.96875 | 4 | import collections
array = [2, 3, 5, 3, 7, 9, 5, 3, 7]
Out = [3, 3, 3, 5, 5, 7, 7, 2, 9]
output = {i: array.count(i) for i in array}
for key, value in sorted(output.iteritems(), key=lambda (k, v): (-v, -k)):
print "%s: %s" % (key, value)
a = []
# Remove duplicates in array
for element in array:
if element not in a :
a.append(element)
else:
pass
print a
# You are given an array with duplicates. You have to sort the array with decreasing frequency of elements.
# If two elements have the same frequency, sort them by their actual value in increasing order.
# To count the frequeny of repeating elements in list
output={i:array.count(i) for i in array}
cat=output.values()
max=max(cat)
# for element in range(0,len(cat)):
# if element is max:
print output
# print cat
|
f0a909ca5858215c7001a0ceeb0fc4ee93eddcb0 | HBinhCT/Q-project | /hackerearth/Math/Number Theory/Primality Tests/Does it divide/solution.py | 438 | 3.96875 | 4 | def is_prime(x):
if x <= 1:
return False
if x == 2 or x == 3:
return True
if x % 2 == 0 or x % 3 == 0:
return False
for i in range(5, int(x ** .5) + 1, 6):
if x % i == 0 or x % (i + 2) == 0:
return False
return True
t = int(input())
for _ in range(t):
n = int(input())
if n == 1:
print('YES')
continue
print('NO' if is_prime(n + 1) else 'YES')
|
af0bb7fd0e86af2cafbeb32f0795ebc8473248e1 | milenatteixeira/cc1612-exercicios | /exercicios/lab 2/testeRelacionais9.py | 318 | 3.5 | 4 |
# coding: utf-8
# In[1]:
a = 4
b = 10
c = 5.0
d = 1
f = 5
print("A = C?:", a==c)
print("A < B?:", a<b)
print("D < B?:", d<b)
print("C != F?:", c!=f)
print("A = B?:", a==b)
print("C < D?:", c<d)
print("B > A?:", b>d)
print("C >= F?:", c>=f)
print("F >= C?:", f>=c)
print("C <= C?:", c<=c)
print("A <= F?:", a<=f)
|
ba291f8843538abc1f8cdef1c0c7207c337d4df3 | juliethrallstewart/Data-Structures-Julie | /binary_search_tree/dll_stack.py | 1,041 | 3.609375 | 4 | import sys
sys.path.append('../doubly_linked_list')
from doubly_linked_list import DoublyLinkedList
#last in first out
class Stack:
def __init__(self):
self.size = 0
# Why is our DLL a good choice to store our elements?
#Answer: Memory, for a queue we have to add and remove from the front and the back
#and since we are using a doublylinked list it is good to keep using one for consistency
self.storage = DoublyLinkedList()
def push(self, value):
#add item to tail
# self.add_to_tail(value)
# self.storage.add_to_tail(value)
self.storage.add_to_head(value)
self.size+= 1
def pop(self):
#remove last item in
# self.remove_from_tail()
if self.size > 0:
self.size -= 1
# return self.storage.remove_from_tail()
return self.storage.remove_from_head()
else:
return None
def len(self):
# self.size = self.length
return self.size |
0f5e86a7e85d6f10eb5c3400d6d7ac206878462a | anthonybgg/Coding-Challenges | /reverseWord.py | 599 | 4.4375 | 4 | """
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace
and initial word order.
Example 1:
Input: "The cat in the hat"
Output: "ehT tac ni eht tah"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
"""
def reverseWord(words : str):
# Fill this in.
worded = words.split()
ret = ''
for i in range(len(worded)):
if i == len(worded):
ret += worded[i][::-1]
else:
ret += worded[i][::-1] + ' '
return ret
|
16ad91f6e6452bd77f78d2083ffb5d54f140044a | belwalter/clases_programacion_i | /clase_poo.py | 5,245 | 3.875 | 4 |
#! Programación orientada a objetos
#! Componentes: Clases, Objetos y Mensajes
#! Caracteristicas: Encapsulamiento, Herencia, Polimorfismo
#! Sobrecarga, Constructor, Ocultamiento de la informacíon
class Persona(object):
"""Clase que representa a una persona."""
def __init__(self, apellido, nombre, edad=None, email=None, n_cuenta=None):
self.__apellido = apellido
self.__nombre = nombre
self.__edad = edad
self.__email = email
self.__n_cuenta = n_cuenta
def apellido(self):
return self.__apellido
def email(self):
return self.__email
def set_email(self, mail):
"""Cambia el valor del atributo mail."""
self.__email = mail
@property
def edad(self):
return self.__edad
@edad.setter
def edad(self, edad):
"""Cambia el valor del atributo mail."""
if(type(edad) is int):
self.__edad = edad
else:
print('la edad debe ser entero')
def mostrar_datos(self):
"""Muestra los datos de cada persona."""
print(self.__apellido, self.__nombre, self.__email)
# from consumo_api import get_charter_by_id
# per1 = get_charter_by_id(20)
# persona0 = Persona(per1['name'], per1['height'])
persona1 = Persona('Perez', 'Maria', email='asdasd@asda.com')
# persona2 = Persona('Gonzalez', 'Maria', 23)
# persona3 = Persona('Caseres', 'Julieta')
# persona3.set_email("123@123.com")
# persona1.mostrar_datos()
# persona2.mostrar_datos()
# persona3.mostrar_datos()
# persona2.edad = 45
# print(persona2.edad)
# print(persona1.apellido, persona1.nombre)
# print(persona2.apellido, persona2.nombre)
# print(persona3.apellido, persona3.nombre)
# print(persona1)
# print(persona2)
# print(persona3)
# print(persona1.apellido == persona3.apellido)
#! Herencia: agrupar objetos de distinta clase
#! que se comportan de manera similar
# class Animal():
# def __init__(self, nombre, especie, cantidad_patas):
# self.nombre = nombre
# self.especie = especie
# self.cantidad_patas = cantidad_patas
# a1 = Animal('caballo', 'mamifero', 4)
# a2 = Animal('pinguino', 'mamifero', 2)
# a3 = Animal('serpiente', 'reptil', 0)
# class Alumno(Persona):
# def __init__(self, fecha_inscripcion, apellido, nombre, edad=None, email=None, n_cuenta=None):
# self.__fecha_inscripcion = fecha_inscripcion
# Persona.__init__(self, apellido, nombre, edad, email, n_cuenta)
# def inscribirse(self):
# print('el alumno se esta inscribiendo a una materia')
# def mostrar_datos(self):
# print(self.apellido(), 'se incribio a cursar en:', self.__fecha_inscripcion)
# class Docente(Persona):
# def __init__(self, cantidad_materias, apellido, nombre, edad=None, email=None, n_cuenta=None):
# self.__cantidad_materia = cantidad_materias
# Persona.__init__(self, apellido, nombre, edad, email, n_cuenta)
# def mostrar_datos(self):
# print(self.apellido(), self.__cantidad_materia)
# def dictar_clase(self):
# print('el docente esta dictanto una cátedra...')
# a = Alumno('01-03-2021', 'perez', 'juan')
# d = Docente(4, 'alvarez', 'maria')
# personas = [a, persona1, d]
# for elemento in personas:
# elemento.mostrar_datos()
class FormaGeometrica():
def __init__(self, nombre, x, y, color):
self.nombre = nombre
self.x = x
self.y = y
self.color = color
def area(self):
print('metodo para calcular el area')
def perimetro(self):
print('metodo para calcular el perimetro')
def info(self):
print(self.nombre, self.color)
class Reactangulo(FormaGeometrica):
def __init__(self, base, altura, nombre, x, y, color):
self.base = base
self.altura = altura
FormaGeometrica.__init__(self, nombre, x, y, color)
def area(self):
return self.base * self.altura
def perimetro(self):
return 2 * self.altura + 2 * self.base
from math import pi
class Circulo(FormaGeometrica):
def __init__(self, radio, nombre, x, y, color):
self.radio = radio
FormaGeometrica.__init__(self, nombre, x, y, color)
def area(self):
return pi * self.radio ** 2
def perimetro(self):
return 2 * pi * self.radio
class Triangulo(FormaGeometrica):
def __init__(self, base, altura, altura2, nombre, x, y, color):
self.base = base
self.altura = altura
self.altura2 = altura2
FormaGeometrica.__init__(self, nombre, x, y, color)
def area(self):
return self.base * self.altura / 2
def perimetro(self):
return self.base + self.altura + self.altura2
formas = []
r1 = Reactangulo(3, 6, 'rectangulo 1', 5, 7, 'rojo')
formas.append(r1)
r2 = Reactangulo(5, 4, 'rectangulo 2', 15, 70, 'azul')
formas.append(r2)
c1 = Circulo(9, 'circulo 1', -6, 21, 'negro')
formas.append(c1)
c2 = Circulo(2, 'circulo 2', -16, 2, 'violeta')
formas.append(c2)
t1 = Triangulo(3, 1, 4, 'triangulo 1', 4, 0, 'amarillo')
formas.append(t1)
for elemento in formas:
elemento.info()
print('area:', elemento.area())
print('perimetro:', elemento.perimetro()) |
7e42dee69a19b39f18b9819803280048954ef773 | jan25/code_sorted | /leetcode/weekly150/max_level_sum.py | 905 | 3.765625 | 4 | '''
https://leetcode.com/contest/weekly-contest-150/problems/maximum-level-sum-of-a-binary-tree/
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
q, qi = [root], 0
pop = 1
max_sum, s = 0, 0
l, curr_l = 1, 1
while len(q) - qi > 0:
if pop == 0:
pop = len(q) - qi
if max_sum < s:
l = curr_l
max_sum = s
s = 0
curr_l += 1
else:
pop -= 1
f = q[qi]
s += f.val
if f and f.left: q.append(f.left)
if f and f.right: q.append(f.right)
qi += 1
return l
|
699954e0445c600703c7f43420eb3423135bb6bd | QuentinDuval/PythonExperiments | /arrays/CardFlippingGame.py | 1,535 | 4.09375 | 4 | """
https://leetcode.com/problems/card-flipping-game/
On a table are N cards, with a positive integer printed on the front and back of each card (possibly different).
We flip any number of cards, and after we choose one card.
If the number X on the back of the chosen card is not on the front of any card, then this number X is good.
What is the smallest number that is good? If no number is good, output 0.
Here, fronts[i] and backs[i] represent the number on the front and back of card i.
A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.
"""
from typing import List
class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
"""
If a number is both on front and back, it cannot be selected.
If not, there is always a way to move all to back the smallest number.
So you can just move through the fronts and back and keep track of the
minimum number that is not both on a front and back.
=> O(N) complexity is possible in two passes
"""
banned = set()
n = len(fronts)
for i in range(n):
if fronts[i] == backs[i]:
banned.add(fronts[i])
min_card = float('inf')
for i in range(n):
if fronts[i] not in banned:
min_card = min(min_card, fronts[i])
if backs[i] not in banned:
min_card = min(min_card, backs[i])
return min_card if min_card != float('inf') else 0
|
b57d366c74737cccf8e7dcfc29c5def49fe3d250 | sneidermendoza/Ejercicios-ciclo-for | /ejercicio_7.py | 1,045 | 3.890625 | 4 | # En un supermercado una ama de casa pone en su carrito los artículos que
# va tomando de los estantes. La señora quiere asegurarse de que el cajero
# le cobre bien lo que ella ha comprado, por lo que cada vez que toma un
# artóculo anota su precio junto con la cantidad de artículos iguales que ha
# tomado y determina cuanto dinero gastará en ese artículo; a esto le suma lo
# que irá gastando en los demás artículos, hasta que decide que ya tomó
# todo lo que necesitaba. Ayúdele a esta señora a obtener el total de su
# compra.
articles = int(input("Por favor, ingrese cuantos articulos compro: "))
number_articles = 0
total = 0
items = 0
for i in range(articles):
number_articles += 1
value_artile = float(input(f"valor del articulo # {number_articles}: $"))
number_items = int(input("numero de articulos: "))
items += number_items
value_x_items = value_artile * number_items
total += value_x_items
print(f"El total de articulos es: {items} unidades, y el toal de la compra es: ${total} ")
|
c22614cafa045ab7288ab4969b0414c046144af5 | automoto/python-code-golf | /arrays_and_lists/all_unique_subsets.py | 507 | 4.09375 | 4 | """
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
"""
import itertools
def subsets(nums):
subsets = []
for i in range(len(nums)):
combinations = [list(i) for i in itertools.combinations(nums, i)]
subsets.extend(combinations)
subsets.append(nums)
return subsets
answer = subsets([1, 2, 3])
print(answer)
assert answer == [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] |
a5b568d4b513754b15132e086038549abbeaf87d | JPeck567/MazeScape | /inputbox/inputbox.py | 1,995 | 3.640625 | 4 | """
by Timothy Downs, input_box written for my map editor
This program needs a little cleaning up
It ignores the shift key
And, for reasons of my own, this program converts "-" to "_"
A program to get user input, allowing backspace etc
shown in a box in the middle of the screen
"""
import pygame
from pygame.locals import *
def get_key():
while True:
event = pygame.event.poll()
if event.type == KEYDOWN:
return event.key
else:
pass
def display_box(screen, message, colour):
# Print a message in a box in the middle of the screen
font_object = pygame.font.Font(None, 25)
pygame.draw.rect(screen, colour, ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10, 300, 20), 0)
pygame.draw.rect(screen, (255, 255, 255), ((screen.get_width() / 2) - 102,
(screen.get_height() / 2) - 12, 304, 24), 1)
if len(message) != 0:
screen.blit(font_object.render(message, 1, (255, 255, 255)), ((screen.get_width() / 2) - 100,
(screen.get_height() / 2) - 10))
pygame.display.flip()
def ask(screen, question, colour):
# ask(screen, question) -> answer
pygame.font.init()
current_string = ""
allowed_chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
display_box(screen, (question + ": "), colour)
while True:
key = get_key()
if key == K_BACKSPACE:
current_string = current_string[0:-1]
elif key == K_RETURN:
break
elif key <= 127:
if set(chr(key)).issubset(allowed_chars):
current_string = current_string + (chr(key))
display_box(screen, ((question + ":") + current_string), colour)
return current_string
def main():
screen = pygame.display.set_mode((320, 240))
print(ask(screen, "Enter Name", (0, 100, 100)))
if __name__ == '__main__':
main()
|
d1fcb8c9d08d53ea2076807f90b44cf47a291cb2 | Jackroll/aprendendopython | /exercicios_udemy/Programacao_Procedural/dictionary_comprehension_63.py | 701 | 4.125 | 4 | #comprehension dictionary
lista = [
('ch1', 'valor ch1'),
('ch2', 'valor ch2'),
]
print('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')
#covertendo a lista 1 em dicionário com comprehension
d1 = {c: v for c, v in lista} #chave : valor para cada chave, valor na lista
print(d1)
print('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')
#convertendo e passando para maiusculo a chave e o valor
d2 = {c.upper(): v.upper() for c, v in lista} #convertendo e passando para maiusculo a chave e o valor
print(d2)
print('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')
#criando dicionário com chave e valor automático com base num range
d3 = {f'ch{x}': x**2 for x in range(5)}
print(d3) |
edd1592df02faaee5fa507cf31a5f4928a68271c | yousuf1318/hypervage | /DSA_step_7/check if the srt palindrome.py | 191 | 4.15625 | 4 | inp=input("Enter Your Word : ")
palindrome =""
for i in inp:
palindrome= i+palindrome
if inp==palindrome:
print("It's a palindrome")
else:
print("it's not a palindrome.") |
1bc367a6672e528a4d1eee45488e6b6ac150c6e4 | SenJia/Reinventing-the-wheel | /LinkedList.py | 359 | 3.8125 | 4 | # When writing sorting toy examples, a linked list can be used to insert an element
# into a sorted sublist.
# I just add a simple implementation of Linked List for later use.
# A linked list consists of a list of nodes.
#
# Author: Sen Jia
#
class Node:
def __init__(self,data,nextNode=None):
self.data = data
self.nextNode = nextNode
|
c98e39e027b67a40fe065f0c7593114c2d9b4523 | Akhila098/test | /strings.py | 192 | 3.59375 | 4 | varOne="hello"
varTwo="world"
varThree="Hey"
#Concat
print(varOne+varTwo)
#Repetition
print(varThree * 3)
#Slice
print(varOne[1:3])
print(max(varOne))
print(min(varTwo))
print(len(varOne))
|
b1e1ae69a0cfc858692705cce7b993acaab2496d | kolyasalubov/Lv-585.2.PythonCore | /HW4/Viktor/4_3.py | 316 | 3.828125 | 4 | fibonacci1 = 1
fibonacci2 = 1
user_number = int(input("Enter a last Fibonacci number: "))
print(0, fibonacci1, fibonacci2, sep=', ', end=', ')
for i in range(2, 50):
fibonacci1, fibonacci2 = fibonacci2, fibonacci1 + fibonacci2
if fibonacci2 > user_number:
break
print(fibonacci2, end=', ')
|
873c5c2cfcb30ae1bc96269a47988f0b560992f6 | Heidyrh13/DataChallenge365FEM-HR | /Challenge_1/pythonIf-Else.py | 373 | 3.625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
i = n % 2
if i != 0:
print("Weird")
elif (i == 0) and (2 <= n <= 5):
print("Not Weird")
elif (i == 0) and (6 <= n <= 20):
print("Weird")
elif (i == 0) and (n > 20):
print("Not Weird")
|
151a28b2ad46d04beec6d61992618d423aa39866 | hemma/aoc2020 | /aoc2020/day7.py | 1,219 | 3.5625 | 4 | # https://adventofcode.com/2020/day/7
import re
def get_color_rules(lines: list[str]) -> dict[str, list]:
color_rules = {}
for line in lines:
outer_color = line.split("bags")[0].strip()
inner_colors = re.findall("\\d ([a-z ]* )", line.split("contain")[1])
color_rules[outer_color] = [x.strip() for x in inner_colors]
return color_rules
def count_bag_colors_can_contain(color_rules: dict[str, list], color: str) -> int:
count = 0
for key in color_rules.keys():
if can_contain_color(color_rules, key, color):
count += 1
return count
def can_contain_color(color_rules: dict[str, list], color_key: str, color_to_match: str) -> bool:
for color in color_rules[color_key]:
a = color_rules[color_key]
if color == color_to_match:
return True
else:
if can_contain_color(color_rules, color, color_to_match):
return True
return False
if __name__ == '__main__':
with open('day7.txt') as f:
inp: list[str] = f.readlines()
rules = get_color_rules(inp)
bag_count = count_bag_colors_can_contain(rules, "shiny gold")
print("Part one %s" % bag_count)
|
185f6591b1eaf4e9b74d8b38adfbc4189ed56455 | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/343/102866/submittedfiles/principal.py | 114 | 3.5625 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
notas = [8.0, 9.5, 10.0]
notas.append(float(input('Digite a nota: ')) |
a7879e0e1d5f1946447ac1403e55bf7b3afbdae2 | shivanshthapliyal/Algorithms | /day-1-sorting/merge-sort.py | 924 | 4.1875 | 4 | # Author => Shivansh Thapliyal
# Date => 1-Jan-2020
def merge(left_arr,right_arr):
output=[]
#adding to output till elements are found
while left_arr and right_arr:
left_arr_item = left_arr[0]
right_arr_item = right_arr[0]
if left_arr_item < right_arr_item:
output.append(left_arr_item)
left_arr.pop(0)
else:
output.append(right_arr_item)
right_arr.pop(0)
while left_arr:
output.append(left_arr[0])
left_arr.pop(0)
while right_arr:
output.append(right_arr[0])
right_arr.pop(0)
return output
def merge_sort(arr):
arr_length = len(arr)
#base case
if arr_length<2:
return arr
left_arr = arr[:arr_length//2]
right_arr = arr[arr_length//2:]
# // forces division
# we then sort the list recursively
left_arr = merge_sort(left_arr)
right_arr = merge_sort(right_arr)
return merge(left_arr,right_arr)
array = [34,12,2,41,53,127]
sortedarray = merge_sort(array)
print(sortedarray) |
2e4674422197e61f9548e949c2835538c40bd981 | Sergey0987/firstproject | /Функции 4/Поиски возвышенного.py | 348 | 3.796875 | 4 | def findMountain(heightsMap):
row = 0
column = 0
for i in range(len(heightsMap)):
for j in range(len(heightsMap[i])):
if heightsMap[i][j] > heightsMap[row][column]:
row = i
column = j
return (row, column)
row, column = findMountain([[1,3,1],[3,2,5],[2,2,2]])
print(row, column)
|
a9b0021b7d93459f98bf274130d094734624960d | erikaosgue/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 1,784 | 4.03125 | 4 | #!/usr/bin/python3
""" 7. Singly linked list """
class Node:
""" Creates A New Node """
__data = 0
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
@property
def data(self):
return (self.__data)
@data.setter
def data(self, value):
if not isinstance(value, int):
raise Exception('data must be an integer')
self.__data = value
@property
def next_node(self):
return self.__next_node
@next_node.setter
def next_node(self, value):
if not isinstance(value, Node) and value is not None:
raise TypeError('next_node must be a Node object')
self.__next_node = value
class SinglyLinkedList:
"""Creates the single Linked list"""
def __init__(self):
self.__head = None
def sorted_insert(self, value):
if self.__head is None:
self.__head = Node(value, self.__head)
return
if self.__head.next_node is None:
if value < self.__head.data:
self.__head = Node(value, self.__head)
else:
self.__head.next_node = Node(value, None)
return
prev = None
curr = self.__head
while curr and value > curr.data:
prev = curr
curr = curr.next_node
if prev is None:
self.__head = Node(value, self.__head)
else:
new_node = Node(value, prev.next_node)
prev.next_node = new_node
def __str__(self):
curr = self.__head
s = ''
while curr:
s += str(curr.data) + '\n'
curr = curr.next_node
if s and s[-1] == "\n":
s = s[:-1]
return s
|
5592a1e3ea539b753573f20b818f885d8536b71c | donutdaniel/Python-Challenge | /p0-9/p0/p0.py | 107 | 3.859375 | 4 | x = 2**38
print("2 to the 38th power is %i" % x)
print("http://www.pythonchallenge.com/pc/def/%i.html" % x) |
5c826df0cf051c98c9bdc051459d53737389446f | Aasthaengg/IBMdataset | /Python_codes/p02552/s759343030.py | 76 | 3.796875 | 4 | x = float(input())
if float(x) == 0:
print(1)
elif float(x)==1:
print(0) |
be222de45118408627f45871074f5dbdc7c6855e | jandres9102/ejercicios-1-a-34 | /ex34.py | 290 | 3.9375 | 4 |
animals=['cat','dog','pig','kangaroo']
print"what animal go you want to see?"
animal=raw_input()
if animal=='1':
print animals[1]
elif animal=='2'
print animals[2]
elif animal=='3'
print animals[3]
elif animal=='0'
print animals[0]
else:
print "this animal isn't in this position" |
82f5cf39c269039d9cd02d066096d17c0241499c | longgb246/MLlearn | /leetcode/dynamic_programming/152_max_product.py | 931 | 3.5625 | 4 | # -*- coding:utf-8 -*-
# @Author : 'longguangbin'
# @Contact : lgb453476610@163.com
# @Date : 2019/2/3
"""
Usage Of '152_max_product.py' :
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 28 ms - 99.66%
# 计算从左到右的相乘的最大值,和计算从右到左的最大值;再将两组最大值相比
B = nums[::-1]
for i in range(1, len(nums)):
nums[i] *= nums[i - 1] or 1
B[i] *= B[i - 1] or 1
return max(max(nums), max(B))
def get_test_instance(example=1):
nums = [2, 3, -2, 4]
if example == 1:
pass
if example == 2:
nums = [-2, 0, -1]
return nums
def main():
nums = get_test_instance(example=1)
# nums = get_test_instance(example=1)
res = Solution().maxProduct(nums)
print(res)
if __name__ == '__main__':
main()
|
88f2765d809edce83f4fde919c812586b8570cda | VStavinskyi/codewars-solutions-in-python | /033-6kyu-Replace With Alphabet Position.py | 373 | 3.9375 | 4 | def alphabet_position(text):
text = text.lower()
print text
res = ""
index = 0
while index < len(text):
item = text[index]
if ord(item) > ord("z") or ord(item) < ord("a"):
index += 1
continue
# print item,ord(item)-ord("a")
res += str(ord(item)-ord("a")+1) + " "
index += 1
return res[:-1] |
26b6f603b5ac82afb11754fdf176c898fca9e06e | TheVille415/list_loops | /list_loops.py | 490 | 3.84375 | 4 | songs = ["ROCKSTAR", "Do It", "For The Night"]
print(songs[0])
print(songs[2])
print(songs[1:3])
songs[2] = "Beauty & Essex"
print(songs)
songs.extend(["Nasty", "Untitled (How Does It Feel)", "Amphetamine"])
songs.pop(1)
# Option 1
for song in songs:
print(song)
# Option 2
for i in range(len(songs)):
print(songs[i])
animals = ["pig", "chicken", "cow"]
animals.extend(["bat", "bear", "deer"])
print(animals[2])
del animals[0]
for i in range(len(animals)):
print(animals[i]) |
21a214d2c57b34d745aa3190477336889bc15cd2 | rflban/sem_04 | /CompAlgo/lab_06/main.py | 2,077 | 3.8125 | 4 | import sys
import derivative
def foo(X):
YY = []
for x in X:
YY.append(-3 * x / (2 + 3*x)**2 + 1 / (2 + 3*x))
return YY
def toStr(num):
if (num != '-'):
num = '{:9.5f}'.format(num)
return num
def main():
argc = len(sys.argv)
fname = ''
if argc <= 1:
fname = input("Введите имя входного файла: ")
else:
fname = sys.argv[1]
inputf = open(fname)
X = []
Y = []
for line in inputf.readlines():
if (str(line).strip() != ''):
x, y = tuple(map(float, line.split()))
X.append(x)
Y.append(y)
inputf.close()
Z1l = derivative.leftside(X, Y)
Z1r = derivative.rightside(X, Y)
Z2l = derivative.leftspace(X, Y)
Z2r = derivative.rightspace(X, Y)
Z3 = derivative.central(X, Y)
Z4l = derivative.runge_l(X, Y)
Z4r = derivative.runge_r(X, Y)
Z5r = derivative.leveling_variables_r(X, Y, lambda x: 1/x, lambda y: 2*y + 3)
Z5l = derivative.leveling_variables_l(X, Y, lambda x: 1/x, lambda y: 2*y + 3)
Z = foo(X)
print("{:^10s} {:^10s} "
"{:^23s} {:^23s} "
"{:^10s} {:^23s} {:^23s} "
"{:^23s}".format("x", "y", "левая", "правая", "центр", "Рунге", "вырав.", "точное"))
for i in range(len(X)):
x = toStr(X[i])
y = toStr(Y[i])
z1l = toStr(Z1l[i])
z2l = toStr(Z2l[i])
z1r = toStr(Z1r[i])
z2r = toStr(Z2r[i])
z3 = toStr(Z3[i])
z4l = toStr(Z4l[i])
z4r = toStr(Z4r[i])
z5r = toStr(Z5r[i])
z5l = toStr(Z5l[i])
z6 = toStr(Z[i])
print("{:>10s} | {:>10s} | {:>10s} | "
"{:>10s} | {:>10s} | {:>10s} | "
"{:>10s} | {:>10s} | {:>10s} | "
"{:>10s} | {:>10s} | {:>10s}".format(x, y, z1l, z2l, z1r, z2r, z3, z4l, z4r, z5l, z5r, z6))
if __name__ == '__main__':
main()
|
0e873b33df30835731220f03dfa0c5ff88bfbea1 | monburan/pythongit | /file.py | 1,029 | 4.34375 | 4 | #coding:UTF-8
filename = raw_input('Enter file name:')
#fileobj = open(filename,'r')
#for eachline in fileobj:
# print eachline,
#fileobj.close()
#filewriteobj = open(filename,'w')
#ͨwģʽļ
#filewriteobj.write("writing in this txt file!")
#ֱ֮ʹreadlineļ
#ֱʹreadlineᱨIOError: File not open for reading
#filewriteobj.close()
#filereadobj = open(filename,'r')
#ǽļͨrģʽͿԽ֮ǰдõʾĻ
#print filereadobj.readline()
#д쳣׳һ¾ٵ
#try:
# fobj = open(filename,'w')
# fobj.write("writing in this txt file!")
# print fobj.readline()
#except IOError,e:
# print 'file error is :',e
#нfile error is : File not open for reading
fileobj = open(filename,'w')
fileobj.write("writing in this txt file!")
fileobj.close()
fileobj = open(filename,'r')
print fileobj.readline()
|
8a8caf230e6351aa634a8ef03020933cc94d7d0c | duongdo27/geeks-for-geeks | /tests/search/algorithms/test_interpolation_search.py | 971 | 3.515625 | 4 | from search.algorithms.interpolation_search import interpolation_search
def test_empty_array():
array = []
value = 4
assert interpolation_search(array, value) == -1
def test_not_found():
array = [1, 2, 3]
value = 4
assert interpolation_search(array, value) == -1
def test_middle():
array = [1, 2, 3]
value = 2
assert interpolation_search(array, value) == 1
def test_left():
array = [1, 2, 3, 4, 5]
value = 1
assert interpolation_search(array, value) == 0
def test_left2():
array = [1, 2, 3, 4, 5]
value = 2
assert interpolation_search(array, value) == 1
def test_right():
array = [1, 2, 3, 4, 5]
value = 4
assert interpolation_search(array, value) == 3
def test_right2():
array = [1, 2, 3, 4, 5]
value = 5
assert interpolation_search(array, value) == 4
def test_long_sequence():
array = [1, 2, 3, 4, 5]
value = 5
assert interpolation_search(array, value) == 4 |
5be1f6c47b18f28383dfbf48fc760dd771734318 | aarshita02/Mini-Python-Projects | /e-mail Slicer.py | 298 | 4.25 | 4 | # The strip function will remove any trailing spaces on both the sides
email = input("Enter your e-mail: ").strip()
username = email[:email.index('@')]
domain = email[email.index('@') + 1:]
# f-string is an alternative to format function
print(f"Your username is {username} & domain is {domain}")
|
adbc826175ac3061a371e066215717c62c40bd06 | William-Zhan-bot/2021_Python_Class | /6.17 extra 參考解答/數字和.py | 269 | 3.625 | 4 | # 數字和
# 輸入為一字串 任意數字構成
# 輸出他們的總和
a = input()
num = []
for i in a:
num.append(int(i)) # 以整數形式逐個儲存列表
total = 0
# 列表中的整數逐個相加
for k in num:
total += k
print(total) |
8a96a34f7d1cd5ae08feea1fb1c210c76ca2d377 | yyeonhee/9th_ASSIGNMENT | /19_최연희/session 04/Q_1.py | 249 | 3.515625 | 4 | list = [500,100,50,10,5,1]
money = int(input())
price = 1000
result = price - money
# 거스름돈 개수
count = 0
# 리스트에 있는 잔돈의 개수만큼 반복문 실행
for i in list:
count += result // i
result %= i
print(count) |
8e99efa0a888c77a59b95dd3f77676a298b6e161 | olotintemitope/Algo-Practice | /nested_listed_weighted_sum.py | 410 | 3.6875 | 4 | def nested_listed_weighted_sum(nestedList, depth=1):
sum_up = 0
for num in nestedList:
if isinstance(num, int):
sum_up += num * depth
if isinstance(num, list):
sum_up += nested_listed_weighted_sum(num, depth + 1)
return sum_up
print(nested_listed_weighted_sum([1, [4, [6]]]))
print(nested_listed_weighted_sum([[1, 1], 2, [1, 1]]))
# print(len([4, [6]]))
|
4f4efd32ccdd3b77b53fca2dfcfc982b539caf6f | microgold/Becca35 | /becca_test/grid_1D_noise.py | 4,925 | 3.734375 | 4 | """
One-dimensional grid task with noise
In this task, the agent has the challenge of discriminating between
actual informative state sensors, and a comparatively large number
of sensors that are pure noise distractors. Many learning methods
make the implicit assumption that all sensors are informative.
This task is intended to break them.
"""
from __future__ import print_function
import numpy as np
import becca.connector
from becca.base_world import World as BaseWorld
class World(BaseWorld):
"""
One-dimensional grid world with noise.
In this world, the agent steps forward and backward
along three positions on a line. The second position is rewarded
and the first and third positions are punished. Also, any actions
are penalized somewhat. It also includes some inputs that are pure noise.
Optimal performance is a reward of about .70 per time step.
Most of this world's attributes are defined in base_world.py.
The few that aren't are defined below.
"""
def __init__(self, lifespan=None):
"""
Set up the world.
"""
BaseWorld.__init__(self, lifespan)
self.name = 'grid_1D_noise'
self.name_long = 'noisy one dimensional grid world'
print("Entering", self.name_long)
self.num_real_sensors = 3
# num_noise_sensors : int
# Of the sensors, these are purely noise.
# These have no basis in the world and are only meant to distract.
# num_real_sensors : int
# Of the sensors, these are the ones that represent position.
self.num_noise_sensors = 10
self.num_sensors = self.num_noise_sensors + self.num_real_sensors
self.num_actions = 2
self.action = np.zeros(self.num_actions)
# energy_cost : float
# The punishment per position step taken.
self.energy_cost = 0.01
# jump_fraction : float
# The fraction of time steps on which the agent jumps to
# a random position.
self.jump_fraction = 0.1
# world_state : float
# The actual position of the agent in the world.
# This can be fractional.
self.world_state = 0
# simple_state : int
# The nearest integer position of the agent in the world.
self.simple_state = 0
self.world_visualize_period = 1e6
self.brain_visualize_period = 1e3
def step(self, action):
"""
Take one time step through the world
Parameters
----------
action : array of floats
The set of action commands to execute.
Returns
-------
reward : float
The amount of reward or punishment given by the world.
sensors : array of floats
The values of each of the sensors.
"""
self.action = action.copy().ravel()
self.action[np.nonzero(self.action)] = 1.
self.timestep += 1
step_size = self.action[0] - self.action[1]
# An approximation of metabolic energy.
energy = self.action[0] + self.action[1]
self.world_state = self.world_state + step_size
# At random intervals, jump to a random position in the world.
if np.random.random_sample() < self.jump_fraction:
self.world_state = (self.num_real_sensors *
np.random.random_sample())
# Ensure that the world state falls between 0 and num_real_sensors.
self.world_state -= (self.num_real_sensors *
np.floor_divide(self.world_state,
self.num_real_sensors))
self.simple_state = int(np.floor(self.world_state))
# Assign sensors as zeros or ones.
# Represent the presence or absence of the current position in the bin.
real_sensors = np.zeros(self.num_real_sensors)
real_sensors[self.simple_state] = 1
# Generate a set of noise sensors
noise_sensors = np.round(np.random.random_sample(
self.num_noise_sensors))
sensors = np.hstack((real_sensors, noise_sensors))
reward = -1.
if self.simple_state == 1:
reward = 1.
reward -= energy * self.energy_cost
return sensors, reward
def visualize_world(self, brain):
"""
Show what's going on in the world.
"""
state_image = ['.'] * (self.num_real_sensors +
self.num_actions + 2)
state_image[self.simple_state] = 'O'
state_image[self.num_real_sensors:self.num_real_sensors + 2] = '||'
action_index = np.where(self.action > 0.1)[0]
if action_index.size > 0:
state_image[self.num_real_sensors + 2 + action_index[0]] = 'x'
print(''.join(state_image))
if __name__ == "__main__":
becca.connector.run(World())
|
f330239ad8b218f2b447b24623064bcaf1d52aca | N3mT3nta/ExerciciosPython | /Mundo 2 - Estruturas de Controle/ex043.py | 440 | 3.59375 | 4 | from time import sleep
peso = float(input('Quantos Kg você pesa: '))
altura = float(input('Qual a sua altura em metros: '))
imc = peso / (altura**2)
print('Analisando dados...')
sleep(1)
print('Seu IMC é {:.1f} e seu status é:'.format(imc))
if imc < 18.5:
print('Abaixo do peso')
elif imc < 25:
print('Peso ideal')
elif imc < 30:
print('Sobrepeso')
elif imc < 40:
print('Obesidade')
else:
print('Obesidade mórbida')
|
98586ea6502cec6b7f480e376836ae8602bc5f52 | sawani02/CodePath-PreWork | /checkpoint3/kth_smallest_element.py | 385 | 3.515625 | 4 | #Question: Find the kth smallest element in an unsorted array of non-negative integers.
#Problem link: https://www.interviewbit.com/problems/kth-smallest-element-in-the-array/
class Solution:
# @param A : tuple of integers
# @param B : integer
# @return an integer
def kthsmallest(self, A, B):
#sort
sorted_A = sorted(A)
return sorted_A[B - 1]
|
7994fd395b83858a2190400b63acc28711636288 | faturita/python-scientific | /scientificnotation.py | 389 | 3.6875 | 4 | # coding: latin-1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Algo de programación científica y métodos numéricos
val = (0.1)**2
print (val == 0.01)
# Numpy da una funcion para chequear valores en punto flotante
print (np.isclose (0.1**2, 0.01))
# Ojo al sumar valores en punto flotantes
a,b,c = 1e14, 25.44, 0.74
print ((a+b)+c)
print (a + (b+c))
|
8dc2ec58104b4dce62a818c453de72987bf58900 | Harsh1347/Matplotlib-python | /bar_chart.py | 356 | 3.5 | 4 | from matplotlib import pyplot as plt
import numpy as np
plt.style.use('fivethirtyeight')
x = [i for i in range(5)]
x_ind = np.arange(len(x))
width = 0.25
y1 = [i+2 for i in range(5)]
y2 = [i+4 for i in range(5)]
y3 = [i for i in range(5)]
plt.bar(x_ind,y1,width=width)
plt.bar(x_ind+width,y2,width=width)
plt.bar(x_ind-width,y3,width=width)
plt.show() |
55a74ab647fb5b20b58ac55852a388a95d759ba6 | zhenyulin/mlcoursework | /ex2/sigmoid.py | 384 | 3.765625 | 4 | import numpy as np
def sigmoid(z):
"""computes the sigmoid of z."""
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the sigmoid of each value of z (z can be a matrix,
# vector or scalar).
z = np.negative(z)
g = np.exp(z)
g = 1 / (g + 1)
# =============================================================
return g |
a362103f14ee2281057ea3939dcb37af389814eb | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/03_generators/03_fibonacci_generator.py | 1,081 | 4 | 4 | #!/usr/bin/python3
"""
Purpose: Fibonacci Series
- first two values are 0 & 1
- subseqeunt values are summation of previous two values
- 0, 1, 1, 2, 3, 5, 8, 13, ...
"""
# Method 1 -- using functions -- you get all values at a time
def fib_series(num):
if num < 0:
return "Invalid Input"
fib_nums = []
a, b = 0, 1
for _ in range(0, num):
fib_nums.append(a)
a, b = b, a + b
return fib_nums
result = fib_series(10)
print(result)
# Method 2 -- using Generators
def fib_series(num):
if num < 0:
yield "Invalid Input"
a, b = 0, 1
for _ in range(0, num):
yield a
a, b = b, a + b
result = fib_series(10)
print(result)
for each_fib in fib_series(10):
print(each_fib)
print()
print(list(fib_series(15)))
print()
print(tuple(fib_series(-3)))
print()
# Method 2b - using generators
def fib_series2(num):
yield 1
yield 1
curr, prev = 2, 1
while curr < num:
yield curr
curr, prev = curr + prev, curr
print(list(fib_series2(10))) # [1, 1, 2, 3, 5, 8]
|
a9005f8fc3b61e1826e6da7ae55c0563456418ec | Michaelndula/Python-Projects | /pset6/Bleep/bleep/bleep.py | 894 | 3.640625 | 4 | from cs50 import get_string
from sys import argv
word = set()
def main():
if not len(argv) == 2:
print("Usage: python bleep.py dictionary")
exit(1)
else:
ban = set()
# open banned words file to read
with open("banned.txt", "r") as f:
# copy words to the set
for line in f:
ban.add(line.strip())
# prompt user for message
msg = get_string("What message would you like to censor?\n")
# split msg to words
msg_words = msg.split(" ")
msg_censor = ""
# censor banned words
for word in msg_words:
if word.lower() in ban:
msg_censor += ("*" * len(word)) + " "
else:
msg_censor += word + " "
# print censored msg
print(msg_censor.strip())
if __name__ == "__main__":
main()
|
8102eba968786e055b08aceeb54db1c35da15b3e | previsualconsent/projecteuler | /p044.py | 508 | 3.765625 | 4 | from itertools import count
def pentagon(n):
return n*(3*n-1)/2
n = 3000
print "making lists"
pentagons =[ pentagon(n) for n in range(1,n+1)]
pns = set(pentagons)
print "running over lists up to",pentagons[-1]
end = False
for i in count(1):
if not i % 100: print i
for j in xrange(0,n-i):
if pentagons[j+i] - pentagons[j] in pns and pentagons[j+i] + pentagons[j] in pns:
print j,",",j+i,"diff:",pentagons[j+i]-pentagons[j]
end = True
break
if end : break
|
abd7f76fbca841e2a852299135d29727a7d5c809 | gedoensmanagement/transkribus_rest_api_client | /astronauts.py | 990 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" List the astronauts that are currently on the ISS
using the Open Notify API: http://api.open-notify.org/ """
import requests
import json
# Build the URL using the "astros.json" endpoint:
api_base_url = "http://api.open-notify.org/"
endpoint = "astros.json"
url = api_base_url + endpoint
# Make a GET request and store the response:
response = requests.get(url)
# Evaluate the response:
if response:
try:
json_response = response.json()
print("The raw JSON response sent by the server:")
print(json.dumps(json_response))
print("\nPeople on the ISS:")
for astronaut in json_response['people']:
if astronaut['craft'] == "ISS":
print("– " + astronaut['name'])
except:
print(f"ERROR: Something went wrong. {response.content}")
else:
print(f"ERROR: Something went wrong. HTTP status code: {response.status_code}")
|
8117a8cf205e19ce2a77f954e93513c7e9245e26 | aspferraz/FuzzyInference | /controller/knowledge/fuzzy_rule.py | 3,119 | 3.796875 | 4 | from controller.knowledge.fuzzy_clause import FuzzyClause
'''
author: https://github.com/carmelgafa
'''
class FuzzyRule():
'''
A fuzzy rule of the type
IF [antecedent clauses] THEN [consequent clauses]
'''
def __init__(self):
'''
initializes the rule. Two data structures are necessary:
Antecedent clauses list
consequent clauses list
'''
self._antecedent = []
self._consequent = []
def __str__(self):
'''
string representation of the rule.
Returns:
--------
str: str, string representation of the rule in the form
IF [antecedent clauses] THEN [consequent clauses]
'''
ante = ' and '.join(map(str, self._antecedent))
cons = ' and '.join(map(str, self._consequent))
return f'If {ante} then {cons}'
def add_antecedent_clause(self, var, f_set):
'''
adds an antecedent clause to the rule
Arguments:
-----------
clause -- FuzzyClause, the antecedent clause
'''
self._antecedent.append(FuzzyClause(var, f_set))
def add_consequent_clause(self, var, f_set):
'''
adds an consequent clause to the rule
Arguments:
-----------
clause -- FuzzyClause, the consequent clause
'''
self._consequent.append(FuzzyClause(var, f_set))
def evaluate(self):
'''
evaluation of the rule.
the antecedent clauses are executed and the minimum degree of
membership is retained.
This is used in teh consequent clauses to min with the consequent
set
The values are returned in a dict of the form {variable_name: scalar min set, ...}
Returns:
--------
rule_consequence -- dict, the resulting sets in the form
{variable_name: scalar min set, ...}
'''
# rule dom initialize to 1 as min operator will be performed
rule_strength = 1
# execute all antecedent clauses, keeping the minimum of the
# returned doms to determine the rule strength
for ante_clause in self._antecedent:
rule_strength = min(ante_clause.evaluate_antecedent(), rule_strength)
# execute consequent clauses, each output variable will update its output_distribution set
for consequent_clause in self._consequent:
consequent_clause.evaluate_consequent(rule_strength)
def evaluate_info(self):
'''
evaluation of the rule.
the antecedent clauses are executed and the minimum degree of
membership is retained.
This is used in teh consequent clauses to min with the consequent
set
The values are returned in a dict of the form {variable_name: scalar min set, ...}
Returns:
--------
rule_consequence -- dict, the resulting sets in the form
{variable_name: scalar min set, ...}
'''
# rule dom initialize to 1 as min operator will be performed
rule_strength = 1
# execute all antecedent clauses, keeping the minimum of the
# returned doms to determine the rule strength
for ante_clause in self._antecedent:
rule_strength = min(ante_clause.evaluate_antecedent(), rule_strength)
# execute consequent clauses, each output variable will update its output_distribution set
for consequent_clause in self._consequent:
consequent_clause.evaluate_consequent(rule_strength)
return f'{rule_strength} : {self}' |
5a0c9b8b5bb0acda50a4298b910522974c1d7729 | PrestonFawcett/Pig_Game | /pig.py | 1,851 | 4.125 | 4 | #!/usr/bin/env python3
""" Pig game written in Python. """
__author__ = 'Preston Fawcett'
__email__ = 'ptfawcett@csu.fullerton.edu'
__maintainer__ = 'PrestonFawcett'
import time
from player import Player
from functions import error
from functions import rearrange
from functions import start_turn
def main():
""" Main function for game. """
# Asking how many players
num_of_players = 0
while num_of_players < 2 or num_of_players > 4:
num_of_players = int(input('How many players (2-4)?: '))
if num_of_players < 2 or num_of_players > 4:
error()
# Initializing players
players = []
if num_of_players == 2:
answer = input('Is player 2 a computer? (y/n): ')
players.append(Player(input('\nEnter your name: '), False))
if answer == 'y':
players.append(Player('John Scarne', True))
else:
players.append(Player(input('\nEnter your name: '), False))
else:
for i in range(0, num_of_players):
players.append(Player(
input('\nPlayer {} enter your name: '.format(i + 1)), False))
# Creating turn order
turn_order = rearrange(players)
print('\n------Turn Order------')
for i in range(0, num_of_players):
print('{}. {}'.format((i + 1), turn_order[i].name))
# Start Pig game
current = 0
while not turn_order[current].winner:
print('\n*******SCOREBOARD*******')
for i in range(0, num_of_players):
print(turn_order[i])
print('************************')
print('\n{}\'s turn.'.format(turn_order[current].name))
time.sleep(1)
start_turn(turn_order[current])
if not turn_order[current].winner:
current = (current + 1) % num_of_players
print('{} wins!'.format(turn_order[current].name))
if __name__ == '__main__':
main()
|
17aa3633a2dff1f3a6286a1b9a99e0927349d62b | Linusrbk/prog1-ovn | /4,4.py | 194 | 3.65625 | 4 | höjd=float(input('hur långt ifråll golvet är din boll i meter?'))
varv = 0
while höjd >= 0.01:
höjd = höjd * 0.7
varv = varv+1
print('din boll har stutsat ',varv ,'gånger ') |
28c085d1f18ca8841dbd6e548fff929e094a53be | vivek07kumar/Number-Sorting-Algorithm-2-Inefficient-Version- | /Number Sorting Algorithm 2 (Inefficient Version).py | 2,777 | 4.0625 | 4 | # Removing Duplicates
# 1. step 1 -: Take a number from user given list and place it in a new list.
# 2. step 2 -: The take another number from user list and try matching its equality with elements of new list. If it matches then don't place it in new list. If it matches then place it in user list.
# 3. Repeat the step 1 and step 2 until matching of all the numbers of user list is completed. New list will be the Non diplicate list.
# Finding Smallest to Greatest or vice versa
# On every index you have to find the highest number on that list and exchange it with the number you were comparing with.
# If you keep doing this for every index then the list will be sorted from Smallest to Greatest. Finding the Smallest number on each of the index will result in a list sorted from Greatest to Smallest.
def number_sorting(a) :
n = len(a)
i = 0
while i < n :
index_tracker = 0
for x in a :
if x > a[i] :
a[i],a[index_tracker] = a[index_tracker],a[i]
index_tracker = index_tracker + 1
i = i + 1
return a
def number_sorting_2(a) :
n = len(a)
i = 0
while i < n :
index_tracker = 0
for x in a :
if x < a[i] :
a[i],a[index_tracker] = a[index_tracker],a[i]
index_tracker = index_tracker + 1
i = i + 1
return a
def non_duplicate_list_function(user_list) :
duplicate_list = user_list[:]
non_duplicate_list = []
duplicate_check = False
duplicate_check_2 = True
for variable_1 in duplicate_list :
if non_duplicate_list == [] :
non_duplicate_list = non_duplicate_list + [variable_1]
else :
for variable_2 in non_duplicate_list :
if variable_1 != variable_2 :
duplicate_check = True
else :
duplicate_check = False
duplicate_check_2 = False
if duplicate_check and duplicate_check_2 :
non_duplicate_list = non_duplicate_list + [variable_1]
duplicate_check_2 = True
return non_duplicate_list
def main() :
user_input = eval(input('>> Please enter numbers seperated by comma -: '))
a = list(user_input)
b = a[:]
c = a[:]
result = number_sorting(b)
print()
print('Smallest to Greatest ----> ',result)
result_2 = number_sorting_2(c)
print()
print('Greatest to Smallest ----> ',result_2)
result_3 = non_duplicate_list_function(result)
print()
print('After Removing Duplicate Number/s ----> ',result_3)
print('Number of Duplicate Element/s found ----> ',len(a) - len(result_3),'Element/s')
print()
main()
|
6d329837a1af32abea5cc84d3ec9a1eb219aed61 | mjadair/intro-to-python | /intro-to-python/mixing-types.py | 672 | 4.1875 | 4 | # Navigate to intro-to-python folder and type python mixing-types.py to run
# * ----- MIXING TYPES 🕺 ------ *
# * 🦉 Practice
# ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/"
# ? Declare two varialbes, "numOne" and "numTwo", set their values to strings of number characters '10' and '5'
# ? Declare a new variable called result, use the "+" operator to assign it a value and print it so it produces "105"
# ? What is the type of result currently? Print it using the built in "type()" function
# ? Now re assign result to add the number 45 and print it. --> 150
# ? Print result in type again, what will it be now?
|
2dc3bd63a7438f8619d4086e50ec41ba086adfc2 | onehao/opensource | /pyml/tools/onedrive/removedup/removeduplicatefiles.py | 877 | 3.671875 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2015年3月23日
@author: wanhao01
'''
import os
def remove_recrusive(folder):
size = 0.0
count = 0
for root, dirs, files in os.walk(folder):
for f in files:
if('(1)' in f or '(2)' in f):
filename = root + os.sep + f
try:
size = size + os.path.getsize(root + os.sep + f)
count = count + 1
os.remove(filename)
print(filename)
except:
continue
return size, count
if __name__ == '__main__':
size, count = remove_recrusive('D:\document\onedrive')
print('total file size: ' + str(size / 1048576.0) + 'MB')
print('there are ' + str(count) + ' files deleted.')
pass |
ad19f51aa86c71d221216cf6710bde9a8e1f66f2 | dkcaliskan/Projects | /Random_Password_Generator.py | 756 | 4 | 4 | import random
import string
print('Hello Welcome to Password Generator')
def password_generator():
try:
length = int(input('\nEnter the length of password: '))
where = input('\nPlease enter the name of website trying to create password for it: ')
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = "-_'."
clean = lower + upper + num + symbols
temp = random.sample(clean, length)
password = ''.join(temp)
print(f'\nYour password for {where.capitalize()} is {password}')
except ValueError:
print('\nPlease Enter a Number')
return password_generator()
if __name__ == '__main__':
password_generator()
|
3faaac34fabaf98dd0f7db9e49cb8a39fb0175c1 | steiryx/raspberrypi-app | /strobe.py | 1,863 | 3.703125 | 4 | # Import the GPIO and time library
import RPi.GPIO as GPIO
import time
# First we initialize some constants and variables
TRANSISTOR = 17
BTN_SPEED_UP = 27
BTN_SLOW_DOWN = 22
DELAY_CHANGE = 0.005
# Never use a strobe light any faster than 4 flashes per sec
DELAY_MIN = 0.125 # 1/8 = '4 on 4 off' flashes
delay = 0.2
def setup():
# Next we initialise setup of the GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRANSISTOR, GPIO.OUT)
GPIO.setup(BTN_SPEED_UP, GPIO.IN)
GPIO.setup(BTN_SLOW_DOWN, GPIO.IN)
# This will call a function when the speed up or slow down
# buttons are pressed
GPIO.add_event_detect(BTN_SPEED_UP, GPIO.RISING)
GPIO.add_event_callback(BTN_SPEED_UP, speed_up)
GPIO.add_event_detect(BTN_SLOW_DOWN, GPIO.RISING)
GPIO.add_event_callback(BTN_SLOW_DOWN, slow_down)
def speed_up(channel):
global delay
# Take away the delay change value from the delay time
# Make sure the delay doesn't go less than minimum
# safe rate for use of stroboscopic lightning.
delay = delay - DELAY_CHANGE
if delay < DELAY_MIN:
delay = DELAY_MIN
def slow_down(channel):
global delay
# Add the delay change value to the current delay
delay = delay + DELAY_CHANGE
def loop():
# The try statement makes sure we clean up properly
# on a keyboard interrupt (CTRL+C)
try:
# loop until the user presses CTRL+C
while True:
# Turn the strobe on, then wait for the delay time
GPIO.output(TRANSISTOR, True)
time.sleep(delay)
# Turn the strobe off, then wait for the delay time
GPIO.output(TRANSISTOR, False)
time.sleep(delay)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
# Now we setup the hardware, and start the main loop of the program
setup()
loop()
|
8d194ac62b7e64d937171827f26568bd157d34b7 | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/15-List-Intersection/Colors_list_inbuilt.py | 424 | 3.90625 | 4 | colorList1 = []
colorList2 = []
colorList1Count = int(input("Total elements in list one :"))
for i in range(colorList1Count):
value = input("Enter a color")
colorList1.append(value)
colorList2Count = int(input("Total elements in list two :"))
for i in range(colorList2Count):
value = input("Enter a color : ")
colorList2.append(value)
set1=set(colorList1)
set2 =set(colorList2)
print(set1.difference(set2))
|
19b23d50fbd5ca40e6d2826c7b7ba793922b16f6 | Gpopcorn/3D-Graphics-Engine | /functions.py | 995 | 3.609375 | 4 | from random import randint
from colors import *
# random color function
def random_color():
color_choice = randint(0, 5)
if color_choice == 0:
return RED
if color_choice == 1:
return YELLOW
if color_choice == 2:
return GREEN
if color_choice == 3:
return INDIGO
if color_choice == 4:
return BLUE
if color_choice == 5:
return MAGENTA
# checks if an object is in range function
def in_range(position_1, position_2, radius):
if position_1[0][0] > position_2[0][0] - radius and position_1[0][0] < position_2[0][0] + radius:
if position_1[1][0] > position_2[1][0] - radius and position_1[1][0] < position_2[1][0] + radius:
if position_1[2][0] > position_2[2][0] - radius and position_1[2][0] < position_2[2][0] + radius:
return True
else:
return False
else:
return False
else:
return False |
7266bfb61fd9cae61aa452177664e411c3785b94 | Molo-M/Arithmetic-Formatter | /Arithmetic Formatter.py | 1,636 | 3.734375 | 4 | def arithmetic_arranger(problems, solve=False):
answ = ''
fst_line = ''
scnd_line = ''
dash = ''
for prbm in problems:
prb = prbm.split(' ')
try:
v1 = int(prb[0])
op = prb[1]
v2 = int(prb[2])
if op == "+":
val = str(v1 + v2)
elif op == "-":
val = str(v1 - v2)
v1 = str(v1)
v2 = str(v2)
if len(problems) > 5:
return "Error: Too many problems."
elif len(prb[0]) > 4 or len(prb[2]) > 4:
return "Error: Numbers cannot be more than four digits."
elif op == "*" or op == "/":
return "Error: Operator must be '+' or '-'."
except ValueError:
return "Error: Numbers must only contain digits."
length = max(len(v1), len(v2)) + 2
upper = str(v1).rjust(length)
middle = op + str(v2).rjust(length - 1)
line = '-' * length
value = str(val).rjust(length)
if prbm is not problems[-1]:
fst_line += upper + ' '
scnd_line += middle + ' '
dash += line + ' '
answ += value + ' '
elif prbm is problems[-1]:
fst_line += upper
scnd_line += middle
dash += line
answ += value
if solve:
arranged_problems = fst_line + '\n' + scnd_line + '\n' + dash + '\n' + answ
else:
arranged_problems = fst_line + '\n' + scnd_line + '\n' + dash
return arranged_problems
print(arithmetic_arranger(['3801 - 2', '123 + 49']))
|
dc2e92101ea33caf4de43f16412d9b8c68a012ea | larusarmann/Forritun | /FORR1FG05AU/skilaverkefni/Tímapróf 3 endurtaka.py | 2,040 | 3.671875 | 4 | #Lárus Ármann Kjartansson
#10/12/2019
#Tímapróf 3
import random
on = True
while on == True:
print("1. sléttar tölur")
print("2. Randomtölur")
print("3. Texti")
print("4. samanburður")
print("5. hætta")
val = int(input("Veldu hvað þú villt gera"))
if val == 1:
for n in range(100, 400):
if n % 2 == 0:
print(n, end=" ")
elif val == 2:
listi1 = []
listi2 = []
listi3 = []
for x in range(100):
randomtala = random.randint(100, 201)
listi1.append(randomtala)
teljari = 0
for number in listi1:
if (number % 3 == 0):
listi3.append(number)
for x in listi1:
if (x > 150):
listi2.append(x)
if (x == 151):
teljari = teljari + 1
summa = sum(listi3)
lengd = len(listi3)
medallengd = summa / lengd
aukastafir = round(medallengd, 2)
print("summa talnana er:", sum(listi1))
print("talan 151 kom", teljari, "sinnum")
print("meðaltal talnana sem gekk upp í 3 er:",aukastafir)
print("tölurnar yfir 150 eru:", sorted(listi2))
elif val == 3:
teljari = 0
teljari1 = 0
texti = input("Skrifaðu texta:")
tel = len(texti.split())
for i in texti:
if i == 'K':
teljari1 = teljari1 + 1
elif i == 'k':
teljari = teljari + 1
print("fjöldi orða: " + str(tel))
print("fjöldi 'K' ", teljari1)
print("fjöldi 'k' ", teljari)
elif val == 4:
ord1 = input("sláðu inn orð")
ord2 = input("sláðu inn annað orð")
stafir1 = ord1[:-2]
stafir2 = ord2[:-2]
if stafir1 == stafir2:
print("síðustu 2 stafirnir eru eins")
else:
print("síðustu tveir stafirnir eru ekki eins")
elif val == 5:
on = False |
8cddba6dc5d267858a3e81f15dd309ca381e9edf | Hammer2900/minipoker | /minipoker/logic/deck.py | 1,173 | 3.828125 | 4 | from random import shuffle
SUITS = ("Hearts", "Diamonds", "Clubs", "Spades")
symbols = {"Spades": u'♠', "Hearts": u'♥', "Diamonds": u'♦', "Clubs": u'♣'}
class Card(object):
def __init__(self, value, suit):
self.value = value
self.suit = suit
def __gt__(self, other):
if not isinstance(other, Card):
return False
return self.value > other.value
def __eq__(self, other):
if not isinstance(other, Card):
return False
return self.value == other.value and self.suit == other.suit
def __repr__(self):
return str(self.value) + self.suit[0]
def __str__(self):
return str(self.value) + symbols[self.suit]
def color(self):
return "red" if self.suit in ("Hearts", "Diamonds") else "black"
class Deck(object):
def __init__(self):
self.cards = [Card(value, suit) for value in range(1, 14) for suit in SUITS]
# don't forget to shuffle
self.shuffle()
def shuffle(self):
shuffle(self.cards)
def draw(self, number=1):
drawn, self.cards = self.cards.pop(0), self.cards[number:]
return drawn
|
8d9d1bb6f00f24f93f5dc2ae9eb83b7386813b63 | SalimRR/- | /5_4.py | 267 | 3.875 | 4 | x = float(input('Введите значение x: '))
k=4.0
f = ()
def info(f, x, k):
if -2.4<=x<= 5.7:
j = x**2
print("Функция f равна = ", j)
elif k:
print("Функция f равна = ", k)
info(f, x, k)
|
3912181a2af5303f13408f579e7c59f2095ddfd8 | chethanagopinath/DSPractice | /Ch2-LinkedLists/2.5.py | 1,586 | 3.9375 | 4 | #Sum of two lists
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def sum_lists(self, list2):
p = self.head
q = list2.head
sum_list = LinkedList()
carry = 0
while p or q:
if not p:
i = 0
else:
i = p.data
if not q:
j = 0
else:
j = q.data
s = i + j + carry
#As you are adding just two lists, the max could be 9 + 9 = 18, with carry 1
#If s is greater than 10, compute remainder and append it, the carry would get added in the next iteration
#Except for the last carry which is dealt with after the loop
if s >= 10:
carry = 1
remainder = s % 10
sum_list.append(remainder)
else:
carry = 0
sum_list.append(s)
if p:
p = p.next
if q:
q = q.next
if carry != 0:
sum_list.append(carry)
sum_list.print_list()
linkedlist1 = LinkedList()
linkedlist1.append(5)
linkedlist1.append(6)
linkedlist1.append(3)
linkedlist2 = LinkedList()
linkedlist2.append(4)
linkedlist2.append(8)
linkedlist2.append(9)
#3 6 5
#9 8 4
#-----
#13 4 9
#Carry is appended to the sum_list after loop - do not forget
print(365 + 984)
linkedlist1.sum_lists(linkedlist2)
|
981ac3b25cd072ef564b5075289149b94f2745bc | Rivarrl/leetcode_python | /leetcode/offer/45.py | 1,138 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 45.py
# @Time : 2020/5/2 14:44
# @Author : Rivarrl
# ======================================
# [面试题45. 把数组排成最小的数](https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/)
from algorithm_utils import *
class Solution:
@timeit
def minNumber(self, nums: List[int]) -> str:
nums = [str(e) for e in nums]
def quick_sort(lo, hi):
if lo >= hi: return
i, j = lo, hi
base = nums[lo]
while i < j:
while i < j and nums[j] + base >= base + nums[j]:
j -= 1
while i < j and nums[i] + base <= base + nums[i]:
i += 1
nums[i], nums[j] = nums[j], nums[i]
nums[lo], nums[i] = nums[i], nums[lo]
quick_sort(lo, i-1)
quick_sort(i+1, hi)
quick_sort(0, len(nums)-1)
return "".join(nums)
if __name__ == '__main__':
a = Solution()
a.minNumber([10,2])
a.minNumber([3,30,34,5,9])
a.minNumber([9,34,55,8,12,402]) |
ce05ac96bf04d20f8ab5da5e4842076ecdf31288 | Aasthaengg/IBMdataset | /Python_codes/p03777/s038429276.py | 82 | 3.625 | 4 | a, b = list(input().split())
if a == 'D':
b = 'D' if b == 'H' else 'H'
print(b)
|
0bd8229097b2fa64b67ce8146811a0ac532e20d7 | Chikus9/Fibonacci | /Fibonaci.py | 328 | 3.859375 | 4 | def fib(n):
a = 0
b = 1
if n < 0:
print('Enter a valid number')
elif n == 1:
print('Enter a no greater than one')
else:
for i in range(2,n):
c= a+b
if c<n:
a = b
b = c
print(i)
fib(10) |
aae3202871db7cac051c6d13cb9c2a4a46a63956 | pankajcoding/source | /learnpython/linkedlist.py | 2,659 | 3.921875 | 4 | class Node:
def __init__(self,data,nxt=None):
self.data=data
self.next=nxt
class LinkedList(object):
"""docstring for LInkedList"""
def __init__(self):
self.begin=None
self.end=None
def push(self,data):
if self.end==None:
n1=Node(data,None)
self.begin=n1
self.end=n1
elif self.end!=None:
n1=Node(data,None)
self.end.next=n1
self.end=n1
def pop(self):
print(self.count())
if self.count()==0:
return None
elif self.count()==1:
temp=self.end
self.head=None
self.begin=None
return temp.data
elif self.count()>1:
temp=self.begin
while temp.next!=self.end:
temp=temp.next
tempnode=self.end
self.end=temp
self.end.next=None
return tempnode.data
def unshift(self):
if self.begin==None:
return None
elif self.count()==1:
data=self.begin.data
self.begin=None
self.end=None
return data
else:
data=self.begin.data
self.begin=self.begin.next
return data
def get(self,index):
print('index',index)
if index>self.count()-1:
return None
else:
i=0
temp=self.begin
while(i<index):
temp=temp.next
i+=1
print(temp.data)
return temp.data
def count(self):
if self.begin==None:
return 0
else:
length=1
temp=self.begin
while temp.next!=None:
temp=temp.next
length+=1
return length
def test_push():
colors=LinkedList()
colors.push("Magneta")
assert colors.count()==1
colors.push("Alizarian")
assert colors.count()==2
colors.push("Alizarian")
print(colors.count())
def test_pop():
colors=LinkedList()
colors.push('Magneta')
colors.push('Alizarian')
assert colors.pop()=="Alizarian"
assert colors.pop()=='Magneta'
assert colors.pop()==None
assert colors.pop()==None
def test_unshift():
colors=LinkedList()
colors.push("Viridian")
colors.push("Sap Green")
colors.push("Van Dyke")
print( colors.unshift())
assert colors.unshift() == "Sap Green"
assert colors.unshift() == "Van Dyke"
assert colors.unshift() == None
assert colors.unshift() == None
def test_get():
colors = LinkedList()
colors.push("Vermillion")
assert colors.get(0) == "Vermillion"
colors.push("Sap Green")
assert colors.get(0) == "Vermillion"
assert colors.get(1) == "Sap Green"
colors.push("Cadmium Yellow Light")
assert colors.get(0) == "Vermillion"
assert colors.get(1) == "Sap Green"
assert colors.get(2) == "Cadmium Yellow Light"
assert colors.pop() == "Cadmium Yellow Light"
assert colors.get(0) == "Vermillion"
assert colors.get(1) == "Sap Green"
assert colors.get(2) == None
colors.pop()
assert colors.get(0) == "Vermillion"
colors.pop()
assert colors.get(0) == None
test_get() |
a8a1038b1c148aab8833c2bcd9bb63b4d5cdbf99 | xiaoshenkejiushu/chapter07 | /0703.py | 4,120 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from pandas import DataFrame
from pandas import Series
data = DataFrame({'k1':['one']*3+['two']*4,
'k2':[1,1,2,3,3,4,4]})
print(data)
print(data.duplicated())
data.drop_duplicates()
print(data)
#去除指定列的重复
data['v1'] = range(7)
print(data.drop_duplicates(['k1']))
print(data.drop_duplicates(['k1','k2'],keep = 'last'))
#利用函数或者映射进行数据转换
data = DataFrame({'food': ['bacon', 'pulled pork', 'bacon', 'Pastrami',
'corned beef', 'Bacon', 'pastrami', 'honey ham',
'nova lox'],
'ounces': [4, 3, 12, 6, 7.5, 8, 3, 5, 6]})
print(data)
meat_to_animal = {'bacon': 'pig',
'pulled pork': 'pig',
'pastrami': 'cow',
'corned beef': 'cow',
'honey ham': 'pig',
'nova lox': 'salmon'} # 动物来源
data['animal'] = data['food'].map(str.lower)
print(data)
data['food'].map(lambda x:meat_to_animal[x.lower()])
print(data)
data = Series([1., -999., 2., -999., -1000., 3.])
data.replace(-999,np.nan)
print(data.replace([-999,-1000],np.nan))
print(data.replace([-999, -1000], ['JJJ', 'Thousand']))
print(data.replace({-99:'JJJ', -1000:'Thousand'}))
data = DataFrame(np.arange(12).reshape((3, 4)),
index=['Ohio', 'Colorado', 'New York'],
columns=['one', 'two', 'three', 'four'])
data.index.map(str.upper)
data.index = data.index.map(str.upper)
print(data.rename(index=str.upper, columns=str.title))
print(data)
print(data.rename(index = {'OHIO':'hcq'},columns = {'one':'sw'}))
data.rename(index = {'OHIO':'hcq'},inplace = True)
print(data)
#离散化处理
ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
bins = [18, 25, 35, 60, 100]
cats = pd.cut(ages,bins)
print(cats)
print(cats.codes)
cats_hcq = pd.cut(ages, [18, 26, 36, 61, 100], right=False) # right设置开闭区间
print(cats_hcq)
group_names = ['Youth', 'YoungAdult', 'MiddleAged', 'Senior'] # 每个区间的名字
cats = pd.cut(ages,bins,labels = group_names)
print(cats)
data = np.random.rand(20)
cats =pd.qcut(data,4)#产生四分位数的区间
print(cats)
print(pd.value_counts(cats))
#检测和过滤异常值
np.random.seed(12345)
data = DataFrame(np.random.randn(1000,4))
print(data.describe())
col = data[3]
print(col[np.abs(col)>3])
print(data[(np.abs(data)>3).any(1)])
data[np.abs(data)>3] = 0
print(data[np.abs(data)>3])
df = DataFrame(np.arange(5 * 4).reshape(5, 4))
sampler = np.random.permutation(5)
print(df)
print(sampler)
print(df.take(sampler))
print(df.take(np.random.permutation(len(df))[:3]))
bag = np.array([5, 7, -1, 6, 4])
sampler = np.random.randint(0,len(bag),size = 10)
print(sampler)
print(bag.take(sampler))
df = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
'data1': range(6)})
print(pd.get_dummies(df['key']))
dummies = pd.get_dummies(df['key'],prefix = 'key')
print(dummies)
df_with_dummy = df[['data1']].join(dummies)
print(df_with_dummy)
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table('./ml-1m/movies.dat',
sep='::',
header=None,
names=mnames)
movies.head()
genre_iter = (set(x.split('|')) for x in movies.genres)
print(genre_iter)
genres = sorted(set.union(*genre_iter))
print(genres)
dummies = DataFrame(np.zeros((len(movies),len(genres))),columns = genres)
print(dummies.head())
for i, gen in enumerate(movies.genres):
dummies.loc[i, gen.split('|')] = 1 # 给每部电影打标签
print(dummies.head())
movies_windic = movies.join(dummies.add_prefix('Genre_'))
print(movies_windic.head())
values = np.random.rand(10)
bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
print(pd.cut(values,bins))
print(pd.get_dummies(pd.cut(values,bins)))
|
f39c789e8ba91acf4898a0809dcc59277b0c273c | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc105/B/4914621.py | 259 | 3.703125 | 4 | N = int(input())
for cake in range(26):
flag = False
for donut in range(15):
if 4 * cake + 7 * donut == N:
print('Yes')
flag = True
break
if flag:
break
else:
print('No') |
0fe17804540f07f2e2d8316479d9b9d3e3644aa9 | TryImpossible/Python-Notes | /python/basic/while.py | 1,302 | 3.59375 | 4 | #coding=utf-8
# count = 0;
# while (count < 9) :
# print 'The count is:', count;
# count += 1;
# print 'Good bye';
# i = 1;
# while i < 10:
# i += 1;
# if i % 2 > 0:
# continue;
# print i;
# i = 1;
# while 1:
# print i;
# i += 1;
# if i > 10:
# break;
# var = 1;
# while var == 1 :
# num = raw_input('Enter a number:');
# print 'You entered:', num;
# print 'Good bye!';
# count = 0;
# while count < 5:
# print count, 'is less than 5';
# count += 1;
# else :
# print count, 'is not less than 5';
# flag = 1;
# while (flag) : print 'Given flag is really true!';
# print 'Good bye!';
import random;
import sys;
import time;
result = [];
while True:
result.append(int(random.uniform(1, 7)));
result.append(int(random.uniform(1, 7)));
result.append(int(random.uniform(1, 7)));
print result;
count = 0;
index = 2;
pointStr = '';
while index >= 0:
currPoint = result[index];
count += currPoint;
index -= 1;
pointStr += '';
pointStr += str(currPoint);
if count <= 11 :
sys.stdout.write(pointStr + '->' + '小' + '\n');
time.sleep(1);
else:
sys.stdout.write(pointStr + '->' + '大' + '\n');
time.sleep(1);
result = []; |
af26b72bee59c984337d6b52d3792cd0960c3c70 | Peng-Zhanjie/The-CP1404-Project | /Work4/list_exercises.py | 1,157 | 3.9375 | 4 | usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob']
def main():
numbers=[]
Count=0
read=True
while (read!=False):
try:
number=int(input("Please enter number{}:".format(Count+1)))
except ValueError:
print("ValueError")
continue
if(number>=0):
numbers.append(number)
Count+=1
else:
print("Input finished")
read=False
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The biggest number is {}".format(max(numbers)))
Average=sum(numbers)/len(numbers)
print("The average of the numbers is {}".format(Average))
loop=True
while(loop==True):
name=input("Please enter your name:")
if name not in usernames:print("Access denied")
else:
print("Access granted")
loop=False
main() |
410a1ba553f4ee638bb14661c16d67c875ad3513 | rdepiero218/math3340-python | /dataFit-testQF.py | 516 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on %(date)s
@author: %reggie
"""
import numpy as np
import matplotlib.pyplot as plt
import dataFit as df
# data to fit
x = np.array([0, 1, 2, 3, 4])
y = np.array([0.68, -1.37, -1.25, 0.78, 4.75])
# gives coefficients of quadratic fit
[A, B, C] = df.quadraticFit(x,y,True)
# data for plotting
x_val = np.linspace(0, 4, 40)
y_val = A[0] * x_val**2 + B[0] * x_val + C[0]
# plot fit against data
plt.figure()
plt.plot(x_val, y_val,'-')
plt.plot(x, y, 'o')
|
bc47c5079248eee78d3279ff2f067e5f96e7a49c | ashukedar/ComputerOrientedNumericalMethods | /Thomas Method for tridiagonal system of Linear Equations/main.py | 1,483 | 3.96875 | 4 | def getIntGreaterThan1(inputText):
while True:
try:
n = int(input(inputText));
if(n >= 1):
return n
else:
raise Exception()
except:
print("Invalid Input. Expected input: Integer greater than 0")
def getFloat(inputText):
while True:
try:
return float(input(inputText));
except:
print("Invalid Input. Expected input: Float")
def getUnknowns():
y = [c[0]/b[0]]
d = [u[0]/b[0]]
for i in range(1,n):
y.append(c[i]/(b[i]-a[i]*y[-1]))
d.append((u[i]-a[i]*d[-1])/(b[i]-a[i]*y[-2]))
unknowns = [d[-1]]
for i in range(1,n):
index = n-i-1
unknowns.insert(0,d[index] - y[index] * unknowns[0])
return unknowns
n = getIntGreaterThan1("Enter the no. of unknowns: ")
a, b, c, u = [0], [], [], []
for i in range(n):
if i != 0:
a.append(getFloat("Enter the value of a"+(str)(i+1)+": "))
b.append(getFloat("Enter the value of b"+(str)(i+1)+": "))
if i != n-1:
c.append(getFloat("Enter the value of c"+(str)(i+1)+": "))
u.append(getFloat("Enter the value of u"+(str)(i+1)+": "))
c.append(0)
print("\nSolution for given linear equations:")
print(getUnknowns())
'''
n = 6
a = [0.0, 3.0, 4.0, 1.0, 1.0, -1.0]
b = [1.0, 2.0, 1.0, 2.0, 5.0, 2.0]
c = [2.0, 3.0, 6.0, 3.0, 6.0, 0.0]
u = [1.0, 3.0, 9.0, -3.0, 2.0, 5.0]
[-9.125 5.0625 6.75 -3. -1.25 1.875 ]
''' |
d22c410622d5b6181c480e9f46f9f66e42ab0ca1 | Shalom5693/Data_Structures | /Sort/Bubble_sort.py | 298 | 4.09375 | 4 | def bubbleSort(array):
# Write your code here.
is_sorted = False
counter = 0
while not is_sorted:
is_sorted = True
for i in range(len(array) - 1 - counter):
if array[i] > array[i+1]:
array[i],array[i+1] = array[i+1],array[i]
is_sorted = False
counter += 1
return array
|
b597809c23f9cde0b57dcab1d66817dea5fc97ee | phoebepx/Algorithm | /LeetCode/Word Ladder II.py | 2,641 | 3.703125 | 4 | # coding:utf-8
# created by Phoebe_px on 2017/3/16
'''
Description:
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
problem-solving ideas:
key point: BFS
'''
class Solution(object):
def findLadders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
if beginWord==endWord:
return [[beginWord]]
graph = {} #create a graph dict, vertex represent word ,edge represent that this two vertex are only one letter different
result = [] #record all paths from beginWord to endWord
graph[beginWord]=self.Only_1_letter(beginWord,wordList)
#init beginWord neighbour
for s in wordList:
graph[s]=self.Only_1_letter(s,wordList)
#use queue def BFS
queue = [(beginWord,[beginWord])]
while queue:
vertex,path = queue.pop(0)
for next in graph[vertex]-set(path):
if next==endWord:
result.append(path+[next])
else:
queue.append((next,path+[next]))
#based on all paths to find the shortest path ,record in final_r
final_r = []
min = len(result[0])
for i in range(len(result)):
if len(result[i])<=min:
final_r.append(result[i])
return final_r
#judge str1,str2 whether only one letter difference
def diff_of_str(self,str1,str2):
count = 0
l1=list(str1);l2=list(str2)
for i in range(len(l1)):
if l1[i]!=l2[i]:
count+=1
return count == 1
# in wordList ,candidate set is a list with str only one letter difference
def Only_1_letter(self,str,wordlist):
candidate = set()
for s in wordlist:
if self.diff_of_str(str,s):
candidate.add(s)
return candidate
#Test
a = Solution()
print(a.findLadders('hit','cog',["hot","dot","dog","lot","log","cog"]))
#[['hit', 'hot', 'lot', 'log', 'cog'], ['hit', 'hot', 'dot', 'dog', 'cog']]
|
ea84d83db6a672ef7a015ef0fec2f0af48368284 | sukhvir786/Python-DAY-4 | /fun12.py | 525 | 4.25 | 4 | """
Problem:
Heron's formula
a,b,c are length of sides of a triangle
s = semi circumference
s = (a+b+c)/2
area = sqroot(s(s-a)(s-b)(s-c))
"""
# %%
def FUN():
""" computes area of triangle using Heron's formula. """
a = float(input("Enter length of side one: "))
b = float(input("Enter length of side two: "))
c = float(input("Enter length of side three: "))
s = (a + b + c)/2
AR = s*((s-a)*(s-b)*(s-c))
print("Area of a triangle with sides",AR**0.5 )
# %%
|
41294564ced5a5aad8c72064eaf39e389f7a921c | luamnoronha/cursoemvideo | /ex.005.py | 151 | 3.84375 | 4 | n1 = int(input('digite um nuemro!: '))
s = (n1 - 1)
ss = (n1 + 1)
print('o antecessor do numero é {} e o sucessor {} '.format(s, ss))
|
f4a1fd8a3e11a0cb37f60c8e967075381005e171 | Laurence84/adrar | /Algo/Arrays/incomplete_functions.py | 2,050 | 3.796875 | 4 | def swap_v1():
a=1
b=999
print("a vaut {} et b vaut {}".format(a,b))
# a vaut 1 et b vaut 999
a=b
b=a
print("a vaut {} et b vaut {}".format(a,b))
# a vaut 999 et b vaut 1
# ?
def swap_v2():
a=1
b=999
c=a
a=b
b=c
print("a vaut {} et b vaut {}".format(a,b))
def min_value(array):
result = array[0]
for i in range(len(array)):
if array[i] < result:
result = array[i]
return result
def max_value(array):
result = array[0]
for i in range(len(array)):
if array[i] > result:
result = array[i]
return result
def count(value,array):
cpt = 0
for i in range(len(array)):
if array[i] == value:
cpt+=1
return cpt
def search_v1(value,array):
cpt = count(value,array)
return cpt > 0
def search_v2(value,array):
for i in range(len(array)):
if array[i] == value:
return True
return False
def search_v3(value,array):
i=0
found=False
while i < len(array) and not found:
if array[i] == value:
found = True
i += 1
return found
def search_in_ordered_v1(value,array):
for i in range(len(array)):
if array[i] == value:
return True
if array[i] > value:
return False
return False
def two_biggest(array):
b1 = -1
b2 = -1
for i in range(len(array)):
if array[i] >= b1:
b2 = b1
b1 = array[i]
elif array[i] > b2:
b2 = array[i]
print("Les deux plus grandes valeurs sont {} et {}.".format(b1,b2))
def search(value,array):
search_in_ordered_v2(value,array,0,len(array)-1)
# DICHOTOMIE
def search_in_ordered_v2(value,array,index1,index2):
print("Je cherche entre les cases {} et {}.".format(index1,index2))
if index1 > index2:
return False
middle = int((index1+index2)/2)
print("Middle = "+str(middle))
# Si le milieu est plus petit que ce que je cherche
if array[middle] < value:
return search_in_ordered_v2(value,array,middle+1,index2)
# Sinon s'il est plus grand
elif array[middle] > value:
return search_in_ordered_v2(value,array,index1,middle-1)
# Sinon il est égal, j'ai trouvé l'élément que je cherche
else:
return True |
1832c705d5ce2565e3a613503f29af8f91ab5859 | kevinczhong/Python_Exercises | /Lvl. 1 Exercises (Cont.)/isalphanum.py | 304 | 3.671875 | 4 | class Solution():
def isalphanum(self, c):
if c.isalpha() is True:
return True
elif c.isnumeric() is True:
return True
else:
return False
s = Solution()
print(s.isalphanum("a"))
print(s.isalphanum("3"))
print(s.isalphanum("!")) |
c28fce9081887bcf5350456edf0f111d8add42de | hon9g/Text-to-Color | /deepmoji/sentence_tokenizer.py | 5,225 | 3.671875 | 4 | '''
Provides functionality for converting a given list of tokens (words) into
numbers, according to the given vocabulary.
'''
from __future__ import print_function, division
import numpy as np
from deepmoji.word_generator import WordGenerator
from deepmoji.global_variables import SPECIAL_TOKENS
from copy import deepcopy
class SentenceTokenizer():
""" Create numpy array of tokens corresponding to input sentences.
The vocabulary can include Unicode tokens.
"""
def __init__(self, vocabulary, fixed_length, custom_wordgen=None,
ignore_sentences_with_only_custom=False, masking_value=0,
unknown_value=1):
""" Needs a dictionary as input for the vocabulary.
"""
if len(vocabulary) > np.iinfo('uint16').max:
raise ValueError('Dictionary is too big ({} tokens) for the numpy '
'datatypes used (max limit={}). Reduce vocabulary'
' or adjust code accordingly!'
.format(len(vocabulary), np.iinfo('uint16').max))
# Shouldn't be able to modify the given vocabulary
self.vocabulary = deepcopy(vocabulary)
self.fixed_length = fixed_length
self.ignore_sentences_with_only_custom = ignore_sentences_with_only_custom
self.masking_value = masking_value
self.unknown_value = unknown_value
# Initialized with an empty stream of sentences that must then be fed
# to the generator at a later point for reusability.
# A custom word generator can be used for domain-specific filtering etc
if custom_wordgen is not None:
assert custom_wordgen.stream is None
self.wordgen = custom_wordgen
self.uses_custom_wordgen = True
else:
self.wordgen = WordGenerator(None, allow_unicode_text=True,
ignore_emojis=False,
remove_variation_selectors=True,
break_replacement=True)
self.uses_custom_wordgen = False
def tokenize_sentences(self, sentences, reset_stats=True, max_sentences=None):
""" Converts a given list of sentences into a numpy array according to
its vocabulary.
# Arguments:
sentences: List of sentences to be tokenized.
reset_stats: Whether the word generator's stats should be reset.
max_sentences: Maximum length of sentences. Must be set if the
length cannot be inferred from the input.
# Returns:
Numpy array of the tokenization sentences with masking,
infos,
stats
# Raises:
ValueError: When maximum length is not set and cannot be inferred.
"""
if max_sentences is None and not hasattr(sentences, '__len__'):
raise ValueError('Either you must provide an array with a length'
'attribute (e.g. a list) or specify the maximum '
'length yourself using `max_sentences`!')
n_sentences = (max_sentences if max_sentences is not None
else len(sentences))
if self.masking_value == 0:
tokens = np.zeros((n_sentences, self.fixed_length), dtype='uint16')
else:
tokens = (np.ones((n_sentences, self.fixed_length), dtype='uint16') *
self.masking_value)
if reset_stats:
self.wordgen.reset_stats()
# With a custom word generator info can be extracted from each
# sentence (e.g. labels)
infos = []
# Returns words as strings and then map them to vocabulary
self.wordgen.stream = sentences
next_insert = 0
n_ignored_unknowns = 0
for s_words, s_info in self.wordgen:
s_tokens = self.find_tokens(s_words)
if (self.ignore_sentences_with_only_custom and
np.all([True if t < len(SPECIAL_TOKENS)
else False for t in s_tokens])):
n_ignored_unknowns += 1
continue
if len(s_tokens) > self.fixed_length:
s_tokens = s_tokens[:self.fixed_length]
tokens[next_insert, :len(s_tokens)] = s_tokens
infos.append(s_info)
next_insert += 1
# For standard word generators all sentences should be tokenized
# this is not necessarily the case for custom wordgenerators as they
# may filter the sentences etc.
if not self.uses_custom_wordgen and not self.ignore_sentences_with_only_custom:
assert len(sentences) == next_insert
else:
# adjust based on actual tokens received
tokens = tokens[:next_insert]
infos = infos[:next_insert]
return tokens, infos, self.wordgen.stats
def find_tokens(self, words):
assert len(words) > 0
tokens = []
for w in words:
try:
tokens.append(self.vocabulary[w])
except KeyError:
tokens.append(self.unknown_value)
return tokens |
6b9a3431c98d7f5f6a5e2323d8571a763b0a3e76 | 200202iqbal/game-programming-a | /Paiza/D111.py | 176 | 3.578125 | 4 | number = int(input())
words = input()
rule = number>=1 and number<=100 and len(words) >=1 and len(words) <=100
if(rule):
x =words[:number]
x = str(x)
print(x)
|
42cce5dca3892d7925713f75f8326fd32c7570e8 | MastersAcademy/Programming-Basics | /homeworks/olha.bezpalchuk_olhabezpalchuk/homework-4/inquestWithArraysAndIFs.py | 1,017 | 4 | 4 | print("Hello!")
answer = 'n'
data = {}
while answer != 'y':
data['name'] = input("What is your name?")
data['age'] = int(input("How old are you?"))
data['phone'] = input("Tell me your phone number?")
data['email'] = input("Input your email address: ")
data['place'] = input("Where do you live?")
data['like'] = input("Do you love cakes? (y/n)")
if data['like'] == "y":
data['cake'] = input("Please tell us what is your favourite type of cake")
elif data['like'] == "n":
data['cake'] = input("Please tell us why don't you love cakes")
else:
print "Wrong input data"
print "Please try again"
continue
print("Confirm your data:")
for key, value in data.items():
print(key + ': ' + str(value))
answer = input("Is it right? (y/n)")
print("Good! Have fun and remember: we know your name and where you live.")
f = open('output.txt', 'w')
for key, value in data.items():
f.write(key + ': ' + str(value) + '\n')
f.close()
|
c35d177e407be5583030cf91a23c4dad8964568a | Saketh7382/neural-encryption | /Project/installation.py | 4,648 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 19:18:02 2020
@author: cp
"""
from os import path
from tkinter import *
from encryptor import Encryptor
class Gui:
flag = 1
window = Tk()
window.geometry("430x450")
window.resizable(0, 0)
window.title("Installation Wizard")
e = Encryptor()
# def btn_click(self, item):
# global expression
# expression = expression + str(item)
# input_text.set(expression)
#
# def btn_clear(self):
# global expression
# expression = ""
# input_text.set("")
#
# def btn_equal(self):
# global expression
# result = str(eval(expression))
# input_text.set(result)
# expression = ""
def execute(self,flag):
if path.exists("./network/encryptor/network.json"):
self.labelText.set("Application is already installed in your system\nClose this window and launch the application")
else:
global expression
expression = ""
self.labelText.set("Installing the encryptor\nSee terminal for details")
self.e.main()
self.labelText.set("Installation Finished")
self.flag = 0
def destroy_session(self, window):
window.destroy()
expression = ""
input_text = StringVar()
labelText = StringVar()
input_frame = Frame(window,
width = 312,
height = 50,
bd = 0,
highlightbackground = "black",
highlightcolor = "black",
highlightthickness = 1)
input_frame.pack(side = TOP)
input_field = Entry(input_frame,
font = ('arial', 18, 'bold'),
textvariable = input_text,
width = 50, bg = "#eee",
bd = 0, justify = RIGHT)
input_field.grid(row = 0, column = 0)
input_field.pack(ipady = 10)
btns_frame = Frame(window, width = 312, height = 272.5)
btns_frame.pack(side=TOP)
btns_frame2 = Frame(window, width = 312, height = 72.5, bg = "grey")
btns_frame2.pack(side=BOTTOM)
label = Label(btns_frame,
text = "Neural Encryptor",
fg = "Red",
width = 55,
height = 3,
bd = 0,
bg = "#cfa").grid(row = 0,
column = 0,
columnspan = 2,
)
install = Button(btns_frame,
text = "Install",
fg = "black",
font=('Times new roman', 12, 'bold'),
width = 24,
height = 3,
bd = 2,
bg = "#fff",
cursor = "hand2",
command = lambda: Gui().execute(Gui().flag)).grid(row = 1,
column = 0, )
destroy = Button(btns_frame,
text = "Exit",
fg = "black",
font=('Times new roman', 12, 'bold'),
width = 24,
height = 3,
bd = 2,
bg = "#fff",
cursor = "hand2",
command = lambda: Gui().destroy_session(Gui().window)).grid(row = 1,
column = 1,)
message = Label(btns_frame,
textvariable = labelText,
fg = "Black",
font=('Times new roman', 12, 'bold'),
width = 55,
height = 12,
bd = 0,
).grid(row = 2,
column = 0,
columnspan = 2,
pady = 5,
)
s = "Developed by : Saketh G"
label2 = Label(btns_frame2,
text = s,
fg = "Black",
width = 55,
height = 1,
bd = 0,
bg = "#cfa").grid(row = 3,
column = 0,
columnspan = 2
)
Gui().window.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.