blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
972362f6ecdfacdfc1559075ee82a2f3ed8500ee | JulieZhang0102/MIS3640 | /session15/exercise2.py | 1,853 | 4.15625 | 4 | import math
class Point:
'''
a point with x, y attributes
'''
class Circle:
'''
Circle with attributes center and radius
'''
center = Point()
circle = Circle()
circle.center.x = 150
circle.center.y = 100
circle.radius = 75
class Rectangle:
"""Represents a rectangle.
attributes:... |
4411b14dc412c058f082fcca89d4d15a7a57bd40 | JulieZhang0102/MIS3640 | /session12/exercises.py | 1,352 | 4.0625 | 4 | # Exercise 2.1
def most_frequent(x):
d = dict()
for letter in x:
d[letter] = d.get(letter, 0) + 1
t = []
for key, value in d.items():
t.append((value, key))
t.sort()
t.reverse()
print(t)
most_frequent('llllllliaaabb')
# Exercise 2.2
from collections import defaultdict
with... |
efafdf24723a1adb993f90515296dedf1206f7f2 | zirin12/Leetcode-InterviewBit-Solutions | /InterviewBit/longest_consecutive_sequence.py | 1,726 | 3.984375 | 4 | '''
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Example:
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
'''
class Solution:
# @param A : tuple of int... |
d2d214f11ddfca04343caae1b94f718c87b7b9e0 | zirin12/Leetcode-InterviewBit-Solutions | /InterviewBit/generate_all_parantheses.py | 838 | 3.984375 | 4 | '''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
'''
class Solution:
# @... |
400bad47313d0cb50b9dcd2e1c9b64d62da5fb8a | zirin12/Leetcode-InterviewBit-Solutions | /InterviewBit/reverse_linked_list_recursion.py | 971 | 4.21875 | 4 | '''
Reverse a linked list using recursion.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
# one of way doing it wi... |
57f2be24179704c122b29df8ede026e46b81335e | magjene/Smart_Calculator | /Smart Calculator/task/calculator/calculator.py | 5,410 | 3.875 | 4 | d = {}
s, sign, temp1, temp2, temp_s = int, 1, int, int, ''
def computer(t):
temp_add = []
act = ''
for j1 in t:
if act is '':
temp_add.append(j1)
elif act == '*':
temp_add.pop()
k = temp_add.pop()
if isinstance(k, int) and isinstance(j1, int... |
afc90959f9f579468f864d7bb18acc82f0e181e5 | jorgeg73/PythonPro | /operaciones cono funciones.py | 949 | 4.03125 | 4 | def suma():
num1 = int(input("primer numero? "))
num2 = int(input("Segundo Numero? "))
r = num1 + num2
print num1, "+", num2, "=", r
def Resta():
num1 = int(input("primer numero? "))
num2 = int(input("Segundo Numero? "))
r = num1 - num2
print num1, "-", num2, "=", r
def multiplicacio... |
b98577a713d74a664a224f52880c0c3aec625aaf | GeovaniTuz/LenguajesYAutomatasIIU3 | /EjercicioU3/Ejercicio4_Ciclos.py | 90 | 3.625 | 4 | #!/user/bin/python
a = [3,4,5]
for b in a:
print(f"I = ({b}) y su cuadrado ({b**2})")
|
34480d310fcbeb1767fa7fe823d960324a38492f | taoyan/python | /Python学习/day05/返回函数.py | 657 | 4 | 4 |
#返回函数
#函数嵌套,函数里返回一个函数
def show():
def show1():
print('哈哈')
#返回了一个函数
return show1
new_func = show()
new_func()
show()()
#根据传入的不同参数,返回不同的函数(返回函数重要的意义所在)
def calc(operation):
if operation == '+':
def sum_num(num1, num2):
result = num1 + num2
return result
... |
9f4f0c09ae11d6f8e156a39bc99d9d3618260d40 | taoyan/python | /Python学习/day10/互斥锁.py | 497 | 3.78125 | 4 | #由于资源竞争
import threading
lock = threading.Lock()
g_num = 0
def AA():
#上锁
lock.acquire()
global g_num
for i in range(1000000):
g_num += 1
lock.release()
print('AA',g_num)
def BB():
lock.acquire()
global g_num
for i in range(1000000):
g_num += 1
lock.release()
... |
df3a322546990b446fa857266e2db2655dcb6272 | taoyan/python | /Python学习/练习/面向对象编程.py | 3,061 | 4.28125 | 4 | #面向对象编程OOP
class Person(object):
#类属性,对类绑定数据,归所有类对象所有
age = 10
person = Person()
print(Person)
print(person)
#对实体对象绑定数据,而非类
person.name = 'yant'
print(person.name)
person.age = 19
print(person.age)
print(Person.age)
#访问限制
#私有变量,前面加__下划线
class Student(Person):
def __init__(self, name):
self.__name... |
d766c4d906776eecc0282d95141da0cf1c817556 | taoyan/python | /Python学习/day07/__del__魔法方法.py | 426 | 3.8125 | 4 | #对象释放时候自动调用
#1.程序退出,程序中所使用的对象全部销毁
#2.当前内存地址没有变量使用时候
import time
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def __del__(self):
print('对象被销毁',self)
xiao_ming = Person('小明',20)
#删除对象
# del xiao_ming
xiao_ming = None
time.sleep(3)
print('程序退出') |
40ba13908f66f0a3ed4960784c01ee1d7d360ef5 | taoyan/python | /Python学习/day07/动态创建对象的属性,获取属性值.py | 268 | 3.6875 | 4 | class Teacher:
def show(self):
print('天气不错')
teacher = Teacher()
#动态添加属性
teacher.name = '李四'
teacher.age = 18
#获取对象属性
print(teacher.name,teacher.age)
#修改
teacher.name = '王五'
print(teacher.name,teacher.age) |
a40b2c6472dedcedd7a983b089a62562f3598151 | njrafi/Competitive-Programming-Solutions | /HackerRank/Text Wrap.py | 278 | 3.578125 | 4 | def wrap(string, max_width):
gg = ''
tem = ''
for i in string:
tem += i
if(len(tem)==max_width):
gg += tem
gg += '\n'
tem = ''
if(len(tem)>0):
gg += tem
gg += '\n'
tem = ''
return gg |
90f022bc7983e53d6b709aa0e4984ec259cc4f62 | njrafi/Competitive-Programming-Solutions | /HackerRank/Python If-Else.py | 138 | 3.96875 | 4 | #!/bin/python3
n = int(input())
if (n%2) != 0:
print("Weird")
elif (n>=6 and n<=20):
print("Weird")
else:
print("Not Weird") |
fc39ee4396637ae9126c041a47f991a0f17ef789 | afoukal/Python | /HomeWorkPythonLesson2.py | 6,986 | 4.21875 | 4 | # 6. Set a variable called total to 0. Ask the user to enter five numbers and after each input ask them if they want that number included. If they do, then add the number to the total. If they do not want it included, don’t add it to the total. After they have entered all five numbers, display the total.
total_6 = 0
in... |
88cb48ba74ffea602fc88abf0d73358de615e316 | rgap/rgap-bin-utils | /rgap_imagecrop.py | 2,328 | 3.625 | 4 | #!/usr/bin/env python3
"""Trim whitespace from images in a directory
Usage:
rgap_imagecrop.py (--c|<input_dir>) <output_dir> [--suffix]
rgap_imagecrop.py (--c|<input_dir>) [--suffix]
rgap_imagecrop.py -h
Arguments:
input_dir input directory containing images
output_dir output directory contain... |
05ef1fc13f0c0cdba75656a471c2b840e7a92938 | rgap/rgap-bin-utils | /rgap_png2pdf_dir.py | 2,281 | 3.546875 | 4 | #!/usr/bin/env python3
"""Crops margins of PDFs in a directory
This script makes use of "ImageMagick" library
http://www.imagemagick.org/script/index.php
On Mac OS X: brew install imagemagick
It allows converting every pdf file in a specific
directoty.
Usage:
rgap_png2pdf_dir.py (--c|<input_dir>) <output_dir> [-... |
5c090451251a7a6b3fa8f45bf3008b3f3ab71a61 | rgap/rgap-bin-utils | /rgap_getanyfile_url.py | 2,130 | 3.75 | 4 | #!/usr/bin/env python3
"""This downloads a file from a url
Usage:
rgap_getanyfile_url.py <base_url> <name> [--short] [--prefix=<prefix>]
rgap_getanyfile_url.py -h
Arguments:
base_url url that contains the file to download
name filename
prefix prefix to put to the file (... |
4c3f4078af2d69e6c2d61569a7bad688a37bad9b | keruicao/Practicum-HW | /HW1/HW1.py | 2,329 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Python Homework 1
# 1. Creating Python lists. There is more than one way to do these!
# (a) [1,2,3,...,19,20]
# In[ ]:
a = range(1,21,1)
list(a)
# (b) [20,19,...,2,1]
# In[ ]:
b = range(20,0,-1)
list(b)
# (c) [1,2,3,...,19,20,19,18,...,2,1]
# In[ ]:
c = list(rang... |
9d11367a5496cf90d3f47d63e5f0d6a234eec5ff | sahithyagadde/Python | /icp1/modify.py | 102 | 3.640625 | 4 | char = raw_input("Enter string of characters ")
newchar = char.replace("on", "")
print(newchar[::-1])
|
1675e521a41945a6ae77ab29285958ed41a4ebb5 | junaid238/PythonBVC | /collections.py | 1,157 | 3.984375 | 4 | names = ["Python" , 101 , 19 , 13 , "february"]
nums = [ 1 , 2 , 2 , 5 , 6 , 8 , 3 ]
tech = ["Python"]
# tech = tech*3
# # print(tec)
# print(tech)
# print(type(names))
# print(type(nums))
# print(names)
# print(nums)
# print(names[0])
# print(names[4])
# print(names[3])
# names[3] = "march" #mutation
# print(name... |
b8826e0882cf6a1a1d77814aff9ff91da2341070 | marcelinorc/semantic-recovery | /semantic_codec/architecture/functions.py | 634 | 3.5625 | 4 |
class ElfFunction(object):
"""
Represents a function from the elf file
"""
def __init__(self, name='unknwon'):
self.name = name
self.instructions = []
def start_addr(self):
if len(self.instructions) > 0:
return self.instructions[0].address
else:
... |
1da90bf31f7e1c6f62fd6b22cd45e1ab2966e240 | payneal/pyspark_ml | /machine_learing/Clustering/k_means_clustering.py | 989 | 3.53125 | 4 | from pyspark.sql import SparkSession
from pyspark.ml.clustering import KMeans
spark = SparkSession.builder.appName('cluster').getOrCreate()
data_set = spark.read.format('libsvm').load("./data/sample_kmeans_data.txt")
# show all of the data
data_set.show()
# to show you that you only need features will get rid of lab... |
a237ce58e37382300da33d009d70e02f80d79a98 | WeiPromise/study | /day06_元组、字典、集合/01-元组的使用.py | 864 | 3.90625 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/8/17 16:01
# 元组和列表很像,都是用来保存多个数据
# 使用一对小括号() 来表示一个元组
# 元组和列表的区别在于,列表是可变的,而元组是不可变的
words = ['hello', 'word']
nums = (1, 2, 3, 4, 5, 4, 4)
words[0] = 'haahaha'
# 'tuple' object does not support item assignment,元组不可变
# nums[2] = 2
# 统计一个元素出现的次数
pr... |
74dafeea0c6a4aeb4ccb063a08118f2d285bb1ee | WeiPromise/study | /day07_函数基础/04-函数调用函数.py | 416 | 3.84375 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/8/18 15:25
# 求和 -> 指定返回值类型
def my_sum(a: int, b: int) -> int:
"""
函数求和
:param a: 参数1
:param b: 参数2
:return: 返回值
"""
return a + b
def sum_factorial(a: int) -> int:
sum = 0
for i in range(a + 1):
sum = m... |
e73b40e752060d23657c8742558ae16f31017b4e | WeiPromise/study | /day12_名片管理系统/05-名片管理系统(查询用户).py | 3,767 | 3.90625 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/10/10 15:15
user_list = [
{'name': 'zhangsan', 'qq': '2342', 'tel': '112432'},
{'name': 'lisi', 'qq': '2113e21', 'tel': 'qwe'},
{'name': 'wangwu', 'qq': '2342', 'tel': '1232431'}
]
def add_user():
# 用户输入信息
name = input('请输入用户姓... |
9f242221c815384f8f21ae313042fd71dd51cbd5 | WeiPromise/study | /day10_面向对象基础/10-单例设计模式.py | 790 | 3.515625 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/9/29 15:48
class Singleton(object):
__instance = None
__is_first = True
@classmethod
def __new__(cls, *args, **kwargs):
# 申请内存,创建一个对象,并把对象的类型设置为cls
if cls.__instance is None:
cls.__instance = object._... |
73441a2d6a783bff4eeccd552d8e22613e330320 | WeiPromise/study | /day06_元组、字典、集合/06-字典的练习.py | 1,152 | 3.625 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/8/17 17:03
# 练习 1
chars = ['a', 'b', 'b', 'c', 'd', 'd', 'a', 'd', 'e', 'r', 'r', 'g', 'g', 'a']
char_count = {}
for char in chars:
# if char in char_count:
# char_count[char] += 1
# else:
# char_count[char] = 1
if cha... |
5554390ed92c91cc0a7e737f789b241073fae887 | WeiPromise/study | /day10_面向对象基础/15-之类重写父类方法.py | 1,005 | 3.75 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/9/30 14:29
class Anumal(object):
def __init__(self, name, age):
self.name = name
self.age = age
def sleep(self):
print(self.name + '正在睡觉')
class Person(object):
def __init__(self, name):
self.name =... |
68c4ba1f050356b595df5c4a8c8dcbd91422588f | s072590/Python-For-Everybody | /C1-6/C2E5.py | 102 | 3.875 | 4 | celcius=float(input('Enter degrees Celsius '))
print('Fahrenheit '+ str(float(celcius*(9.0/5)+32.0))) |
6ad5253335b9b2ef6078250071bc7d96618463a8 | s072590/Python-For-Everybody | /C1-6/C6.E3.py | 214 | 4 | 4 | def count1(string, searched_letter):
count = 0
for letter in string:
if letter == searched_letter:
count = count +1
return count
hest = count1("banana","a")
print(hest)
|
f9f6bbbdf553e9deda6244345e8daa101375c833 | s072590/Python-For-Everybody | /C8/C8E5.py | 486 | 3.609375 | 4 | fhand = open('mbox-short.txt')
wordlist = []
count = 0
for line in fhand:
splitted = line.split()
if len(splitted) <= 1 : continue
if splitted[0] != 'From' : continue
count = count + 1
print (splitted[1])
print ('There were', count, 'lines in the file with From as the first word')
# ... |
f672281c9a2859bf857308aa40b3c83df24e193c | llpk79/Algorithms | /knapsack/knapsack.py | 7,406 | 4.03125 | 4 | #!/usr/bin/python
import sys
from math import floor
from collections import namedtuple
Item = namedtuple('Item', ['index', 'size', 'value'])
class MaxHeap(list):
"""MaxHeap keeps maximum element available for pop in O(log n) time.
Inherits from list.
Overrides methods pop, insert and clear.
Instant... |
9224e8d1bdbfe848797f7e2b4a5ed5753020dcd9 | Nafani4/Home_work | /task_01_04.py | 934 | 3.53125 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x3 = int(input())
y3 = int(input())
x31 = x3-x1
if x31 > 0:
x31 = x31
else:
x31 = x31*(-1)
y31 = y3 - y1
if y31 > 0:
y31 = y31
else:
y31 = y31*(-1)
x21 = x2 - x1
if x21 > 0:
x21 = x21
else:
x21 = x21*(-1)
y21 = y2 - y1
if y2... |
552cf9298ca2e2cb498833118c139d7bb8143c25 | Nafani4/Home_work | /draft.py | 1,603 | 3.546875 | 4 | from abc import *
class CommandException(Exception):
pass
class Command(metaclass=ABCMeta):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
@abstractmethod
def execute(self):
pass
@abstractmethod
def show_name(self):
pass
class Menu(... |
28de3beb02e39cc6b3e1a95b0cc7a3e217384652 | Nafani4/Home_work | /task_03_01.py | 471 | 4.09375 | 4 | from datetime import datetime
from datetime import date
def get_days_to_new_year():
day_now = datetime.today()
new_year = day_now.year+1
new_year_date = datetime(new_year, 1, 1)
time_to_new_year = new_year_date - day_now
days_to_new_year = int(time_to_new_year.days)
# days_to_new_year = int((date... |
d0da5a922698d92b911be218198c69aaecf7166e | Nafani4/Home_work | /task_02_02.py | 2,983 | 4.09375 | 4 | def bubble_sort(lst):
result = lst #Результатом выполнение функции является список
m = len(lst) - 1 #Определяем количество проходов по списку, как количество элементов списка -1.
#-1 чтобы не превысить индекс списка после сравнения предпослед... |
b2341851ecff558d71ac5c77c746611d2432b75c | marcelobarbosadg87/algoritmosempython | /bubble-sort.py | 871 | 3.859375 | 4 | #Algoritmo de Ordenação Bolha
#Bubble Sort
A = [2, 4, 18, 21, 3, 10, 14, 20, 15] # Vetor com os numeros a serem ordenados
size = len(A) # Captura o tamanho do vetor
#funcao para ordenar // passando o vetor como referencia
def ordenarBolha(A):
#primeiro laco de interação
for posicao in range(len(A)-1,0,-1):
... |
9dcfb3de6077324989af24f9d4422ce973cb87f2 | gopal2109/Data | /Python-programs/oops/abstaction.py | 377 | 4 | 4 | from abc import ABCMeta, abstractmethod
class Animal(object):
__metaclass__ = ABCMeta
@abstractmethod
def say_someting(self):
return "I am an animal"
class Cat(Animal):
def say_someting(self):
s = super(Cat, self).say_someting()
return "{} {}".format(s, "maiuu")
if __name_... |
11ac9cefe24a237723a9365f963ce27bc94ea282 | gopal2109/Data | /Python-programs/list_comprehension.py | 346 | 4.3125 | 4 | """
It is concise way(easy way)to create a list based on the requirement.
This is advanced methodology for map,filter,loops and conditions.
The output of list comprehension is always a list.
syntax:-
[expression for i in variable if(condition)]
"""
print [i for i in range(0, 10) if i % 2 == 0]
print [i for i in ra... |
b7d98a0bca6e3f59d5b794334f5e61202d5be238 | igorvrykolakas/training.py | /pintando paredes.py | 225 | 3.703125 | 4 | lparede = float(input('Qual é a largura da sua parede?'))
aparede = float(input('Qual é a altura da sua parede?'))
print('Você vai precisar de {} litros de tinta para pintar esta parede.'.format(lparede * aparede / 2))
|
29921e502dd5fe798a9283e9dee86ae3a7a448d6 | igorvrykolakas/training.py | /reajustes salarial.py | 158 | 3.546875 | 4 | sal = float(input('Qual seu salário atual?'))
asal = sal*0.15
print('Parabéns, com seu novo aumento, seu salário passa a ser R${}.'.format(sal + asal))
|
7122139c895040cf9db462a5cd2c81da9fb17129 | liyuhuan123/Learnselenium | /pythonStudy/实战-猜数字.py | 725 | 3.59375 | 4 | # 在1-100之间随机产生一个整数,让用户反复猜,只提示'猜大了'或'猜小了'猜对结束游戏
# str---string : int----整数
# 键盘默认输入的是一个字符串类型的
import random
# m是1-100之间的一个整数
m = random.randint(1,100)
total = 5 # 可以猜的总数
count = 0 # 我猜了多少次了,默认是0次
# 只允许猜5次,如果5次没有猜对就结束游戏
while True:
n = int(input('输入1-100之间的整数:'))
if n < m:
print('猜小了!')
eli... |
9c0c2563051de9809ae965cef7c9a26761256930 | liyuhuan123/Learnselenium | /pythonStudy/python字符串.py | 3,099 | 4.40625 | 4 | # 字符串操作
a = "hello"
b = "world"
print(a + b) # helloworld
print(a * 2) # hellohello
print(a[1]) # a
print(a[1 : 4]) # ell
print('h' in a) #True
print('m' in b) # False
print(r'hello\nworld') # hello\nworld
# 字符串格式化
print("我叫%s,今年%d岁" % ('lyh', 21)) # 我叫lyh,今年21岁
# python三引号
str = """ 这是一个多行字符串的实例
多行字符串... |
57cc121cc3550ec7a9283ac4fa3ab8aa0de86dc5 | liyuhuan123/Learnselenium | /pythonStudy/语法学习.py | 4,535 | 4.15625 | 4 | # 行与缩进
# if True:
# print("True")
# else:
# print("False")
# 多行语句:用反斜杠来连接
# item_one = 0
# item_two = 2
# item_three = 3
# total = item_one + \
# item_two + \
# item_three
# print(total) # 5
# # 在[],{},()中的多行语句,不需要使用反斜杠(\)
# total = ['item_one', 'item_two', 'item_three']
# print(total) # ['ite... |
4b7d00ff5c1d65771f901a6540f2c0a9c5b122df | amauryTCassola/Trabalhos-IA-2020-2 | /trabalho 1/src/astar_h2.py | 5,785 | 3.671875 | 4 | import sys
import heapq
class Node:
"""Classe representando um nodo no grafo de busca"""
def __init__(self, pai, estado, acao, custo):
self.pai = pai
self.estado = estado
self.acao = acao
self.custo = custo
def __lt__(self, other):
return self.custo < other.custo
v... |
83343afc35a9452e0251f09fda5588657b706e8a | maj3r1819/LPTHW | /Exercises/exp15.py | 278 | 3.5 | 4 | from sys import argv
script=argv
filename=argv
txt=open('F:\python\sagar.txt','r')
print("Here's your file %r:"%'F:\python\sagar.txt','r')
print(txt.read())
print("Type the filename again:")
file_name=input(">")
txt_again=open('F:\python\sagar.txt','r')
print(txt_again.read())
|
40b1d9da74a54de3705e0aa009f94117ee0ddf54 | maj3r1819/LPTHW | /Exercises/exp14.py | 495 | 3.625 | 4 | from sys import argv
script=argv
user_name='Sagar'
prompt='>'
print("Hi %s, Im the %s script"%(user_name,script))
print("Id like to ask you a few questions.")
print("Do you likeme %s?"%user_name)
likes=input(prompt)
print("Where do you live %s?"%user_name)
lives=input(prompt)
print("what kind of computer do u have?")
c... |
d00d914b05f6eaf7a680677261b9dff508ee3133 | tuancoiz4/Classes_home_work | /home_work_9.py | 3,344 | 3.78125 | 4 | class Vehicle:
def __init__(self,make,model,year,weight,Trips,NeedMaintenance = False):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.NeedMaintenance = NeedMaintenance
self.trips = Trips
# Vehicle1 = Vehicle("Honda","Civic","20... |
b6fe73b75e450f11c9067105cf1abaffaa9926b4 | deepakg0401/Chess-Engine-using-Alphabeta-Algorithm. | /flipboard.py | 458 | 3.53125 | 4 | from Board import *
class flipboard:
def __init__(self):
self.p=Board()
def flipboard(self):
for i in range(32):
r=i//8
c=i%8
if self.t[r][c].isupper()==True:
temp=self.t[r][c].lower()
else:
temp=self.t[r][c].upper()
if self.t[7-r][7-c].isupper()==True:
self.t[r][c]=self.t[7-r][7-c].low... |
719616b18e809ee6e9b955ae3a3a02b9a50b1b5d | Zengor/adventofcode2019 | /python/day4.py | 1,267 | 3.515625 | 4 | from functools import reduce
digit_offset = [1, 10, 100, 1000, 10000, 100000]
def get_digit(num, digit):
return (num // digit_offset[digit]) % 10
# takes a list with the number of digits in each sequence of repeated digits
# returns (bool, bool) with the validity for part 1 and part 2 respectively
def valid_count... |
95bf9ea374aadd5533bdb0bcc43db32fae2f0b54 | raghu74us/DATA-608 | /Project4/app2.py | 3,153 | 3.5 | 4 | """
Created on Mon Mar 18
Question 1
@author: Raghu
Question 2:
This time you are building an app for scientists. You’re a public health researcher
analyzing this data. You would like to know if there’s a relationship between the
amount of rain and water quality. Create an exploratory app that allows other
rese... |
472761ecf22c642f7154405c3992b812a8a190be | josephabero/learning_for_fun | /learn_python/OOP/1_class_instance.py | 660 | 3.859375 | 4 | # Python Object-Oriented Programming
class Employee:
def __init__(self, first_name, last_name, pay):
self.first_name = first_name
self.last_name = last_name
self.email = f"{first_name}.{last_name}@email.com"
self.pay = pay
def get_full_name(self):
return f"{se... |
89d3a1a691bfc9ddd02b5c375ca5a7af763f0794 | StephenSnow379/Selection | /selection revision task 3.py | 242 | 4.0625 | 4 | #Stephen Snow
#30/09/2014
#Revision exercises Selection statements
number = int(input("Please enter a number between 21 and 29:"))
if number >=21 <=29:
print("This number is acceptable")
else:
print("This number is out of range")
|
a066f3d20d99fb4d7515a0e68565e514019e64c7 | towfiq046/core-python-getting-started | /10. Classes/function.py | 560 | 4.15625 | 4 | def nth_root(number, root):
return number ** (1/root)
def ordinal_suffix(number):
if number % 100 == 11:
return 'th'
elif number % 100 == 12:
return 'th'
elif number % 100 == 13:
return 'th'
elif number % 10 == 1:
return 'st'
elif number % 10 == 2:
retur... |
740a08270d5fcf7c6328930f1ed54a073fb2e8a4 | hungitytng99/robot | /app/computer_vision/until.py | 264 | 3.546875 | 4 | import numpy as np
def angleBetweenPoints(a, b, c):
""" compute the angle in degress betwen 3 points as a float """
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
return np.arccos(cosine_angle)
|
8458bc6a279bbe83601804dc0e9f29e2f43511ec | yunlum/Othello | /set_dialogs.py | 6,488 | 3.671875 | 4 | # Yunlu Ma ID: 28072206
import tkinter
class Dialogs:
# This Class builds the dialogs in tkinter for the player to set the game
def __init__(self):
# The __init__() function builds a dialog window to ask for
# row number, col number, first turn and the winning way... |
a59619e2241c9564b005b9bea7640a768906955c | luiscarlosjunior/100-days-of-code | /python/estrutura de dados/array/array.py | 599 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 12:43:41 2020
Escreva uma função rotate (ar [], d, n) que gere arr [] do
tamanho n pelos elementos d.
@author: luisc
"""
# Função para rotacionar o arr[] de tamanho d
def leftRotate(arr, d, n):
for i in range(d):
leftRotateByOne(arr, n)
def leftRot... |
6c67d7c9bd62038a491ff3b82cd35f1685fa4df5 | Certinax/cst383-data-science | /spyderProjects/hello.py | 394 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
print("Hello world!")
x = np.array([4,2,1,8])
print(x)
# Print first element
print(x[0])
# Print length of x
print(len(x))
# Print sum of el's in x
print(sum(x))
# Subract 1 from every element
for i in x:
prin... |
c3958bfa6617cff901cd6b11b18466feb4e5e39e | matt-land/paperrockscissor | /paperrockscissor/__init__.py | 1,020 | 3.703125 | 4 | import random
__author__ = 'matt-land'
PAPER = 'paper'
ROCK = 'rock'
SCISSOR = 'scissor'
PLAYER1 = 'player1'
PLAYER2 = 'player2'
TIE = 'tie'
CHOICES = [PAPER, ROCK, SCISSOR]
def get_random_choice():
return random.choice(CHOICES)
def challenge(player1val, player2val):
"""
:param player1val: string
... |
4a8bde08520217b7d454f6d0f7c1989f6b7e56bb | trillian31337/aoc2020 | /24/lobby_layout.py | 1,447 | 3.578125 | 4 | import numpy as np
def print_grid(grid):
# find min and max for x and y
for coord in grid:
print("{}: {}".format(coord,grid[coord]))
def move(flipcount,grid,path):
directions = {'e':(1,0),'w':(-1,0),'se':(1,1),'ne':(0,-1),'sw':(0,1),'nw':(-1,-1)}
coord = (0,0)
for instr in path:
coord = tuple(np.add(np.arra... |
2f85e7c4edd54d6587a6a410d9e3cdd17d592168 | imperfectskillz/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 207 | 3.6875 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
newa = tuple_a + (0, 0)
newb = tuple_b + (0, 0)
result1 = newa[0] + newb[0]
result2 = newa[1] + newb[1]
return result1, result2
|
0c1cdc35e35c76186768b9549a0bc85375faddf2 | imperfectskillz/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 183 | 3.578125 | 4 | #!/usr/bin/python3
"""
Module, method checks if object == class
"""
def is_same_class(obj, a_class):
"""
Checks if object is a_class
"""
return type(obj) == a_class
|
85da8245421dc2bf036f569deb27f5746a8fac88 | imperfectskillz/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 221 | 3.828125 | 4 | #!/usr/bin/python3
def best_score(my_dict):
if not my_dict:
return None
sort_dict = sorted(my_dict.values())
for k, v in my_dict.items():
if my_dict[k] == sort_dict[-1]:
return k
|
0c24a40a3ee610402b055a78968c9db62b38f551 | bhushan23/StonyBrookMasters | /Fall_17/Courses/AI/assignments/3_CSP/submit.py | 8,624 | 3.71875 | 4 | #do not modify the function names
#You are given L and M as input
#Each of your functions should return the minimum possible L value alongside the marker positions
#Or return -1,[] if no solution exists for the given L
#Your backtracking function implementation
## Class ConsistencyInfo -
## Class to be used t... |
1d803ef1b6775f660cb9dd4d541f15bf49c70412 | Librason/learn_python | /17more_files_ex17.py | 913 | 3.984375 | 4 | from sys import argv
from os.path import exists
# exists function can tell if a file exist or not.
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}.")
print(f"Does the input file exist? {exists(from_file)}.")
# use print(f"{exist()}.") to see if the input file exists.
in_file = o... |
e6c86389bca16e87f6c5336f5916eaaf09fde45c | Librason/learn_python | /5format_string_ex5.py | 981 | 4.03125 | 4 | my_name = "Librason"
my_age = 18
my_height = 173
my_weight = 60
my_eyes = "Blue"
my_teeth = "White"
my_hair = "Brown"
print(f"Let's talk about {my_name}.")
print(f"I'am {my_height} cm tall.")
print(f"I'm {my_weight} kg heavy.")
print("Actually that's not too heavy.")
print(f"I have {my_eyes} eyes and {my_h... |
0b63122c094f499945dc657b73b05d30af9b6c46 | adcneto/PythonCode | /scripts/Imprime_Soma_Digitos.py | 451 | 3.90625 | 4 | num = input("Entre com um número inteiro: ")
comprimento = len(num)
ExpoentePotenciaDez=1
temp=0
SomaDosDigitos=0
while ExpoentePotenciaDez <= comprimento:
ValorCasaDecimal = ((int(num)%(10**ExpoentePotenciaDez))-temp)/(10**(ExpoentePotenciaDez-1))
print(int(ValorCasaDecimal))
temp = int(num)%(10**E... |
5da1345221bbbfcc7209a6987bd082a6f08af231 | adcneto/PythonCode | /scripts/VerificaNumerosViznhos2.py | 956 | 4.1875 | 4 | #Outro jeito de verificar se há em um número (representado em base 10) dois dígitos adjacentes iguais
PrimeiroDigitoZero = True
while PrimeiroDigitoZero:
num = input("Entre com um número inteiro que não comece com '0': ")
if int(num)/(10**(len(num)-1)) < 1:
PrimeiroDigitoZero = True
else:
... |
8c59d98d98887e9a71451baa527c9ed66361e5a6 | traveling-desi/basic_python | /mergeSort.py | 698 | 3.640625 | 4 |
def ms(l, first, last):
if not last > first:
return
print "HERE"
print "LAST", last
print "FIRST", first
mid = first + (last - first)/2
ms(l, first, mid)
ms(l, mid+1, last)
merge(l, first, mid, last)
def merge(l, first, mid, last):
temp = []
i = first
j = mid
while i < mid or j < last:
print "ALIS... |
6efa358afff70730cd038d28e03b42179a1e62d0 | singo112ok/HackerRank | /Implementation/Breaking the Records.py | 883 | 3.546875 | 4 | # https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
# 문제 난이도가 갑자기 너무 내려가서 당황..
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the breakingRecords function below.
def breakingRecords(scores):
maxScore=scores[0]
minScore=scores[0]
maxCnt = 0
... |
a84ce896e989659727ab0794ba20570475968d51 | singo112ok/HackerRank | /Implementation/Diagonal Difference.py | 968 | 3.75 | 4 | # https://www.hackerrank.com/challenges/diagonal-difference/problem
# 샘플 데이터로 공식을 짜놓고 i, i 의 합 i, n-i-1 의 합을 그대로 구현
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts ... |
83adc2acae091020b24a16d02b0cec4383a67703 | singo112ok/HackerRank | /Bit Manipulation/Maximizing XOR.py | 786 | 3.671875 | 4 | # https://www.hackerrank.com/challenges/maximizing-xor/problem
#!/bin/python3
# 간만에 쉬운거푸니 속이 다 편안하다
# 이거도 무슨 공식이 있을까 이중포문돌리면 타임아웃나지 않을까
# 노심초사했는데 일단 패스 ㅎㅎ
import math
import os
import random
import re
import sys
# Complete the maximizingXor function below.
def maximizingXor(l, r):
nMaxVal = 0
for i in rang... |
5c8a155879f4e2886a3a457d855e133a024b005a | singo112ok/HackerRank | /Implementation/Sock Merchant.py | 1,099 | 3.6875 | 4 | # https://www.hackerrank.com/challenges/sock-merchant/problem
# 리스트를 이용하여 종류별로 카운트를 세고
# 2로 나눈 몫으로 쌍의 수를 구했다 어렵진 않았으나
# 더 쉽게 할 방법도 있지 않았을까 싶었던 문제
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
arType = list(set(ar));
... |
28e897b8554b0aa89fd2fe42320ed67e4f368554 | Bondarev2020/infa_2019_Bondarev2020 | /ferz.py | 201 | 3.859375 | 4 |
a1 = int(input())
b1 = int(input())
a2 = int(input())
b2 = int(input())
if a1==a2 or b1==b2 or abs(b2-b1)==abs(a2-a1):
print('YES')
else:
print('NO')
print(a1)
|
3254516b8092e33acbfc992acb45143319453316 | Bondarev2020/infa_2019_Bondarev2020 | /kontr2.py | 378 | 3.71875 | 4 | a = int(input())
b = int(input())
c = int(input())
if a > b:
(a,b)=(b,a)
if b > c:
(b,c)=(c,b)
if a > b:
(a,b)=(b,a)
if a+b>c and a+c>b and b+c>a:
if c**2==a**2+b**2:
print ('right')
if c**2<a**2+b**2:
print ('acute')
if c**2>a**2+b**2:
print ('obt... |
8aa59aa8763975480d21f72bd670e18d5ffe719c | Bondarev2020/infa_2019_Bondarev2020 | /turtle2.py | 211 | 3.671875 | 4 | import turtle
def nugolnik(x, shag, ugol):
for i in range(x):
turtle.forward(shag)
turtle.left(ugol)
turtle.shape('turtle')
nugolnik(360, 1, 1)
input()
turtle._root.mainloop() |
2388a4cee7348624dd31f33417d110615b1afffa | Bondarev2020/infa_2019_Bondarev2020 | /turtle4.py | 239 | 3.984375 | 4 | import turtle
turtle.shape('turtle')
n=12
for i in range(n):
turtle.forward(100)
turtle.left(180)
turtle.stamp()
turtle.forward(100)
turtle.left(180)
turtle.left(360/n)
input()
turtle._root.mainloop() |
7ea03cde33f27b1ee43e76b90c99284650ccea21 | Mayank-tech-code/py3_get_started | /basic/while_loop.py | 451 | 4.25 | 4 | while(True):
signal_value = input("What is the traffic light showing?")
if signal_value.lower() == "green":
print("Drive past the signal.")
elif signal_value.lower() == "orange":
print("Wait if you are away from the signal. Cross if you have already crossed the signal.")
elif signal_valu... |
28c0f56c4ac0fd172cc466a97dd60a349506f964 | ibnahmadCoded/how_to_think_like_a_computer_scientist_Chapter_14 | /study.py | 1,691 | 3.828125 | 4 | import pygame
import time
def main():
"""Set up the game and run the main loop """
pygame.init() #Prepare the pygame module for use
#Create surface of (width, height), and its window.
main_surface = pygame.display.set_mode((480, 240))
#set up the ball image to use in game loop
ball = pygame... |
b5ea725b8fd4b2a8da04121b5ff30267e358f051 | exuqiuy/Python-Projects | /1.Python编程[从入门到实战]/7.用户输入和while循环/5.counting.py | 150 | 4.0625 | 4 | # while()循环
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
'''
1
2
3
4
5
''' |
6af693da6550771f647de31365b78c79afb6f3fb | m4reQ/Oss-2.0 | /oss/Utils/other.py | 578 | 3.640625 | 4 | if __name__ == "__main__":
import sys
sys.exit()
def Ask(question):
"""
Creates a (Y/N) question with given question string.
:param question: (str) question string
:returns: bool
"""
q = ''
while not any([q.upper() == 'Y', q.upper() == 'N']):
try: q = raw_input(question + '(Y/N): ')
except NameError... |
1aa5023a71d8720263e919862904e32f4e77d9e0 | concord/cmd | /tests/testing_utilities.py | 1,107 | 3.65625 | 4 | import os
import json
class CmdTestException(Exception):
pass
def json_from_file(filename):
data = None
with open(filename) as data_file:
data = json.load(data_file)
return data
def test_filepath(filepath):
path = os.path.dirname(os.path.realpath(__file__))
return path + '/' + filepat... |
2a21a0e575ff4bf235c827c8011246e1b8c06a8b | aroller/autoeyes | /demo/python/led_communicator.py | 11,857 | 3.578125 | 4 | from abc import ABCMeta, abstractmethod
from math import floor
from time import sleep, time
from colour import Color
from actor import Actor, Action, Urgency, Direction
from animation import HasAnimation
from communicator import Communicator
from led_strip_controller import LedStripController
from utils import min_fi... |
525702d4c774c78dc1c0ad1219cec568134da8af | Mrzhangjwei/python-cjj | /mydemo2.py | 8,995 | 3.734375 | 4 | #coding:gbk -->ַ
#!D:\Python27\python.exe -->
'''
python ģ飺
1ģ
2дģ
3ģ
.py űļ .pyc ʱļ .pyw ͼλļ
'''
#ע ---> #
#ע ---> ˫
#python
# int
# float
#
#
# + - * / ** //(ذ) ==(ֵ) is(ȫ)
#+= -= *= /= %(ȡ)
#a = 10 (=ֵ)
#a += 10 ---> a = a + 10
... |
d5214a1abc8c405cf7f5d6eec7c9ad77afa44d75 | barbar1k1/HW | /DZ/HW2/HM2.3(Переделанное).py | 307 | 3.5625 | 4 | fizz = int(input())
buzz = int(input())
a = int(input())
k = range(1, a+1)
list = []
for m in k:
if m % fizz == 0 and m % buzz == 0:
list.append("FB")
elif m % fizz == 0:
list.append("F")
elif m % buzz == 0:
list.append("B")
else:
list.append(m)
print(list)
|
bdf3a6f19dacc7d931971f165ff122eaebbf7cea | rudrasingh21/Python-For-Beginners---1 | /Exception.py | 2,627 | 4.3125 | 4 | *********************************
Exception And Finally Statement:-
*********************************
Exception in the Python are Instance of class.
try:
raise Exception('Memory Error')
except Exception as e:
print(e)
-------------
Using Exception we save our program to stop / terminate in middle an... |
82cac9db2222ce901f7abc521ef06ba3756ef0a1 | rudrasingh21/Python-For-Beginners---1 | /26.1 Multithreading.py | 1,216 | 4.46875 | 4 | #Multithreading , basically all thread are for same processes.
#Every thread has a specific task and using there own code.
#All thread shares the same Address Space.
#IF we have a global variable defined in our program , they can be accessed by all threads.
#If there is a error / memory leak in a thread , then ... |
d743191110a4d9f8e0e01f9fcb07ef56c7f1c51a | rudrasingh21/Python-For-Beginners---1 | /29.1 Sharing Data Between Processes Using Queue.py | 1,097 | 4.25 | 4 | #Sharing Data Between Processes Using Queue
# In Multiprocessing , multiple processers has there own address space
# They Don't share address space
# In previous example , we saw that , inside and outside process don't share values.
# when Global Variable passes in a process address space then it creates i... |
274873d4f56fabe33b634b61d4aedf8125789a16 | rudrasingh21/Python-For-Beginners---1 | /31. Multiprocessing pool.py | 1,314 | 4.09375 | 4 | #Multiprocessing Pool (Map Reduce)
#Using Pool --> map --> reduce
#NOTE:-
# it may be possible taht in your CPU , only 1 core is processing your program
# If you are doing lot of Image processing and computation then one core will not be a good idea
# In these scenarios we think about parallalism by usin... |
eac910970293946c332493bd001a58884f2e3c1e | imnotkind/jungsigi | /lab7/lab7.py | 4,963 | 3.84375 | 4 | from collections import Counter
class Node: # Node used in BinaryTree
def __init__(self, data):
self.left = None
self.right = None
self.data = data
class BinaryTree: # Simple Binary Tree, no specific implementation of Huffman Coding
def __init__(self, root):
self.root = root #... |
2ec28285d1343c83963ce7a55f409e181a45db4e | YogaMegantoro/Python_Fundamental | /titis/Tugas5.py | 2,532 | 3.796875 | 4 | # # PERCOBAAN 1 MASIH SALAH
# def MainMenu() :
# inputUser = input("Main Menu : \n 1. Pilih Angka\n 2. Lihat List Angka\n 3. Lihat Score Board\n 4. Keluar\n\n Pilih Menu : ");
# return inputUser;
# def pilihAngka(inputAngka) :
# print("Pilihan Angka : ");
# for i in range(len(inputAngka)) :
# p... |
8ad60da7b83cdf7a80f9c2464806dbd8f6500215 | YogaMegantoro/Python_Fundamental | /Solve Modul 1.py | 16,071 | 3.734375 | 4 | ############01Intro to Python#############
#Solve 1
x = 4
y = 3
z = 2
w = ((x/y*z)/(x+y))**2
print("jadi:",w)
#Solve 2
import math
a = int(input("Masukan angka:"))
print("pangkat: ",math.pow(a,2))
#Solve 3
import math
a = 485
tahun = 360
bulan = 30
minggu = 7
hari = 1
tahun = math.floor(a/360)
print(tahun,"tahu... |
a130d859d603387036916041d585392c5c843609 | eugishuge/DojoAssignments | /_Python/1.Python_Fundamentals/Day 1/ComparingArrays.py | 359 | 3.5625 | 4 | list_one = ['celery','carrots','bread','milk']
list_two = ['celery','carrots','bread','milk']
def compare (list_one, list_two):
if (list_one == list_two): # Excelsior! Can you do this in javascript? Why? Why not?
print "you have identical lists"
else:
print "your lists are not t... |
3eff3a64cdd8c1b6b06bf7f9c65d8abfa618ada7 | eugishuge/DojoAssignments | /_Python/1.Python_Fundamentals/Day 1/TypeList v1.py | 408 | 3.71875 | 4 | data = ['magical unicorns', 19, 'hello', 98.98, 'world']
# def output (data):
sum = 0
string = ''
IntCount = 0
StrCount = 0
for ele in data:
if(type(ele) == int) or (type(ele)=='float'):
sum = sum + ele
IntCount += 1
print sum
print IntCount
elif(type(ele)== str):
strin... |
2f889bf1349a07d22795807129a1191ed7e90106 | Epilef-coder/conteo_ciclovias_minvu | /counter/parser/parser.py | 706 | 3.84375 | 4 | import csv
class Parser:
@staticmethod
def parse_data(input_file, data_mapper, delimiter, header: bool = False):
"""
to parse a input file with a specific structure data give by data_mapper
"""
results = []
with open(input_file, newline='', encoding="utf8") as co... |
39f4602aec58ea67b8e95408444a8f241e412d6c | ebenolson/solvertools-rage | /solvertools/normalize.py | 458 | 3.84375 | 4 | import re
NONALPHA_RE = re.compile(r'[^a-z]')
def alpha_slug(text):
"""
Return a text as a sequence of letters. No spaces, digits, hyphens,
or apostrophes.
"""
return NONALPHA_RE.sub('', text.lower())
def unspaced_lower(text):
"""
Remove spaces and apostrophes from text. This is a gentle... |
c6e974db979e3cbb02029cd9e5c3df22ed40a49b | paujjone/Primer | /Primer.py | 1,687 | 3.8125 | 4 | ##########################################################
# P R I M E R #
##########################################################
# A simple python scipt to find prime numbers #
# Ideally this is a good script that can be added #
# to other f... |
1c67198981aa3d122af1b8675703974b867d81ab | hyunsooryu/Data_Engineering | /190403_PANDAS_LEVEL_UP_REVIEW.py | 6,429 | 3.90625 | 4 | import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1, 7, (5, 2)), columns = ['A', 'B'])
print(df)
#SERIES TYPE OF A
print(df['A'])
print(type(df['A']))
#SERIRS TYPE OF B
print(df['B'])
print(type(df['B']))
#Masking is possible in DataFrame like numpy.
print(df[df['A'] > 3])
#what about the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.