blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7af27b0f76dd9c466cb1d5d5dc58d99381be6f10 | ksamala/k_python | /scripts/17_opn_clse.py | 774 | 3.703125 | 4 | #Open and close file in one line.
with open('/Users/kalyansamala/Downloads/test.txt') as open_instance:
print(open_instance.read())
#Open and write contents in a file
with open('/Users/kalyansamala/Downloads/test.txt', mode='a') as afile:
afile.write('new line added \n')
with open('/Users/kalyansamala/Downloads/test.txt') as open_instance:
print(open_instance.read())
with open('/Users/kalyansamala/Downloads/newtest.txt',mode='w') as wfile:
wfile.write("I have added text to file")
# mode='r' = read only
# mode='w' = write only ( will overwrite or create new file )
# mode='a' = append only ( adds new lines to file )
# mode='r+' = read and write
# mode='w+' = writing and reading( overwirtes existing files or creates new file ) |
01cb6d73ca5ebd12fb69157668da2365e5a327e6 | ksamala/k_python | /scripts/23_for_continue.py | 220 | 4.09375 | 4 | name = 'malayalam'
for letter in name:
if letter == 'a':
continue
print(letter)
print("Check break statment")
name = 'malayalam'
for letter in name:
if letter == 'a':
break
print(letter) |
18c07f03236f4d5b8294f843aba0ba1a53ce8b03 | ksamala/k_python | /scripts/3_area.py | 326 | 4.03125 | 4 | # Use functions to caluculate area
def gather_details():
lnt = int(input("Enter length"))
brt = int(input("Enter breadth"))
return (lnt, brt)
def compute(lnth, brth):
area = lnth*brth
return area
while True:
ln, br = gather_details()
area = compute(ln, br)
print(f"Area is {area}") |
8a8bcb8b2060791d4e257a5fee7e6d551ea4f38e | ksamala/k_python | /scripts/32_handle_incorrect_input.py | 165 | 3.609375 | 4 | def ask():
try:
a = int(input("Enter integer "))
return a
except:
print("Enter Integer only")
while True:
z = ask()
print(z) |
23579f6ff0e1b600c90c90b1618e6b9cb8e0e2d5 | mukobi/pozyx-clone | /house_code/main_programs/PSUPozyx/modules/file_writing.py | 35,702 | 3.546875 | 4 | from .data_functions import DataFunctions as DataFunctions
class SensorDataFileWriting:
@staticmethod
def write_sensor_data_header_to_file(file,
header=("Index,Time,Difference,Hz,AveHz,"
"Pressure,"
"Acceleration-X,Acceleration-Y,Acceleration-Z,"
"Magnetic-X,Magnetic-Y,Magnetic-Z,"
"Angular-Vel-X,Angular-Vel-Y,Angular-Vel-Z,"
"Heading,Roll,Pitch,"
"Quaternion-X,Quaternion-Y,Quaternion-Z,Quaternion-W,"
"Linear-Acceleration-X,Linear-Acceleration-Y,Linear-Acceleration-Z,"
"Gravity-XGravity-X,Gravity-Y,Gravity-Z")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_line_of_sensor_data_to_file(index, elapsed_time, time_difference,
file, sensor_data):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(sensor_data.pressure) + ","
+ str(sensor_data.acceleration.x) + ","
+ str(sensor_data.acceleration.y) + ","
+ str(sensor_data.acceleration.z) + ","
+ str(sensor_data.magnetic.x) + ","
+ str(sensor_data.magnetic.y) + ","
+ str(sensor_data.magnetic.z) + ","
+ str(sensor_data.angular_vel.x) + ","
+ str(sensor_data.angular_vel.y) + ","
+ str(sensor_data.angular_vel.z) + ","
+ str(sensor_data.euler_angles.heading) + ","
+ str(sensor_data.euler_angles.roll) + ","
+ str(sensor_data.euler_angles.pitch) + ","
+ str(sensor_data.quaternion.x) + ","
+ str(sensor_data.quaternion.y) + ","
+ str(sensor_data.quaternion.z) + ","
+ str(sensor_data.quaternion.w) + ","
+ str(sensor_data.linear_acceleration.x) + ","
+ str(sensor_data.linear_acceleration.y) + ","
+ str(sensor_data.linear_acceleration.z) + ","
+ str(sensor_data.gravity_vector.x) + ","
+ str(sensor_data.gravity_vector.y) + ","
+ str(sensor_data.gravity_vector.z) + ","
+ "\n")
except AttributeError:
for i in range(0, 23):
output += "nan,"
output += "\n"
file.write(output)
class SensorAndPositionFileWriting:
@staticmethod
def write_position_header_to_file_1d(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Position")):
"""
Writes column headers for position data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_position_and_velocity_header_to_file_1d(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Position,"
"Velocity")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_sensor_and_position_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Pressure,"
"Acceleration-X,Acceleration-Y,Acceleration-Z,"
"Magnetic-X,Magnetic-Y,Magnetic-Z,"
"Angular-Vel-X,Angular-Vel-Y,Angular-Vel-Z,"
"Heading,Roll,Pitch,"
"Quaternion-X,Quaternion-Y,Quaternion-Z,Quaternion-W,"
"Linear-Acceleration-X,Linear-Acceleration-Y,Linear-Acceleration-Z,"
"Gravity-X,Gravity-Y,Gravity-Z,"
"Position")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_sensor_and_position_and_velocity_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Pressure,"
"Acceleration-X,Acceleration-Y,Acceleration-Z,"
"Magnetic-X,Magnetic-Y,Magnetic-Z,"
"Angular-Vel-X,Angular-Vel-Y,Angular-Vel-Z,"
"Heading,Roll,Pitch,"
"Quaternion-X,Quaternion-Y,Quaternion-Z,Quaternion-W,"
"Linear-Acceleration-X,Linear-Acceleration-Y,Linear-Acceleration-Z,"
"Gravity-X,Gravity-Y,Gravity-Z,"
"Position,"
"Velocity")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_position_data_to_file_1d(
index, elapsed_time, time_difference, file, position_data):
"""
This function writes the position data to the file each cycle in the while iterate_file.
"""
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(position_data.distance) + "\n")
except AttributeError:
for i in range(0, 26):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_position_and_velocity_data_to_file_1d(
index, elapsed_time, time_difference, file, position_data, velocity):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(position_data.distance) + ","
+ str(velocity) + "\n")
except AttributeError:
for i in range(0, 11):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_sensor_and_position_data_to_file_1d(
index, elapsed_time, time_difference, file, sensor_data, position_data):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(sensor_data.pressure) + ","
+ str(sensor_data.acceleration.x) + ","
+ str(sensor_data.acceleration.y) + ","
+ str(sensor_data.acceleration.z) + ","
+ str(sensor_data.magnetic.x) + ","
+ str(sensor_data.magnetic.y) + ","
+ str(sensor_data.magnetic.z) + ","
+ str(sensor_data.angular_vel.x) + ","
+ str(sensor_data.angular_vel.y) + ","
+ str(sensor_data.angular_vel.z) + ","
+ str(sensor_data.euler_angles.heading) + ","
+ str(sensor_data.euler_angles.roll) + ","
+ str(sensor_data.euler_angles.pitch) + ","
+ str(sensor_data.quaternion.x) + ","
+ str(sensor_data.quaternion.y) + ","
+ str(sensor_data.quaternion.z) + ","
+ str(sensor_data.quaternion.w) + ","
+ str(sensor_data.linear_acceleration.x) + ","
+ str(sensor_data.linear_acceleration.y) + ","
+ str(sensor_data.linear_acceleration.z) + ","
+ str(sensor_data.gravity_vector.x) + ","
+ str(sensor_data.gravity_vector.y) + ","
+ str(sensor_data.gravity_vector.z) + ","
+ str(position_data.distance) + ","
+ "\n")
except AttributeError:
for i in range(0, 26):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_sensor_and_position_and_velocity_data_to_file_1d(
index, elapsed_time, time_difference, file, sensor_data, position_data, velocity):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(sensor_data.pressure) + ","
+ str(sensor_data.acceleration.x) + ","
+ str(sensor_data.acceleration.y) + ","
+ str(sensor_data.acceleration.z) + ","
+ str(sensor_data.magnetic.x) + ","
+ str(sensor_data.magnetic.y) + ","
+ str(sensor_data.magnetic.z) + ","
+ str(sensor_data.angular_vel.x) + ","
+ str(sensor_data.angular_vel.y) + ","
+ str(sensor_data.angular_vel.z) + ","
+ str(sensor_data.euler_angles.heading) + ","
+ str(sensor_data.euler_angles.roll) + ","
+ str(sensor_data.euler_angles.pitch) + ","
+ str(sensor_data.quaternion.x) + ","
+ str(sensor_data.quaternion.y) + ","
+ str(sensor_data.quaternion.z) + ","
+ str(sensor_data.quaternion.w) + ","
+ str(sensor_data.linear_acceleration.x) + ","
+ str(sensor_data.linear_acceleration.y) + ","
+ str(sensor_data.linear_acceleration.z) + ","
+ str(sensor_data.gravity_vector.x) + ","
+ str(sensor_data.gravity_vector.y) + ","
+ str(sensor_data.gravity_vector.z) + ","
+ str(position_data.distance) + ","
+ str(velocity) + ","
+ "\n")
except AttributeError:
for i in range(0, 26):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_sensor_and_position_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Pressure,"
"Acceleration-X,Acceleration-Y,Acceleration-Z,"
"Magnetic-X,Magnetic-Y,Magnetic-Z,"
"Angular-Vel-X,Angular-Vel-Y,Angular-Vel-Z,"
"Heading,Roll,Pitch,"
"Quaternion-X,Quaternion-Y,Quaternion-Z,Quaternion-W,"
"Linear-Acceleration-X,Linear-Acceleration-Y,Linear-Acceleration-Z,"
"Gravity-X,Gravity-Y,Gravity-Z,"
"Position-X,Position-Y,Position-Z")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_sensor_and_position_and_velocity_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Pressure,"
"Acceleration-X,Acceleration-Y,Acceleration-Z,"
"Magnetic-X,Magnetic-Y,Magnetic-Z,"
"Angular-Vel-X,Angular-Vel-Y,Angular-Vel-Z,"
"Heading,Roll,Pitch,"
"Quaternion-X,Quaternion-Y,Quaternion-Z,Quaternion-W,"
"Linear-Acceleration-X,Linear-Acceleration-Y,Linear-Acceleration-Z,"
"Gravity-X,Gravity-Y,Gravity-Z,"
"Position-X,Position-Y,Position-Z"
"Velocity-X,Velocity-Y,Velocity-Z")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_position_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Position-X,Position-Y,Position-Z")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_position_and_velocity_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Position-X,Position-Y,Position-Z,"
"Velocity-X,Velocity-Y,Velocity-Z")):
"""
Writes column headers for all of the sensor data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_position_data_to_file(index, elapsed_time, time_difference,
file, position_data):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(position_data.x) + ","
+ str(position_data.y) + ","
+ str(position_data.z) + "," + "\n")
except AttributeError:
for i in range(0, 11):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_position_and_velocity_data_to_file(
index, elapsed_time, time_difference, file, position_data, velocity_x, velocity_y, velocity_z):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(position_data.x) + ","
+ str(position_data.y) + ","
+ str(position_data.z) + ","
+ str(velocity_x) + ","
+ str(velocity_y) + ","
+ str(velocity_z) + "," + "\n")
except AttributeError:
for i in range(0, 11):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_sensor_and_position_data_to_file(index, elapsed_time, time_difference,
file, sensor_data, position_data):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(sensor_data.pressure) + ","
+ str(sensor_data.acceleration.x) + ","
+ str(sensor_data.acceleration.y) + ","
+ str(sensor_data.acceleration.z) + ","
+ str(sensor_data.magnetic.x) + ","
+ str(sensor_data.magnetic.y) + ","
+ str(sensor_data.magnetic.z) + ","
+ str(sensor_data.angular_vel.x) + ","
+ str(sensor_data.angular_vel.y) + ","
+ str(sensor_data.angular_vel.z) + ","
+ str(sensor_data.euler_angles.heading) + ","
+ str(sensor_data.euler_angles.roll) + ","
+ str(sensor_data.euler_angles.pitch) + ","
+ str(sensor_data.quaternion.x) + ","
+ str(sensor_data.quaternion.y) + ","
+ str(sensor_data.quaternion.z) + ","
+ str(sensor_data.quaternion.w) + ","
+ str(sensor_data.linear_acceleration.x) + ","
+ str(sensor_data.linear_acceleration.y) + ","
+ str(sensor_data.linear_acceleration.z) + ","
+ str(sensor_data.gravity_vector.x) + ","
+ str(sensor_data.gravity_vector.y) + ","
+ str(sensor_data.gravity_vector.z) + ","
+ str(position_data.x) + ","
+ str(position_data.y) + ","
+ str(position_data.z) + ","
+ "\n")
except AttributeError:
for i in range(0, 26):
output += "nan,"
output += "\n"
file.write(output)
@staticmethod
def write_sensor_and_position_and_velocity_data_to_file(
index, elapsed_time, time_difference, file, sensor_data, position_data, velocity_x, velocity_y, velocity_z):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(sensor_data.pressure) + ","
+ str(sensor_data.acceleration.x) + ","
+ str(sensor_data.acceleration.y) + ","
+ str(sensor_data.acceleration.z) + ","
+ str(sensor_data.magnetic.x) + ","
+ str(sensor_data.magnetic.y) + ","
+ str(sensor_data.magnetic.z) + ","
+ str(sensor_data.angular_vel.x) + ","
+ str(sensor_data.angular_vel.y) + ","
+ str(sensor_data.angular_vel.z) + ","
+ str(sensor_data.euler_angles.heading) + ","
+ str(sensor_data.euler_angles.roll) + ","
+ str(sensor_data.euler_angles.pitch) + ","
+ str(sensor_data.quaternion.x) + ","
+ str(sensor_data.quaternion.y) + ","
+ str(sensor_data.quaternion.z) + ","
+ str(sensor_data.quaternion.w) + ","
+ str(sensor_data.linear_acceleration.x) + ","
+ str(sensor_data.linear_acceleration.y) + ","
+ str(sensor_data.linear_acceleration.z) + ","
+ str(sensor_data.gravity_vector.x) + ","
+ str(sensor_data.gravity_vector.y) + ","
+ str(sensor_data.gravity_vector.z) + ","
+ str(position_data.x) + ","
+ str(position_data.y) + ","
+ str(position_data.z) + ","
+ str(velocity_x) + ","
+ str(velocity_y) + ","
+ str(velocity_z) + ","
+ "\n")
except AttributeError:
for i in range(0, 26):
output += "nan,"
output += "\n"
file.write(output)
class PositionFileWriting:
@staticmethod
def write_position_header_to_file(
file,
header=("Index,Time,Difference,Hz,AveHz,"
"Position-X,Position-Y,Position-Z")):
"""
Writes column headers for position data to a file
:param file: the file to write to
:param str header: The header labels, already set by default
"""
file.write(header + '\n')
@staticmethod
def write_position_data_to_file(index, elapsed_time, time_difference,
file, position_data):
"""
This function writes the position data to the file each cycle in the while iterate_file.
"""
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
output += (str(position_data.x) + ","
+ str(position_data.y) + ","
+ str(position_data.z) + ","
+ "\n")
except AttributeError:
for i in range(0, 26):
output += "nan,"
output += "\n"
file.write(output)
class MultiDevicePositionFileWriting:
@staticmethod
def write_multidevice_position_header_to_file(
file, tags,
header_start="Index,Time,Difference,Hz,AveHz,"):
"""
Writes column headers for all of the sensor data to a file
:param list tags: the tags that will be measured
:param str header_start: The start of the header labels, already set by default
:param file: the file to write to
"""
header = header_start
print(tags)
for tag in tags:
header += hex(tag) + "-X,"
header += hex(tag) + "-Y,"
header += hex(tag) + "-Z,"
file.write(header + '\n')
@staticmethod
def write_multidevice_1D_header_to_file(
file, tags,
header_start="Index,Time,Difference,Hz,AveHz,"):
"""
Writes column headers for 1D data to a file
:param list tags: the tags that will be measured
:param str header_start: The start of the header labels, already set by default
:param file: the file to write to
"""
header = header_start
print(tags)
for tag in tags:
header += hex(tag) + ","
file.write(header + '\n')
@staticmethod
def write_multidevice_position_data_to_file(
index, elapsed_time, time_difference, file, position_array):
"""
This function writes the position data to the file each cycle in the while iterate_file.
"""
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
for idx, element in enumerate(position_array):
# only print position data, not tags since they are in header
if idx % 4 != 0:
output += str(element) + ","
file.write(output + "\n")
except AttributeError:
pass
@staticmethod
def write_multidevice_1D_data_to_file(
index, elapsed_time, time_difference, file, position_array):
"""
This function writes 1D data to the file each cycle in the while iterate_file.
"""
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
try:
for idx, element in enumerate(position_array):
# only print position data, not tags since they are in header
if idx % 4 != 0:
output += str(element) + ","
file.write(output + "\n")
except AttributeError:
pass
class RangingFileWriting:
@staticmethod
def write_range_headers_to_file(file, tags, attributes_to_log):
header = "Index,Time,Difference,Hz,AveHz,"
for tag in tags:
if "pressure" in attributes_to_log:
header += (hex(tag) + " Pressure,")
if "acceleration" in attributes_to_log:
header += (hex(tag) + " Acceleration-X,")
header += (hex(tag) + " Acceleration-Y,")
header += (hex(tag) + " Acceleration-Z,")
if "magnetic" in attributes_to_log:
header += (hex(tag) + " Magnetic-X,")
header += (hex(tag) + " Magnetic-Y,")
header += (hex(tag) + " Magnetic-Z,")
if "angular velocity" in attributes_to_log:
header += (hex(tag) + " Angular-Vel-X,")
header += (hex(tag) + " Angular-Vel-Y,")
header += (hex(tag) + " Angular-Vel-Z,")
if "euler angles" in attributes_to_log:
header += (hex(tag) + " Heading,")
header += (hex(tag) + " Roll,")
header += (hex(tag) + " Pitch,")
if "quaternion" in attributes_to_log:
header += (hex(tag) + " Quaternion-X,")
header += (hex(tag) + " Quaternion-Y,")
header += (hex(tag) + " Quaternion-Z,")
header += (hex(tag) + " Quaternion-W,")
if "linear acceleration" in attributes_to_log:
header += (hex(tag) + " Linear-Acceleration-X,")
header += (hex(tag) + " Linear-Acceleration-Y,")
header += (hex(tag) + " Linear-Acceleration-Z,")
if "gravity" in attributes_to_log:
header += (hex(tag) + " Gravity-X,")
header += (hex(tag) + " Gravity-Y,")
header += (hex(tag) + " Gravity-Z,")
header += hex(tag) + " Range,"
header += hex(tag) + " Smoothed Range,"
header += hex(tag) + " Velocity,"
header += "\n"
file.write(header)
@staticmethod
def write_range_data_to_file(file, index, elapsed_time, time_difference, loop_output_array, attributes_to_log):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
for single_output in loop_output_array:
motion = single_output.sensor_data
if "pressure" in attributes_to_log:
output += (str(motion.pressure) + ",")
if "acceleration" in attributes_to_log:
output += (str(motion.acceleration.x) + ",")
output += (str(motion.acceleration.y) + ",")
output += (str(motion.acceleration.z) + ",")
if "magnetic" in attributes_to_log:
output += (str(motion.magnetic.x) + ",")
output += (str(motion.magnetic.y) + ",")
output += (str(motion.magnetic.z) + ",")
if "angular velocity" in attributes_to_log:
output += (str(motion.angular_vel.x) + ",")
output += (str(motion.angular_vel.y) + ",")
output += (str(motion.angular_vel.z) + ",")
if "euler angles" in attributes_to_log:
output += (str(motion.euler_angles.heading) + ",")
output += (str(motion.euler_angles.roll) + ",")
output += (str(motion.euler_angles.pitch) + ",")
if "quaternion" in attributes_to_log:
output += (str(motion.quaternion.x) + ",")
output += (str(motion.quaternion.y) + ",")
output += (str(motion.quaternion.z) + ",")
output += (str(motion.quaternion.w) + ",")
if "linear acceleration" in attributes_to_log:
output += (str(motion.linear_acceleration.x) + ",")
output += (str(motion.linear_acceleration.y) + ",")
output += (str(motion.linear_acceleration.z) + ",")
if "gravity" in attributes_to_log:
output += (str(motion.gravity_vector.x) + ",")
output += (str(motion.gravity_vector.y) + ",")
output += (str(motion.gravity_vector.z) + ",")
output += str(single_output.device_range.distance) + ","
output += str(single_output.smoothed_range) + ","
if elapsed_time == 0: # don't log zero velocity
output += ","
else:
output += str(single_output.velocity) + ","
output += "\n"
file.write(output)
class PositioningFileWriting:
@staticmethod
def write_position_headers_to_file(file, tags, attributes_to_log):
header = "Index,Time,Difference,Hz,AveHz,"
for tag in tags:
if "pressure" in attributes_to_log:
header += (hex(tag) + " Pressure,")
if "acceleration" in attributes_to_log:
header += (hex(tag) + " Acceleration-X,")
header += (hex(tag) + " Acceleration-Y,")
header += (hex(tag) + " Acceleration-Z,")
if "magnetic" in attributes_to_log:
header += (hex(tag) + " Magnetic-X,")
header += (hex(tag) + " Magnetic-Y,")
header += (hex(tag) + " Magnetic-Z,")
if "angular velocity" in attributes_to_log:
header += (hex(tag) + " Angular-Vel-X,")
header += (hex(tag) + " Angular-Vel-Y,")
header += (hex(tag) + " Angular-Vel-Z,")
if "euler angles" in attributes_to_log:
header += (hex(tag) + " Heading,")
header += (hex(tag) + " Roll,")
header += (hex(tag) + " Pitch,")
if "quaternion" in attributes_to_log:
header += (hex(tag) + " Quaternion-X,")
header += (hex(tag) + " Quaternion-Y,")
header += (hex(tag) + " Quaternion-Z,")
header += (hex(tag) + " Quaternion-W,")
if "linear acceleration" in attributes_to_log:
header += (hex(tag) + " Linear-Acceleration-X,")
header += (hex(tag) + " Linear-Acceleration-Y,")
header += (hex(tag) + " Linear-Acceleration-Z,")
if "gravity" in attributes_to_log:
header += (hex(tag) + " Gravity-X,")
header += (hex(tag) + " Gravity-Y,")
header += (hex(tag) + " Gravity-Z,")
header += hex(tag) + " Measured-X,"
header += hex(tag) + " Measured-Y,"
header += hex(tag) + " Measured-Z,"
header += hex(tag) + " Smoothed-X,"
header += hex(tag) + " Smoothed-Y,"
header += hex(tag) + " Smoothed-Z,"
header += hex(tag) + " Velocity-X,"
header += hex(tag) + " Velocity-Y,"
header += hex(tag) + " Velocity-Z,"
header += "\n"
file.write(header)
@staticmethod
def write_position_data_to_file(file, index, elapsed_time, time_difference, loop_output_array, attributes_to_log):
hz = DataFunctions.convert_hertz(time_difference)
ave_hz = DataFunctions.find_average_hertz(index, elapsed_time)
output = (str(index) + "," + str(elapsed_time) + ","
+ str(time_difference) + "," + str(hz) + ","
+ str(ave_hz) + ",")
for single_output in loop_output_array:
motion = single_output.sensor_data
if "pressure" in attributes_to_log:
output += (str(motion.pressure) + ",")
if "acceleration" in attributes_to_log:
output += (str(motion.acceleration.x) + ",")
output += (str(motion.acceleration.y) + ",")
output += (str(motion.acceleration.z) + ",")
if "magnetic" in attributes_to_log:
output += (str(motion.magnetic.x) + ",")
output += (str(motion.magnetic.y) + ",")
output += (str(motion.magnetic.z) + ",")
if "angular velocity" in attributes_to_log:
output += (str(motion.angular_vel.x) + ",")
output += (str(motion.angular_vel.y) + ",")
output += (str(motion.angular_vel.z) + ",")
if "euler angles" in attributes_to_log:
output += (str(motion.euler_angles.heading) + ",")
output += (str(motion.euler_angles.roll) + ",")
output += (str(motion.euler_angles.pitch) + ",")
if "quaternion" in attributes_to_log:
output += (str(motion.quaternion.x) + ",")
output += (str(motion.quaternion.y) + ",")
output += (str(motion.quaternion.z) + ",")
output += (str(motion.quaternion.w) + ",")
if "linear acceleration" in attributes_to_log:
output += (str(motion.linear_acceleration.x) + ",")
output += (str(motion.linear_acceleration.y) + ",")
output += (str(motion.linear_acceleration.z) + ",")
if "gravity" in attributes_to_log:
output += (str(motion.gravity_vector.x) + ",")
output += (str(motion.gravity_vector.y) + ",")
output += (str(motion.gravity_vector.z) + ",")
output += str(single_output.position.x) + ","
output += str(single_output.position.y) + ","
output += str(single_output.position.z) + ","
output += str(single_output.smoothed_x) + ","
output += str(single_output.smoothed_y) + ","
output += str(single_output.smoothed_z) + ","
if elapsed_time == 0: # don't log zero velocities
output += ",,,"
else:
output += str(single_output.velocity_x) + ","
output += str(single_output.velocity_y) + ","
output += str(single_output.velocity_z) + ","
output += "\n"
file.write(output)
|
63d67329e94978a29fcdf6bd2ee3a1d200660cbf | pyjune/python3_doc | /2_4.py | 555 | 4.125 | 4 | # 사칙연산
a = 3
b = 5
print(a+b)
print(a+10)
print(a-b)
print(a*b)
print(b*6)
print(a/b)
print(a/10)
# 정수형 나눗셈
print(3//2)
print(5//2)
# 모드 연산
print(a%2) #a를 2로 나눈 나머지
print(b%a) #b를 a로 나눈 나머지
# 거듭 제곱
print(a**2)
print(a**3)
print(b**a)
# 비교연산
a = 3
b = 5
print(a>0)
print(a>b)
print(a>=3)
print(b<10)
print(b<=5)
print(a==3) #a에 들은 값과 3이 같으면 True
print(a==b) #a와 b에 들어있는 값이 같으면 True
print(a!=b) #a와 b에 들어있는 값이 다르면 True
|
1a94a3de903e70d1b8c7c263beebcd1e4fb8268c | pyjune/python3_doc | /5_2.py | 958 | 3.859375 | 4 | menu = ['','Americano', 'Latte', 'Espresso', 'Mocha', '식혜', '수정과']
price = [0,1500, 2000, 1700, 2500, 2000, 1900]
# 메뉴 보이기
i = 1
#while i <= 6:
while i< len(menu):
print(i, menu[i], price[i])
#print("%d. %-10s %5d"% (i, menu[i], price[i]))
i = i+1
# 음료 선택
n = int(input("음료를 선택하세요 : "))
total = price[n]
print(menu[n], price[n],'원 ', '합계 ', total, '원')
# 음료 추가
while n != 0:
print()
n = int(input("계속 주문은 음료 번호를, 지불은 0을 누르세요 : "))
if n > 0 and n < len(menu):
total = total + price[n]
print(menu[n], price[n],'원 ', '합계 ', total, '원')
else :
if n == 0 :
print("주문이 완료되었습니다.")
else :
print("없는 메뉴입니다.")
# 지불
pay = 0
pay = int(input("지불 금액을 입력하세요 : "))
change = pay - total
print('거스름 ', change, '원')
|
c0559f619307150cfccbfe7337230fcab9da3abe | priyash555/Automation-Bots | /KS/MAIN APP/dol_extractor.py | 492 | 3.59375 | 4 | import pytz
import date_extractor
def extract_dol(lines):
'''take list as input
break it into lines and
extract date from each lines
if present
'''
dates_arr = []
for line in lines:
dates = date_extractor.extract_dates(line)
for date in dates:
dates_arr.append(date.date())
return dates_arr
# TEST CASE
# text = "need to get two signatures.DoL: 9 feb 1986 with accident yesterday dOL: 19 feb, 2019"
# for i in extract_dol(text):
# print i
|
5a91714dc26aae0d9398fdd3ea4bffa11693ca6f | SamirIngley/CS1.1 | /backwards_poetry.py | 569 | 4.09375 | 4 | poem1 = ["hello", "whatsup", "go"]
def lines_printed_backwards(poem):
''' returns text words in backwards order. takes a list of strings. '''
# get the poem , be able to access each element. access the last one. append it to new list.
backwards = []
length = len(poem) - 1
enum_poem = [(word) for word in enumerate(poem)]
print(enum_poem)
print(length)
for word in poem:
backwards.append(poem[length])
length -= 1
backwards = (' ').join(backwards)
return print(backwards)
lines_printed_backwards(poem1) |
e50bdbb27ed6cb65eeaaf4752b349aac3839be41 | coding-hamster/Udacity-Programming-Foundations-with-Python | /turtle_scripts.py | 549 | 3.546875 | 4 | import turtle
window = turtle.Screen()
window.bgcolor('red')
def draw_square():
brad = turtle.Turtle()
for i in range(1, 5):
brad.forward(100)
brad.right(90)
draw_square()
def draw_circle():
window = turtle.Screen()
angie = turtle.Turtle()
angie.shape('arrow')
angie.color('blue')
angie.circle(100)
draw_circle()
def draw_triangle():
bard = turtle.Turtle()
for i in range(1, 5):
bard.right(120)
bard.forward(100)
draw_triangle()
window.exitonclick() |
92af7504ba29fb231a94e3d623e73e86a8d12e6d | contactpunit/python_sample_exercises | /ds/ds/martiniq.py | 308 | 3.5 | 4 | def get_index_different_char(chars):
alnum = []
special = []
for index, char in enumerate(chars):
if str(char).isalnum():
alnum.append(index)
else:
special.append(index)
if len(alnum) == 1:
return alnum[0]
else:
return special[0]
|
7386ce12bbf8da0b9bc87978528ff3ebe0aa63df | contactpunit/python_sample_exercises | /ds/ds/password_validate.py | 1,169 | 3.65625 | 4 | import string
from collections import defaultdict
PUNCTUATION_CHARS = list(string.punctuation)
used_passwords = set('PassWord@1 PyBit$s9'.split())
def validate_password(password):
if not len(password) >= 6 and not len(password) <= 12:
return False
if password in used_passwords:
return False
charmap = _prepare_map(password)
if not len(charmap['digit']) >= 1:
return False
if not len(charmap['lower']) >= 2:
return False
if not len(charmap['upper']) >= 1:
return False
if not len(charmap['punc']) >= 1:
return False
used_passwords.add(password)
return True
def _prepare_map(password):
d = defaultdict(list)
for char in password:
if digit(char):
d['digit'].append(char)
elif alpha(char) and upper(char):
d['upper'].append(char)
elif alpha(char) and lower(char):
d['lower'].append(char)
elif punc(char):
d['punc'].append(char)
return d
digit = lambda w: w.isdigit()
alpha = lambda a: a.isalpha()
lower = lambda l: l.islower()
upper = lambda u: u.isupper()
punc = lambda p: p in PUNCTUATION_CHARS
|
471bb7458f78b94190321bdcbaa0dce295cdb3f9 | contactpunit/python_sample_exercises | /ds/ds/mul_table.py | 1,088 | 4.21875 | 4 | class MultiplicationTable:
def __init__(self, length):
"""Create a 2D self._table of (x, y) coordinates and
their calculations (form of caching)"""
self.length = length
self._table = {
(i, j): i * j
for i in range(1, length + 1)
for j in range(1, length + 1)
}
print(self._table)
def __len__(self):
"""Returns the area of the table (len x* len y)"""
return self.length * self.length
def __str__(self):
return '\n'.join(
[
' | '.join(
[
str(self._table[(i, j)])
for j in range(1, self.length + 1)
]
)
for i in range(1, self.length + 1)
]
)
def calc_cell(self, x, y):
"""Takes x and y coords and returns the re-calculated result"""
try:
return self._table[(x, y)]
except KeyError as e:
raise IndexError()
m = MultiplicationTable(3)
print(m)
|
21f4ed0a79f4a0f826cad6224de312a2f0d7469d | contactpunit/python_sample_exercises | /ds/ds/length_convertor.py | 671 | 3.59375 | 4 | import numbers
import decimal
def convert(value: float, fmt: str) -> float:
#TODO: Complete this
"""Converts the value to the designated format.
:param value: The value to be converted must be numeric or raise a TypeError
:param fmt: String indicating format to convert to
:return: Float rounded to 4 decimal places after conversion
"""
if not isinstance(value, numbers.Real):
raise TypeError()
if fmt.lower() not in ['cm', 'in']:
raise ValueError()
if fmt.lower() == 'cm':
return round(value / 0.39370, 2)
else:
decimal.getcontext().prec = 4
return decimal.Decimal(str(value * 0.39370))
|
2f11dedc0c3c5e393b0ad0228ca82171f5797f9a | contactpunit/python_sample_exercises | /ds/ds/averager.py | 266 | 3.71875 | 4 | def averager():
count = 0
total = 0
avg = 0
while True:
num = yield avg
total += num
count += 1
avg = total/count
a = averager()
print(a)
print(next(a))
print(a.send(20))
print(a.send(10))
print(a.send(12))
a.close() |
fe5b3f647a9a1cba98baf36b5e799fe0045d8a6a | contactpunit/python_sample_exercises | /ds/ds/count_dirs.py | 430 | 3.9375 | 4 | import os
def count_dirs_and_files(directory='.'):
"""Count the amount of of directories and files in passed in "directory" arg.
Return a tuple of (number_of_directories, number_of_files)
"""
countd, countf = 0, 0
for (dirpath, dirnames, filenames) in os.walk(directory):
countd += len(dirnames)
countf += len(filenames)
return (countd, countf)
print(count_dirs_and_files('/tmp/a'))
|
963384575a80de01b2c87d8ad911db047bb90e2b | raipier8818/PyTorch | /2_LinearRegression/Autograd.py | 400 | 3.53125 | 4 | import torch
w = torch.tensor(2.0, requires_grad = True)
y = w**2
z = 2*y + 5
z.backward()
print('{}'.format(w.grad))
w = torch.tensor(2.0, requires_grad = True) # 기울기 저장
b = torch.tensor(1.0, requires_grad = True)
z = (b*w)**2 + b**2
z.backward() # z를 미분한 다음 각 값(w = 2.0, b = 1.0)을 대입하여 w.grad와 b.grad에 저장
print('{}, {}'.format(w.grad, b.grad)) |
10f2d2d007005edc0a52585ed89893217cb49b79 | EduardoCostaEXE/Calculadora_Simples | /calculadora.py | 464 | 3.84375 | 4 | class Calculadora:
def __init__(self, num1, num2) :
self.a = num1
self.b = num2
def soma(self):
return self.a + self.b
def subtracao(self):
return self.a - self.b
def multiplacacao(self):
return self.a * self.b
def divisao(self):
return self.a / self.b
contador = Calculadora(10, 5)
print(contador.soma())
print(contador.subtracao())
print(contador.multiplacacao())
print(contador.divisao()) |
b0aca5370c680946127c5792b4957e37f9df67e8 | CrRaul/AvoidBlocksNN | /Matrix.py | 4,221 | 3.84375 | 4 | import random
# Class Matrix contain number of rows, number of columns, data of matrix and operation with matrix
class Matrix():
# Desc:
# In:
# Out:
def __init__(self, rows, cols):
self.__rows = rows
self.__cols = cols
self.__data = []
for i in range(0, self.__rows):
self.__data.append([])
for j in range(0, self.__cols):
self.__data[i].append(0)
def getRows(self):
return self.__rows
def getCols(self):
return self.__cols
def getData(self):
return self.__data
def getDataPos(self, posI, posJ):
return self.__data[posI][posJ]
def setDataPos(self, posI, posJ, val):
self.__data[posI][posJ] = val
# Desc: populate data of matrix with random number
# In: ----
# Out: new data in matrix
def randomize(self):
for i in range(0, self.__rows):
for j in range(0, self.__cols):
self.__data[i][j] = random.uniform(-1,1)
# Desc: create a Matrix object from an array
# In: array
# Out: Matrix with one column
def fromArray(arr):
m = Matrix(len(arr), 1)
for i in range(0, len(arr)):
m.__data[i][0] = arr[i]
return m
def toArray(self):
arr = []
for i in range(0, self.__rows):
for j in range(0, self.__cols):
arr.append(self.__data[i][j])
return arr
# Desc: create transpose of matrix
# In: self object
# Out: return transpose of current matrix
def transpose(matrix):
result = Matrix(matrix.__cols, matrix.__rows)
for i in range(0, result.__rows):
for j in range(0, result.__cols):
result.__data[i][j] = matrix.__data[j][i]
return result
# Desc: multiply two Matrix
# In: two Matrix
# Out: return the Matrix result
def multiply(a, b):
if a.getCols() != b.getRows():
raise ValueError("columns of a != rows of b")
else:
result = Matrix(a.getRows(), b.getCols())
for i in range(0, result.__rows):
for j in range(0, result.__cols):
sum = 0
for k in range(0, a.__cols):
sum += a.__data[i][k] * b.__data[k][j]
result.__data[i][j] = sum
return result
# Desc: multiply all value of matrix with a number
# In: number m
# Out: modify current Matrix
def multiplyValue(self, m):
for i in range(0, self.__rows):
for j in range(0, self.__cols):
self.__data[i][j] *= m
# Desc: add to all value of matrix a number
# In: number m
# Out: modify current Matrix
def add(self, m):
if(isinstance(m, Matrix)):
mat = m.getData()
for i in range(0, self.__rows):
for j in range(0, self.__cols):
self.__data[i][j] += mat[i][j]
else:
for i in range(0, self.__rows):
for j in range(0, self.__cols):
self.__data[i][j] += m
# Desc: substract a from b
# In: matrix a and b
# Out: substract Matrix
def substract(a, b):
result = Matrix(a.__rows, b.__cols)
for i in range(0, result.__rows):
for j in range(0, result.__cols):
result.__data[i][j] = a.__data[i][j] - b.__data[i][j]
return result
# Desc: applay a function to all elements of matrix
# In: number m
# Out: modify current Matrix
def map(self, fn):
for i in range(0, self.__rows):
for j in range(0, self.__cols):
val = self.__data[i][j]
self.__data[i][j] = fn(val)
# Desc: print current Matrix
# In: --
# Out: --
def print(self):
print(self.__data)
|
5355734d9c928e1fddbc49437bd5f8d545581e76 | vijaymaddukuri/rest_api_project | /utils/service/restlibrary.py | 1,586 | 3.515625 | 4 | from requests.sessions import Session
class RestLib(Session):
"""
Library for REST API Calls
"""
def get(self, url, **kwargs):
"""Sends a GET request. Returns :class:`Response` object.
Args:
:param url: URL for the new :class:`Request` object.
:param kwargs: Optional arguments that ``request`` takes.
"""
kwargs.setdefault('timeout', 60)
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
"""Sends a POST request. Returns :class:`Response` object.
Args:
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the :class:`Request`.
:param kwargs: Optional arguments that ``request`` takes.
"""
kwargs.setdefault('timeout', 60)
return self.request('POST', url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
"""Sends a PUT request. Returns :class:`Response` object.
Args:
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param kwargs: Optional arguments that ``request`` takes.
"""
kwargs.setdefault('timeout', 60)
return self.request('PUT', url, data=data, **kwargs) |
5a782b26a97db6c36626fb332c310d8560a73185 | jtcressy/oop-final-project-spring-2018 | /gamepad/mouse.py | 375 | 3.5625 | 4 |
class Mouse:
BUTTON_LEFT = 1
BUTTON_RIGHT = 2
BUTTON_MIDDLE = 3
BUTTON_FORWARD = 4
BUTTON_BACK = 5
BUTTON_4 = BUTTON_FORWARD
BUTTON_5 = BUTTON_BACK
def click(self, button):
"""Click mouse button"""
def move(self, x, y):
"""move mouse to absolute"""
def move_rel(self, x, y):
"""move mouse delta x and y"""
|
22513ff4531ecdca739376893b289f061e33f544 | debargha12/MNIST_Keras | /MNIST_Keras.py | 1,752 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
import matplotlib.pyplot as plt
# import the data
from keras.datasets import mnist
# read the data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train.shape
# In[2]:
plt.imshow(X_train[0])
# In[3]:
# flatten images into one-dimensional vector
num_pixels = X_train.shape[1] * X_train.shape[2] # find size of one-dimensional vector
num_pixels
# In[4]:
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') # flatten training images
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32') # flatten test images
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
num_classes = y_test.shape[1]
print(num_classes)
# In[5]:
# define classification model
def classification_model():
# create model
model = Sequential()
model.add(Dense(num_pixels, activation='relu', input_shape=(num_pixels,)))
model.add(Dense(100, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# compile model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
# In[6]:
model = classification_model()
# fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, verbose=2)
# evaluate the model
scores = model.evaluate(X_test, y_test, verbose=0)
# In[7]:
print('Accuracy: {}% \n Error: {}'.format(scores[1], 1 - scores[1]))
# In[8]:
model.predict(X_test[:5])
# In[ ]:
|
d727cc2970a57f8343b1d222cae1a626727431ad | helong20180725/CSCE580-Projects | /machinelearning/helloTest.py | 753 | 4.125 | 4 | #note
#1. Strings
"""
print("helloworld")
capital="HI, YOU ARE CAPITAL LETTERS"
print(capital.lower())
print(capital.isupper())
print(capital[4])
print(capital.index("T"))
print(capital.replace("ARE","is"))
print("\"")
"""
#2. numbers
"""
a =10
b = 3
c = -19
d = 4.23
print(10%3)
#error print("the number is "+a)
print("the number is "+str(a))
print(pow(a,b))
print(abs(c))
print(max(a,b,c)) # min()
print(round(d))
"""
"""
from math import *
print(ceil(3.1))
print(sqrt(4))
"""
#3.input
"""
a = input("Please input something: ")
print(a+" right!")
"""
#4. build a basic calculator
"""
numberOne= int(input("The first number: "))
numberTwo= int(input("The second number: "))
result = float(numberOne) + numberTwo
print(result)
"""
#5. mad libs
|
340e343b09e5903ef146d19cbce86781899d0244 | kesterallen/surlyfritter-appspot | /scripts/wordle.py | 1,412 | 3.671875 | 4 | # TODO: can't specify two locations for a "yes" letter, e.g. "L" in swill
BAD_LETTERS = "dieshorjoinsoldforge"
LETTERS = dict(
a=dict(yes=1, no=[]),
p=dict(yes=2, no=[]),
u=dict(yes=3, no=[]),
t=dict(yes=4, no=[]),
)
def get_words():
words = []
with open("/usr/share/dict/american-english") as lines:
for line in lines:
word = line.strip()
if len(word) == 5 and "'" not in word and word.islower():
words.append(word)
return words
def letter_locations_good(word, letters):
"""
Does the word have the right letters in the right locations, and not in the
wrong places?
"""
goods = []
for letter, indices in letters.items():
# Is the letter in the word at all?
goods.append(letter in word)
# If the letter's position is known, is it in the right place?
if indices["yes"] is not None:
goods.append(word[indices["yes"]] == letter)
# If there are excluded spots for the letter, is it NOT there in this word?
if indices["no"]:
for index in indices["no"]:
goods.append(word[index] != letter)
return all(goods)
for word in get_words():
no_bad_letters = all((l not in word for l in BAD_LETTERS))
in_right_places = letter_locations_good(word, LETTERS)
if no_bad_letters and in_right_places:
print(word)
|
d8c454028e3c65b07acd2cc95bb91ab357eabee4 | officialyenum/CS50 | /pset6/readability/readability.py | 630 | 3.796875 | 4 | from cs50 import get_string
import re
import math
#declare count variables
letter = 0
word = 0
sentence = 0
text = get_string("Text: ")
#iterate through text
for i in text:
if i.isalpha():
letter+= 1
#use regex to findall words and return the length
word=len(re.findall(r'\w+', text))
#use regex to findall sentences and return the length
sentence=len(re.findall(r'([A-Z][^\.!?]*[\.!?])', text))
L = 100.0 * letter / word
S = 100.0 * sentence / word
grade = round(0.0588 * (L) - 0.296 * (S) - 15.8)
if grade<1:
print("Before Grade 1")
elif grade < 16:
print(f"Grade {grade}")
else :
print("Grade 16+"); |
6a9037fda33b82e8b7abae2f798d8a1e297be938 | drewthayer/methods-and-functions | /SignalProcessing/Preprocessing.py | 1,277 | 3.6875 | 4 | import numpy as np
''' functions for pre-processing digital signals '''
def clip_signal_start(signal, index):
return signal[index:]
def clip_signal_both_ends(signal, clip_pcnt=0.05):
clip_length = int(len(signal)*clip_pcnt)
return signal[clip_length: -1*clip_length]
def cutoff_threshold_from_signal_max(signal, n_bins=10, cutoff_pcnt=0.33):
''' defines a cutoff amplitude for a signal based on the percent of the
average max value within n number of bins '''
n = len(signal)
bins = [int(x) for x in np.linspace(1,n,n_bins+1)]
bin_maxs = []
for i in range(1,n_bins+1):
xx = signal[bins[i-1]:bins[i]]
bin_maxs.append(np.max(xx))
mean_binmax = np.mean(bin_maxs)
return mean_binmax * cutoff_pcnt
def clip_signal_start_by_threshold(signal, threshold):
''' clips the start of a signal:
removes all values until threshold is reached, starting at first value '''
i = np.argmax(signal > threshold)
return signal[i:]
def clip_signal_end_by_threshold(signal, threshold):
''' clips the start of a signal:
removes all values until threshold is reached, starting at first value '''
arr_flip = np.fliplr([signal])[0]
i = np.argmax(arr_flip > threshold)
return signal[:-i]
|
448310e4307a91ed2ba7b7755840b621b5f7bddd | chooco/2017sum_wiet_kol2 | /kol2.py | 1,220 | 3.828125 | 4 | # Class diary
#
# Create program for handling lesson scores.
# Use python to handle student (highscool) class scores, and attendance.
# Make it possible to:
# - Get students total average score (average across classes)
# - get students average score in class
# - hold students name and surname
# - Count total attendance of student
# The default interface for interaction should be python interpreter.
# Please, use your imagination and create more functionalities.
# Your project should be able to handle entire school.
# If you have enough courage and time, try storing (reading/writing)
# data in text files (YAML, JSON).
# If you have even more courage, try implementing user interface.
class Diary:
def __init__(self, name, surname, attendance):
self.name = name
self.surname = surname
self.attendacne = attendance
self.student = []
self.student.append.(name + " " + surname)
self.student.append(attendance)
def name(self):
return self.student[0]
def attendance(self):
return self.student[1]
def scores(self):
return self.student[2]
def average(self):
average = 0
for i in self.student[2]:
avgerage += i
avgerage = avgverage/len(self.student[2])
return avgerage
|
7ed946e0cd092c710d2c32fdb0c0a7aafd57f452 | Roboyantriki-SNU/Python_Workshop | /OOP/Inheritance2.py | 556 | 4.03125 | 4 | class Computers:
def processor(self,name):
self.processor_name = name
def memory(self,capacity):
self.memory_capacity = capacity
def showSpecs(self):
print(self.processor_name+" "+self.memory_capacity+" "+self.screen_size) #Even though the base class doesn't have screen size, the derived class has it
class Mobiles(Computers):
def screenSize(self,size):
self.screen_size = size
my_mobile = Mobiles()
my_mobile.processor("SD 835")
my_mobile.screenSize("5.6")
my_mobile.memory("4 GB")
my_mobile.showSpecs()
|
41aad46fa18d56b77474294cbd7bfc1e0713c0ac | sztxr/JetBrains_Projects | /Coffee Machine/Problems/The mean/task.py | 121 | 3.765625 | 4 | numbers = []
x = input()
while x != '.':
numbers.append(int(x))
x = input()
print(sum(numbers) / len(numbers))
|
b1cb1dc20c3f46e9147e84aff2f6e1c37307e567 | Abdulrauf-alhariri/Intermidate_level | /calculator.py | 3,352 | 3.75 | 4 | from tkinter import *
from operator import add, mul, sub, truediv
import string
import math
root = Tk()
root.title("My Calculate")
equation = StringVar()
expression = " "
e = Entry(root, textvariable=equation, width=60, borderwidth=7)
e.grid(row=0, column=0, columnspan=4, pady=15, padx=5)
def button_click(number):
global expression
expression = expression + str(number)
equation.set(expression)
def equal_press():
try:
global expression
result = str(eval(expression))
total = math.floor(float(result))
result = str(total)
equation.set(result)
expression = ""
except:
equation.set("erorr")
expression = ""
def clear():
global expression
expression = ""
equation.set("")
def window():
myButton_7 = Button(root, text="7", pady=20, padx=40,
command=lambda: button_click(7))
myButton_4 = Button(root, text="4", pady=20, padx=40,
command=lambda: button_click(4))
myButton_1 = Button(root, text="1", pady=20, padx=40,
command=lambda: button_click(1))
myButton_8 = Button(root, text="8", pady=20, padx=40,
command=lambda: button_click(8))
myButton_5 = Button(root, text="5", pady=20, padx=40,
command=lambda: button_click(5))
myButton_2 = Button(root, text="2", pady=20, padx=40,
command=lambda: button_click(2))
myButton_9 = Button(root, text="9", pady=20, padx=40,
command=lambda: button_click(9))
myButton_6 = Button(root, text="6", pady=20, padx=40,
command=lambda: button_click(6))
myButton_3 = Button(root, text="3", pady=20, padx=40,
command=lambda: button_click(3))
myButton_0 = Button(
root, text="0", command=lambda: button_click(0), pady=20, padx=40)
myButton_add = Button(
root, text="+", command=lambda: button_click("+"), pady=20, padx=40, bg="orange")
myButton_sub = Button(
root, text="-", command=lambda: button_click("-"), pady=20, padx=40, bg="orange")
myButton_mul = Button(
root, text="X", command=lambda: button_click("*"), pady=20, padx=40, bg="orange")
myButton_truediv = Button(
root, text="/", command=lambda: button_click("/"), pady=20, padx=40, bg="orange")
myButton_equal = Button(
root, text="=", command=equal_press, pady=20, padx=40)
myButton_clear = Button(
root, text="Clear", command=clear, pady=20, padx=30)
myButton_0.grid(row=4, column=0)
myButton_clear.grid(row=4, column=1)
myButton_equal.grid(row=4, column=2)
myButton_truediv.grid(row=4, column=3)
myButton_1.grid(row=3, column=0)
myButton_2.grid(row=3, column=1)
myButton_3.grid(row=3, column=2)
myButton_add.grid(row=3, column=3)
myButton_4.grid(row=2, column=0)
myButton_5.grid(row=2, column=1)
myButton_6.grid(row=2, column=2)
myButton_sub.grid(row=2, column=3)
myButton_7.grid(row=1, column=0)
myButton_8.grid(row=1, column=1)
myButton_9.grid(row=1, column=2)
myButton_mul.grid(row=1, column=3)
mainloop()
window()
|
c535dfc204b22ca27597680773e056713fb6ab1f | Iliya-Yeriskin/Learning-Path | /Python/Class_work/L10_Functions/L10.4 No input Yes output.py | 260 | 4.03125 | 4 | def calculating():
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
sum = num1 * num2
print("Your new number is: " + str(sum))
return sum
a = calculating() + 5
print("Post function number: " + str(a))
|
94d359f111fed2d732ecc9890a2deb5956e751d3 | Iliya-Yeriskin/Learning-Path | /Python/Class_work/L9_While/L9.1.py | 155 | 4.15625 | 4 | #While loops
#while = if+for together
num=int(input("Enter a number: "))
while(num!=7) :
print(num*400)
num = int(input("Enter a number: ")) |
c06217c63dd9a7d955ae6f2545773486d84158b0 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/4.py | 266 | 4.40625 | 4 | '''
4. Write a Python program to accept a filename from the user and print the extension of that.
Sample filename : abc.java
Output : java
'''
file=input("Please enter a file full name: ")
type=file.split(".")
print("Your file type is: " + repr(type[-1]))
|
a65b5ff8cc9f556dcfad4bce1864f3e807579fa5 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/13.py | 173 | 4.0625 | 4 | '''
13. Write a Python program to sum all the items in a list.
'''
my_list=[1,2,3,4,5,6,7]
sum=0
for i in range((len)(my_list)):
sum=sum+my_list[i]
print(sum) |
0d19a4381c7c94180999bc78613aecdf65cf04a0 | Iliya-Yeriskin/Learning-Path | /Python/Projects/Rolling Cubes.py | 2,517 | 4.1875 | 4 | '''
Cube project:
receive an input of player money
every game costs 3₪
every round we will roll 2 cubes,
1.if cubes are the same player wins 100₪
2.if the cubes are the same and both are "6" player wins 1000₪
3.if the cubes different but cube 2 = 2 player wins 40₪
4.if the cubes different but cube 1 = 1 player wins 20₪
in the end we'll print how much money the player won.
'''
from random import randint
from time import sleep
print("Welcome to the Rolling Cube Game\n--------------------------------\nEach round costs 3₪\n")
money = input("How much money do you have?: \n")
start_money = money
turns = int(money)//3
change = int(money) % 3
print("Your Change is: "+str(change)+"₪")
print("Prepare to play: "+str(turns)+" Rounds\n-----------------------")
money = int(turns)*3
cube1 = 0
cube2 = 0
for i in range(turns):
start_money = int(int(start_money)-3)
money = int(int(money)-3)
print("Round: "+str(i+1)+" Rolling...")
sleep(2)
cube1 = randint(1, 6)
cube2 = randint(1, 6)
if cube1 == cube2 & cube1 == 6:
print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 1000₪!!\n-----------------------")
money = money+1000
elif cube1 == cube2:
if cube1 == 1:
print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 120₪\n-----------------------")
money = money+120
elif cube2 == 2:
print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 140₪\n-----------------------")
money = money+140
else:
print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 100₪\n-----------------------")
money = money+100
elif cube1 == 1:
if cube2 == 2:
print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 60₪\n-----------------------")
money = money+60
else:
print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 20₪\n-----------------------")
money = money+20
elif cube2 == 2:
print("You Rolled (" + str(cube1) + "," + str(cube2) + ") And Won 40₪\n-----------------------")
money = money+40
else:
print("You Rolled ("+str(cube1)+","+str(cube2)+") Sorry you didn't win\n-----------------------")
print("Calculating your Prize....\n")
sleep(3)
print("Your Total winning are: ["+str(money)+"₪]\nNow you have: ["+str(int(start_money)+int(money))+"₪]" +
"\nHope to see you again :-)")
|
aa255b7fcbedd6c9498f6415597c46d7b7196d8f | Iliya-Yeriskin/Learning-Path | /Python/Exercise/End Exercise/5.py | 305 | 4 | 4 | '''
Write a Python program to calculate the sum of three given numbers, if
the values are equal then return three times of their sum.
'''
def summery(a, b, c):
sum = a + b + c
if a == b == c:
sum = sum * 3
return sum
print(summery(1, 2, 3))
print(summery(2, 2, 2))
|
d54a45eb4727576c684d76e643f236d4a2b04c13 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/End Exercise/6.py | 385 | 4.09375 | 4 | '''
Write a Python program to sum of two given integers. However, if the sum
is between 15 to 20 it will return 20.
'''
def summery(x,y):
sum = x + y
if sum in range(15, 20):
sum = 20
return sum
print(summery(3,7))
print(summery(11,7))
print(summery(12,14))
print(summery(11,4))
print(summery(8,1))
print(summery(10,10))
print(summery(10,4)) |
5736199cbc797c8ae7d2cc6d8fc09da59023d5e2 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/10.py | 306 | 4.3125 | 4 | '''
10. Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string.
Sample string : 'Net4U'
Expected output: {'N': 1, 'e': 1, 't': 2, '4': 1, 'U': 1}
'''
word=input("Please enter a word: ")
dict={i:word.count(i) for i in word}
print(dict)
|
22b12e7b0d842a0430852b5213f9b78826971f62 | MHieu128/exercise_python | /Exercise_1.py | 99 | 3.703125 | 4 | a = int(input("input number a: "))
b = int(input("input number b: "))
print(f'{a} ^ {b} = {a**b}')
|
cae8ae844248ac65925e97ee6672de2fa1659607 | isaiah279/kivy_basics | /inputs.py | 319 | 3.921875 | 4 | from tkinter import *
root = Tk()
e = Entry(root, width=50, bg="maroon", fg="white")
e.insert(0,"Enter your name")
e.pack()
# borderwidth=50
def clickme():
name=e.get()
mylabel = Label(root, text=name)
mylabel.pack()
button = Button(text="click me", command=clickme)
button.pack()
root.mainloop()
|
e09832ba59dde120d54dde56fc68560c552bad76 | cleversokol/python_sber | /module1/1_6_9.py | 659 | 3.53125 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
# Реализуйте класс LoggableList, отнаследовав его от классов list и Loggable таким образом,
# чтобы при добавлении элемента в список посредством метода append в лог отправлялось сообщение,
# состоящее из только что добавленного элемента.
class LoggableList(list, Loggable):
def append(self, elem):
super(LoggableList, self).append(elem)
self.log(elem)
|
deef94120340b3395b95196edc70d6f0562313c1 | cleversokol/python_sber | /module2/2_4_5.py | 841 | 3.5 | 4 | import os
import os.path
import shutil
# Print current directory
print(os.getcwd())
# List all files in current directory
print(os.listdir())
# Check if dir/file exists in FS
# Return True/False respectively
print(os.path.exists("some/destination/here"))
# Check if path if a file/directory
print(os.path.isfile("some/destination/here"))
print(os.path.isdir("some/destination/here"))
# Change directory
os.chdir("new/destination/path")
# Walk through all sub-directories recursively
# os.walk returns current dir path, list of directories inside, list of files inside
for current_dirs, dirs, files in os.walk("."):
print(current_dirs, dirs, files)
# Copy file
shutil.copy("source/destination", "target/destination")
# Copy entire directory
shutil.copytree("source/destination", "target/destination")
|
3ae72fce672cdc964b8af5ff038ce969583abfc6 | cleversokol/python_sber | /module3/3_2_12.py | 386 | 3.609375 | 4 | import re
import sys
pattern = re.compile(r'human')
for line in sys.stdin:
line = line.rstrip()
line = re.sub(pattern, "computer", line)
print(line)
#string = "I need to understand the human mind"
#string = "humanity"
#
#if re.search(pattern, string) != None:
# string = re.sub(pattern, "computer", string)
# print(string)
#else:
# print("no")
|
fea00a738c0ad95e10063a78ee6e8ce835849ad3 | cleversokol/python_sber | /module1/1_4_9.py | 1,662 | 3.875 | 4 | # namespaces is dict of pairs namespace:parent
namespaces = {}
# variables is dict of pairs namespace:[list of variables]
variables = {"global":[]}
def create(namespace, parent):
namespaces.update({namespace:parent})
variables.update({namespace:[]})
def add (namespace, var):
variables[namespace].append(var)
def get(namespace, var):
list = variables.get(namespace)
if var in list:
return namespace
elif namespace == "global":
return "None"
else:
namespace = namespaces.get(namespace)
return get(namespace, var)
# First input value is number of pending commands
n = int(input())
for i in range(n):
# var can be either parent namespace or variable name
command, namespace, var = input().split()
if command == "create":
# create <namespace> <parent> – создать новое пространство имен
# с именем <namespace> внутри пространства <parent>
create(namespace, var)
elif command == "add":
# add <namespace> <var> – добавить в пространство <namespace> переменную <var>
add(namespace, var)
elif command == "get":
# get <namespace> <var> – получить имя пространства,
# из которого будет взята переменная <var> при запросе из пространства <namespace>,
# или None, если такого пространства не существует
print(get(namespace, var))
else:
print("Unknown command")
|
7261b319e11b125b64d3e2bcff780e1337a0921f | cleversokol/python_sber | /module2/2_3_5.py | 361 | 3.796875 | 4 | import itertools
def primes():
number = 1
while True:
divisors = 0
number += 1
for i in range(1, number+1):
if number % i == 0:
divisors += 1
if divisors < 3 :
yield number
print(list(itertools.takewhile(lambda x : x <= 31, primes())))
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
|
a01b945ef2c4ec1391b0bdf315a0413f84cbcf41 | Alemani29/CBT | /CBT.py | 11,771 | 3.65625 | 4 | #Import files
import intro
import time
import random
import pygame
from pygame.locals import *
#Pinya Colada Song
pygame.mixer.init()
#Variables
pinya = 0
pinyapelada = 0
poma = 0
money = 0
ganivet = 0
ganivetma = 0
zona = 1
CBT = False
Barra = False
#Zones
# ?.CBT
# 0.End
# 1.Bosc
# 2.Ciutat
# 3.Botiga
# 4.Cel·la
# 5.Presó
# 6.Taverna
intro.intro()
while True:
#Basics
inp = input(">>")
if inp == "motxilla":
print ("tens", poma, "poma/es")
print ("tens", pinya, "pinya/es")
print ("tens", pinyapelada, "pinya/es pelada/es")
print ("tens", money, "$")
if inp == "bosc":
zona = 1
print("Ets al bosc. Aquí pots collir fruita")
if inp == "ciutat":
zona = 2
print("Ets a la ciutat. Escriu >>mapa per veure els llocs que pots visitar")
if inp == "menjar poma":
if poma<=0:
print("No pots tenir pomes negatives!")
else:
poma-=1
print ("tens", poma, "poma/es")
if inp == "menjar pinya":
if pinya<=0:
print("No pots tenir pinyes negatives!")
else:
print("Tros de ruc! No has pelat la pinya!")
if inp == "pelar pinya":
if pinya<=0:
print("Com pots pelar una cosa que no tens?!")
else:
if ganivetma>=1:
pinyapelada = pinyapelada+1
pinya = pinya-1
print("Has pelat la pinya")
print ("tens", pinyapelada, "pinya/es pelada/es")
else:
print("Mare meva! Però en què estàs pensant!")
time.sleep(1)
print("No has agafat ganivet!")
if inp == "agafar ganivet":
if ganivet>=1:
ganivetma = ganivetma+1
print("Ara si!")
time.sleep(1)
print("Ja pots pelar la pinya")
else:
print("No tens ganivet")
time.sleep(1)
print("pots comprar un anant a la botiga")
print("proba amb >>botiga per veure el preu")
if inp == "menjar pinya pelada":
if pinyapelada<=0:
print("Que intentes fer?")
else:
zona = 0
if inp == "restart":
pinya = 0
pinyapelada = 0
poma = 0
money = 0
ganivet = 0
ganivetma = 0
zona = 1
intro.intro()
#The End
if zona == 0:
print("La pinya estava en mal estat")
time.sleep(2)
print("Has mort")
time.sleep (2)
print("-Game Over-")
print("Escriu restart per tornar a començar")
#Bosc
if zona == 1:
if inp == "agafar poma":
poma = poma+1
print("tens", poma, "poma/es")
if inp == "agafar pinya":
pinya = pinya+1
print("tens", pinya, "pinya/es")
if inp == "agafar pinya pelada":
print ("Que em prens per imbècil?!")
if inp == "botiga":
print("Estàs en un bosc, per comprar, vés a la ciutat")
print("fes servir >>ciutat")
#Ciutat
if zona == 2:
if inp == "agafar poma":
print("D'on agafes les pomes? Ets a la ciutat!")
print("Has d'anar al bosc amb >>bosc")
if inp == "agafar pinya":
print("D'on agafes les pinyes? Ets a la ciutat!")
print("Has d'anar al bosc amb >>bosc")
if inp == "mapa":
print("pots anar a:")
print(">>botiga")
print(">>taverna")
print(">>port")
print(">>palau")
if inp == "botiga":
zona = 3
print("Benvingut a la botiga")
print("pots comprar amb >>comprar+objecte")
print("poma - 1$")
print("ganivet - 50$")
print("pinya - ?$")
if inp == "taverna":
print("Benvingut a la taverna de l'OGRE CRIDANER")
time.sleep(1)
print("Aqui pots trobar tot tipus de viatgers:")
print("mercaders, trobadors, soldats i exploradors, entre altres")
time.sleep(2)
print("Si vas a la barra (>>barra) pots demanar tant menjar com begudes")
print("Ara ets a la teva taula")
zona = 6
if inp == "port":
print("Aquesta zona està en obres torna en un futur per poder-la visitar")
if inp == "palau":
print("Aquesta zona està en obres torna en un futur per poder-la visitar")
#Botiga
if zona == 3:
if inp == "comprar poma":
print("Costa 1$")
if money<=0:
print("Com vols pagar?!")
print("No tens suficients $!")
print("proba a vendre amb >>vendre+objecte")
else:
poma = poma+1
money = money-1
print("Aquí tens")
print("tens", poma, "poma/es")
print("tens", money, "$")
if inp == "comprar pinya":
if money<=0:
print("Com vols pagar?!")
print("No tens suficients $!")
print("proba a vendre amb >>vendre+objecte")
else:
print("Però es pot saber que fas?!")
print("Es que no saps el problema que hi ha amb les pinyes?!!!")
if inp == "comprar ganivet":
print("Costa 50$")
if money<=49:
print("Com vols pagar?!")
print("No tens suficients $!")
print("proba a vendre")
else:
ganivet = ganivet+1
money = money-50
print("Aquí tens")
print("tens", ganivet, "ganivet/s")
print("tens", money, "$")
if inp == "vendre poma":
if poma<=0:
print("No pots tenir pomes negatives!")
print("Pots agafar pomes al bosc")
else:
poma = poma-1
money = money+1
print("Has venut una poma, guanyes 1$")
print ("tens", poma, "poma/es")
print("tens", money, "$")
if inp == "vendre pinya":
if pinya<=0:
print("No pots tenir pinyes negatives!")
print("Pots agafar pinyes al bosc")
else:
if random.randint(0,100) <1:
pinya =pinya-1
money = money+100
print("Has venut una pinya, tot i que és il·legal, compte no t'atrapin. Guanyes 100$")
print ("tens", pinya, "pinya/es")
print("tens", money, "$")
else:
print("La venda de pinyes és il·legal")
time.sleep(2)
zona = 4
ganivet = 0
poma = 0
pinya = 0
money = 0
pinyapelada = 0
print("Has estat arrestat, ara ets a la presó")
print("Tots els teus objectes han estat requisats")
time.sleep(1)
print("Tot i així la porta de la cel·la sembla bastant antiga")
#Cel·la
if zona == 4:
ganivet = 0
poma = 0
pinya = 0
money = 0
pinyapelada = 0
if inp == "obrir porta":
print("La porta és antiga, però encara aguanta")
print("Potser si fas molta força pots trencar la porta")
if inp == "trencar porta":
print("La porta ha cedit! Has aconseguit escapar!")
time.sleep(2)
print("Ets a una gran sala on hi ha alguns cofres")
print("També hi ha una gran porta")
zona = 5
#Presó
if zona == 5:
if inp == "obrir cofre":
if random.randint(0,3) <1:
if random.randint(0,5) <1:
if random.randint(0,10) <1:
print("Un ganivet!")
else:
print("Has trobat 10 pomes i 10$")
poma = poma+10
money = money+10
else:
print("Has trobat 5 pomes")
poma = poma+5
else:
print("No hi ha res")
if inp == "obrir porta":
print("Ets a la ciutat")
zona = 2
#Taverna
if zona == 6:
if inp == "barra":
print("Ets a la barra. Pots prendre:")
time.sleep(1)
print(">>Aigua")
print(">>Cervesa")
print(">>Pinya Colada")
time.sleep(2)
print("Que vols demanar?")
Barra = True
if Barra == True:
if inp == "aigua":
print("Costa 5$")
if money<=4:
print("Com vols pagar?!")
print("No tens suficients $!")
print("proba a vendre a la botiga")
else:
money = money-5
print("Aquí tens")
time.sleep(1)
print("glup")
time.sleep(1)
print("glup")
time.sleep(2)
print("Es nota que tenies sed")
time.sleep(1)
print("Has tornat a la teva taula")
Barra = False
if inp == "pinya colada":
pygame.mixer.music.load("songs\pinyacolada.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
time.clock()
print("Has pres una Pinya Colada! No cal que paguis, convida la casa")
time.sleep(2)
print("Has tornat a la teva taula")
Barra = False
#CBT
if CBT == False:
if random.randint(0,1000000) <1:
time.sleep(2)
print("Ha aparegut un CBT! Una Cabra Boja Tridimensional!!!")
time.sleep(1)
print("Això és un event únic!")
time.sleep(1)
print("Ràpid atrapa-la abans que escapi! Fes servir >>atrapar CBT")
CBT = True
#Atrapa CBT
if CBT == True:
if inp == "atrapar CBT":
print("Però a que jugues?!")
time.sleep(1)
print("És un CBT serà molt més difícil que escriure atrapar CBT!")
time.sleep(1)
print("Proba a agafar una pakeball!")
time.sleep(1)
print("Sí! El CBT és un Pakemun interdimensional")
if inp == "agafar pakeball":
print("Evidentment tens una pakeball! Has atarpat el CBT")
time.sleep(4)
print("Era sarcasme")
time.sleep(1)
print("El CBT ha creat un vòrtex interdimensional")
time.sleep(2)
print("El CBT t'ha teletransportat al bosc. Tens sort de no haver mort")
CBT = False
zona = 1
|
621a2421b18dad2c135788e201de171493a79fe0 | Typical-dev/C-97-Python-project | /NumberGuessingGame.py | 986 | 4.03125 | 4 | Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
============================================================================================================== RESTART: Shell ==============================================================================================================
>>> import random
TitleString='Number guessing game:5'
print(TitleString)
chances=0
while chances<5:
InputNumber=int(input('Enter your number(from 1 to 9)'))
print(InputNumber)
number=random.randint(1,9)
if(InputNumber==number):
print('YOU ARE CORRECT AND HAVE WON THE GAME')
break
elif(InputNumber<number):
print(' YOU HAVE ENTERED A LOWER NUMBER')
else:
print('YOU HAVE ENTERED A HIGHER NUMBER')
chances+=1
if(chances==5):
print('SORRY YOUR ATTEMPTS ARE OVER YOU LOSE')
|
8146be5d85020e6b965d2c4caf1991678677e410 | Balgeum-Cha/vscode | /class.py | 796 | 4.3125 | 4 | #%%
a = [1,2,3,4,]
a.append(5)
print(a)
# %%
def test():
pass
class Person:
pass
bob = Person()
cathy = Person()
a = list()
b = list()
# %%
# 생성자
class Person:
def __init__(self):
print(self,'is generated')
self.name = 'Kate'
self.age = 10
p1 = Person()
p2 = Person()
p1.name = 'arron'
p1.age = 20
print(p1.name, p1.age)
# %%
# %%
class Person:
def __init__(self,n,a):
print(self,'is generated')
self.name = n
self.age = a
p1 = Person('Bob',30)
p2 = Person('Kate',20)
print(p1.name,p1.age)
print(p2.name, p2.age)
# %%
# %%
class Person:
def __init__(self,name,age = 10):
self.name = name
self.age = age
p2 = Person('Bob', 20)
p3 = Person('Aaron')
print(p2.name, p2.age)
print(p3.name, p3.age)
# %%
|
e7f74aeb6375b5d5b847552a649091aee4ed8115 | ICTSoEasy/Write-Your-Own-Adventure-Games | /Files/Week 2/main2.py | 515 | 4 | 4 | #import the classes we have written
from GAME import Game
from ROOM import Room
#Create (instantiate) an instance of Game, called game
game = Game()
#Create a room (we used room 1 for an example, and it currently does not
# contain anything)
room = Room(1,'Starboard Bows',None,None)
#Add the room to the game
print('Adding room 1')
game.addRoom(room)
game.listRooms()
#We can actually combine this into a single line:
print()
print('Adding room 2')
game.addRoom(Room(2,'Port Bows',None,None))
game.listRooms()
|
eb5a3d9e105deeb1f742198a6c5ec21ce44ee6c7 | theawesomestuff/codingchallenge | /glasses.py | 1,880 | 3.625 | 4 | class TriangularGlassStack:
"""
A triangular stack of glasses, where you can pour liquid on the glasses
"""
def __init__(self):
self.glass_capacity = 250 # glass capacity in ml
self.rows = [] # Contains glass capacity of each glasses in each row
def add_liquid(self, amount):
"""
Pour liquid into top most glass
:param amount: amount of liquid in ml
:return:
"""
remaining_liquid = amount
curr_row_index = 0
if amount < 0:
raise ValueError(f"Amount added cannot be negative :{amount}")
while remaining_liquid > 0:
curr_row_glasses_count = curr_row_index + 1
curr_row_capacity = curr_row_glasses_count * self.glass_capacity
if remaining_liquid <= curr_row_capacity:
# Handle case where there is NO overflow
curr_row = [remaining_liquid/curr_row_glasses_count
for i in range(curr_row_glasses_count)]
self.rows.append(curr_row)
remaining_liquid = 0
else:
# Handle case where there is an overflow
curr_row = [curr_row_capacity / curr_row_glasses_count
for i in range(curr_row_glasses_count)]
self.rows.append(curr_row)
remaining_liquid -= curr_row_capacity
curr_row_index += 1
def get_liquid(self, i, j):
"""
Get how much liquid is in the j'th glass of the i'th row
Assume that if the given i and/or j indexes are invalid,
then return None
:param i: row index
:param j: glasses index in the particular row
:return: amount of liquid in ml
"""
try:
return self.rows[i][j]
except IndexError:
return None
|
a55b30511787064e1c9b85619116d9fa3b08c681 | songkunhuang/Python_Learn | /dowhile.py | 557 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 7 15:43:36 2017
@author: Song
"""
"""
prompt = "Tell me something, and I will repeat it back to you:"
prompt += "\nThank you! "
message = input(prompt)
print(message)
"""
"""
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
"""
prompt = "Please input something, and I will repeat it back to you:\n"
prompt += "Enter 'quit' to end the program.\n"
message = ""
while message != 'quit':
message = input(prompt)
print(message)
|
dbcbe5ef4c2d402da10aef85537a82acc36cd167 | season101/Math4009-Project_1 | /Question4_Handled.py | 545 | 3.78125 | 4 | from ciphertext import cipher;
import string;
#To count chars and its count
inputChars = []
for each in cipher:
inputChars.append(chr(each+65))
#print(len(inputChars))
'''
for j in range(65,91):
print(str(chr(j))+" : "+str(inputChars.count(chr(j))))
'''
inputChars = str(inputChars)
#print(inputChars)
#only on first loop -> output = inputChars.translate(str.maketrans('', '', string.punctuation)).replace(" ","")
output = "THZXHDBHTTHZXTGETNVTGXRKXVTNHBWGXTGXDNTNVBHZQXDNBTGXONBYTHVKFFXDTGXVQNBIVEBYEDDHWVHFHKTDEIXHKVFHDTKBXHDTHTEAXEDOVEIENBVTEVXEHFTDHKZQXVEBYZCHLLHVNBIXBYTGXOTHYNXTHVQXXLBHOHDXEBYZCEVQXXLTHVECWXXBYTGXGXEDTEPGXEBYTGXTGHKVEBYBETKDEQVGHPAVTGETFQXVGNVGXNDTHNTNVEPHBVKOOETNHBYXSHKTQCTHZXWNVGXYTHYNXTHVQXXLTHVQXXLLXDPGEBPXTHYDXEOECTGXDXNVTGXDKZFHDNBTGETVQXXLHFYXETGWGETYDXEOVOECPHOXWGXBWXGESXVGKFFQXYHFFTGNVOHDTEQPHNQOKVTINSXKVLEKVXTGXDXNVTGXDXVLXPTTGETOEAXVPEQEONTCHFVHQHBIQNFXFHDWGHWHKQYZXEDTGXWGNLVEBYVPHDBVHFTNOXTGXHLLDXVVHDVWDHBITGXLDHKBYOEBVPHBTKOXQCTGXLEBIVHFYXVLNVXYQHSXTGXQEWVYXQECTGXNBVHQXBPXHFHFFNPXEBYTGXVLKDBVTGETLETNXBTOXDNTHFTGXKBWHDTGCTEAXVWGXBGXGNOVXQFONIGTGNVRKNXTKVOEAXWNTGEZEDXZHYANBWGHWHKQYFEDYXQVZXEDTHIDKBTEBYVWXETKBYXDEWXEDCQNFXZKTTGETTGXYDXEYHFVHOXTGNBIEFTXDYXETGTGXKBYNVPHSXDXYPHKBTDCFDHOTGHVXZHKDBBHTDESXQXDDXTKDBVLKJJQXVTGXWNQQEBYOEAXVKVDETGXDZXEDTGHVXNQQVWXGESXTGEBFQCTHHTGXDVTGETWXABHWBHTHFTGKVPHBVPNXBPXYHXVOEAXPHWEDYVEBYTGKVTGXBETNSXGKXHFDXVHQKTNHBNVHSXDWNTGTGXLEQXPEVTHFTGHKIGTEBYXBTXDLDNVXVHFIDXETLNTPGEBYOHOXBTWNTGTGNVDXIEDYTGXNDPKDDXBTVTKDBEWDCEBYQHVXTGXBEOXHFEPTNHBVHFTCHKBHWTGXFENDHLGXQNEBCOLGNBTGCHDNVHBVZXEQQOCVNBVDXOXOZXDXY"
temp = output.replace("E","/")
temp = temp.replace("Z","E")
temp = temp.replace("/","Z")
print(temp) |
9d6ab0f6e472bbfac8acb5c367c144a266a22ecb | tanaychaulinsec/AlgorithmsAndDataStructure | /Python/DataStructure/TreeDS/levelOrderTreeTravarsal.py | 686 | 4.0625 | 4 | #Title:-Level Order Traversal
#Author : Tanay Chauli
import queue
class newNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
self.next=None
def LevelOrder(root):
q=[root]
res=[]
while q:
n=q.pop(0)
res.append(n.val)
if n.left:
q.append(n.left)
if n.right:
q.append(n.right)
return res
if __name__ == '__main__':
root = newNode(5)
root.left = newNode(9)
root.right = newNode(3)
root.left.left = newNode(6)
root.right.right = newNode(4)
root.left.left.left = newNode(8)
root.left.left.right = newNode(7)
print(LevelOrder(root))
|
fab1c90fdd937fae97c1259d241395c2ec8d0d80 | zykt/pyglet_game_of_life | /main.py | 2,699 | 3.71875 | 4 | import pyglet
from board import Board
class Cell:
DEAD = 0
ALIVE = 1
def neighbors(board: Board, x: int, y: int) -> int:
"""Count neighbors of x, y on board"""
n = 0
def border_check(x_, y_):
"""Helper for determining whether given x_ and y_ are valid"""
return 0 <= x_ < board.width and 0 <= y_ < board.height
# for each offset in [-1; 1]
for i in range(-1, 2):
for j in range(-1, 2):
if i != 0 or j != 0:
if border_check(x + i, y + j):
n += 1 if board[x+i][y+j] == Cell.ALIVE else 0
return n
def turn(board: Board) -> Board:
"""Calculate next turn in game of Life"""
new_board = Board(board.width, board.height)
for w in range(board.width):
for h in range(board.height):
neighbor_count = neighbors(board, w, h)
if neighbor_count == 3:
new_board[w][h] = Cell.ALIVE
elif neighbor_count == 2 and board[w][h] == Cell.ALIVE:
new_board[w][h] = Cell.ALIVE
else:
new_board[w][h] = Cell.DEAD
return new_board
def board_batch(board: Board, x, y, x_size, y_size) -> pyglet.graphics.Batch:
"""Create batch of vertices from board for later rendering"""
batch = pyglet.graphics.Batch()
width_coef = x_size // board.width
height_coef = y_size // board.height
for w in range(board.width):
for h in range(board.height):
colours = (255, 255, 255) * 4 if board[w][h] == Cell.ALIVE else (0, 0, 0) * 4
batch.add(4, pyglet.gl.GL_QUADS, None,
('v2i', (x + w * width_coef + 1, y + h * height_coef + 1,
x + w * width_coef + 1, y + (h+1) * height_coef - 1,
x + (w+1) * width_coef - 1, y + (h+1) * height_coef - 1,
x + (w+1) * width_coef - 1, y + h * height_coef + 1)),
('c3B', colours))
return batch
window = pyglet.window.Window()
board = Board(8, 8, Cell.DEAD)
board[4][2] = Cell.ALIVE
board[4][3] = Cell.ALIVE
board[4][4] = Cell.ALIVE
# board[3][3] = Cell.ALIVE
# board[3][4] = Cell.ALIVE
print(board)
print(neighbors(board, 1, 2))
def helper(dt):
"""Horrible hack to hook up Game of Life to pyglet clock"""
global board
board = turn(board)
# print("Turn!")
# print(board)
pyglet.clock.schedule_interval(helper, 1)
@window.event
def on_draw() -> None:
"""Redraws screen every time it's called"""
window.clear()
batch = board_batch(board, 10, 10, 400, 400)
batch.draw()
def main() -> None:
pyglet.app.run()
if __name__ == '__main__':
main()
|
03a72365c3d05751de58a9e973736dd925ea6bb2 | Stefan1502/Practice-Python | /exercise 13.py | 684 | 4.5 | 4 | #Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
#Take this opportunity to think about how you can use functions.
#Make sure to ask the user to enter the number of numbers in the sequence to generate.
#(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence.
#The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
def sum(a):
return a[-2] + a[-1]
def Fibonnaci(inp):
li = [1, 1]
for i in range(0, (inp - 2)):
li.append(sum(li))
return li
inpp = int(input("number pls: "))
print(Fibonnaci(inpp)) |
252901028a8feadeb4070b57ff330d2c2751757c | Stefan1502/Practice-Python | /exercise 9.py | 894 | 4.21875 | 4 | #Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
#(Hint: remember to use the user input lessons from the very first exercise)
#Extras: Keep the game going until the user types “exit” Keep track of how many guesses the user has taken, and when the game ends, print this out.
import random
num = random.randint(1, 9)
guess = 10
attempts = 0
while guess != num and guess != "exit":
guess = int(input("guess the num: "))
if guess < num:
print('too low')
attempts += 1
elif guess > num:
print('too high')
attempts += 1
elif guess == "exit":
break
elif guess == num:
print('you won')
print(f'attempts = {attempts}')
num = random.randint(1, 9)
attempts = 0
|
b831314d05f1b2a996e687d3f43f046ef46eab0d | Stefan1502/Practice-Python | /exercise 28.py | 421 | 4.375 | 4 | # Implement a function that takes as input three variables, and returns the largest of the three.
# Do this without using the Python max() function!
# The goal of this exercise is to think about some internals that Python normally takes care of for us.
# All you need is some variables and if statements!
def return_max(x,y,z):
li = sorted([x,y,z])
return li[-1]
print(return_max(1,156,55))
|
22de4e1e29760b9cde35221ced9f35d2a2f5954b | Stefan1502/Practice-Python | /exercise 11.py | 474 | 4.0625 | 4 | #Ask the user for a number and determine whether the number is prime or not.
#(For those who have forgotten, a prime number is a number that has no divisors.).
#SOLUTION BELLOW
def prim(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
print("not a prime num")
break
else:
print("prime num")
break
inp = int(input("number?: "))
print(prim(inp)) |
1fee179b3526076819536510e1626cbc9a5bd991 | rishitc/Codechef_Hacktoberfest-2021 | /Codechef-2019/FEB19B/PRDRG.py | 562 | 3.71875 | 4 | from fractions import Fraction
A = list(map(int, input().split()))
T = A[0]
list_1 = A[1:]
my_list = []
for i in range(T):
p = list_1[i]
if p == 1 or p == 2:
val = ((1/2)**(list_1[i]))
value = int(1/val)
my_list.append(1)
my_list.append(value)
else:
mean = [1/2, 1/4]
for i in range(p-2):
new_mean = (mean[i] + mean[i+1])/2
mean.append(new_mean)
z = Fraction(mean[-1])
my_list.append(z.numerator)
my_list.append(z.denominator)
print(*my_list, sep =" ")
|
b01731d3d25bf551e82deaeb445bcfbc3191ee16 | DaphneKouts/NCWIT | /TicTacToe_Skeleton.py | 5,412 | 4.125 | 4 | '''
Created on March 15, 2017
@author: KJHolmes
'''
## This function takes in the list and prints the tictactoe board
# board: the list that represents the tictactoe board
def print_TTT(board):
print('''__''' + board[0][0] + '''___l___''' + board[0][1] + '''___l___''' + board[0][2] + '''__
__''' + board[1][0] + '''___l___''' + board[1][1] + '''___l___''' + board[1][2] + '''__
__''' + board[2][0] + '''___l___''' + board[2][1] + '''___l___''' + board[2][2] + '''__''')
## Adds a mark on the board if the spot is not already filled. The board
## should not be changed if there is already a mark.
## return True if you can add a mark, False if the spot already had a mark.
# r: the row number (0 -> 2)
# c: the column number (0 -> 2)
# mark: "X" or "O"
# board: the list that represents the tictactoe board
def add_mark(r, c, mark, board):
if board[r][c] != " ":
return False, board
else:
board[r][c] = mark
return True, board
## Returns False if there is an open square, True there are no blank spots on the board
## An open square is represented by a blank: " "
# board: the list that represents the tictactoe board
def isFull(board):
full = True
for r in range(3):
for c in range(3):
if board[r][c] == " ":
full = False
return full
### YOU DO NOT NEED TO CHANGE THIS FUNCTION, but you may want to look at
# it to see some sample code.
## Returns true if there are three in a row on a row, a column or a diagonal
# This version of the function works by comparing all the items in a
# row, column or diagonal to see if they are the same (but not blank)
# board: the list that represents the tictactoe board
def game_over(board):
for row in range(3):
# if the first spot is not blank and all the values in the row are the same
# then return true
if ((board[row][0] != " ") and
(board[row][0]==board[row][1]) and
(board[row][0]==board[row][2])):
return True
for col in range(3):
# if the first spot is not blank and all the values in the column are the same
# then return true
if ((board[0][col] != " ") and
(board[0][col]==board[1][col]) and
(board[0][col]==board[2][col])):
return True
# if the first spot is not blank and all the values in the diagonal are the same
# then return true
if ((board[0][0] != " ") and
(board[0][0]==board[1][1]) and
(board[0][0]==board[2][2])):
return True
# Same, but going upper right to lower left
if ((board[0][2] != " ") and
(board[0][2]==board[1][1]) and
(board[0][2]==board[2][0])):
return True
# Nothing won so return False
return False
### YOU DO NOT NEED TO CHANGE THIS FUNCTION, but you may want to look at
# it to see some sample code.
### The main program
# board: the list that represents the tictactoe board
# mark: X or O. X always starts
def ttt():
#
# initialize all the variables
#
board = [[" ", " ", " "],[ " ", " ", " "],[ " ", " "," "]]
print_TTT(board)
mark = "X"
print("Welcome to Tic Tac Toe")
# "Q" will force it to exit
# This loop keeps going until the game is over
while mark != "Q":
# good_val will be set to True when a valid place on the board is given
good_val = False
while not good_val:
print(" ")
# subtract 1 because the index starts counting at 0 and people start counting at 1
r = int(input("row: "))-1
c = int(input("column: "))-1
print(" ")
# Check if the row & column are invalid
if not((0 <= r <=2 ) and (0 <= c <=2 )): # Remember, we subtracted 1 from r and c
print("The row and column must be 1, 2, or 3")
# Check if the place was already filled
else:
ok, board = add_mark(r, c, mark, board)
if not(ok):
print("There was already a mark there. Pick a new place.")
else:
# place is accepted - note that the add_mark function added it to
# the board if it could, so the mark has already been added.
# add_mark was called as part of the elif above.
good_val = True
## end of inner while loop
print_TTT(board)
print(" ")
# call isFull to see if the board is full (might be a tie) and
# game_over is called to figure out if someone won. If either is true,
# set mark to "Q" to force the outer loop to exit.
full = isFull(board)
win = game_over(board)
if (win):
print(mark + " Wins!")
mark = "Q"
elif (full):
print("It's a tie!")
mark = "Q"
# No one won and there are still spaces open, so switch the mark
elif (mark == "O"):
mark = "X"
else:
mark = "O"
## end of outer while loop
print("game over!")
ttt() |
e6cf6be5dd4d4809c90088f965290fcb6a4dc8b1 | DaphneKouts/NCWIT | /Branching and output corrections.py | 515 | 4.09375 | 4 | def letter_in_word(guess,word):
'''Returns true if guess is one of the letters in the word.
Otherwise, it returns false'''
if guess in word:
print(True)
else:
print(False)
def hint(color,secret):
'''Returns whether or not the color is in the secret'''
if color in secret:
print("The color " + str(color) + " IS in the sequence of colors")
else:
print("The color " + str(color) + " IS NOT in the sequence of colors")
|
1a2daaf3670f34d0b145132e69d0aad2b2b1ba75 | TroyJeffrey/Inventory-Control-System | /stack.py | 247 | 3.515625 | 4 | # Troy Jeffrey Amegashie
# Stack
# 03/05/2020
from LinkedLists import LinkedList
class Stack:
def __init__(self):
self.mystack = []
def push(self,data):
self.mystack.append(data)
def pop(self):
return self.mystack.pop()
|
d0fdd8537fc6e96de145f6c409cc166699a51ee1 | ericrommel/codenation_python_web | /Week01/Chapter04/Exercises/ex_4-10.py | 1,171 | 4.34375 | 4 | # Extend your program above. Draw five stars, but between each, pick up the pen, move forward by 350 units, turn right
# by 144, put the pen down, and draw the next star. You’ll get something like this:
#
# _images/five_stars.png
#
# What would it look like if you didn’t pick up the pen?
import turtle
def make_window(color="lightgreen", title="Exercise"):
win = turtle.Screen()
win.bgcolor(color)
win.title(title)
return win
def make_turtle(pensize=3, color="blue"):
a_turtle = turtle.Turtle()
a_turtle.color(color)
a_turtle.pensize(pensize)
return a_turtle
def draw_star(a_turtle, side=100):
for i in range(5):
a_turtle.right(144)
a_turtle.forward(side)
wn = make_window(title="Exercise 9")
star = make_turtle()
star.penup()
star.setposition(-250, 0)
star.pendown()
star.speed(0)
for j in range(5):
draw_star(star)
star.penup()
star.forward(500)
star.right(144)
star.pendown()
star2 = make_turtle(color="red")
star2.penup()
star2.setposition(-100, 0)
star2.pendown()
star2.speed(0)
for j in range(5):
draw_star(star2)
star2.forward(150)
star2.right(144)
wn.mainloop()
|
7fcd55b167623ad4139ebe7d9eab75f958c78fb2 | ericrommel/codenation_python_web | /Week01/Chapter04/Exercises/ex_4-09.py | 694 | 4.53125 | 5 | # Write a void function to draw a star, where the length of each side is 100 units. (Hint: You should turn the turtle
# by 144 degrees at each point.)
#
# _images/star.png
import turtle
def make_window(color="lightgreen", title="Exercise"):
win = turtle.Screen()
win.bgcolor(color)
win.title(title)
return win
def make_turtle(pensize=3, color="blue"):
a_turtle = turtle.Turtle()
a_turtle.color(color)
a_turtle.pensize(pensize)
return a_turtle
def draw_star(a_turtle, side=100):
for i in range(5):
a_turtle.right(144)
a_turtle.forward(side)
wn = make_window(title="Exercise 9")
star = make_turtle()
draw_star(star)
wn.mainloop()
|
f4aeba34d229b94abb230c2d9607b8f39570fede | ericrommel/codenation_python_web | /Week01/Chapter03/Exercises/ex_3-06.py | 871 | 4.3125 | 4 | # Use for loops to make a turtle draw these regular polygons (regular means all sides the same lengths, all angles the same):
# An equilateral triangle
# A square
# A hexagon (six sides)
# An octagon (eight sides)
import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Exercise 6")
triangle = turtle.Turtle()
triangle.color("hotpink")
triangle.pensize(3)
for i in range(3):
triangle.forward(80)
triangle.left(120)
square = turtle.Turtle()
square.color("hotpink")
square.pensize(4)
for i in range(4):
square.forward(80)
square.left(90)
hexagon = turtle.Turtle()
hexagon.color("hotpink")
hexagon.pensize(6)
for i in range(6):
hexagon.forward(80)
hexagon.left(60)
octagon = turtle.Turtle()
octagon.color("hotpink")
octagon.pensize(8)
for i in range(8):
octagon.forward(80)
octagon.left(45)
wn.mainloop()
|
80628bffd69f711dba4887a74db2c7b005dd0e19 | ericrommel/codenation_python_web | /Week01/Chapter03/herd_of_turtles.py | 762 | 3.90625 | 4 | import turtle
# bg_color = input("Write a background color for the window: ")
wn = turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Tess and Alex")
# turtle_color = input("Write a color for the turtle: ")
# pen_size = int(input("Write a size for the turtle: "))
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(5)
alex = turtle.Turtle()
# Make Tess draw equilateral triangle
tess.forward(80)
tess.left(120)
tess.forward(80)
tess.left(120)
tess.forward(80)
tess.left(120)
# Complete the triangle
tess.right(180) # Turn Tess around
tess.forward(80) # Move her away from the origin
# Make Alex draw a square
alex.forward(50)
alex.left(90)
alex.forward(50)
alex.left(90)
alex.forward(50)
alex.left(90)
alex.forward(50)
alex.left(90)
wn.mainloop()
|
e6066fc636848204cd6d5740a5a78fc23b6d4637 | ifryed/navigation_algo | /Exercises/ex1_histogram_filter/main.py | 442 | 3.640625 | 4 | ##
# Main function of the Python program.
#
##
from histogram import *
def main():
Map = [['G', 'G', 'G'],
['G', 'R', 'R'],
['G', 'G', 'G']]
measurements = ['R','R']
motions = [[0,0],[0,1]]
sensor_right = .8
p_move = 1.0
ans = histogram_localization(Map, measurements, motions, sensor_right, p_move)
show(ans) # displays your answer
print(ans[0])
if __name__ == '__main__':
main()
|
10440f62b0dfacf1baba831661d59c401218eb5a | emeceerre/m02_keep_0 | /p1.py | 277 | 3.515625 | 4 | def sumatodos(limitTo):
resultado = 0
for i in range(0, limitTo+1):
resultado += i
return resultado
def sumatodosLosCuadrados(limitTo):
resultado = 0
for i in range(limitTo+1):
resultado += i*i
return resultado
print(sumaTodos(100))
print(sumatodosLosCuadrados(3))
|
9d2b810bfc5d1efe9139c383f786ad7b15686067 | cpm02/python-gui-with-data-base | /book_front.py | 2,369 | 3.6875 | 4 | from tkinter import *
from PIL import ImageTk,Image
import sqlite3
root=Tk()
root.geometry("1000x1000")
canvas=Canvas(root,width=1000,height=1000)
image =ImageTk.PhotoImage(Image.open('lib.jpg'))
canvas.create_image(0,0,anchor=NW,image=image )
canvas.pack()
#_________________database_____________________
text1=StringVar()
text2=StringVar()
text3=StringVar()
text4=StringVar()
text5=StringVar()
text6=IntVar()
text7=IntVar()
def submit():
bookid=text1.get()
bookname=text2.get()
author=text3.get()
genre=text4.get()
edition=text5.get()
cost=text6.get()
quantity=text7.get()
conn = sqlite3.connect('project.db')
with conn:
cursor = conn.cursor()
cursor.execute('INSERT INTO book VALUES (?, ?, ?, ?, ?, ?, ?)',(bookid,bookname,author,genre,edition,cost,quantity,))
def show():
connt = sqlite3.connect('project.db')
with connt:
cursor = connt.cursor()
cursor.execute("SELECT * FROM book ")
rows=cursor.fetchall()
for row in rows:
box.insert(END,row,str(""))
#_____________________books_________________
Label(canvas,text='BookID',bg='white').place(x=10,y=10)
e1=Entry(canvas,textvar=text1).place(x=100,y=10)
Label(canvas,text='Name',bg='white').place(x=10,y=50)
e2=Entry(canvas,textvar=text2).place(x=100,y=50)
Label(canvas,text='Author',bg='white').place(x=10,y=90)
e3=Entry(canvas,textvar=text3).place(x=100,y=90)
Label(canvas,text='Genre',bg='white').place(x=10,y=130)
e4=Entry(canvas,textvar=text4).place(x=100,y=130)
Label(canvas,text='Edition',bg='white').place(x=10,y=170)
e5=Entry(canvas,textvar=text5).place(x=100,y=170)
Label(canvas,text='Cost',bg='white').place(x=10,y=210)
e6=Entry(canvas,textvar=text6).place(x=100,y=210)
Label(canvas,text='Quantity',bg='white').place(x=10,y=250)
e7=Entry(canvas,textvar=text7).place(x=100,y=250)
f1=Frame(canvas,bg="grey")
f1.place(x=350,y=10)
scroll=Scrollbar(f1)
scroll.pack(side=RIGHT,fill=Y)
box=Listbox(f1,height=20,width=60)
box.pack()
box.config(yscrollcommand=scroll.set)
scroll.config(command=box.yview)
#________________Button_____________________
add=Button(canvas,text='Add',command=submit).place(x=10,y=300)
show=Button(canvas,text='Show',command=show).place(x=60,y=300)
delete=Button(canvas,text='Delete').place(x=110,y=300)
home=Button(canvas,text='Home').place(x=160,y=300)
mainloop()
|
89d6b8bf63e9a6aa50b9063ee02acdd8d6153c9f | ohassa/code-eval | /p082.py | 177 | 3.53125 | 4 | import sys
for n in [line.rstrip() for line in open(sys.argv[1])]:
digitSum = 0
numDigits = len(n)
for i in n:
digitSum += int(i) ** numDigits
print(str(digitSum) == n) |
5f277302bc8e52e87c9e9701159aa14ea96f28df | ohassa/code-eval | /p139.py | 2,800 | 3.5625 | 4 | import sys
MONTH_NAME_TO_NUMBER_MAP = {
'Jan': '01',
'Feb': '02',
'Mar': '03',
'Apr': '04',
'May': '05',
'Jun': '06',
'Jul': '07',
'Aug': '08',
'Sep': '09',
'Oct': '10',
'Nov': '11',
'Dec': '12'
}
def dateDiff(date1String, date2String):
'''
Parameters
----------
date1String:str
Date in format "YYYY-MM"
date2String:str
Date in format "YYYY-MM"
Returns
-------
int
The difference date1String - date2String in months
'''
date1 = parseDateString(date1String)
date2 = parseDateString(date2String)
return (date1[0] - date2[0]) * 12 + date1[1] - date2[1] + 1
def parseDateString(dateString):
'''
Parameters
----------
dateString:str
Date in format "YYYY-MM"
Returns
-------
list
List containing two integers [year, month]
'''
return [int(x) for x in dateString.split('-')]
for line in open(sys.argv[1]):
intervals = []
for intervalString in line.rstrip().split('; '):
boundaries = [boundary.split(' ') for boundary in intervalString.split('-')]
startDateString = boundaries[0]
endDateString = boundaries[1]
intervals.append({
'startDate': startDateString[1] + '-' + MONTH_NAME_TO_NUMBER_MAP[startDateString[0]],
'endDate': endDateString[1] + '-' + MONTH_NAME_TO_NUMBER_MAP[endDateString[0]]
})
experience = 0
skippedIntervalIndices = []
i = 0
numIntervals = len(intervals)
while i < numIntervals:
interval = intervals[i]
overlapDetected = False
# if this interval has already been included in other intervals, skip it
if i not in skippedIntervalIndices:
# if this interval overlaps with any other, include the other
# interval in this one
for j in range(i + 1, numIntervals):
# don't check intervals[i] against itself or against skipped
# intervals
if j in skippedIntervalIndices:
continue
# if there's an overlap
possiblyOverlappingInterval = intervals[j]
if interval['endDate'] >= possiblyOverlappingInterval['startDate'] and possiblyOverlappingInterval['endDate'] >= interval['startDate']:
# extend interval to include possiblyOverlappingInterval
interval['startDate'] = min(interval['startDate'], possiblyOverlappingInterval['startDate'])
interval['endDate'] = max(interval['endDate'], possiblyOverlappingInterval['endDate'])
# skip the interval
skippedIntervalIndices.append(j)
# now that the interval has changed its size, we need to
# check if its new size overlaps with any intervals
overlapDetected = True
# if this interval doesn't overlap with any other
if not overlapDetected:
# add this interval's length to total experience
if i not in skippedIntervalIndices:
experience += dateDiff(interval['endDate'], interval['startDate'])
# check the next interval
i += 1
print(int(experience / 12)) |
35da7c155a1d54f1e941e58340e43121a898e006 | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe16.py | 1,294 | 4.40625 | 4 | """Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá
pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
- Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os
demais valores, sendo encerrado;
- Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;
- Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;
- Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;"""
from math import sqrt
a = float(input("Digite o valor de a: "))
b = c = 0
if a == 0:
print(" Valor invalido. Nao eh uma equacao de 2º grau. ")
exit()
else:
b = float(input("Digite o valor de b: "))
c = float(input("Digite o valor de c: "))
delta = b ** 2 - 4 * a * c
if delta < 0:
print("A equacao no possui raizes reais.")
elif delta == 0:
print("Delta igual a 0. Apenas uma raiz real -> {}".format(-b / (2 * a)))
else:
x1 = (-b - sqrt(delta)) / (2 * a)
x2 = (-b + sqrt(delta)) / (2 * a)
print("A equacao possui duas raizes reais: {} e {}".format(x1, x2))
|
4c938991598211f2149d3628ac7caf1d8d9cd2bd | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe26.py | 1,212 | 4.03125 | 4 | """Um posto está vendendo combustíveis com a seguinte tabela de descontos:
Álcool:
até 20 litros, desconto de 3% por litro
acima de 20 litros, desconto de 5% por litro
Gasolina:
até 20 litros, desconto de 4% por litro
acima de 20 litros, desconto de 6% por litro
Escreva um algoritmo que leia o número de litros vendidos,
o tipo de combustível (codificado da seguinte forma: A-álcool, G-gasolina), calcule e imprima o valor a ser pago pelo
cliente sabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90."""
preco_gas = 2.5
preco_alc = 1.9
litros = float(input("Digite o total de litros: "))
tipo = input("Digite o tipo do combustivel: [A]Alcool - [G]Gasolina: ")
if tipo.upper() == "G":
if litros > 20:
print("{} litros de Gaoslina. Valor R${:.2f}.".format(litros, litros * preco_gas * 0.94))
else:
print("{} litros de Gaoslina. Valor R${:.2f}.".format(litros, litros * preco_gas * 0.96))
if tipo.upper() == "A":
if litros > 20:
print("{} litros de Alcool. Valor R${:.2f}.".format(litros, litros * preco_alc * 0.95))
else:
print("{} litros de Alcool. Valor R${:.2f}.".format(litros, litros * preco_alc * 0.97))
|
5760b3a9d3a22ff5c9fd0065db155cf87d873abf | Elton86/ExerciciosPython | /ExerciciosListas/Exe13.py | 618 | 4.1875 | 4 | """Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Após isto, calcule
a média anual das temperaturas e mostre todas as temperaturas acima da média anual, e em que mês elas ocorreram
(mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, . . . )."""
mes = []
media = 0
for i in range(12):
mes_nome = str(input("Digite o mes: "))
temp = float(input("Digite a temperatura: "))
mes.append([mes_nome, temp])
media += temp
media /= 12
for i in range(12):
if mes[i][1] > media:
print("Mes {} - Media {}".format(mes[i][0], mes[i][1]))
|
b1a8fc48cef00b4dc443de2f2292e46576bd5e45 | Elton86/ExerciciosPython | /EstruturaDeRepeticao/Exe14.py | 370 | 3.953125 | 4 | """Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a quantidade de
números impares."""
par = impar = 0
for i in range(10):
num = int(input("Digite um numero: "))
if num % 2 == 0:
par += 1
else:
impar += 1
print("Total de pares: {}".format(par))
print("Total de impares: {}".format(impar))
|
bc7321cb0a9bb06e00df001975f0772fcfeb13be | Elton86/ExerciciosPython | /ExerciciosListas/Exe15.py | 1,511 | 4.125 | 4 | """Faça um programa que leia um número indeterminado de valores, correspondentes a notas, encerrando a entrada de
dados quando for informado um valor igual a -1 (que não deve ser armazenado). Após esta entrada de dados, faça:
Mostre a quantidade de valores que foram lidos;
Exiba todos os valores na ordem em que foram informados, um ao lado do outro;
Exiba todos os valores na ordem inversa à que foram informados, um abaixo do outro;
Calcule e mostre a soma dos valores;
Calcule e mostre a média dos valores;
Calcule e mostre a quantidade de valores acima da média calculada;
Calcule e mostre a quantidade de valores abaixo de sete;
Encerre o programa com uma mensagem;"""
valor = []
soma = media = quanti = x = quanti_7 = 0
while True:
x = int(input("Digite um valor: "))
if x != -1:
valor.append(x)
soma += x
else:
break
media = soma / len(valor)
print("Total de Elementos: {}\n"
"Valores em ordem: {}".format(len(valor), valor))
print("Soma: {}\n"
"Media: {}".format(soma, media))
print("Ordem inversa")
cont = len(valor)
while cont != 0:
print(valor[cont - 1])
cont -= 1
print("valores acima da media: ")
for i in range(len(valor)):
if valor[i] > media:
print(valor[i])
quanti += 1
print("Valores acima da media: {}".format(quanti))
print("valores menores que 7: ")
for i in range(len(valor)):
if valor[i] < 7:
print(valor[i])
quanti_7 += 1
print("Valores menores que 7: {}".format(quanti_7))
|
0cf837e2723157e30c5708ce5a867ebb8c1c3fea | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe18.py | 591 | 4.0625 | 4 | """Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida."""
data = str(input("Digite a data: "))
if len(data) != 10:
print("Data invalida!")
exit()
data_dia = int(data[0:2])
data_mes = int(data[3:5])
data_ano = int(data[6:10])
# Depois validar corretamente de acordo com mês.
if 0 < data_dia <= 31 \
and 0 < data_mes <= 12 \
and 0 < data_ano \
and len(data[6:10]) == 4 \
and data[2] == "/" and data[5] == "/":
print("Data digitada: {}".format(data))
else:
print("Nao eh uma data valida!")
|
5de87c8f9022f227208214470e78d6cb200dff8a | Elton86/ExerciciosPython | /ExerciciosComStrings/Exe04.py | 281 | 4.25 | 4 | """Nome na vertical em escada. Modifique o programa anterior de forma a mostrar o nome em formato de escada.
F
FU
FUL
FULA
FULAN
FULANO"""
nome = input("Digite o nome: ")
for i in range(1, len(nome) + 1):
for j in range(0, i):
print(nome[j], end=" ")
print(" ")
|
9f35127cd417cd6d1e90e3387b2f01887f950a5f | Elton86/ExerciciosPython | /EstruturaDeRepeticao/Exe24.py | 288 | 4.09375 | 4 | """Faça um programa que calcule o mostre a média aritmética de N notas."""
soma = cont = 0
while True:
nota = float(input("Digite a nota: [-1 para sair] "))
if nota == -1:
break
else:
soma += nota
cont += 1
print("Media = {}".format(soma / cont))
|
81dab0084e763e0a4c367fe3ab139f69faf82c26 | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe17.py | 328 | 3.96875 | 4 | """Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se
este ano é ou não bissexto."""
ano = int(input("Digite o ano: "))
if (ano % 4 == 0 or ano % 400 == 0) and ano % 100 != 0:
print("{} eh ano bissexto!".format(ano))
else:
print("{} Nao eh ano bissexto!".format(ano))
|
5f8d04547f72564b308b9645c73f192b12a4c2b1 | Elton86/ExerciciosPython | /ExerciciosFuncoes/Exe09.py | 236 | 4.3125 | 4 | """Reverso do número. Faça uma função que retorne o reverso de um número inteiro informado. Por exemplo: 127 -> 721.
"""
def inverte_num(num):
return num[::-1]
numero = input("Digite o numero: ")
print(inverte_num(numero))
|
42c303f65b898acf24cfba091cae42212ff6d355 | Elton86/ExerciciosPython | /ExerciciosListas/Exe17.py | 1,222 | 3.984375 | 4 | """Em uma competição de salto em distância cada atleta tem direito a cinco saltos. O resultado do atleta será
determinado pela média dos cinco valores restantes. Você deve fazer um programa que receba o nome e as cinco
distâncias alcançadas pelo atleta em seus saltos e depois informe o nome, os saltos e a média dos saltos.
O programa deve ser encerrado quando não for informado o nome do atleta. A saída do programa deve ser conforme o
exemplo abaixo:
Atleta: Rodrigo Curvêllo
Primeiro Salto: 6.5 m
Segundo Salto: 6.1 m
Terceiro Salto: 6.2 m
Quarto Salto: 5.4 m
Quinto Salto: 5.3 m
Resultado final:
Atleta: Rodrigo Curvêllo
Saltos: 6.5 - 6.1 - 6.2 - 5.4 - 5.3
Média dos saltos: 5.9 m"""
atletas = []
soma = 0
nome = ""
while True:
cont = soma = 0
nome = str(input("Digite o nome: "))
if nome == "":
break
else:
saltos = []
for i in range(5):
salto = float(input("Digite a nota: ")) # Esta duplicando
saltos.append(salto)
soma += salto
media = soma / 5
atletas.append([nome, saltos, media])
for i in range(len(atletas)):
print("Nome: {} - Notas: {} - Media: {}"
.format(atletas[i][0], atletas[i][1], atletas[i][2]))
|
09ba9986b624fd74ed77eeec11c5c2272e4ce74b | Elton86/ExerciciosPython | /ExerciciosListas/Exe06.py | 635 | 3.90625 | 4 | """Faça um Programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor a média de cada aluno,
imprima o número de alunos com média maior ou igual a 7.0."""
notas_medias = []
for i in range(10):
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
nota3 = float(input("Digite a terceira nota: "))
nota4 = float(input("Digite a quarta nota: "))
print("*" * 20)
media = (nota1 + nota2 + nota3 + nota4) / 4
if media >= 7:
notas_medias.append(media)
print("Total de alunos com media 7: {} - {}".format(len(notas_medias), notas_medias))
|
a162b0d81c04f48b892668b25d8a7c86307d12ef | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe13.py | 693 | 4.03125 | 4 | """Faça um Programa que leia um número e exiba o dia correspondente da semana.
(1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido."""
numero = int(input("Digite um numero de 1 a 7: "))
if numero == 1:
print("{} - Domingo.".format(numero))
elif numero == 2:
print("{} - Segunda.".format(numero))
elif numero == 3:
print("{} - Terca.".format(numero))
elif numero == 4:
print("{} - Quarta.".format(numero))
elif numero == 5:
print("{} - Quinta.".format(numero))
elif numero == 6:
print("{} - Sexta.".format(numero))
elif numero == 7:
print("{} - Sabado.".format(numero))
else:
print("{} eh um numero invalido.".format(numero))
|
1a668b82b4ff825596621fcc92cd01a82bdba461 | Elton86/ExerciciosPython | /ExerciciosListas/Exe10.py | 627 | 4.0625 | 4 | """Faça um Programa que leia dois vetores com 10 elementos cada. Gere um terceiro vetor de 20 elementos,
cujos valores deverão ser compostos pelos elementos intercalados dos dois outros vetores."""
vetor_intercalado = []
vetor1 = []
vetor2 = []
for i in range(10):
vetor1.append(input("Digite o elemento para o vetor 1: "))
for i in range(10):
vetor2.append(input("Digite o elemento para o vetor 2: "))
for i in range(10):
vetor_intercalado.append(vetor1[i])
vetor_intercalado.append(vetor2[i])
print("Vetor_1: {}\n"
"Vetor_2: {}\n"
"Vetor_Final: {}".format(vetor1, vetor2, vetor_intercalado))
|
d28b390190aaabc5337d48153e746f12a78ebe77 | reacktor/RTR105 | /dgr_20181105.py | 1,980 | 3.734375 | 4 | Python 3.6.5 (default, Apr 1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "copyright", "credits" or "license()" for more information.
>>> str1 = "Hello"
>>> str2 = 'there'
>>> bob = str1 + str2
>>> print(bob)
Hellothere
>>> str3 = '123'
>>> str3 = str3 + 1
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
str3 = str3 + 1
TypeError: must be str, not int
>>> x = int(str3) + 1
>>> print(x)
124
>>> ______________
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
______________
NameError: name '______________' is not defined
>>> name = input("Enter:")
Enter:CJ
>>> print(name)
CJ
>>> apple = input("Enter:")
Enter:100
>>> x = apple - 10
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
x = apple - 10
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> x= apple-10
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
x= apple-10
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> x = int(apple)-10
>>> print(x)
90
>>> fruit = "banana"
>>> latter = fruit[1]
>>> print(latter)
a
>>> x = 3
>>> w = fruit[x - 1]
>>> print(w)
n
>>> fruit = "banana
SyntaxError: EOL while scanning string literal
>>> fruit = 'banana'
>>> index = 0
>>> while index < len(fruit):
latter = fruit[index]
print(index,letter)
index = index + 1
Traceback (most recent call last):
File "<pyshell#29>", line 3, in <module>
print(index,letter)
NameError: name 'letter' is not defined
>>> fruit = "banana"
>>> for letter in fruit :
print(letter)
b
a
n
a
n
a
>>> index = 0
>>> while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
\
SyntaxError: invalid syntax
>>> word = "banana"
>>> count = 0
>>> for letter in word:
if letter == "a":
count = count + 1
print(count)
SyntaxError: invalid syntax
>>> print(count)
0
>>> for letter in word :
if letter == "a":
count = count + 1
>>> print(count)
3
>>>
|
7b9c08b5275f6cb606e9b3367baf9a9abf1daf4d | austinszeng/qna-study | /qna_study.py | 3,470 | 3.828125 | 4 | import os
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def press_enter():
enter_key = input('(Press enter to continue...)')
# wrong_key = True
# while wrong_key:
# enter_key = input('(Press enter to continue...)')
# if enter_key == '':
# wrong_key = False
print('Welcome to QnA Study!')
press_enter()
playing = True
options = ['y', 'n']
while playing:
##### Reading questions and answers from qna.txt #####
score = 0
questions = []
answers = []
with open('qna.txt') as f:
for line in f:
if not line.strip(): # check for blank line
break
questions.append(line.rstrip())
for line in f:
answers.append(line.rstrip())
##### Questions #####
i = 0
user_answers = []
right_or_wrong = []
while i < len(questions):
clear()
answer = input(str(i + 1) + '. ' + questions[i].lstrip('1234567890. ') + ' ')
if answer.lower() == answers[i].lstrip('1234567890. ').lower():
# print()
# input('Correct!')
score += 1
user_answers.append(answer)
right_or_wrong.append(True)
elif answer.lower() == 'q':
for j in range(i, len(questions)):
user_answers.append('None')
right_or_wrong.append(False)
break
elif answer.lower() == 's':
i += 1
user_answers.append('None')
right_or_wrong.append(False)
continue
else:
# print()
# input('Incorrect...')
user_answers.append(answer)
right_or_wrong.append(False)
i += 1
##### Score #####
clear()
if ((score / len(questions)) * 100).is_integer():
print('Percent: ' + str(int(((score / len(questions)) * 100))) + "%")
else:
print('Percent: ' + str(round(((score / len(questions)) * 100), 1)) + "%")
print('You got ' + str(score) + "/ " + str(len(questions)) + " questions correct!")
##### Review #####
valid_input = False
while valid_input != True:
review_yn = input('Would you like to review your answers (y/n)? ')
if review_yn in options:
valid_input = True
else:
print()
input('Please input either "y" or "n"...')
clear()
clear()
if review_yn == 'y':
i = 0
while i < len(questions):
if right_or_wrong[i] == True:
print('[ ] ' + str(i + 1) + '. ' + questions[i].lstrip('1234567890. ') + ' ' + user_answers[i])
else:
print('[x] ' + str(i + 1) + '. ' + questions[i].lstrip('1234567890. ') + ' ' + user_answers[i] + ' [' + answers[i].lstrip('1234567890. ') + ']' )
i += 1
print()
press_enter()
##### Retry ####
clear()
valid_input = False
while valid_input != True:
retry_yn = input('Would you like to retry (y/n)? ')
if retry_yn in options:
valid_input = True
else:
print()
input('Please input either "y" or "n"...')
clear()
clear()
if retry_yn != 'y':
print('Thanks for using QnA Study!')
input('(Press enter to quit...)')
playing = False
quit()
|
a09141fca6646cbfa9626d147119189ab7b216d7 | aspineonxyz/Hackerrank-Challenge | /Python/Regex and Parsing/Hex Color Code Working Copy.py | 2,267 | 3.734375 | 4 | """CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB).
Specifications of HEX Color Code
■ It must start with a '#' symbol.
■ It can have 3 or 6 digits.
■ Each digit is in the range of 0 to .F (1,2,3,4,5,6,7,8,9,0,A,B,C,D,E and F).
■ A-F letters can be lower case. (a,b,c,d,e and f are also valid digits).
Examples
Valid Hex Color Codes
#FFF
#025
#F0A1FB
Invalid Hex Color Codes
#fffabg
#abcf
#12365erff
You are N lines of CSS code. Your task is to print all valid Hex Color Codes, in order of their occurrence from top to bottom.
CSS Code Pattern
Selector
{
Property: Value;
}
Input Format
The first line contains N, the number of code lines.
The next N lines contains CSS Codes.
Constraints
0<N<50
Output Format
Output the color codes with '#' symbols on separate lines.
Sample Input
11
#BED
{
color: #FfFdF8; background-color:#aef;
font-size: 123px;
background: -webkit-linear-gradient(top, #f9f9f9, #fff);
}
#Cab
{
background-color: #ABC;
border: 2px dashed #fff;
}
Sample Output
#FfFdF8
#aef
#f9f9f9
#fff
#ABC
#fff
Explanation
#BED and #Cab satisfy the Hex Color Code criteria, but they are used as selectors and not as color codes in the given CSS.
Hence, the valid color codes are:
#FfFdF8
#aef
#f9f9f9
#fff
#ABC
#fff
Note: There are no comments ( // or /* */) in CSS Code. """
#this is my working copy. The output for the input above is:
#FfFdF8
#f9f9f9
#the output should be:
#FfFdF8
#aef
#f9f9f9
#fff
#ABC
#fff
lines_of_text = int(input("Enter the number of lines to be scanned: "))
for values in range(lines_of_text):
css = input()
match = re.findall(r"(#[0-9,A-F,a-f]{3} | #[0-9,A-F,a-f]{6})", css)
# findall() searches for the Regular Expression and return a list upon finding
#[0-9,A-F,a-f]{3} | #[0-9,A-F,a-f]{6}) is broken down like this:
#[0-9,A-F,a-f]{3} means any number between 0-9 or upper or locase letter from a-f or A-F. These combine for a size of 3 digits
# [0-9,A-F,a-f]{6} is the same but size 6.
# the | means or so its a group of 3 or 6 digits.
if match:
print(*match, sep="\n") |
19b73d3ae56b3e0d25bdf866ee26c4e815ad07de | francis2001tw/BasicPython | /SourceCode/02_Flow Control/02_Loop/continue.py | 211 | 3.8125 | 4 | # continue
myString = 'My name is Frank'
index = -1
while index < 16:
index = index + 1
if index % 2 == 0:
# [POINT 1]
continue
else:
print(myString[index] + '-', end='')
|
4cf139f3855d30f7ddad5c38fbb27b84809a24cc | francis2001tw/BasicPython | /SourceCode/01_Basic Concepts/08_String/concatenation.py | 269 | 3.90625 | 4 | # concatenation
# [POINT 1]
string1 = 'My '
string2 = 'name '
string3 = 'is '
string4 = 'Frank'
print(string1+string2+string3+string4)
# [POINT 2]
string4 = '{0} + {1} = {2}'.format('2', '3', '5')
string5 = '%s + %s = %s' % (2, 3, 5)
print(string4)
print(string5)
|
945786723aac202753c4584e2c6500e0f33f584b | francis2001tw/BasicPython | /SourceCode/02_Flow Control/02_Loop/while.py | 149 | 3.625 | 4 | # while loop
myString = 'My name is Frank'
index = 0
# [POINT 1]
while index < 16:
print(myString[index] + '-', end='')
index = index + 1
|
67185cd525c4eb67b4223a5c8d2eb6cf0ec4d8aa | francis2001tw/BasicPython | /SourceCode/03_Data Structure/01_List/comprehension.py | 372 | 3.734375 | 4 | # comprehension
data1 = list()
for num in range(0, 10):
if num % 2 == 0:
data1.append(num)
print(data1)
# [POINT 1]
data2 = [num for num in range(0, 10) if num % 2 == 0]
print(data2)
# [POINT 2]
pairs2D = [(x, y) for x in range(2) for y in range(2)]
print(pairs2D)
pairs3D = [(x, y, z) for x in range(2) for y in range(2) for z in range(2)]
print(pairs3D)
|
89b5918192fae2cf42cfb4afcf92b345a7ed7c42 | francis2001tw/BasicPython | /SourceCode/02_Flow Control/01_Conditional/euqal.py | 92 | 3.53125 | 4 | # equal Conditional
a = float(100)
b = float(100)
# [POINT 1]
print(a is b)
print(a == b)
|
024fb158327c3a10094ba2cc1010abdccf3b6638 | calliope-pro/Matplotlib_ | /基本_描画.py | 557 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# シード固定
np.random.seed(0)
# 変数x・y
x = np.linspace(0, 1, 10)
y = 2 * x + 0.1 * np.random.randn(10)
print(y)
# 折れ線(テンプレ)
# plt.figure(figsize=(10, 7)) # figsize=(width, height)
# plt.plot(x, y)
# plt.show()
# 折れ線(汎用)
fig = plt.figure() # グラフ領域の準備(ベースのキャンバス)
ax: plt.Axes = fig.add_subplot(111) # 実際にはAxesを使ってグラフを書く(gridの指定)
ax.plot(x, y) # 描画
plt.show() # 表示
|
0b7126b33d6e297c905dd98c63bedb1b15c435e9 | fwar34/DataStruct | /mine/circlequeue/queue.py | 1,902 | 3.765625 | 4 | import logging
class QError(BaseException):
def __init__(self, value, message):
self.value = value
self.message = message
def __str__(self):
# return repr(self.message)
return self.message
class Queue:
def __init__(self, capacity):
self.queue = []
self.front = 0
self.back = 0
self.capacity = capacity + 1
for i in range(capacity + 1):
self.queue.append(0)
def Front(self):
return self.queue[self.front + 1]
def Back(self):
return self.queue[self.back]
def Push(self, element):
if self.Full():
raise QError(-1, 'Queue full')
else:
self.back = (self.back + 1) % self.capacity
self.queue[self.back] = element
def Pop(self):
if self.Empty():
raise QError(-2, 'Queue empty')
else:
self.front = (self.front + 1) % self.capacity
def Full(self):
return (self.back + 1) % self.capacity == self.front
def Empty(self):
return self.front == self.back
if __name__ == '__main__':
q = Queue(5)
print(q.Empty())
print(q.Full())
try:
q.Push(3)
print(q.Empty())
print(q.Full())
q.Push(4)
q.Push(5)
q.Push(6)
q.Push(7)
print(q.Empty())
print(q.Full())
q.Pop()
print(q.Empty())
print(q.Full())
q.Pop()
q.Pop()
q.Pop()
print(q.Empty())
print(q.Full())
q.Pop()
print(q.Empty())
print(q.Full())
#queue already empty
q.Pop()
except QError as e:
# 通过配置,logging还可以把错误记录到日志文件里,方便事后排查
logging.exception(e)
print('END')
|
141e4194e10e9004093dfa2fb3ba21ce31746d13 | mwnuk/PythonCode | /Pycharm_Syntax/StringsNum.py | 3,351 | 4.34375 | 4 | # These are called modules
import random
import sys
import os
# Hello world is just one line of code
# print() outputs data to the screen
print("Hello World")
'''
This is a multi-line comment
'''
# A variable is a place to store values
# Its name is like a label for that value
name = "Derek"
print(name)
# A variable name can contain letters, numbers, or _
# but can't start with a number
# There are 5 data types Numbers, Strings, List, Tuple, Dictionary
# You can store any of them in the same variable
name = 15
print(name)
# The arithmetic operators +, -, *, /, %, **, //
# ** Exponential calculation
# // Floor Division
print("5 + 2 =", 5+2)
print("5 - 2 =", 5-2)
print("5 * 2 =", 5*2)
print("5 / 2 =", 5/2)
print("5 % 2 =", 5%2)
print("5 ** 2 =", 5**2)
print("5 // 2 =", 5//2)
# Order of Operation states * and / is performed before + and -
print("1 + 2 - 3 * 2 =", 1 + 2 - 3 * 2)
print("(1 + 2 - 3) * 2 =", (1 + 2 - 3) * 2)
# A string is a string of characters surrounded by " or '
# If you must use a " or ' between the same quote escape it with \
quote = "\"Always remember your unique,"
# A multi-line quote
multi_line_quote = ''' just
like everyone else" '''
print(quote + multi_line_quote)
# To embed a string in output use %s
print("%s %s %s" % ('I like the quote', quote, multi_line_quote))
# To keep from printing newlines use end=""
print("I don't like ",end="")
print("newlines")
# You can print a string multiple times with *
print('\n' * 5)
# USER INPUT -------------
print('What is your name?')
# Stores everything typed up until ENTER
name = sys.stdin.readline()
print('Hello', name)
# STRINGS -------------
# A string is a series of characters surrounded by ' or "
long_string = "I'll catch you if you fall - The Floor"
# Retrieve the first 4 characters
print(long_string[0:4])
# Get the last 5 characters
print(long_string[-5:])
# Everything up to the last 5 characters
print(long_string[:-5])
# Concatenate part of a string to another
print(long_string[:4] + " be there")
# String formatting
print("%c is my %s letter and my number %d number is %.5f" % ('X', 'favorite', 1, .14))
# Capitalizes the first letter
print(long_string.capitalize())
# Returns the index of the start of the string
# case sensitive
print(long_string.find("Floor"))
# Returns true if all characters are letters ' isn't a letter
print(long_string.isalpha())
# Returns true if all characters are numbers
print(long_string.isalnum())
# Returns the string length
print(len(long_string))
# Replace the first word with the second (Add a number to replace more)
print(long_string.replace("Floor", "Ground"))
# Remove white space from front and end
print(long_string.strip())
# Split a string into a list based on the delimiter you provide
quote_list = long_string.split(" ")
print(quote_list)
# FILE I/O -------------
# Overwrite or create a file for writing
test_file = open("test.txt", "wb")
# Get the file mode used
print(test_file.mode)
# Get the files name
print(test_file.name)
# Write text to a file with a newline
test_file.write(bytes("Write me to the file\n", 'UTF-8'))
# Close the file
test_file.close()
# Opens a file for reading and writing
test_file = open("test.txt", "r+")
# Read text from the file
text_in_file = test_file.read()
print(text_in_file)
# Delete the file
os.remove("test.txt")
|
e9ad53744bce611675534a83e93cb475b07b2d62 | AlexWanyoike/Password_PythonIP | /user.py | 1,353 | 3.796875 | 4 | import pyperclip
import random, string
class User:
'''
Create a new User with both Username and Password
'''
user_list = []
@classmethod
def __init__(self, user_name, password):
self.user_name = user_name
self.password = password
def save_user(self):
'''
saves users into user_list
'''
User.user_list.append(self)
def delete_user(self):
'''
# delete_contact method deletes a saved account from the user_list
# '''
User.user_list.remove(self)
@classmethod
def find_by_user_name(cls, user_name):
'''
search name & return detail info
'''
for user in cls.user_list:
if user.user_name == user_name:
return user
@classmethod
def user_exist(cls, user_name):
'''
This is to check if the user exists
'''
for user in cls.user_list:
if user.user_name == user_name:
return True
else:
return False
@classmethod
def display_users(cls):
'''
return user list
'''
return cls.user_list
@classmethod
def copy_email(cls, user_name):
user_found = User.find_by_user_name(user_name)
pyperclip.copy(user_found.email)
|
d2a04ec1a49d26a0a15361524a226e918a8435f5 | arabindamahato/personal_python_program | /programming_class_akshaysir/eliminate_last_digit.py | 153 | 4.03125 | 4 | print('To eliminate the last digit of any number')
n=int(input('Enter your no : '))
o=n//10
print('After eliminating last digit of {} is {}'.format(n,o)) |
5326bd592b7cdaa500d1f5809ffed190de7b6257 | arabindamahato/personal_python_program | /class_object/atm_issue.py | 627 | 3.78125 | 4 | class Bank:
bank_name = 'Bank of Boroda'
ifsc_code = 'BARBAMUND'
def __init__(self, name, age, ph_no, atm = False):
self.name = name
self.age = age
self.ph_no = ph_no
self.atm = atm
def atminfo(self):
if self.atm == True:
print('Atm already issued')
else:
self.atm == True:
oa=Bank('arabinda', '25', 123456)
#oa1=Bank('Ramesh', '21', 321654)
# #calling the object by using class name
# Bank.disp(oa)
# #calling the object by using object name/ object variable
# oa.disp()
#-------modify-------
oa.disp()
oa.modify()
oa.disp() |
1661637a1221678a1a6bd61dce3336ff7ca569c1 | arabindamahato/personal_python_program | /inheritance/has-a_relationship.py | 298 | 3.953125 | 4 | ''' example of has-a relationship'''
class A:
def m1(self):
print('def m1')
class B(A):
oa=A() #object created in child class
def m2(self):
print('def m2')
ob=B() # creating object for object B
ob.m2()
ob.oa.m1() # calling m1() function from object A inside object B
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.