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 |
|---|---|---|---|---|---|---|
af2c9210984ebe527c7dbbbee58f3558d18a634e | OlgaLsh/Pyton_course_homework | /1.1/ex_1.1_2.py | 301 | 4.03125 | 4 | # 2 exercise
def leap_year(year):
if year % 4 != 0 or (year % 100 == 0 and year % 400 != 0):
print("Это не високосный год")
else:
print("Это високосный год")
your_year = input("Введите год: ")
year = int(your_year)
leap_year(year) |
f669facabbf66643c92d8309da12945089eb2a95 | skafis/CodeKata | /picture_hide.py | 2,121 | 3.59375 | 4 | #! /usr/bin/env python
#picture_hide.py
#Hidding a message in an image
from PIL import Image
def encode_image (img,msg):
#hiding msg string as characters in ASII values
length = len (msg)
#limit the length of msg to 255
if length > 255:
print ("text too long; dont exceed 255 characters")
return False
if img.... |
30c0ea22a7dd575a30beea8f0159a54f12bcedf4 | Eclipseop/OrbAI | /board.py | 2,038 | 3.5 | 4 | import random
import move
def on_board(index):
return 0 <= index <= 29
# TODO: rewrite this
def count_matches(board_string):
matches = 0
already_matching = set()
for i, color in enumerate(board_string):
if i in already_matching:
continue
moves = move.get_available_moves... |
79e412dd7f4ff6709e3aab5c2a75a1a016c8abb3 | Nomercy-ops/UserRegistrationProblem | /Test/UserValidation.py | 2,486 | 3.734375 | 4 | """
@Author: Rikesh Chhetri
@Date: 2021-07-05
@Last Modified by: Rikesh Chhetri
@Last Modified time: 2021-07-05 07:03:30
@Title : Program Aim is to validate user entered details using regular expression.
"""
import re
from RegexPattern import RegexPattern as regex_pattern
from LogHandler import logger
class ValidateU... |
2f7951dd283e37582c91190985c2f9e42218ecc3 | WillMcIntosh/PythonMegaCourse | /Section2-VariablesDataTypes/age2.py | 186 | 3.65625 | 4 | #! /usr/bin/python
def age_foo(age):
new_age = float(age) + 50
return new_age
age_asked = input("Enter your age: ")
print ("In 50 year, you will be" , int(age_foo(age_asked)))
|
c61b54496ed378c9bcd0e8c825af92cc5728a9fc | WillMcIntosh/PythonMegaCourse | /Exercises/Exercise4.py | 256 | 3.78125 | 4 | def CtoF(temp_C):
if temp_C > -273.15:
temp_F = (temp_C * 9/5) + 32
return temp_F
else:
return "That Temperature is literally impossible."
temperatures=[10,-20,-289,100]
for temp in temperatures:
print(CtoF(temp))
|
5c3a910bfc59b8ce6b4f6e6113c7e11e7177d474 | evgenylahav/refactoring-workshop | /statement_orig.py | 1,415 | 3.59375 | 4 | import math
def statement(invoice, plays):
total_amount = 0
volume_credits = 0
result = "Statement for {}\n".format(invoice["customer"])
format = lambda x: '${:,.2f}'.format(x)
for perf in invoice["performances"]:
play = plays[perf["playID"]]
this_amount = 0
... |
18b10f087dc14b4b797c8572f2b36ff9736f687d | noogler617/python-calculator | /script.py | 328 | 3.828125 | 4 |
class calculator:
def addition(x,y):
added = x + y
print(added)
def subtration(x,y):
subtract = x - y
print(subtract)
def multiplication(x,y):
mult = x * y
print(mult)
def division(x,y):
div = x / y
print(div)
calculator.multiplicati... |
bc99dacc9afe9c08397a058427ca4c8c83e08e80 | Iftakharpy/Data-Structures-Algorithms | /section 13 implementaion_of_Insertion_sort.py | 1,977 | 4.09375 | 4 | #space O(1)
#time O(n^2)
# worst case: Sorted in descending order | O(n^2)
# best case: Nearly sorted | O(n)
def insertion_sort(array,reversed=False):
length = len(array)
#looping from 1-st index to the last index
for i in range(1,length):
#saving the value of i-th index
shifting_value ... |
c5b888d5e03ff34a38d74ae16fb3f4fb3300edd3 | Iftakharpy/Data-Structures-Algorithms | /section 6 merge_2_sorted_arry.py | 1,160 | 3.546875 | 4 | #poject closed
list1=[x for x in range(1,11,2)]
list2=[x for x in range(0,11,2)]
sorted_list=[]
print(list1,list2)
list1_indx = 0
list2_indx = 0
#O(1)
def check_index_error(lst,indx):
try:
a=lst[indx]
return False
except IndexError:
return True
#O(a+b) | a=len(list1),b=len(list2)
whil... |
5640294cdf3d30f67af661fc674b2c35ac60738a | Iftakharpy/Data-Structures-Algorithms | /section 6 reverse_string.py | 256 | 4.15625 | 4 | usr_input = input('Write something : ')
reversed_str = ''
#custom implementation
#O(n) time
#O(n) space
for i in range(len(usr_input)-1,-1,-1):
reversed_str+=usr_input[i]
print(reversed_str)
#built in function
print(input('Write something : ')[::-1])
|
e16db2b0b84353a335e960a77d6938f224a8d075 | haha-ok/OpenCV | /FaceDetection.py | 968 | 3.546875 | 4 | import cv2
"""Cascade classifier object, it will contain the face features"""
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
"""Reading the image"""
img = cv2.imread("C:\\Users\\Akashbhardwaj\\Pictures\\Camera Roll\\giri.jpg", 1)
"""GrayScaling the image"""
gray =... |
f0499de132924504b7d808d467e88af636eb5d27 | KindaExists/daily-programmer | /easy/3/3-easy.py | 1,057 | 4.21875 | 4 |
"""
[easy] challenge #3
Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pkw2m/2112012_challenge_3_easy/
"""
# This can most likely be done in less than 2 lines
# However still haven't figured a way to stop asking "shift" input
def encrypt(string, shift):
return ''.join([chr((((ord(char... |
e9d13f3729747a47736ddd0efe8b25c301e7bcab | KindaExists/daily-programmer | /easy/8/8-easy.py | 618 | 3.875 | 4 |
"""
[easy] challenge #8
Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pserp/2162012_challenge_8_easy/
"""
# With Extra Credit
for n in range(100, 0, -1):
bottle = 'bottles' if n != 1 else 'bottle'
bottle_l = 'bottles' if n-1 != 1 else 'bottle'
print(f'{n} {bottle} of beer on ... |
8922508990b19628df5880741ce7698a432dcd06 | Elena-Dergaus/Learning | /Pyton/is_prime.py | 127 | 3.5625 | 4 | def is_prime(x):
for i in range(2,x):
if x%i==0:
return False
return True
|
39a9f7d6905a7b5db17900047ba94a1da019dd0c | gaogep/LeetCode | /栈/5.根据前中序遍历构造二叉树.py | 1,193 | 3.703125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
# 若... |
01ef92e24380525a13eee4c41d4095019006677e | gaogep/LeetCode | /数组/19.加一.py | 1,035 | 3.734375 | 4 | #
# @lc app=leetcode.cn id=66 lang=python3
#
# [66] 加一
#
# https://leetcode-cn.com/problems/plus-one/description/
#
# algorithms
# Easy (37.87%)
# Total Accepted: 47.8K
# Total Submissions: 124.7K
# Testcase Example: '[1,2,3]'
#
# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
#
# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
#
# 你可以假设除了整数 ... |
f299d2000b6ba12f30939fd06867e46459c52f2d | gaogep/LeetCode | /剑指offer/1.数组中重复数字.py | 1,293 | 3.6875 | 4 | # 在一个长度为n的数组中所有的数字都在0~n-1范围内
# 找出其中重复的数字
arr = [2, 3, 1, 0, 2, 5, 3]
# 注意考虑特殊情况 如数组为空的情况
def repeat(arr):
rep = []
if arr:
meet = []
for num in arr:
if num not in meet:
meet.append(num)
else:
rep.append(num)
return rep
# 优化->将空间复杂度... |
8d3e6dc9cf98b4f4cd2f6819f9a4e315d0405b9a | gaogep/LeetCode | /数组/12.组合总和-ii.py | 1,616 | 3.65625 | 4 | #
# @lc app=leetcode.cn id=40 lang=python3
#
# [40] 组合总和 II
#
# https://leetcode-cn.com/problems/combination-sum-ii/description/
#
# algorithms
# Medium (53.83%)
# Total Accepted: 10.7K
# Total Submissions: 19.7K
# Testcase Example: '[10,1,2,7,6,1,5]\n8'
#
# 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为... |
d84ec922db8eeb84c633c868b5c440b5de7f9445 | gaogep/LeetCode | /剑指offer/28.二叉树的镜像.py | 1,116 | 4.125 | 4 | # 请完成一个函数,输入一棵二叉树,改函数输出它的镜像
class treeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = treeNode(1)
root.left = treeNode(2)
root.right = treeNode(3)
root.left.left = treeNode(4)
root.right.right = treeNode(5)
def showM... |
c864295773774beff0b03ff88f7b3a9defc8594b | gaogep/LeetCode | /剑指offer/66.找出大的数字.py | 218 | 3.8125 | 4 | # 请编写一个方法,找出两个数字中最大的那个
# 条件是不得使用if-else等比较和判断运算符
def getBigger(a, b):
b = a-b
a -= b & (b >> 31)
return a
print(getBigger(10, 7))
|
c2a442b7eca17b794e336891054da90c9568d24f | gaogep/LeetCode | /DsAl/13.BucketSort.py | 309 | 3.53125 | 4 | from random import shuffle
my_list = [i for i in range(30)]
shuffle(my_list)
print(my_list)
def bucketsort(arr):
max_val = max(arr)
bucket = [0 for i in range(max_val+1)]
for val in arr:
bucket[val] = 1
return [i for i in range(max_val+1) if bucket[i]]
print(bucketsort(my_list))
|
253dc3b19cf61fa0359c17e420c076e3ab2645a2 | gaogep/LeetCode | /栈/4.二叉树最大深度.py | 667 | 3.625 | 4 | class Treeroot(object):
def __init__(self, x):
self.val = x
self.left = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
que = []
if root:
que.append(root)
depth = 0
... |
0b3270380de140db9cfe5811f4a661b3ad433df0 | gaogep/LeetCode | /剑指offer/71.高度最小的BST.PY | 587 | 3.640625 | 4 | # 对于一个元素各不相同且按升序排列的有序序列,请编写一个算法,创建一棵高度最小的二叉查找树。
# 给定一个有序序列int[] vals,请返回创建的二叉查找树的高度
class treeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def createMinmalBst(arr):
if not arr:
return
mid = len(arr) // 2
... |
90233e801ae204d17c260c32f126d52529858083 | gaogep/LeetCode | /剑指offer/25.反转链表.py | 771 | 4.15625 | 4 | # 定义一个函数,输入一个链表的头结点
# 反转该链表并输出反转后链表的头结点
class listNode:
def __init__(self, Value, Next=None):
self.Value = Value
self.Next = Next
def insert(self, Value):
next_node = listNode(Value)
while self.Next:
self = self.Next
self.Next = next_node
head = listNode(... |
6502c0cd221435010a37c3d4fefd51f3354258bc | gaogep/LeetCode | /剑指offer/63.和为s的连续正数序列.py | 713 | 3.8125 | 4 | # 输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)
# 例如,输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以打印出3个连续序列
# 1-5 4-6 7-8
def printSerialSeq(number):
if number < 3:
return
start, end = 1, 2
stop = (1 + number) // 2
curSum = start + end
while start < stop:
if curSum == number:
printSeq(start, e... |
a5e599b1f11f16de46a04c0f454de094708da50c | gaogep/LeetCode | /DsAl/12.HeapSort.py | 732 | 3.6875 | 4 | from random import shuffle
my_list = [i for i in range(100)]
shuffle(my_list)
print(my_list)
def adjust(arr, root, rest):
init_val = arr[root]
parent = root
while parent * 2 + 1 < rest:
child = parent * 2 + 1
if child != rest - 1 and arr[child+1] > arr[child]:
child += 1
... |
c9e28695106a8d143cfce7b3b2385b42bf9729c8 | zanewebb/codebreakerspractice | /NewProblemSprint/AddAndSearchWordDataStructure.py | 8,778 | 3.875 | 4 | # got it
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.values = collections.defaultdict(set)
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
... |
d52d3ad533846709d2d0bfadb07a750fe00f9d02 | zanewebb/codebreakerspractice | /Interview Practice/productOfArrayExceptSelf.py | 1,945 | 3.5 | 4 | # so close, shouldnt have tried setting the intial rolling prod to a value other than 1
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
if len(nums) <= 1:
return nums
output = [0] * len(nums)
output[0] = 1
... |
96e9680171c727a5fb41bfbb4373a47805055ddf | zanewebb/codebreakerspractice | /Interview Practice/missingConsecutiveNaturalNum.py | 320 | 3.6875 | 4 |
def solution(nums):
numsDict = set(nums)
# print(numsDict)
for n in range(1,nums[-1] + 1):
if n not in numsDict:
return n
return nums[-1] + 1
if __name__ == "__main__":
print(solution([1,2,3,4,6,7,8,9,10,11,12]))
print(solution([1,2,3,4,5,6,7,8,9,10,11,12])) |
23f8d86a998a94b4d7e702542b34a605c56267a6 | zanewebb/codebreakerspractice | /NewProblemSprint/LongestPalindromeSubstring.py | 1,452 | 3.5 | 4 | # got it this time
class Solution:
def longestPalindrome(self, s: str) -> str:
longest = ""
for i in range(len(s)):
longest = max(self.search(i, i, s), self.search(i, i+1, s), longest, key=len)
return longest
def search(self, l, r, s):
ret = ""
... |
3c817e4a414158cf4e1a004a8b953bd2c0afe8d5 | zanewebb/codebreakerspractice | /Interview Practice/singleNonDuplicate.py | 2,178 | 3.671875 | 4 | # im stupid
# doesnt work
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
hi, lo, i = len(nums)-1, 0, (len(nums)-1)//2
while hi > lo:
i = (hi-lo) // 2
if nu... |
c443a9e49799ff4979b4a10f9f978cf79de09595 | zanewebb/codebreakerspractice | /Fundamentals/validParentheses.py | 4,402 | 3.578125 | 4 |
# 7th time
class Solution:
def isValid(self, s: str) -> bool:
while "()" in s or "[]" in s or "{}" in s:
s = s.replace("{}", "").replace("[]","").replace("()","")
if len(s) != 0:
return False
return True
# slick but less efficient solution
def isVal... |
8fb55c1fff72a590de2404eab11107eb074c03a3 | zanewebb/codebreakerspractice | /Interview Practice/validateBinarySearchTree.py | 2,483 | 3.84375 | 4 |
# third time
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
ret... |
6a27349d8215be402a4f960025538756edcbfffc | SGH-otus/OTUS_Homeworks | /1_Random/1_random.py | 850 | 3.53125 | 4 | import random, math
size_1 = 12 # number of values in range
size_2 = 10000 # how many times to repeat
arr = [0] * size_2 # array of values
n = {} # counter of occurrences
for j in range(size_2):
for i in range(size_1):
arr[j] = arr[j] + (random.random()) # generates floats in range [0;1)
a... |
485cdd2cf9e5e057d190ae68ff5ff700a14da85d | Supermathie/adventofcode | /2021/util.py | 714 | 3.59375 | 4 | #!/usr/bin/env python3
import functools
import io
import operator as op
from itertools import islice
def bits_to_uint(bits):
'''Treats a big-endian bitstream of arbitrary size as an unsigned integer
>>> bits_to_uint(())
0
>>> bits_to_uint((1,))
1
>>> bits_to_uint((0,1))
1
>>> bits_to_uint((1,0))
... |
1c43e20b0b16d913a3728ef7203fc9493207a09a | ogawa18056/100knock | /100/knock00.py | 122 | 3.625 | 4 | str = 'stressed'
str = str[::-1] #始点のインデックス番号:終点のインデックス番号
print(str)
|
f00305f18c8d7b3c33cffd0af5a595f945d339e5 | kmualim/phylo | /UPGMAalgo.py | 4,715 | 3.53125 | 4 | import itertools
class Node(object):
def __init__(self, dist, left=None, right=None):
self.dist = dist
self.left = left
self.right = right
self.nn = None
self.dist_to_NN = None
# prints all the nodes
def __str__(self):
#list = []
return ",".join(str(node) for node in self.__iter__())
# itera... |
3f508261b762fb7d2e66aae50828e31612af7261 | jemper12/ITEA_lesson_igor_gaevuy | /lessons_2/1_task.py | 2,003 | 4.3125 | 4 | """
Создать класс автомобиля. Описать общие аттрибуты. Создать классы легкового автомобиля и грузового.
Описать в основном классе базовые аттрибуты для автомобилей.
Будет плюсом если в классах наследниках переопределите методы базового класса.
"""
from random import randrange as rand
class Car:
engine = 'Gasoline... |
5eac3b9145cde1b5a446051ea1afce36f15aabae | jemper12/ITEA_lesson_igor_gaevuy | /lessons_2/learning.py | 5,514 | 3.703125 | 4 | class Cat:
def __init__(self, name, weight):
self._name = name
self._weight = weight
def __add__(self, other):
return Cat(self._name + other._name, self._weight + other._weight)
# return len(self) + len(other)
def __len__(self):
return 1
cat = Cat('kitty', 3)
cat2... |
038e4b42eb03cd2f40293fff83367f52917741c8 | jemper12/ITEA_lesson_igor_gaevuy | /lessons_6/generator.py | 613 | 3.765625 | 4 | """
123
"""
import random
def random_generator(qnt_of_random_numbers):
start = 0
while start < qnt_of_random_numbers:
start += 1
yield random.randint(0, 100)
for i in random_generator(3):
print(i)
iterator = iter(random_generator(3))
print(next(iterator))
print(next(iterator))
print(ne... |
8a74e3c563dc91284a094d91ed8f25ceac95fb9e | jemper12/ITEA_lesson_igor_gaevuy | /lessons_5/task_1.py | 948 | 3.953125 | 4 | """
Создать декоратор, который будет запускать функцию в отдельном потоке.
Декоратор должен принимать следующие аргументы:
1) название потока
2) является ли поток демоном
"""
from threading import Thread
def simple_decorator(name_thread, is_daemon):
def actual_simple_decorator(func_to):
def wrapp... |
aa027be0ea441ca01e274133f491ee0d5295ce94 | gerald-tetteh/Virtual-World-Arduino | /virtual_world_python.py | 874 | 3.75 | 4 | """
Author: Gerald Addo-Tetteh
The code recieves dat from an arduino
and uses it to control the length of
the virtual cylinder
"""
import serial
from vpython import *
#change the port to be the same as yours
arduino_data = serial.Serial("com4",9600)
measuring_rod = cylinder(length = 6, color = color.yellow, raduis = ... |
1e4e111e7d3b92797457a12485dd4a0751d47120 | markbrown314/advent-of-code-2019 | /day-10/solution.py | 3,127 | 4.0625 | 4 | #!/usr/bin/python3
"""
🎅 Advent of Code 2019 Day #10 Monitoring Station Part 1
by Mark F. Brown <mark.brown314@gmail.com>
"""
import sys
import math
def radians_to_degrees(radians):
""" normalize radians to 360° system"""
angle = math.degrees(radians) + 180
if angle == 360:
return 0
return ... |
fbcec41c40060d5fd32f18847b2b3d2dcd748bc4 | markbrown314/advent-of-code-2019 | /day-4/solution_2.py | 1,633 | 3.75 | 4 | """
🎅🏻
--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching digits
are not part of a larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the following
are now true:
112233 meets these criteria because the digits never decrease ... |
9e34baf591bdc705558c775eb93819d7305bc97e | nikolayparfianovich/PythonSelenium | /Task 3.py | 399 | 3.8125 | 4 | #вариант 2
value = int(input("Введите значение P: "))
value_2 = int(input("Введите значение Q: "))
A=[]
while value < value_2:
value = value * 1.03
A.append(value)
print("Выручка будет {} в тот день, когда P превысит Q ".format(value))
days = (len(A))
print("На это потребуется {} дней".format(days)) |
1cfeed5e8e735af570ad5b8137490689f11f270b | bogosmith/SamplingSimulator | /src/py/test.py | 175 | 3.8125 | 4 |
class Employee:
pass
emp_1 = Employee()
emp_2 = Employee()
print(emp_1)
print(emp_2)
emp_1.first = 'aa'
emp_1.last = 'bb'
print('{}{}'.format(emp_1.first, emp_1.last))
|
d8a26ef2693af5e9ac3c41548aafee6ea218e881 | duckingod/news_analysis | /feature/generate.py | 650 | 3.53125 | 4 | from abc import ABCMeta, abstractmethod
class VectorGenerator:
__metaclass__ = ABCMeta
"""
Generate vector from a string
"""
@abstractmethod
def generate(self, content):
pass
class SimpleNGramGenerator(VectorGenerator):
def __init__(self, n=2):
self.n = n
def generate(... |
6de2e9e33281d8277532b019d94dba7c1bdc2a18 | PacktPublishing/Frank-Kanes-Taming-Big-Data-with-Apache-Spark-and-Python | /popular-movies-dataframe.py | 1,426 | 3.609375 | 4 | from pyspark.sql import SparkSession
from pyspark.sql import Row
from pyspark.sql import functions
def loadMovieNames():
movieNames = {}
with open("ml-100k/u.ITEM") as f:
for line in f:
fields = line.split('|')
movieNames[int(fields[0])] = fields[1]
return movieNam... |
d91338540b84765ea9ddb3221985e828a74c371f | yordan-marinov/brewery_etl | /src/etl/transform.py | 920 | 3.640625 | 4 | # Transforms raw data .
def date_format(date_str):
"""Formats date to yyyy-mm-dd. Returns date as string"""
# The day in row data is not supplied
day = '01'
split_date = date_str.split('/')
# When month is not supplied
if len(split_date) < 2:
month, year = '01', split_date[0]
else... |
1e18b7a08b74e804774882603eabc30829622571 | pchandraprakash/python_practice | /mit_pyt_ex_1.5_user_input.py | 686 | 4.1875 | 4 | """
In this exercise, we will ask the user for his/her first and last name, and
date of birth, and print them out formatted.
Output:
Enter your first name: Chuck
Enter your last name: Norris
Enter your date of birth:
Month? March
Day? 10
Year? 1940
Chuck Norris was born on March 10, 1940.
"""
def userin... |
8f218fa0e2d493433e027da4565c7057a159e155 | pchandraprakash/python_practice | /homework 3.py | 4,176 | 4.25 | 4 | """
Exercise 3.1 – Additional List Practice
Write a function list intersection
that takes two lists as parameters. Return a list that gives the intersection of the two lists- ie, a list of elements that
are common to both lists. Run the following test cases and make sure your results are the same (nb: the orderin... |
d1ef01453cfdc803ac3a23d6fab392cc0380b7e0 | anikom95/LPTHW | /EX45/ex45.py | 3,794 | 4.1875 | 4 | from sys import exit
from random import randint
class Scene (object):
def enter(self):
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = ... |
4cb75f3641915c66854c60183acec3676a0fbb89 | DFRUfO/one-onion | /result.py | 1,330 | 3.59375 | 4 | import tkinter as tk
from tkinter import *
import sys
def Result(datas,filename):
"""统计结果窗口"""
root = tk.Tk()
root.title("选择文件")
root.geometry("420x320")
file_name = tk.Label(root, text='文件名: %s'%filename, justify=tk.RIGHT, width=80)
line = tk.Label(root, text='行数: %s'%datas['line'... |
921f1e9341055c5e7999284ded410283f90d19dc | marcin-bakowski-intive/python3-training | /code_examples/builtin_types/boolean.py | 327 | 3.609375 | 4 | #!/usr/bin/env python3
# Booleans
# https://docs.python.org/3/library/stdtypes.html#truth-value-testing
a = True
b = False
print("%s AND %s == %s" % (a, b, a and b))
print("%s & %s == %s" % (a, b, a & b))
print("%s OR %s == %s" % (a, b, a or b))
print("%s | %s == %s" % (a, b, a | b))
print("NOT %s == %s" % (a, not ... |
f0b876199e5d81c475ef1586a02083a41651db8e | marcin-bakowski-intive/python3-training | /code_examples/advanced/decorators.py | 781 | 3.71875 | 4 | from functools import wraps
def shout(fn):
""" Function appends '!!!' to the original result"""
def decorated(name):
ret = fn(name)
print("Function '%s' returned '%s'" % (fn.__name__, ret))
return "%s!!!" % ret
return decorated
@shout
def hello(name):
return "Hello %s" % name... |
b3cccd80b43cda1068d0990b8823395e7ca570b9 | marcin-bakowski-intive/python3-training | /code_examples/builtin_types/tuples.py | 1,220 | 4.25 | 4 | #!/usr/bin/env python3
# https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
animals = ("dog", "cat")
lookup = ("dog", "horse", "cat")
for lookup_value in lookup:
if lookup_value in animals:
print("'%s' found in animals tuple" % lookup_value)
else:
print("'%s' not ... |
30589fbb59a848e34b7f28db6ef04c5421b60a56 | spncrbck/projects | /trajectoryPhysicsSim.py | 4,574 | 4 | 4 | from math import *
from time import sleep
from termcolor import colored
decimalPlaces = 2
acceleration = -9.81 # gravitational constant = acceleration
def newLine():
return print("")
def introduction():
print(colored("Welcome to spncrbck's Basic Trajectory Calculator.", 'white', attrs=['bold', 'underline']))
... |
c0d6e23c458c56b008aefd27d92bfc331f603a86 | mal-pal/Pong3 | /venv/Pong1pythonfile.py | 3,167 | 4.0625 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("black")
wnTopLine = 300
wnBottomLine = -300
wnRightLine = 400
wnLeftLine = -400
wn.setup(width = 800, height = 600) #00 is in the center, up +300, down=300, left -400, right +400
wn.tracer(0) #stops the window from updating, so you manually update. Inc sp... |
490eeb33c1effd1c86e0389e2f700d2457fbbeac | Dano-drevo/Kiwi.com-_Python-v-kend_-task- | /book_flight.py | 4,446 | 4.125 | 4 | """
Main part of the application. It's resposible for optional arguments and work with them.
Also with help of other modules, it executes all the process of finding, checking and booking a flight, ending with outputing PNR code.
"""
import os
import argparse
from inputs import *
from flights import *
import time
import... |
8600a8963d63f2c4eb2c928b592e508056d7a46b | jackhall/Lyapunov | /lyapunov/demo/motor_demo.py | 8,716 | 3.5625 | 4 | #!/usr/bin/python
#Lyapunov: a library for integrating nonlinear dynamical systems
#Copyright (C) 2013-2018 John Wendell Hall
#
#The author may be reached at jackwhall7@gmail.com.
import sys
import math
import matplotlib.pyplot as plt
import time
import numpy
from itertools import izip
import pdb
import lyapunov
cla... |
fdecf2edc0e41dbd63abc00e613f85400e69a47d | SaySOwha/AI2021_labs | /LAB2_for_student/src2/test.py | 1,234 | 3.53125 | 4 | from MLP_manual import MLP
import numpy as np
from pytorch_mlp import PYTORCH_MLP
import torch
input_nodes = 5
hidden1_nodes = 4
hidden2_nodes = 4
output_nodes = 3
epochs = 10
learning_rate = 0.01
mlp = MLP(input_nodes, hidden1_nodes, hidden2_nodes, output_nodes, learning_rate,epochs)
pytorch_mlp = PYTORCH_MLP()
tra... |
d82efe4dfbb855e866e000564922f7a6392dfe95 | NikeshRaikar/HackerRankPython | /listComprehensions.py | 395 | 3.65625 | 4 | x = input()
y = input()
z = input()
n = input()
list1 = []
for i in range (x+1):
list1.append(i)
list2 = []
for j in range(y+1):
list2.append(j)
list3 = []
for k in range(z+1):
list3.append(k)
# list comprehension code here
list4 = [[i, j, k] for i in list1
for j in l... |
f1501d4453bfbe8b9ac668d0347efd61be61d382 | habibi05/ddp-lab-4 | /main.py | 1,175 | 4.125 | 4 | # DDP LAB-4
# Nama: Habibi
# NIM: 0110220247
# SOAL 1 - Mencetak nama
# Tuliskan program untuk Soal 1 di bawah ini
# Simpan masukan nama kedalam variabel nama
nama = input("Masukkan nama: ")
# Simpan panjang nama kedalam variabel lenNama
lenNama = len(nama)
# Deklarasi variabel iNama dengan nilai 1 untuk kebutuhan pe... |
7a5f5552b062b69368a7f0f4cb02e12cad2dfe37 | vehamar/retirementCalc | /Full Retirement.py | 3,172 | 4.09375 | 4 | def main():
yob = int(input("Enter your year of birth: "))
mob = int(input("Enter the month of birth: "))
# calculates how old you are at the full retirement age
if yob <= 1937:
print("Your full retirement age is 65 and 0 months.")
months = 0
year = 65
elif yob ==... |
b82739886b7bd5e7d35d91b79b87fd0649cd3086 | J-pcy/Jffery_Leetcode_Python | /Medium/247_StrobogrammaticNumberII.py | 1,342 | 4.28125 | 4 | """
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Find all strobogrammatic numbers that are of length = n.
Example:
Input: n = 2
Output: ["11","69","88","96"]
"""
class Solution:
def findStrobogrammatic(self, n):
"""
:type n: int
... |
a8ed1f002d2ce99df4e8761764af1e7a6e8d8777 | J-pcy/Jffery_Leetcode_Python | /Medium/5_LongestPalindromicSubstring.py | 820 | 4.09375 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution:
def longestPalindrome(self, s):
"""
:type ... |
c694af077e0c81bcae5c096de6b1e95f9115a658 | J-pcy/Jffery_Leetcode_Python | /Hard/301_RemoveInvalidParentheses.py | 3,167 | 3.9375 | 4 | """
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Example 1:
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())()... |
168dc62c500050599b5a0729b8233ddab44e85e8 | J-pcy/Jffery_Leetcode_Python | /Medium/659_SplitArrayintoConsecutiveSubsequences.py | 1,359 | 4.0625 | 4 | """
You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.
Example 1:
Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split... |
1e10d7f86e975ef682821785ebe59bc5e499d219 | J-pcy/Jffery_Leetcode_Python | /Medium/418_SentenceScreenFitting.py | 2,233 | 4.28125 | 4 | """
Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
Note:
A word cannot be split into two lines.
The order of words in the sentence must remain unchanged.
Two consecutive words in a line must be separated by a sing... |
68e2e169dea1dde70a2840a8fdda2dd18883d215 | J-pcy/Jffery_Leetcode_Python | /Hard/140_WordBreakII.py | 2,649 | 3.9375 | 4 | """
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume ... |
35242ea727ffb5d291b71700eea7d632f232efb1 | J-pcy/Jffery_Leetcode_Python | /Easy/400_NthDigit.py | 681 | 3.953125 | 4 | """
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9... |
59d65538006384256d07ebce8d26e446f95e27b4 | J-pcy/Jffery_Leetcode_Python | /Hard/272_ClosestBinarySearchTreeValueII.py | 3,059 | 3.859375 | 4 | """
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the ... |
a541c51672bafc9fbb33f4c313fa488d8b94915c | J-pcy/Jffery_Leetcode_Python | /Medium/254_FactorCombinations.py | 1,703 | 4.09375 | 4 | """
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Example 1:
Input: 1
Output: []... |
c75df56aed95a3e74e0436c54ea4e22e669c395f | J-pcy/Jffery_Leetcode_Python | /Medium/75_SortColors.py | 2,518 | 4.25 | 4 | """
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the l... |
a70949ddc105f35000cf6c44947010f717d791ea | Daneidy1807/CreditosIII | /estudio/condi_if/if_2.py | 219 | 4.09375 | 4 | # Ejemplo 2
print("\n############# EJEMPLO 2 ###############")
year = 2020
#year = int(input("¿En que año estamos? "))
if year < 2021:
print("Estamos antes de 2021 !!")
else:
print("Es un año posterior a 2021") |
b2c6dc8fdd2f25b0e7ed668f2af2237120e33184 | Daneidy1807/CreditosIII | /07/ejercicio4.py | 449 | 4.34375 | 4 | """
Ejercicio 4. Pedir dos numeros al usuario y hacer todas las
operaciones básicas de una calculadora y mostrarlo por pantalla.
"""
numero1 = int(input("Introduce un primer número: "))
numero2 = int(input("Introduce el segundo número: "))
print("#### CALCULADORA ####")
print("Suma: " + str(numero1+numero2))
print("... |
fe6501f231bfea3c15e793db2140a7b649260f50 | Daneidy1807/CreditosIII | /ct2/cp_ej2.py | 212 | 3.53125 | 4 | #añadir valores a un alista mientras len sea menor "x"
lista=[]
#llenando lista
for l in range(1,1000):
if lista.__len__()<119:
lista.append(l);
# mostrar lista
print(lista)
print(lista.__len__()) |
59b452de4162c58132f5dfd117684605f38ca119 | Daneidy1807/CreditosIII | /c1_2/03-operadores/asignacion.py | 347 | 3.578125 | 4 | # Operadores de asignacion
edad = 55
print(edad)
edad += 5
edad = edad + 5
edad -= 5
print(edad)
# Operadores incremento y decremento
year = 2021
# Incremento
#year = year + 1
year += 1
# Decremento
#year = year - 1
year -= 1
# Pre incremento
year = 1 + year
# Pre decremento
year = 1 - year
print(year)
"""
year... |
27bc70d0896b88280b82ecb1a81928acf5395e68 | Daneidy1807/CreditosIII | /estudio/condi_if/if_1.py | 230 | 4.0625 | 4 | print("############# EJEMPLO 1 ###############")
color = "verde"
#color = input("Adivina cual es mi color favorito: ")
if color == "verde":
print("Muy bien!!")
print("El color es verde")
else:
print("Color incorrecto !!") |
cf9510c941f431a7ea38519eda8133eb0a870abb | Daneidy1807/CreditosIII | /POO/main.py | 865 | 3.828125 | 4 | class coche:
color= "rojo"
marca= "ferrari"
modelo= "aventador"
velocidad= 300
caballos_f= 500
asientos=2
def setcolor(self, color):
self.color = color
def acelerar(self):
self.velocidad +=1
def frenar(self):
self.velocida... |
a994bdd622273982d4c77834f1ab0e9d3e7217b0 | Daneidy1807/CreditosIII | /Fun-Lis-Dic-ManError/Funcion_Multi.py | 324 | 3.796875 | 4 | def Opreaciones(numero1, numero2):
suma=numero1+numero2
resta=numero1-numero2
multiplicacion=numero1*numero2
division=numero1/numero2
print(f"la Suma es: {suma}")
print(f"la esta es: {resta}")
print(f"la multiplicacion es: {multiplicacion}")
print(f"la division es {division}")
... |
2e79af910ca7cf302ddaeb9f32480d21d865501d | Daneidy1807/CreditosIII | /taller1/Ejercicio_8.py | 141 | 3.734375 | 4 | valor=int(input("Ingresa valor: "))
porcentaje=int(input("Aplica porcentaje: "))
print("el porciento del numero es: ",(valor*porcentaje)/100) |
789d1bcf5970783c0b2e7cb736570598ebcbf821 | Daneidy1807/CreditosIII | /ct1/cp_ej5.py | 182 | 3.90625 | 4 | #muestre todos los nuemros entre dos numeros
n1= int(input("ingresa el primer numero "))
n2= int(input("ingresa el segundo numero "))
for numeros in range(n1,n2):
print(numeros) |
f9690496271282c74fa180f084eed89046dbbdc7 | chaoticgood1/Mind-Map-Panda3D | /src/utils/rect.py | 852 | 3.78125 | 4 |
class Rect():
def __init__(self, x, y, width, height):
halfW = width / 2
halfH = height / 2
self.width = width
self.height = height
self.left = x - halfW
self.right = x + halfW
self.bottom = y - halfH
self.top = y + halfH
def collidesWith(self, rect):
# print(c... |
c999bf9a26db60a33bf8c6e7c0cc5aed4a9bdead | lil-lab/cerealbar | /agent/environment/tree.py | 3,236 | 3.515625 | 4 | """ Contains various types of tree objects.
Classes:
TreeType (Enum): Types of trees. See below for description of the tree types.
Tree (environment_objects.EnvironmentObject): A tree object.
"""
from enum import Enum
from agent.environment import environment_objects
from agent.environment import position
... |
1a263ffb40e61b54e800069a9a41fd055be8adca | nilizadeh/twitter-glass-ceiling | /code/gender_by_name.py | 3,730 | 4.0625 | 4 | import os
import io
import sys
class gender():
def __init__(self, indir, outdir):
self.dir = indir
self.outdir = outdir
self.names_female = {}
self.names_male = {}
def get_names_counts(self):
'''
The names for each year are listed in a file.
Read all the files and combine the info from all the yea... |
bb7b31b34fc66a0d41b29659eb34187969f05b8f | flavio-brusamolin/py-scripts | /list02/ex02.py | 363 | 4.125 | 4 | numbers = list()
option = 'Y'
while option == 'Y':
numbers.append(int(input('Enter a number: ')))
option = input('Keep inserting? Y/N ')
even = list(filter(lambda number: number % 2 == 0, numbers))
odd = list(filter(lambda number: number % 2 != 0, numbers))
print(f'All numbers: {numbers}')
print(f'Even numb... |
e033240eb3b2acaa5031b0e4940731dd36e6afc2 | flavio-brusamolin/py-scripts | /list01/ex19.py | 782 | 4.03125 | 4 | from statistics import mean
people = list()
for i in range(4):
name = input(f'Enter the name of person {i + 1}: ')
age = int(input(f'Enter the age of person {i + 1}: '))
gender = input(f'Enter the gender (Male or Female) of person {i + 1}: ')
people.append({
'name': name,
'age': age,
... |
86ae3c002aa943acebcd763c1ddb170fd987e5c6 | flavio-brusamolin/py-scripts | /list01/ex05.py | 202 | 4.03125 | 4 | width = float(input('Wall width in meters: '))
height = float(input('Wall height in meters: '))
area = width * height
print(f'Area: {area} square meters')
print(f'Amount of ink: {area / 2.0} liters')
|
ed48621526936236768db70af7778c759ce41caa | flavio-brusamolin/py-scripts | /list01/ex12.py | 112 | 3.8125 | 4 | salary = float(input('Enter your salary: '))
print(f'Rise: {salary * 0.1 if salary > 1500 else salary * 0.15}')
|
385f252eeb14b67cdc63f070174e131c48b18f39 | AngelikaH123/test_project | /Hello_function.py | 578 | 3.84375 | 4 | # Define class
class Dog:
# Initialization class
def __init__(self, breed, height, weight):
self.breed = breed
self.height = height
self.weight = weight
self.height_plus_weight = None
# Define method for class
def g(self):
self.height_plus_weight = self.height... |
177ca9f6e54fcaa132393d3911f794b745e2aaf1 | ToxicGLaDOS/quicktionary | /blue.py | 10,110 | 3.8125 | 4 | import cmudict
from pysyllables import get_syllable_count
from helpers import *
vowels = 'aeiouAEIOU'
def b1(s):
"""Does not contain two vowels next to each other"""
for a, b in adjacent_pairs(s):
if a in vowels and b in vowels:
return False
return True
def b2(s):
"""Has exac... |
2d8491624e72ef82b1a1b7179dbc13bbbacb8ebb | juan-g-bonilla/Data-Structures-Project | /problem_2.py | 1,293 | 4.125 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffi... |
e659af27e894ad494a6a2f47a6c646547825c2b2 | manumathew23/python-oops | /inheritance.py | 3,242 | 4.53125 | 5 | # Inheritance
'''
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class. Classes can inherit one or more classes
'''
# Single Inheritance
class User:
name = ""
def __init__(self, name):
... |
2f4e731f24534f9071e1d2b2ac01a4253874a167 | ishaniray/Python-Basics | /fahrenheit_to_celsius.py | 243 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 21:28:21 2017
@author: RAY
"""
fah = float(input("Enter the temperature in Fahrenheits: "))
cel = (fah - 32) * 5 / 9
print("Equivalent temperature in Celsius: " + format(cel, '.2f')) |
31b93a072533214b5f1e592442d6072e1a83c01c | texrer/Python | /CIS007/Lab2/BMICalc.py | 658 | 4.40625 | 4 | #Richard Rogers
#Python Programming CIS 007
#Lab 2
#Question 4
#Body mass index (BMI) is a measure of health based on weight.
#It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters.
#Write a program that prompts the user to enter a weight in pounds and height i... |
4bfad79311e1c7d34856f67da9135a957fa3a511 | Abhishekbhande21/Uplift-Python-resources-Abhishek | /Problems/list.py | 172 | 3.921875 | 4 |
duplicate = [1,2,3, 2, 1,7,6,6,5,4]
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
final_list.sort()
print(final_list) |
08ca2459bcf08b1e1feb3d022bcae86b48a8dbaf | Maingron/GPIO-Projects | /beep2/beep2.py | 1,043 | 3.859375 | 4 | import RPi.GPIO as GPIO
import time
# Variables
mystate = 0
# Init GPIOs
GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.OUT) # Our output pin which then controls our NPN Transistor; #! Pin enabled by default = Power on
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Out input pin which checks if our button is presse... |
0d4bc07fcefdb261aadad08764adcfb43bc6e031 | Farah-H/python_modules | /exception_handling.py | 590 | 3.65625 | 4 | # we will have a look at the practice use acases and implementation of try, except, raise and finally
# we wil create a variable to store file data using open()
try:
file = open('orders.text')
except FileNotFoundError as errmssg: # creating an alias for file not found error in except block
print('Alert someth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.