blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
779ec6a9356ef1c65424163a42ad8cbd6806b2d9 | eugenesamozdran/lits-homework | /200_line_homework.py | 9,580 | 3.734375 | 4 | import random
#defining the order
def player_order(p1,p2):
global order
print("Player 1 rolled ", p1)
print("Player 2 rolled ", p2)
if p1 == "rock" and p2 == "scissors":
print("Player 1 goes first!")
order = 1
elif p1 == "rock" and p2 == "paper":
print... |
0128fa703349d1414a6b4b0610d6afa18329cfc1 | daveclouds/python | /mississippichallenge.py | 128 | 3.53125 | 4 | import time
for second in range (1 , 6):
print(second, "Mississippi")
time.sleep(1)
print('Ready or not, Here I come') |
54eb01f1115e223c35fe1d1ee49d1561d2f960c1 | megaprokoli/data-glasses | /drawer/text_drawer.py | 1,288 | 3.71875 | 4 | from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from drawer.drawer import Drawer
class TextDrawer(Drawer):
def __init__(self, content):
super().__init__(content)
def draw(self, disp):
print("drawing text ({})".format(self._content))
disp.clear()
dis... |
63dd4aeff91caf6065f0d502647a66e2d3c3f129 | philipdongfei/Think-python-2nd | /Chapter11/rotate_pairs.py | 513 | 3.84375 | 4 | from rotate import rotate_word
def make_word_dict():
d = dict()
fin = open('words.txt')
for line in fin:
word = line.strip().lower()
d[word] = None
return d
def rotate_pairs(word, word_dict):
for i in range(1, 14):
rotated = rotate_word(word, i)
if rotated in word_... |
4297e89b3c6500d3b0fd16953346b79db44e7edb | rafaelperazzo/programacao-web | /moodledata/vpl_data/129/usersdata/230/44242/submittedfiles/al7.py | 178 | 3.65625 | 4 | # -*- coding: utf-8 -*-
n=int(input('Digite valor de n: '))
soma=0
for i in range (1,n,1):
if n%i==0:
soma=soma+i
if soma==n:
print('sim')
else:
print('não') |
dc096b12fda1e7bf1441045c001b56adaac3bb2b | bhirtzer/crypto | /vigenere.py | 641 | 3.96875 | 4 | import string
from helpers import alphabet_position, rotate_character
def encrypt(text, key):
new_text = ''
count = 0
k = 0
for i in text:
if i.isalpha():
k = alphabet_position(key[count])
new_text = new_text + rotate_character(i, k)
count = ((coun... |
52a073b1375aceeb57482327183cd6caa0f8ae9b | kaviraj333/pythonprogram | /58.py | 136 | 3.6875 | 4 | p,q=map(int,raw_input().split())
list=[int(a) for a in raw_input().split()]
if p and q in list:
print "yes"
else:
print "no"
|
70f87a62bf044d68c1f0e89182243b4375e0b2a8 | glennlopez/CS50.HarvardX | /pset6/2022/sandbox/upper.py | 183 | 3.921875 | 4 | from cs50 import get_string
usr_str = get_string("Before: ")
print("After: ", end="")
for i in usr_str:
print(i.upper(), end="")
print()
print(f"Lower cased: {usr_str.lower()}") |
68a56526eea5530a1ce436414fc25ec737c2c7a3 | tebeka/pythonwise | /euler24.py | 1,504 | 3.71875 | 4 | #!/usr/bin/env python
''' Solving http://projecteuler.net/index.php?section=problems&id=24
Note that Python's 2.6 itertools.permutations return the permutation in order so
we can just write:
from itertools import islice, permutations
print islice(permutations(range(10)), 999999, None).next()
And it'll work mu... |
1085aed0df68240ace4cd4d67b65921c030c73b6 | zooonique/Coding-Test | /괄호회전.py | 660 | 3.5 | 4 | def solution(s):
answer = 0
sample = ['()','{}','[]']
case = s
for cnt in range(len(s)):
# n번 rotate
case = case[1:len(s):]+case[0]
tmp = case
while case:
if sample[0] in case:
case=case.replace(sample[0],'')
elif sampl... |
fc8aa3a629eb87ac062e23ad828a8f1b7ab03a2b | rprasai/Assignment2 | /Car.py | 407 | 3.8125 | 4 | import car_class
def main():
model_year = input("Enter the Car Year Model: ")
make = input("Enter the car Make:")
car = car_class.Car(model_year, make)
accele(car)
brake(car)
def accele(car):
for count in range(1, 6):
car.accelerate()
print(car.get_speed())
def brake(car):... |
f4a8f8b169238a92af87a2503dec467900e4763a | soneyaa/Python-Assignment | /Python Assignment/module3/exercise10/pattern1_12.py | 275 | 3.953125 | 4 | n=int(input())
i=1
for i in range(n):
for j in range(n-i):
print("* ",end='')
if(i==n-1):
continue
else:
print()
for i in range(n+1):
for j in range(i):
print("* ",end='')
print()
|
ee2d0f86464490aa66cf8a2f7d26308fbc6b05a9 | OSGeoLabBp/tutorials | /hungarian/python/code/point2d.py | 2,269 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Point2D(object): # object a bázis osztály
""" kétdimenziós pontok osztálya
"""
def __init__(self, east = 0, north = 0): # __init__ a konstruktor
""" Pont inicializálás
:param east: első koordináta
... |
fd003e4bbf4384a0a0f24e9724761391349e77be | Apondon/testtest | /demo/16-list.py | 277 | 4.09375 | 4 | # Using a list comprehension, create a new list called "newlist" out of the list "numbers",
# which contains only the positive numbers from the list, as integers.
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7 ,10]
newlist = [int(num) for num in numbers]
print(newlist) |
75b361e15026eeedff1a4e96aca30ec817056b24 | chielk/beautiful_data | /ex1/visualize.py | 4,141 | 3.65625 | 4 | import sys
from operator import itemgetter
import matplotlib.pyplot as plt
def i(name):
"""Convert a cars.csv file name to an index."""
if name == "model":
return 0
elif name == "mpg":
return 1
elif name == "cylinders":
return 2
elif name == "horsepower":
return 3
... |
180d4e246357c0bf9966d24f75361acbfbe1e970 | ThomasLee94/firecode | /is_palindrome.py | 766 | 4.125 | 4 | def is_palindrome_recursive(text: str, forward=None, backward=None) -> bool:
# set forward and backward
if forward == None and backward == None:
forward = 0
backward = len(text) - 1
# check if forward is less than backwards
if forward >= backward:
return True
# sk... |
341110cb4216e6be3f520aa02338470f513ab43b | rlatmd0829/algorithm | /알고리즘풀이/21.07.03/괄호의값.py | 1,008 | 3.515625 | 4 | node = list(input())
stack = []
answer = 0
for i in node:
if i == ')':
t = 0
while len(stack) != 0:
top = stack.pop()
if top == '(':
if t == 0:
stack.append(2)
else:
stack.append(2 * t)
b... |
45ad7f54414b2072b389cc0d6180187da3be7b4f | Hidorikun/Calculator-Converter-for-numbers-in-base-2..16- | /Code/src/domain/entities.py | 29,850 | 3.859375 | 4 |
class ProgramException(Exception):
pass
class BaseNumException(ProgramException):
pass
class BaseNum(object):
def __init__(self, value, base):
'''
This method initialises the object:
:args:
value - string representing the value
... |
b64c75bc84fe397f35e38079363c67f9376f1e58 | workherd/Python006-006 | /week07/c07_08.py | 526 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/2/13 10:34
# @Author : john
# @File : c07_08.py
# nonlocal 访问外部函数的局部变量
# 注意start的位置, return的作用域和函数内的作用域不同
def counter2(start=2):
def incr():
nonlocal start
start += 1
return start
return incr
c1 = counter2(5... |
34cec2557cce19ae82f0deedd764f3952b00715e | warrenwrate/python_scripts | /reduce.py | 753 | 3.90625 | 4 | import functools
# initializing list
lis = [ 4 , 3, 5, 6, 2 ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
# using reduce to compute maximum element from list
print ("The maximum element of the list is : ",end="")
print (f... |
2a58d5e6ee5239649181dead9bcabeaf4540367b | levindoneto/lanGen | /utils/LangModels.py | 2,542 | 4.09375 | 4 | ''' Function for creating n-grams.
@Parameters: List: sequence, Integer: n (type of the n-gram).
@Return: List: n-grams.
'''
def generateNGrams(sequence, n):
ngrams = []
for i in range(len(sequence)-n+1):
ngrams.append(sequence[i:i+n])
return ngrams
''' Function for counting how often each ... |
5adfa549b335a7ab18ac1eed1b0eb05cf3b970d2 | bmclay/python_notes | /lists_tuples.py | 3,219 | 4.6875 | 5 | """
Collections are an ordered or un-ordered group of elements.
lists are set using square brackets []
inside of the square brackets you can have a series of elements (some data type).
To define a list, create a variable and open up square brackets with some elements inside
Lists can contain values of differe... |
c58ed18dccefd2a136729dd56473dcacae4b575a | evasu9582/python | /pawn.py | 268 | 3.671875 | 4 | def pawn(N,P):
cn=[]
if N:
for i in range(N,P+1):
cn.append(i)
else:
for j in range(N,P):
cn.append(j)
decision=max(cn)
return ('Block',decision*2) if decision%2==0 else ('White',decision*2)
print(pawn(0,8)) |
4a9677b6e10b1e7c7258a982d04bd6d27376350a | ttuttlej/Python-Asteroids-Game | /Asteroids - Mass Effect/Asteroids/images/Asteroids.py | 17,136 | 4.21875 | 4 | """
File: asteroids.py
Original Author: Br. Burton
Designed to be completed by others
This program implements the asteroids game.
"""
import arcade
import random
import math
from abc import ABC
from abc import abstractmethod
# These are Global constants to use throughout the game'
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 60... |
c4d0c138d0e9dc05355c08e8d871b2931bf91885 | sachin16495/Question_Category_Classification | /question_classification_naive_bayes.py | 2,920 | 3.5 | 4 | import os
import string
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
from nltk.tokenize import sent_tokenize, word_tokenize
#Load Excel file from the c... |
55c1abc266ffcefe3accc27a38a3bbbc5e76e266 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2490/60624/266108.py | 221 | 3.734375 | 4 | def func8():
nums1 = list(map(int, input()[1:-1].split(",")))
nums2 = list(map(int, input()[1:-1].split(",")))
temp = [val for val in nums1 if val in nums2]
print(sorted(set(temp)))
return
func8() |
c79b12b96ce84f0e742231bc7837e1fab693ebd6 | priyamehta2772/cracking-the-coding-interview | /Unit 2_ Linked List/2.2_Kth_from_last.py | 1,226 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 18:42:03 2019
2.2 Return Kth from last
@author: PriyaMehta
"""
class LinkedListNode:
def __init__(self, val, link):
self.value = val
self.link = link
class LinkedList:
def __init__(self, h):
self.head = h
def print_list(self... |
3a981164be19b9f03018a6e2725366fa68181387 | anfernee84/Learning | /python/for-while.py | 173 | 3.625 | 4 | i = 1000
while i > 100:
print(i)
i /= 2
for j in 'hello world':
if j == 'a':
break
print(j * 2, end = '' )
else:
print('There`s no letter "a" ') |
4e7e2d4c7c9a03189893bca6f2fb65f60a384f75 | Nchekwube1/pong-game-py | /pong.py | 1,324 | 3.640625 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong game by @FrancisUnekwe")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("lightblue")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.g... |
96dc3231e53d5a24a1a9eb504c1a94afbcc070a0 | MarcinSzyc/EDX_Introduction-to-Computer-Science- | /polysum.py | 235 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 14:42:14 2018
@author: Marcin
"""
import math
def polysum(n,s):
area = (0.25*n*(s*s))/(math.tan(math.pi/n))
perim = n*s
return round((area + math.pow(perim,2)),4) |
e6fcac86e6cfbc1b845f027feb6e950190ffde76 | sidmen/python | /basics_and_misc/calendar_text.py | 240 | 4.03125 | 4 | import calendar
year = input('Year: ')
month = input('Month (num): ')
start_day = calendar.TextCalendar(calendar.SUNDAY)
# cal = calendar.month(int(year), int(month))
cal = start_day.formatmonth(int(year), int(month))
print(cal)
|
e7deb6b66b482c79957988709fb4d80fd9a0aec5 | RoyalTux/Tic_Tac_Toe | /tic_tac_toe.py | 4,492 | 4.1875 | 4 | X = "X"
O = "O"
EMPTY = " "
TIE = "draw"
NUM_SQUARES = 10
#выводим название игры в начале
def game_name():
print("\n\t\t\tThe game - Tic Tac Toe")
#функция для задания вопроса о первом ходе
def who_first(question):
answer = None
while answer not in ("y", "n"):
answer = input(question).lower()
... |
d24abba1f19ba86b8ac121305deb505c4e21c60c | mikej803/digitalcrafts-2021 | /python/homework/lets-speak.py | 574 | 3.78125 | 4 |
# A = "4", E = "3", "G" = "6", "I" = "1", "O" = "0", "S" = "5", "T" = "7"
# userinput = Whats up
# output = Wh475 up
userInput = input("Type your sentence? ")
output = ""
for char in userInput:
if char == "a":
output += "4"
elif char == "e":
output += "3"
elif char == "g":
o... |
24acdcb080bfaa6fb17c34b08debfe1154e27039 | syudaev/lesson01 | /lesson01_task02.py | 398 | 4.0625 | 4 | # перевод числа секунд в часы, минуты, секунды
# формат вывода - чч:мм:сс
number_seconds = int(input("Введите количество секунд:"))
my_hours = number_seconds // 3600
my_minutes = (number_seconds - my_hours * 3600) // 60
my_seconds = number_seconds % 60
print("%02d:%02d:%02d" % (my_hours, my_minutes, my_seconds))
... |
4f2fccbe0ae1cc04750fa406d3594584c1ecf612 | snimrod/RepoAnalyzer | /outputStats.py | 5,297 | 3.640625 | 4 | import csv
from engineer import Engineer
def all_same_char(s):
n = len(s)
for i in range(1, n):
if s[i] != s[0]:
return False
return True
def all_qe_marks(s):
n = len(s)
for i in range(1, n):
if s[i] != '?' and s[i] != '!':
return False
return True
... |
2726d03db151046c1091b93d14a5593c2d368e52 | vrillusions/python-snippets | /ip2int/ip2int_py3.py | 963 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Asks for an IPv4 address and convert to integer.
In Python v3.3 the ipaddress module was added so this is much simpler
"""
import sys
import ipaddress
__version__ = '0.1.0-dev'
def main(argv=None):
"""The main function.
:param list argv: List of arguments ... |
27b96f58a6ea04996ba1a63ab7ca886cf0a2dbec | gill-chen/Code-Exercises | /Code Exercises/Calculating total salary.py | 350 | 3.890625 | 4 | def computepay(h,r):
h = float(h)
r = float(r)
if h > 40:
overtime = h -40
overpay = overtime * 1.5 * r
grosspay = overpay + (40 * r)
else
grosspay = h * r
return grosspay
hrs = raw_input("Enter Hours:")
rate = raw_input("Enter rate:")
p = computepay(hr... |
c9de209f7acddd5edece8f913740a3fc21769b7e | tasawar-hussain/fyyur | /utils.py | 454 | 4.09375 | 4 | import re
def is_valid_phone(number):
""" Validate phone numbers like:
1234567890 - no space
123.456.7890 - dot separator
123-456-7890 - dash separator
123 456 7890 - space separator
Patterns:
000 = [0-9]{3}
0000 = [0-9]{4}
-. = ?[-. ]
Note: (? = optional) - Learn more: http... |
5bc5cb7726ed9eec5db57fe14068323a9ad1b5d9 | mattl1598/Project-Mochachino | /Python files/tkinter learn.py | 2,378 | 3.5 | 4 | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: matthewl9
#
# Created: 06/02/2018
# Copyright: (c) matthewl9 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
from ... |
74e8d703b4e1e1364484fa490fe7c8645ab016c9 | ShawDa/Coding | /coding-interviews/25复杂链表的复制.py | 1,317 | 3.734375 | 4 | # -*- coding:utf-8 -*-
__author__ = 'ShawDa'
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead == None:
return None
... |
64f7238a8133358a78417b03204ad0ba98f272a5 | jinweijia/CodeSamples | /OtherCoding/fortuneOrRuin.py | 3,251 | 4.09375 | 4 | """Question:
Johnny is a gambler, and he really likes to play for high stakes in casinos. Recently,
his favorite casino is advertising a new betting game, where one can possibly win a fortune! (What
they are not advertising is that you can also lose everything.) The rules are the following: the
player bets a certain a... |
c0c85e0ef0aeeaa8578d74ecfd84b8a6cebf800f | changediyasunny/Challenges | /leetcode_2018/981_time_based_key_value.py | 2,332 | 3.953125 | 4 | """
981. Time Based Key-Value Store
Create a timebased key-value store class TimeMap, that supports two operations.
1. set(string key, string value, int timestamp)
Stores the key and value, along with the given timestamp.
2. get(string key, int timestamp)
Returns a value such that set(key, value, timestamp_prev) was... |
48c5fcb15ed1e88e930cbf5638b257f36d40bef8 | nickedes/Areeba | /RSA/encrypt.py | 1,756 | 3.8125 | 4 | from random import randrange
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in xrange(3, int(num ** 0.5) + 2, 2):
if num % n == 0:
return False
return True
def egcd(a, b):
"To find gcd of two numbers."
if a == 0:... |
9b6bd3a6e789e2621db65bbc1b99ca3d2ec47c20 | alex75042/les6 | /les6_job3.py | 2,093 | 3.890625 | 4 | #3. Реализовать базовый класс Worker (работник).
#● определить атрибуты: name, surname, position (должность),
# income (доход);
#● последний атрибут должен быть защищённым
# и ссылаться на словарь, содержащий
#элементы: оклад и премия, например,
# {"wage": wage, "bonus": bonus};
#● создать класс Position (должно... |
b43511403e059ed78fb0b3b6f876901c960c8009 | Ashish-kumar-pradhan/python | /python basic/loop.py | 134 | 3.578125 | 4 |
i=1
while i<=5:
print("Ashish",end="")
j=1
while j<=4:
print(" kumar",end="")
j=j+1
i=i+1
print() |
74ccd2161f8f827fc27abd4691679512f8d7c586 | rafaelperazzo/programacao-web | /moodledata/vpl_data/16/usersdata/74/7155/submittedfiles/triangulo.py | 626 | 3.84375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a = input('Primeiro valor')
b = input('Segundo valor')
c = input('Terceiro valor')
a1 = b+c
a2 = b**2+c**2
h = a**2
if a1>a:
print('S')
if a == b and b == c:
print('Eq')
print('Ac')
elif b == c and a =! c
print('I... |
4215ba2f757aebd58cdf7de5554b2e3ce4f3d024 | lyy901207/Data-Structure | /stack.py | 729 | 4.3125 | 4 | #用数组实现一个顺序栈
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
#向栈顶插入项
self.items.append(item)
def pop(self):
#返回栈顶的项,并从堆栈中删除该项
self.items.pop()
def clear(self):
#清空堆栈
del self.items[:]
def is_empty(self):
#判断堆栈是否为空
return len(self.items) == 0
def get_size(se... |
4c0b090c10048f2014baeb8ea38bc37c449938b6 | priyankaauti123/Python | /string/generate_n_char.py | 335 | 3.703125 | 4 | n=int(input("Enter no:="))
ch=input("Enter character:=")
def generate_n_char(ch,n):
str=[]
for i in range(n):
str.append(ch)
print ''.join(str)
generate_n_char(ch,n)
def histogram(lst):
for i in lst:
generate_n_char('*',i)
list_1=[4,7,2]
histogram(list_1)
[lambda x:generate_n_char('... |
2dfb290f41dc0ea642c0cae27add2ce27db454ca | Sigafoos/advent | /2016/python/day1.py | 1,351 | 3.75 | 4 | from copy import deepcopy
def walk(part = 1):
position = [0, 0]
facing = 'N'
visited = []
with open('../input/input1.txt') as fp:
for line in fp: # only one
directions = line.split(', ')
for direction in directions:
turn = direction[0]
steps = int(direction[1:])
if (facing == 'N' and turn == 'R') or ... |
dd65d446a97ab5420ff90813f9f07e9c2ffc937f | mikedeeno84/mikedbyte | /first_factorial.py | 585 | 4.0625 | 4 | def FirstFactorial(num):
result=1
while num>0: # loop down from starting number multiplying each number by the result variable and decrementing the num variable on each iteration
result=result*num
num=num-1
return result
print FirstFactorial(raw_input())
#Have the function FirstFactorial(num)... |
9241ace26552ab624a1beab2a867cba7e94eca88 | prateek1404/AlgoPractice | /CareerCup/FB/swap.py | 88 | 3.875 | 4 | def swap(a,b):
a = a^b
b = a^b
a = a^b
return (a,b)
(a,b) =swap(10,11)
print a,b
|
72fa57018d0eb94b044c0c8b5cf7db9e78a024cd | akashgupta97/Image-Recognition-System-for-Cats- | /Main file.py | 20,306 | 3.8125 | 4 |
# # Image Recognition System
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
get_ipython().magic('matplotlib inline')
# ## 2 - Overview of the Problem set ##
#
# **Problem Statement**: given a dataset ("d... |
afb92296f90e7ced30c27eb65afb444d832f7458 | Siumnoor/Django_classWorks | /GPA.py | 459 | 3.953125 | 4 | a = int (input("Enter Marks : "))
if (a>=80 and a<=100):
print("A+")
elif (a>=75 and a<=79):
print("A")
elif (a>=70 and a<=74):
print("A-")
elif (a>=65 and a<=69):
print("B+")
elif (a>=60 and a<=64):
print("B")
elif (a>=55 and a<=59):
print("B-")
elif (a>=50 and a<=54):
print("C+")
elif (... |
6778614ff38a44feab76fdaa231838fd583d964b | luamnoronha/cursoemvideo | /ex.045.py | 1,292 | 3.734375 | 4 | import random
print('vamos jogar! jokempo!')
print('=='*20)
print('''escolha umas da jogadas a seguir
[1] PEDRA
[2] TESOURA
[3] PAPEL ''')
player = int(input('qual sua jogada: '))
opc = [1, 2, 3]
pc = random.choice(opc)
if player == 1 and pc == 2:
print('a jogada do pc foi TESOURA e a sua PEDRA, PARABÉNS VOCÊ É ... |
d4380956795987ff74be6d01e875d13ac800a8b2 | rashmikamath/data_structures | /iocamp1/longest_common_subsequence.py | 451 | 3.53125 | 4 | def lcs(str1, str2):
m = len(str1)
n = len(str2)
dp = [[0 for i in range(n+1)] for j in range(m+1)]
for i, s1 in enumerate(str1):
for j, s2 in enumerate(str2):
if s1 == s2:
dp[i+1][j+1] = 1+dp[i][j]
else:
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
return dp[-1][-1]
text1 = "abcde"
text2 = "ace"
p... |
887b25315af5764c1f924e7b7a72c67ecdb5b320 | davidchoi-dev/fastcampus_python_basic | /section06.py | 7,260 | 3.515625 | 4 | # Section06
# 파이썬 함수식 및 람다(lambda)
# 함수 정의 방법
# def 함수명(parameter):
# code
# 함수 호출
# 함수명(parameter)
# 함수 선언 위치 중요
# 예제1
def hello(world):
print("Hello", world)
hello("Hayong")
# 예제2
def hello_return(world):
val = "Hello " + str(world)
return val
abc = hello_return("Hayong!!!")
print(abc)
# 예... |
c00eb9d5d02376796c7e3552a9ee8e542042cb5c | SamGoodin/c200-Assignments | /CodeDemonstrations/InClass1.py | 593 | 4.46875 | 4 | #Create a program to give opinion on input color
while 0 < 1:
color = (input("What is your favorite basic color? ")).lower()
if color == "red" or color == "blue" or color == "yellow":
print("That is a primary color.")
elif color == "black" or color == "white":
print("That color is basic.")
... |
c3e5e38290c99e7ec8e7a5bf00c452fbc4caad84 | mzmudziak/py-umcs | /zaj2/zadania/zad4.py | 437 | 3.65625 | 4 | #!/usr/bin/python
import sys
def patternSearch(pattern, f):
for line in f:
if pattern in line:
print line
def read():
file_lines = ''
while True:
l = sys.stdin.readline()
if l == "":
return file_lines
file_lines += l
if sys.argv[2] == '-':
p... |
402bd4d9b3d51e4c025e5070ced11e1343f42afc | nigomezcr/Programming-Basics | /06-Arrays/1-arrays-example-I.py | 724 | 3.890625 | 4 | """
Description: Arrays in python.
"""
import numpy as np
#Built-in arrays in numpy:
N = 11 #number of elements
a = np.zeros(N)
b = np.ones(N)
c = np.arange(N)
d = np.eye(N)
#To fill our array
for i in c:
a[i] = 2*i+1
#Operations with the array: average
suma = 0
for i in c:
suma += a[i]
... |
cab09bb76642d241407047839f2793e5f4061647 | tospolkaw/CloanGit_PythonHealthcare | /py_files/0107_tensorflow_image.py | 7,639 | 3.734375 | 4 | """
Code, apart from the confusion matrix,taken from:
https://www.tensorflow.org/tutorials/keras/basic_classification#
"""
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
... |
890a2cb8e115d6dcf769700e468f91eb91225213 | atulgupta9/DigitalAlpha-Training-Programs | /Day3/prog1.py | 1,582 | 3.6875 | 4 | #1. Given the rent data file, write a Python program to do the following.
#a) Calculate the mean, mode and median of the rents.
#b) Generate a frequency distribution and print the table
#c) Print the cumulative frequent distribution
#d) Calculate 25th, 50th and 75th percentile values
#e) Calculate variance and coe... |
eaae699afb15ebac7069895a5424738ad3ca5e97 | maurus56/exercism | /python/reverse-string/reverse_string.py | 145 | 3.78125 | 4 | def reverse(input=''):
"""With extended slicing
string[start:end:step]
"python"[3::] = "hon"
"""
return input[::-1] |
8938a8b03318a4a9762165f5638be45c03c523f4 | lcbm/cesar-is-cool | /matemática-discreta/laGrange_interpolation.py | 671 | 3.6875 | 4 | os.system('cls')
print("Interpolação: Método de LaGrange\n")
x = sp.symbols('x')
xn_fn = [float(x) for x in input("Digite coordenadas dos pontos no formato 'x, fx': ").split(',')]
xn = xn_fn[0::2]
fn = xn_fn[1::2]
coordenadas = list(zip(xn,fn))
print(f"As coordenadas inseridas (xn,fn) f... |
28607212510d1e1998c1e83e2f3f5b9dc2c731b4 | cad75/GBLessons | /Lesson_7_HW_1.py | 802 | 3.828125 | 4 | class Matrix:
def __init__(self, all_titels):
self.all_titels = all_titels
def __str__(self):
result = ''
for i in self.all_titels:
for el in i:
result += str(el) + ' '
result += '\n'
return result
def __add__(self, other):
re... |
65a4f6f6e493dc68909113aaceaf3431d3626341 | rkreml/Python-Course | /Week 1/Assignment 1.4.b.py | 859 | 3.859375 | 4 | ## Name: Robert Kreml
## Date: September 6, 2019
## Class: EPSY 5200
##Study Drill 6 from Exercise 4 from LP3TH by Zed Shaw
print("I want to do some calculations.")
print("This is my attempt at using Python as a calculator using a .py script.")
print("Specifically this one will be using python to store and retrieve i... |
28b6de8d6f77f2413898de1e9acea450e22952b8 | mish-a14/python_functions | /question1.py | 871 | 4.15625 | 4 | # 1) (Concept: Calling a function that has already been defined.)
# The following function definition defines a function called pokemon_contains that will tell you if a single
# incoming_letter passed into this function exists in the word "pokemon". This function returns a boolean
# (ie., True or False). Your task i... |
30763452117929da6469318c1462bc4cf32ace96 | DaniAkiode/portfollio | /Python Practice/Software Development/Somthing floats.py | 123 | 3.75 | 4 | anything = float(input("Give me a number:"))
something = anything ** 2.0
print(anything, "to the power of 2 is", something) |
3cccefb8ea1c4564c3961ecd8c7658ea72ccff84 | Man0j-kumar/python | /dict_key_sum.py | 166 | 3.515625 | 4 | d1={'a':1,'b':2,'c':4}
d2={'a':3,'b':3,'d':8}
for i in d1:
for j in d2:
if(i==j):
d1[i]=d1[i]+d2[j]
d2.update(d1)
print(d2)
|
5978e19ac3f68aad2e26d779e04e75ef4541fbfb | ICB-DCM/pyPESTO | /pypesto/logging.py | 1,902 | 4.0625 | 4 | """
Logging
=======
Logging convenience functions.
"""
import logging
def log(
name: str = 'pypesto',
level: int = logging.INFO,
console: bool = True,
filename: str = '',
):
"""
Log messages from `name` with `level` to any combination of console/file.
Parameters
----------
name:... |
dc3654a282490f6aa8045b86bec0d7dfc9bef37c | avinashraghuthu/Trees | /bst_check.py | 837 | 3.984375 | 4 | from tree_utils import *
from sys import maxint
def is_bst(root):
min_int = -maxint -1
return is_bst_util(root, min_int, maxint)
def is_bst_util(root, min_val, max_val):
if not root:
return True
if root.data < min_val or root.data > max_val:
return False
return is_bst_util(root.left, min_val, root.data) ... |
9ed9c26c05f38513362d91505c4d6f9adc002fa5 | sqw3Egl/Code_Academy | /Games_of_Chance/games.py | 1,062 | 3.890625 | 4 | import random
import time
money = 100
num = random.randint(1, 10)
#Casino Games - functions
def coin_flip():
bank = money
bet = input('How much do you want to bet? \n')
call = input('Make the call - type "heads" or "tails"... \n')
print('OK mate, ' + call + ' it is! \nFlipping the coin........')
... |
62cc0d48162ae0a9bef59c9cf20a8dd9e1e088e8 | chenxu0602/LeetCode | /2608.shortest-cycle-in-a-graph.py | 1,349 | 3.734375 | 4 | #
# @lc app=leetcode id=2608 lang=python3
#
# [2608] Shortest Cycle in a Graph
#
# @lc code=start
from collections import defaultdict
class Solution:
def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
# Assume a node is root and apply bfs search,
# where we recode the:
# ... |
a64aa03070144d88b6cee9034b4130655a5f61d6 | byrozaurowe/Computer-Science-studies | /4th semester/Python course - Python/Laboratorium 3/python5.py | 273 | 3.75 | 4 | def list_powerset(lst):
return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]])
def powerset(s):
return list(map(list, list_powerset(list(s))))
def main():
print(powerset([1, 3, 5, 7]))
if __name__ == "__main__":
main() |
95f34fccaa743bc000aa9bec0203db24009d00e2 | chenhaoxxx/pythonProject1 | /prac 4/lists_warmup.py | 599 | 4.0625 | 4 | numbers = [3, 1, 4, 1, 5, 9, 2]
numbers[0]#output 3
print(numbers[0])
numbers[-1]# output 2
print(numbers[-1])
numbers[3] #output 1
print(numbers[3])
numbers[:-1] # output 3,1,4,1,5,9
print(numbers[:-1])
numbers[3:4] #output 1
print(numbers[3:4])
5 in numbers # output True
print(5 in numbers)
7 in numbers # output F... |
ef0c94149ed13b8c6185293379d50e985e9af691 | tdrvlad/Fractals | /Sierpinsky_Triangle.py | 2,620 | 3.546875 | 4 | import graphics
import random
import time
import sys
#________________Parameters________________
scale = 500
start_triangle = ((1,1),(0.5,0),(0,1)) #Coordinates are in mirror
win=graphics.GraphWin("Figure",scale,scale)
win.setBackground("white")
colour=graphics.color_rgb(random.randint(0,255),random.randint(0,255),... |
dc153441de367d5c39d0362ad52a94b7781a8a07 | JonneyLloyd/CS4227 | /code/packages/tests/test_encryption.py | 604 | 4 | 4 | import unittest
from framework.encryption import Encryption, FernetEncryptor
class Tests(unittest.TestCase):
def encrypt_test(self):
text = "Hello World!"
encryption = Encryption(FernetEncryptor())
encrypted = encryption.encrypt(text)
self.assertTrue(text != encrypted)
se... |
acb3ef6799b675d0cc82b4b06bd7e2c1ea31d432 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/2321.py | 1,565 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# untitled.py
#
# Copyright 2014 Phiradet Bangcharoensap <phiradet@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either ve... |
80428764f62fdfa335ef61101b82a0fb3a908361 | jwxingfpp/learnPython | /assign.py | 898 | 4.15625 | 4 | # coding: utf-8
"""
@Time : 2019/8/8 上午9:57
@Author : xingjiawei
---------------------------
python赋值机制
"""
def new_print(x):
print 'value assign to:{}'.format(id(x))
def print_seperator():
print '-'*20
def print_info(s1, s2):
new_print(s1)
new_print(s2)
print s1 is s2
print_seperator()... |
32caad0eb0a8c6b0e7807d75a6ef6bacdfc2036a | dward2/UnitTestingClass | /temp_conversion_script.py | 155 | 4 | 4 | temp_c_str = input("Enter temperature in degC: ")
temp_c = float(temp_c_str)
temp_f = 1.8 * temp_c + 32
print("The temperature is {} degF".format(temp_f))
|
6a0db2c2585e0461abe0f0763d4da6cccd75ea92 | SecretAardvark/Python | /pycrashcourse/ex10-7.py | 381 | 4.1875 | 4 | while True:
print("Enter two numbers to be added.")
print("type 'q' to quit.")
first_number = input("First number? ")
if first_number == 'q':
break
second_number = input("Second number? ")
try:
result = int(first_number) + int(second_number)
except ValueError:
print("Y... |
5abdd95588c47155715d01f577536c7fc9b5e42b | bhushanwalke/DSA_Python | /Sorting/shellsort.py | 758 | 3.828125 | 4 | __author__ = 'bhushan'
def shellSort(items_list):
sublist = len(items_list)/2
while sublist > 0:
for start_pos in range(sublist):
gap_insertionSort(items_list, start_pos, sublist)
print(sublist, "", items_list)
sublist = sublist/2
def gap_insertionSort(items_list, start... |
656870d4ba887cfd702750093ddb916cbc97eb9c | AnumHassan/Class-Work | /Table.py | 95 | 3.5 | 4 | able = int(input("Enter a No:" ))
for i in range(1,11):
print(able, "x",i,"=",str(able*i)) |
3a650742b98ce29296d00ce4e0be035e797a7db0 | snehilk1312/dataStructuresAlgorithms | /1_dataStructures/06_linkedListReversalRecursion.py | 1,002 | 4.25 | 4 | class Node:
# initializes a node
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
# initializes Linked List
def __init__(self, head=None):
self.head = head
# prints the LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data)
te... |
df79183023f114b28bafd5ac95c728a75d637353 | chris09/Python-tut | /PACKT_Learning_Python/03/looping.py | 800 | 3.703125 | 4 | for number in [1,2,3,4]:
print(number)
for number in range(5):
print(number)
surnames = ['Rivest', 'Shamir', 'Adleman']
for surname in surnames:
print(surname)
for position, surname in enumerate(surnames):
print(position, surname)
people = ['Jonas', 'Julio', 'Mike', 'Mez']
ages = [25, 30, 31, 39]
fo... |
6c51badb250e80e625115387ac81d808a6043aa2 | lowpro59/CS7641_SLearn | /decision_tree.py | 581 | 3.53125 | 4 | from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0)
input_file = "adult_data.csv"
column_labels = ["age","workclass","fnlwgt","education","education-num","marital-status","occupation","relationship","race","sex",
"capital-gai... |
743b135a40b527c6d28ce0e2799b4ce38f7ccc37 | vladgithub211/pythonlesson3 | /dzpythonlesson3/3.py | 219 | 3.84375 | 4 | list = ['Олег','Дима','Вася','Рома']
print(list)
remove_element = list.pop(2)
print('Не приглашены:', remove_element)
remove = list.pop(0)
print('Не приглашены:', remove)
|
c586b1eb3dbe05af79e51172c666a80664b05655 | AyrtonDev/Curso-de-Python | /Exercicios/ex039.py | 854 | 3.765625 | 4 | from datetime import date
cores = {
'limpa' : '\033[m',
'lilas' : '\033[4;35m',
'vermelho' : '\033[1;31m'
}
nasc = int(input('Ano de nascimento: '))
data = date.today().year
idade = data - nasc
print('Quem nasceu em {} tem {} anos em {}'.format(nasc, idade, data))
if idade < 18:
print('Aind... |
66aebf9f8756c7b4c2b0ddf4bd81f38412d28bdd | rangapv/pybasics | /array1.py | 134 | 3.828125 | 4 | #!/usr/bin/env python
a = [2,3,4,5]
print(a)
b = []
for i in a:
if ( i % 2) == 0:
print(i)
b.append(i)
print(b)
|
dcbbf7a80e9f36d917e9074687bdb5b425759fd4 | vinuv296/luminar_python_programs | /pythonProject2/flow_controls/pattern/pattern_3.py | 99 | 3.640625 | 4 | y=10
for i in range(0,y):
for j in range(y,0,-1):
print(j,end=" ")
print()
y-=1 |
0bcdcbed8c00b6df607edac8540a87dd295a6b79 | Murad255/Sharaga_ | /Моделирование МРС/Лаба_1/ЛАБ_1/kinematics.py | 8,353 | 3.640625 | 4 | import numpy as np
class Vector:
"""Vector represents translation and stores 3 values
Attributes
----------
x
The x value
y
The y value
z
The z value
"""
def __init__(self, x, y, z):
"""
Parameters
----------
x
The x... |
2adbdeaf4910f88e4cddb9f9a1dcd7c057e49990 | SebastianCiesla/JSP-2020 | /Lista 6/trojkat.py | 1,192 | 3.671875 | 4 | #-------------------------------Zadanie 1-----------------------------------
import math
def boki(a,b,c):
#sprawdzanie czy trojkat o takich bokach istnieje
l=[a,b,c]
maxn=max(l)
l.remove(maxn)
ls=sum(l)
#Sprawdzanie warunku na istnienie trojkata
if maxn<=ls:
#obwód
... |
750a9491b7eea753913486cb467385535a9c7e00 | HUGGY1174/MyPython | /Chapter02/P02.py | 273 | 4 | 4 | first = int(input("첫번째 수를 입력하시오:"))
second = int(input("두번째 수를 입력하시오:"))
third = int(input("세번째 수를 입력하시오:"))
avg = (first + second + third)/3
print(first, second, third, "의 평균은", avg, "입니다.")
|
ac8fa91f33cd0b2d7a6a0f05e5cd63f071549448 | Borgaard/sf-wdi-51-assignments | /brandon-vagarioustoast/week-8/codebar/codebar.py | 1,682 | 4.03125 | 4 | class Member():
def __init__(self, full_name):
self.full_name = full_name
def introduce(self):
print(f'My name is {self.full_name}')
class Student(Member):
def __init__(self, full_name, reason):
Member.__init__(self, full_name)
self.reason = reason
class Instructor(Membe... |
068587a234ca6f946ad11de2a45856538ef263d7 | gyang274/leetcode | /src/0800-0899/0814.prune.bt.py | 889 | 3.6875 | 4 | from config.treenode import TreeNode, listToTreeNode
class Solution:
def recursive(self, node):
l = 0
if node.left:
l = self.recursive(node.left)
if not l:
node.left = None
r = 0
if node.right:
r = self.recursive(node.right)
if not r:
node.right = None
retu... |
081bd103d01857d85d9732cd4ab7e3d1600e53ef | miguelgamendes/SDM_CPAB | /Clients/Healthclub.py | 728 | 3.578125 | 4 | from User import User
# a health club can insert TRAINING data for a patient
# who is a member of the health club
class Healthclub(User):
def __init__(self, ID, insertion_key):
attributes = {str(ID), "HEALTHCLUB", "TRAINING"}
User.__init__(self, ID, attributes)
self.insertion_key = inserti... |
cfa407011010aef35888744f742138b1e5497c2a | kyosukekita/ROSALIND | /Algorithmic Heights/median.py | 379 | 3.625 | 4 | file = open('Desktop/Downloads/rosalind_med.txt').read()
n=int(file.split()[0])
A=[int(i) for i in file.split()[1:n+1]]
k=int(file.split()[-1])
def qSort(a):#クイックソート
if len(a) in (0,1):
return a
p=a[-1]
l=[x for x in a[:-1] if x<=p]
r=[x for x in a[:-1] if x>p ]
return qSort(l)+[... |
48fec799ce043385b02ab40c91624278759d4dd4 | UX404/Leetcode-Exercises | /#1295 Find Numbers with Even Number of Digits.py | 784 | 4.3125 | 4 | '''
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contain... |
07ec5fca7ed56878155a0583b7a5eac171d5bca7 | jiajingchen/Projects-for-Rice-Coursera-Programming-in-Python | /Yahtzee/Done1.py | 3,927 | 3.734375 | 4 | """
Planner for Yahtzee
Simplifications: only allow discard and roll, only score against upper level
"""
# Used to increase the timeout, if necessary
import codeskulptor
codeskulptor.set_timeout(20)
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequ... |
0cf23397c4927300df972ca4cf92b541a496e7b5 | kofinyx/test | /chap2_2.py | 366 | 3.703125 | 4 | '''
Created on Jan 19, 2018
@author: ehagan
'''
# more tuple unpacking
print(divmod(20, 8))
t = (30, 8)
print(divmod(*t))
# unpacking by prefixing an arg with *
for x in [(2, 4), (1, 2, 5), (3, 6, 1, 4)]:
print('Adding {1} items to get {0}'.format(sum(x), len(x)))
*head, a, b = range(6)
print(head)
... |
b53a824e340838d6025308d26b30ab6d4d1cde21 | a1ip/Checkio-26 | /absolute_sorting.py | 445 | 4.125 | 4 | #Input: An array of numbers , a tuple.
#Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.
def checkio(numbers_array):
abs_numbers = sorted([i if i > 0 else -i for i in numbers_array])
answer = []
for absnum in abs_numbers:
if absnum not in numbers_ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.