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 |
|---|---|---|---|---|---|---|
4da9a78205d4aab5a7b5cb88611d636e92fcca91 | nishizumi-lab/sample | /python/basic/re/finditer.py | 522 | 3.75 | 4 | # -*- coding: utf-8 -*-
import re
data = 'abcdefghijklmnabcdefghijklmn'
pattern = re.compile(r'd.*?g') # パターン式の定義(dで始まりgで終わる最短の文字列)
match_datas = pattern.finditer(data)# パターン式との一致判定
for match in match_datas:
print( match.group() ) # 一致したデータを表示
print( match.start() ) # 一致した開始位置を表示
print( match.end() ) # 一... |
c3fcceea355dbdbf410a608f38ee84c343ed0239 | nishizumi-lab/sample | /python/opencv/opencv-old/zoom.py | 640 | 3.53125 | 4 | # -*- coding:utf-8 -*-
import cv2
import numpy as np
def main():
# 画像の取得
im = cv2.imread("fubuki.png")
# 画像の拡大・縮小
h = im.shape[0] # 画像の高さ
w = im.shape[1] # 画像の幅
resize1 = cv2.resize(im,(w*2,h*2)) # 画像を2倍に拡大
resize2 = cv2.resize(im,(w/2,h/2)) # 画像を1... |
f32b7b9b2923ef4b2f4bf2fa7acf96c6f79fb4b6 | nishizumi-lab/sample | /python/basic/List/itertools.py | 1,869 | 3.9375 | 4 | import itertools
# 3P2の順列:1, 2, 3の玉が入った袋から2つの玉を取り出す
# 第2引数を省略すると3P3 (= 3!)になる
num_list = [1, 2, 3]
new_list = []
for num in itertools.permutations(num_list, 2):
new_list.append(num)
print(new_list)
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# 1, 2, 3と書かれた玉が入った袋から、2つの玉を区別なく同時に取り出す (3C2の組み合わせ)
num_list ... |
58d34b965e55dc57480d62718a6de206ae68bb37 | nishizumi-lab/sample | /python/basic/Class/constructor.py | 382 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# クラスの定義
class MyClass():
# コンストラクタ(初期化メソッド)
def __init__(self, text):
self.text = text
def main():
# コンストラクタでインストラクタ変数を初期化
my = MyClass("Nyan Pass!")
# インストラクタ変数を表示
print(my.text)
if __name__ == "__main__":
main()
|
63ac3c0052490de621f8596e8d52f51e3aea3312 | nishizumi-lab/sample | /python/scraping/02_bs4/sample03.py | 1,130 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
def table_to_csv(file_path, url, selecter):
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
# セレクタ(タグ:table、クラス:test)
table = soup.findAll("table", selecter)[0]
trs = table.findAll("t... |
b2eb47334a63860d472823f9a3bc5814ee3780e7 | mariagarciau/EjAmpliacionPython | /ejEscalera.py | 795 | 4.375 | 4 | """Esta es una escalera de tamaño n= 4:
#
##
###
####
Su base y altura son iguales a n. Se dibuja mediante #símbolos y espacios. La última línea no está precedida por espacios.
Escribe un programa que imprima una escalera de tamaño n .
Función descriptiva
Complete la función de staircase. staircase tiene los sigu... |
3522927ed8c6e794396706ec5f5c8779c73fa383 | cloudersjun/python_pro | /hello_world.py | 367 | 3.75 | 4 | # a = [5, 3, 45, 3, 4]
#
#
# def quicksort(a):
# if len(a) <= 1:
# return a
# l = [x for x in a[1:] if x <= a[0]]
# r = [x for x in a[1:] if x > a[0]]
# return quicksort(l) + [a[0]] + quicksort(r)
#
#
# print str(a)
# a = quicksort(a)
# print str(a)
import datetime
print datetime.datetime.strpt... |
983a91b383f63fedd4ba16a2cb8f2eaceaffc57a | rlugojr/FSND_P01_Movie_Trailers | /media.py | 926 | 4.3125 | 4 |
'''The media.Movie Class provides a data structure to store
movie related information'''
class Movie():
'''The media.Movie constructor is used to instantiate a movie object.
Inputs (required):
movie_title --> Title of the movie.
movie_year --> The year the movie was released.
... |
69bc1a768917c8545ec939fc1f931eaf488d05fa | EmillyLopes/Projetos_python | /area.py | 507 | 3.65625 | 4 | A,B,C = input().split(" ")
A = float(A)
B = float(B)
C = float(C)
Atri = A * C / 2
Acir = 3.14159 * C ** 2
Atrap = (A + B) * C / 2
Aquad = B ** 2
Aret = A * B
print("TRIANGULO: {:.3f}\nCIRCULO: {:.3f}\nTRAPEZIO: {:.3f}\nQUADRADO: {:.3f}\nRETANGULO: {:.3f}".format(Atri, Acir,
... |
52b63c5cced274b037fd2aaaf67f28e71f8d90df | EmillyLopes/Projetos_python | /funcao.py | 416 | 3.734375 | 4 | def calcular_pagamento (str_horas, str_hora):
horas = float(str_horas)
taxa = float(str_hora)
if horas <= 40:
salario = horas*taxa
else:
h_excd = horas - 40
salario = 40*taxa+(h_excd*(1.5*taxa))
return salario
str_horas= input('Digite as horas: ')
str_taxa=input('Digite a taxa: ')
total_salario =... |
65f06d23f3290bb7af3ffc0495705b2a51adab8f | EmillyLopes/Projetos_python | /reforma na sala.py | 186 | 3.703125 | 4 | H= int(input())
C= int(input())
L= int(input())
Apiso= L*C
Vsala= H*C*L
Aparede= (2*H*L)+(2*H*C)
print("Área da sala: {}, Volume: {}, Área das paredes: {}".format(Apiso,Vsala,Aparede)) |
a6661855dcf44d732b7020fd5b54047999a58c84 | egreenius/ai.python | /Lesson_4/hw_4_7.py | 1,271 | 4.09375 | 4 | '''
Home work for Lesson 4
Exercise 7
7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом:
for el in fact(n). Функция отвечает за получение факториала числа,
а в цикле необхо... |
ddb6e2b6bd78f654a9a74065898f8b44c8628de2 | egreenius/ai.python | /Lesson_7/hw_7_1.py | 5,612 | 3.96875 | 4 | '''
Home work for Lesson 7
Exercise 1
1. Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()),
который должен принимать данные (список списков) для формирования матрицы.
Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы.
П... |
b79f79e1f9631e96d485282e5024d7bc917a01bf | egreenius/ai.python | /Lesson_4/hw_4_6.py | 1,879 | 4.28125 | 4 | '''
Home work for Lesson 4
Exercise 6
6. Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание,
что создаваемый цикл... |
c8ad0b1cd319d0647fed0320f10bf9b682203523 | apeterson91/fundamentals-of-computing | /introduction to python/memory.py | 1,910 | 3.53125 | 4 | # http://www.codeskulptor.org/#user38_ZCNxFdMNgtrLchB.py
# implementation of card game - Memory
# implementation of card game - Memory
import simplegui
import random
state=0
cards= []
exposed=[False]*16
turns=0
tempone=100
temptwo=100
# helper function to initialize globals
def new_game():
global cards,exposed
... |
e93bd1d37465c9976728899914d468b036f3b1f3 | kannan5/Algorithms-And-DataStructures | /Queue/queue_py.py | 829 | 4.21875 | 4 | """
Implement the Queue Data Structure Using Python
Note: In This Class Queue was implemented using Python Lists.
List is Not Suitable or Won't be efficient for Queue Structure.
(Since It Takes O(n) for Insertion and Deletion).
This is for Understanding / Learning Purpose.
"""
cl... |
b8767de04143e1b937109ffa22002b9b7ff01639 | kannan5/Algorithms-And-DataStructures | /sorting/selection_sort.py | 516 | 4.03125 | 4 | import sys
arr1 = [5,7,2,5,6,8,3]
def selection_sort(arr):
current_idx, len_arr = 0, len(arr)
while current_idx < len_arr - 1:
smallest_idx = current_idx
for x in range(current_idx +1, len_arr):
if arr[smallest_idx] > arr[x]:
smallest_idx = x
arr[smallest... |
8e5c3324d1cf90eb7628bf09eca7413260e39cb7 | kannan5/Algorithms-And-DataStructures | /LinkedList/circularlinkedlist.py | 2,310 | 4.3125 | 4 | "Program to Create The Circular Linked List "
class CircularLinkedList:
def __init__(self):
self.head = None
def append_item(self, data_val):
current = self.head
new_node = Node(data_val, self.head)
if current is None:
self.head = new_node
new_node.next... |
3a88e472c67a7ebf1a87da77ca86384f35664822 | kannan5/Algorithms-And-DataStructures | /LinkedList/doublylinkedlist.py | 2,331 | 3.828125 | 4 |
class DoublyLinkedList:
def __init__(self):
self.head = None
def append_item(self, data_val):
current = self.head
while current.next is not None:
current = current.next
current.next = node(data_val, current)
def add_by_index(self, data_val, index):
curr... |
e14d613c0530913277cfe4d10bbb43838d7404f4 | Tiger-C/python | /python教程/第二集.py | 1,077 | 3.828125 | 4 | #python教程第二集(一个一个运行)
# message="Hello everybody."
# print(len(message))# 显示元素有多少个字母组成
# print(message[15])#从0开始一共有16个字母,最后一个是第15个
# print(message[0:7])#输出从第0个字母开始的7个字母
# print(message[8:7])#无法输出
# print(message[:9])#默认输出从0开始的9个字母
# print(message[4:])#默认输出从4到最后一个字母
# print(message.count('l'))#l出现过几次
# print(message.coun... |
193052cadf507e12e1d77e76fff1989b3e9e396a | Tiger-C/python | /python教程/第七集.py | 1,238 | 4.25 | 4 | #第七集
# #``````````````````````start`````````````````````````````````````
# nums=[1,2,3,4,5]#此行必开
# for num in nums:
# if num == 3:
# print('Found!')
# break #停止
# print(num)
# for num in nums:
# if num == 3:
# print('Found!')
# continue #继续
# print(num)
# for num in nums:
# for le... |
38636bab16d889fae1c893d91e8ccf9136d09a6b | MMGit64/HolidayCruise | /HolidayCruise.py | 17,101 | 3.859375 | 4 | def flight_Destination_Price(numOf_Passengers, flightDist_KM, direct_Flight, flightDuration_DAYS, Airline, Airport_Terminal): ##Defines conditions for the flight to holiday destination where the cruise will sail from
FlightPrice = (numOf_Passengers * (flightDist_KM * direct_Flight * flightDurati... |
504b483a9e10efb2b34a3d07f320beda9e9c1f11 | johnfrye/SoftwareCarpentryBootcamp | /day1/partA/countChars.py | 713 | 3.765625 | 4 | import sys
import string
# Grab the input
sentence_1 = sys.argv[1]
sentence_2 = sys.argv[2]
# one character in common,
# sentence 1 has 1 unique character
# sentence 2 has 2 unique characters
#sentence_1 = "She sells seashells by the seashore."
#sentence_2 = "Someone yell out a sentence?"
alphabet = string.lowercas... |
04bc69b2549aa2d254dee08735392d67a59bccb4 | Job-Colab/Coding-Preparation | /Day-27/Purvi.py | 481 | 3.59375 | 4 | class Solution:
def judgeCircle(self, code: str) -> bool:
x, y=0, 0
for i in range(0, len(code)):
if(code[i]=='l' or code[i]=='L'):
x=x-1
elif(code[i]=='r' or code[i]=='R'):
x=x+1
elif(code[i]=='u' or code[i]=='U'):
... |
7c6e52e76e1b2169f03edb0a7bd896028fcfe361 | louisbaum/AM205-Numerical-Methods | /hw2/APMTH205 HW2p2.py | 1,995 | 3.5625 | 4 | """
Created on Fri Sep 30 16:37:35 2016
@author: Louis
"""
import numpy
import scipy
import matplotlib.pyplot as plt
"""
Part A)
to check for a 0 diagonal element it takes the product of the diagonals and determines it the result is 0
"""
def fsolve(L,b):
check = 1
n = len(L)
for i in r... |
7edac04a3461774f558cd3b18f289b1360b57de5 | xingyunsishen/Python_CZ | /50-存放家具.py | 1,328 | 3.71875 | 4 | #-*- coding: utf-8 -*-
#定义一个家类
class Home:
#初始化对象
def __init__(self, new_area, new_info, new_addr):
self.area = new_area
self.info = new_info
self.addr = new_addr
self.left_area = new_area
self.contain_items = []
def __str__(self):
msg = "\033[5;37;40m 房屋总面... |
522aa71688162a99bee7f7e5f925f5b89a483990 | xingyunsishen/Python_CZ | /32-有参函数.py | 184 | 3.78125 | 4 | #-*- coding:utf-8 -*-
def sum_2_nums():
a = int(input("请输入第一个数:"))
b = int(input("请输入第二个数:"))
print("%d+%d=%d" %(a, b, a+b))
sum_2_nums()
|
68a7f314fbaa79d5bb1308465ffc32e08b8ca6df | xingyunsishen/Python_CZ | /temp.py | 4,517 | 3.59375 | 4 | #-*- coding:utf-8 -*-
class Person(object):
"""人的类"""
def __init__(self, name):
super(Person, self).__init__()
self.name = name
self.gun = None#用来保存枪对象的引用
self.hp = 100
def install_bullet_to_gun(self, clip_temp, bullet_temp):
"""把子弹装到弹夹中"""
#弹夹.保存子弹(子弹)
clip_temp.save_bullet(bullet_temp)
def instal... |
32b81febcc393249b8d5825e65b78663c9e973bf | xingyunsishen/Python_CZ | /15-剪刀石头.py | 550 | 3.890625 | 4 | #-*- coding: utf-8 -*-
import random
#1.提示获取用户输入
player = int(input("请输入0:剪刀 1:石头 2:布"))
#2.电脑随机数
computer = random.randint(0,2)
#3.判断用户的输入,并显示对应的结果
if (player == 0 and computer == 2) or (player == 1 and computer == 0) or (player == 2 and computer == 1):
print("player win~~~~gagaga")
print("computer=%d" %(comp... |
c367c139d0802a16b9b6677b1222b4cdb7ca0428 | xingyunsishen/Python_CZ | /68-new方法.py | 908 | 3.609375 | 4 | #-*- coding:utf-8 -*-
class Dog(object):
def __init__(self):#init方法只负责初始化
print('---init方法---')
def __del__(self):
print('---del方法---')
def __str__(self):
print("---str方法---")
return "对象描述信息"
def __new__(cls): #new方法只负责创建
print(id(cls))
print('---new方法---'... |
4210e23ec19821b73e780735c080a7619a68dcb6 | xingyunsishen/Python_CZ | /17-break.py | 134 | 4.03125 | 4 | #-*- coding:utf-8 -*-
num = 1
while num <= 50:
print("++++")
if num % 3 == 1:
# break
print(num)
num += 1
|
a4265c4e472b9ac4f39aebc3f1f1480fee25cfaf | xingyunsishen/Python_CZ | /65-4S-store.py | 327 | 3.71875 | 4 | #-*- coding:utf-8 -*-
class Car(object):
#定义车的方法
def move(self):
print('---车在奔跑---')
def stop(self):
print('---停车---'):
# 定义一个销售车的店类
class CarStore(object):
def order(self):
self.car = Car()
self.car.move()
self.car.stop()
|
03b1ff13856c5d60fdcaf16916aca5f5acc6dff4 | xingyunsishen/Python_CZ | /51-对象属性和方法.py | 830 | 4.125 | 4 | #-*- coding:utf-8 -*-
'''隐藏对象的属性'''
"""
#定义一个类
class Dog:
def set_age(self, new_age):
if new_age > 0 and new_age <= 100:
self.age = new_age
else:
self.age = 0
def get_age(self):
return self.age
dog = Dog()
dog.set_age(-10)
age = dog.get_age()
print(age)
dog.a... |
8255932c9bda63c910d3f913a554f56bde9ae48f | xingyunsishen/Python_CZ | /25-名片管理系统.py | 416 | 4 | 4 | #-*- coding: utf-8 -*-
#1.打印菜单选项
print("=="*6, "名片管理系统", "**"*6)
print("1.查询")
print("2.添加")
print("3.删除一个成员")
print("4.修改")
print("5.退出")
print("=="*40)
while True:
#2.获取用户输入
num = int(input("请输入操作序号:"))
#3.根据用户输入执行对应的功能
if num == 1:
new_name=input("请输入要查找的名字:")
|
d0317041da8a9a9b1ba2aca189c06c02a246699f | fkrhtmq123/Python | /Ch06/6-1.py | 497 | 3.65625 | 4 | def GuGu(n):
print(n)
result = GuGu(2)
def GuGu(n):
result = []
result.append(n*1)
result.append(n*2)
result.append(n*3)
result.append(n*4)
result.append(n*5)
result.append(n*6)
result.append(n*7)
result.append(n*8)
result.append(n*9)
return result
print(GuGu(2))
i = 1... |
b419b706b46a4bd90b36b2a4ebb4e0b2154ae994 | erfanSW/ply-parser | /TreePrinter.py | 4,131 | 3.5 | 4 |
import AST
def addToClass(cls):
def decorator(func):
setattr(cls,func.__name__,func)
return func
return decorator
def tprint(l, s):
print "| " * l + s
class TreePrinter:
@addToClass(AST.Node)
def printTree(self, l):
raise Exception("printTree not define... |
6589224c8524b4f7187c4f24ef7d93bb4d5dac6e | ayachim/Python | /trianglerec.py | 390 | 3.859375 | 4 | #definir si les trois nombres saisit correspondent a un
#triangle rectangle ou ton
a=[]
print("Saisir les 3 cotés du triangle")
for i in range(3):
a.append(input())
a.sort(reverse=True)
h=int(a[0])**2
b=int(a[1])**2
c=int(a[2])**2
if int(h) == int(b) + int(c):
print("C'est un triangle rectangle !")
else:
... |
236e25224f01546a4a030757c99c849d178ac8d9 | HarshalGarg/opencv-python | /a.py | 99 | 3.671875 | 4 | n=input()
listt=[]
nn=int (n)
for i in range(0,nn):
x=input()
listt.append(x)
print (listt) |
5258ec7c3ecebab9284e207acd96eba627170ce7 | GPAlexis/palechor | /happy/media/media/repaso.py | 248 | 3.5625 | 4 | nombre = "kenneth"
apellido = 'rivas'
numero = 6.5
boleano = True
lista = [5,5.5,10]
tupla = (5,5.5,10, "hola")
dic = {'llave': nombre}
lista.append("numero")
print nombre
print apellido
print numero
print boleano
print lista
print tupla
print dic |
2917b91e7801f4a881cd33caf4e6cfb77325089f | PedroRuizCode/imageNoiseFiltering | /noise.py | 3,360 | 3.671875 | 4 | ''' Image processing and computer vision
Alejandra Avendaño y Pedro Ruiz
Electronic engineering students
Pontificia Universidad Javeriana
Bogotá - 2020
'''
import cv2 #import openCV library
import numpy as np #import numpy library
class noise: #C... |
16611048e70ee94c4fbb49ed8fde92ca2fc9ab41 | Shravan98/Credit-Card-Fraud-Detection | /final/logistic-regression.py | 5,119 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Credit Card Fraud
# We will be detecting credit card fraud based on the different features of our dataset with 3 different models. Here is the Logistic Regression one.
#
# We're looking to minimize the False Negative Rate or FNR.
#
# Since the dataset is unbalanced, we can ... |
4174970c4a82e72c15fc243ccdafb2aa4e4a6a5a | ritik047/Gui-python-examples | /voting.py | 1,271 | 3.671875 | 4 | from tkinter import *
from tkinter import messagebox
#count=0
#global count1=0
count=0
def hello():
global count
print("HY Ritik this side !!!")
messagebox.showinfo("Welcome Superpower2020","Welcome to the Detention Centre\n#Copied from China")
count =count+1
def chutiya():
... |
952b645f8ba4d792112e905bc646976bec523670 | blairsharpe/LFSR | /LFSR.py | 1,205 | 4.125 | 4 | def xor(state, inputs, length, invert):
"""Computes XOR digital logic
Parameters:
:param str state : Current state of the register
:param list inputs: Position to tap inputs from register
Returns:
:return output: Output of the XOR gate digital logic
:rtype int :
"""
... |
d833b000e1a39c2b142242c4694876a24e2a6d2a | davidwittenbrink/uno | /uno.py | 10,516 | 3.546875 | 4 | import random
from collections import namedtuple, defaultdict
from datetime import datetime
COLORS = RED, YELLOW, BLUE, GREEN = ['R', 'Y', 'B', 'G']
BLACK = 'b'
SKIP = 'S'
DRAW_2 = '+2'
COLOR_WISH = 'C'
DRAW_4 = '+4'
CHANGE_DIRECTION = 'CD'
ARBITRARY_KIND = '_'
CARDS_PER_PLAYER = 7
PUT = 'put'
DRAW = '... |
9797712be1f4256e65ed9c9ed4586d1d5051cec0 | heretic314/Cryptography_Scripting | /PrimeFactorsAndGenerators.py | 940 | 3.734375 | 4 | n=int(input("Enter an integer p: "))
modulus = n
x = n-1
Array = []
print("Factors of p = " +str(n)+ " is/are:")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
i=i+1
n... |
ef851f6f1a17eacfe0489d9bc5954d39066588a1 | GHIaayush/Phylogenetic-Tree | /phylo.py | 8,180 | 3.671875 | 4 |
#importd the genome file
from genome import*
#imports the tree file
from tree import*
"""
File:phylo.py
Author: Aayush Ghimire, Date:05/2/2018,
Purpose: To construct phylogenetic trees starting from
the genome sequences of a set of organisms.
"""
"""
This function ask the user for the input f... |
d3d01d0cecf4477d34af951dd48f60e046fa9e1b | robquant/adventofcode2017 | /01/december1.py | 1,131 | 3.609375 | 4 | def test_captcha_part1():
assert captcha("1122", next_digit_wrap) == 3
assert captcha("1111", next_digit_wrap) == 4
assert captcha("1234", next_digit_wrap) == 0
assert captcha("91212129", next_digit_wrap) == 9
def test_captcha_part2():
assert captcha("1212", halfway_around_wrap) == 6
as... |
2ebd32c3b5edd8c210c996b94f8a883a85628fbb | robquant/adventofcode2017 | /09/december9.py | 1,755 | 3.75 | 4 | def total_score(input):
garbage_mode = False
bracket_level = 1
assert input[0] == '{'
assert input[-1] == '}'
index = 1
score = 1 # outermost group
garbage_characters = 0
while index < len(input) - 1:
symbol = input[index]
if symbol == '!':
index += 2
... |
d828820d508dc11f1502311e6f2ad7da4dfeb49c | faraza72/python | /angle.py | 302 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
ab = int(raw_input())
bc = int(raw_input())
mc = math.sqrt(math.pow(ab,2)+math.pow(bc,2))/2
mb = math.sqrt(math.pow(bc,2)-math.pow(mc,2))
angle = math.acos(mc/bc)
dg = int(round(math.degrees(angle)))
print str(dg+"°")
|
02ba36e379d274b643fb316f877ce355d3719895 | faraza72/python | /panagram.py | 232 | 3.734375 | 4 | from collections import Counter;
str="qwertyuioplkjhgfdsazxcvbnm"
str1=raw_input()
c=0
for i in range(26):
if str[i] in str1.lower():
c+=1
print str[i]
if c==26:
print "panagaram"
else:
print "not panagram" |
f78af85e9232971297fbc9c855280f39c91805b1 | Zohaib37/Snake-Game | /snake.py | 1,342 | 4.09375 | 4 | from turtle import Turtle
class Snake:
def __init__(self):
self.snakes = []
self.create_snake()
self.head = self.snakes[0]
def create_snake(self):
x = 0
for i in range(3):
turtle = Turtle("square")
turtle.color("white")
... |
29e88495ffcda7ad711ad40c4b251d6446ebdecd | riley-csp-2019-20/1-2-4-turtle-escape-Tieonautry12 | /124TieonAutry.py | 1,462 | 3.53125 | 4 | import turtle as trtl
import random
ty = trtl.Turtle()
ty.pensize(3)
ty.ht()
ty.speed(0)
fish = trtl.Turtle()
fish.pencolor("red")
door_width = 15
wall_width = 15
count = 20
def fish_up():
fish.setheading(90)
fish.forward(10)
def fish_down():
fish.setheading(270)
fish.f... |
a1ef1389a32a72a21afa87d70997abc5c94636c3 | pavel-malin/data_generation | /country_codes.py | 432 | 3.5 | 4 | from pygal.maps.world import COUNTRIES
def get_country_code(country_name):
"""Returns for a given country its Pygal code,
consisting of 2 letters."""
for code, name in COUNTRIES.items():
if country_name == 'Yemen, Rep':
return 'ye'
elif name == country_name:
return ... |
0974349f5b3f2131a009346af2935f3a39d5ac87 | mccarthyryanc/chaos_game | /ChaosGame.py | 550 | 3.640625 | 4 | #! /usr/bin/env python
#
# Methods to generate the points while playing The Chaos Game
#
class ChaosGame:
#method to play
@staticmethod
def play(ngon,frac,max_iter=10**2):
points = []
i = 0
x1,y1 = ngon.rand_in()
while i <= max_iter:
x2,y2 = ngon.rand_vert(... |
d8682203e56116075e37f11f98156733ea3ea0f3 | Shah-Jainam/Logistic-Regression-from-Scratch | /Logistic Regression.py | 9,427 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Imported All Required Libraries
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Reading CSV file using pandas and Printing of Head of the dataset
# In[2]:
train = pd.read_csv('adult-training.csv')
test = pd.read_csv... |
38e5aa511311ea150047a0e340c6c7ef5a3ca8a4 | wputra/learning-python | /some-scripts/max-toys.py | 387 | 3.5 | 4 | #!/usr/bin/python3
def maximumToys(prices, k):
s = 0
for i in prices:
if i<=k:
s+=1
k-=i
#else:
# break
return s
in1 = "7 50"
in2 = "1 12 5 111 200 1000 10"
n,k = map(int, in1.split())
#prices = sorted(map(int,input().split()))
prices = map(int, in2.spl... |
468feb84967473cab07c92df93c29d6226314b2a | saytosid/dodgem-playing-framework | /framework/Board.py | 6,192 | 3.9375 | 4 | '''
File name: Board.py
Author: Siddhant Kumar
Email: saytosid@gmail.com
Date created: 1 Oct 2017
Date last modified: 1 Oct 2017
Python Version: 3.0
'''
from Piece import Piece
class Board:
def __init__(self,size = 3):
'''
:param size: Defines the size of the board
'... |
31f01f01b4e5abec5c6bb6e42ec704047b78d42e | DLaMott/Calculator | /com/Hi/__init__.py | 826 | 4.125 | 4 |
def main():
print('Hello and welcome to my simple calculator.')
print('This is will display different numerical data as a test.')
value = float(input("Please enter a number: "))
value2 = float(input("Please enter a second number: "))
print('These are your two numbers added t... |
46883d94f62e9078f0593150db583fd96fbff475 | onkelhoy/Machine-Learning | /Recurrent Neural Network/wildml turorial/preprocessing.py | 2,185 | 3.609375 | 4 | import nltk
import csv
import itertools
import numpy as np
unknown_token = "UNKNOWN_TOKEN"
sentence_start_token = "SENTENCE_START"
sentence_end_token = "SENTENCE_END"
def preprocess_data(vocabulary_size):
print("Reading the CSV file...")
with open('data/reddit-comments-2015-08.csv', 'rt') as f:
re... |
9036f29d1db991ab061a6b27045bbc7b5f6ad50b | GunterBravo/Python_Institute | /2_1_4_9_Lab_Variables.py | 610 | 3.828125 | 4 | #Escenario
#Millas y kilómetros son unidades de longitud o distancia.
#Teniendo en mente que 1 equivale aproximadamente a 1.61 kilómetros, complemente el programa en el editor para que convierta de:
#Millas a kilómetros.
#Kilómetros a millas.
kilometros = float(input("Ingresa longitud en Kilometros: "))
millas = flo... |
acf4f9abb3deab9bf3752aae70ac76537f66b92f | GunterBravo/Python_Institute | /2_1_4_10_Lab_Operadores.py | 914 | 4.125 | 4 | ''' Escenario
Observa el código en el editor: lee un valor flotante, lo coloca en una variable llamada x, e imprime el valor de la variable llamada y. Tu tarea es completar el código para evaluar la siguiente expresión:
3x3 - 2x2 + 3x - 1
El resultado debe ser asignado a y.
Recuerda que la notación algebraica clásica... |
e48382f4282df95b1f268af7648eec1c885cef18 | viticlick/PythonProjectEuler | /archive1.py | 331 | 4.3125 | 4 | #!/usr/bin/python
"""If we list all the natural numbers below 10 that are multiples of 3 or 5 \
we get 3, 5, 6 and 9. The sumof these multiples is 23.\
\
Find the sum of all the multiples of 3 or 5 below 1000."""
values = [ x for x in range(1,1001) if x % 3 == 0 or x % 5 == 0]
total = sum(values)
print "The result i... |
78e3f14e195e78ef32ffd9cfdcf4aa8ba5f3c3ca | rzv09/web-scrape | /graphics.py | 824 | 3.75 | 4 | """
this file produces graphics for data from vehicle_info.csv
also this thing doesn't work
!SLICE PRICES AND CAST TO AN INT INSTEAD OF STR!
author: Raman Zatsarenko
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data_csv = pd.read_csv('vehicle_info.csv')
print(data_c... |
5dc1970499b8dbaad825b147c9ac1c8e2a81bcd2 | Dmendoza3/Python-exercises | /random/collectionGame.py | 972 | 3.609375 | 4 | import random
rarities = ['common', 'uncommon', 'rare', '']
collection = {}
collectionRate = {}
collected = []
def generateCollection(num, nRarities=3, rate=0.75):
cardsLeft = num
for r in range(nRarities):
if r < nRarities - 1:
nPerRarity = int(cardsLeft * rate)
else:
... |
13ce56ad5b2ec62b12a13d86df9fb61410f67007 | Dmendoza3/Python-exercises | /basic/for.py | 1,012 | 3.921875 | 4 | #For loop
words = ['cat', 'window', 'defenestrate']
arrtp = [('a',1),('b',2),('c',3)]
for w in words:
print(w, len(w))
#Allows to modify list not affecting the loop
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
#Loop with numbers
for i in range(5,15... |
ec2c40ac1acbc9375d4c92228a6d8ccd17e982c5 | Dmendoza3/Python-exercises | /random/infinite_monkey.py | 682 | 4.09375 | 4 | from PyDictionary import PyDictionary
import random
def generate_word():
letter = "abcdefghijklmnopqrstuvwxyz"
wlen = random.randint(4, 9)
word = ""
for x in range(wlen):
wselect = random.randint(0, len(letter) - 1)
word += letter[wselect]
return word
dictionary=PyDictionary()... |
bdf720357d2aa437046614207848241b2c358360 | YazdanGeshani/POO | /POO.py | 541 | 3.734375 | 4 | """cette classe permis de definir l'objet(c'est a dire nous allons donner des
attributs a un objet pour le definir)"""
class Pet:
def __init__(self, name, greeting = "Hello"):
self.name = name
self.greeting = greeting
"""ici on définit l'action dont va faire cet objet"""
def say_hi(self):
print(f"{self... |
aa17589a9b237b787437941eb9adc05c3c3facc8 | oddduckden/lesson8 | /task2.py | 1,053 | 4.09375 | 4 | """
2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных,
вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту
ситуацию и не завершиться с ошибкой.
"""
class CustomErr(Exception):
def __init_... |
2ee0d6cb2127b0e61d1331be60dc34a8a42611e7 | raissaputra/praktikum2 | /lab1.py | 960 | 3.796875 | 4 | # penggunaan end
print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')
# PENGGUNAAN SEPARATOR
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')
# string format
print(0... |
4129d04e0e2e69416363192f30ab46bdc4437377 | DanTGL/AdventOfCode2020 | /day6/day6_1.py | 269 | 3.546875 | 4 | import string
inputs = [line.strip() for line in open("day6/input").read().split("\n\n")]
def count():
count = 0
for group in inputs:
count += len(list(filter(lambda x: x in group, string.ascii_lowercase)))
return count
print(count()) |
14ba91c2a426ed9c533e1b4854caecf0c853e4c6 | rnvarma/KosbieSays | /KosbieSays/doittt.py | 845 | 3.59375 | 4 | import string, bisect, random
def get_start():
x = random.random()
idx = bisect.bisect(start_vals, x)
result = start_words[idx]
if result == "**s** **s**":
return get_start()
return result
def get_next_word(gram):
if gram not in nexts:
print "----", gram
return "**s*... |
3ba74634dd2ccbe7b9ff8e2545198a039c43fd5e | Salekya/pythonScripts | /String.py | 161 | 3.75 | 4 | def string(s,n):
j=len(s)
for i in range(0,j):
e=s[i:i+n]
if len(e)==n:
print(e)
return e
e=string("hello",3)
print(e)
|
3a0d7e9cf63863fbad8ba4bc395a4cc87d1e2c82 | lotario123/seguridadTI | /cifradorAm.py | 1,053 | 4.03125 | 4 | import sys
import cifrar
import descifrar
#palabra: corresponde a un texto a cifrar o descifrar
#modo: para cifrar utilizar la palabra "cifrar" y para descifrar "descifrar"
def main(palabra,modo):
#eliminar espacios en blanco
#palabraFormateada =palabra.replace(" ", "").upper()
palabraFormateada = palabra.... |
0454c7ae55f844ffa0289a850ce5020e6f02f08d | Abdurrahmans/Star-Pattern-Problem-Solving | /StarPattern/pascales_triangle.py | 474 | 3.9375 | 4 | n = int(input("Enter the number of rows:"))
list1 = []
for i in range(n):
temp_list = []
for j in range(i + 1):
if j == 0 or j == i:
temp_list.append(1)
else:
temp_list.append(list1[i-1][j-1] + list1[i-1][j])
list1.append(temp_list)
for i in range(n):
f... |
5395b82d4e6cc5bc911098ce23763f5e6d7d0ddd | Abdurrahmans/Star-Pattern-Problem-Solving | /StarPattern/RightTriangle.py | 157 | 3.796875 | 4 | number = int(input("Enter the number of rows:"))
for i in range(0, number):
for j in range(0, i + 1):
print('* ', end=' ')
print("\r")
|
0bb9b40d8a9fbcd501c74823163c2daf0ea9fcef | Abdurrahmans/Star-Pattern-Problem-Solving | /StarPattern/Another reverse number pattern.py | 178 | 4.15625 | 4 | number = int(input("Enter the positive number: "))
for i in range(number, 0, -1):
for j in range(1, i + 1):
print(i, end=" ")
i = i - 1
print(" ")
|
d1591a9c8713b2f55fb70f8b2c6f3126b5384aad | Juan319-u/Parcial-5 | /punto88renovado.py | 1,533 | 3.671875 | 4 | '''Este codigo verifica que la expresion 6 dividido pi al cuadrado
es igual a casos favorables sobre casos posibles de los numeros enteros libres de cuadrados
Autor : Juan Felipe Corrales Toro
ULTIMA ACTUALIZACION : 13 de Octubre / 2021'''
#está función toma de entrada un entero positivo mayor que 1 y mues... |
58e3199b3aa27ff16249d45c0ea1f331a701b24f | pavancd/algorithms | /BranchSums/BranchSums.py | 907 | 3.71875 | 4 |
class BinaryTree():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def add(self, value):
pass
def BranchSums(root):
sums = []
calculateBranchSum(root, sums, 0)
return sums
def calculateBranchSum(root, sums, runningSum):
... |
029698592fbd477a8433b08c37925d9f5846e51f | pavancd/algorithms | /MaxPathSum/MaxPathSum.py | 1,190 | 3.65625 | 4 |
class BinaryTree():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def add(self, value):
pass
def maxPathSum(root):
_, maxPathSum = findMaxPathSum(root)
return maxPathSum
def findMaxPathSum(root):
if root is None:
retur... |
ed23e96ea643c57812dd309759a9f13b4f3c0833 | pavancd/algorithms | /BSTComparision/BSTComparision.py | 744 | 3.75 | 4 |
def compareBST(arr1, arr2):
print(f'arr1 {arr1}')
print(f'arr2 {arr2}')
if len(arr1) == 0 and len(arr2) == 0:
return True
if not arr1[0] == arr2[0]:
return False
if len(arr1) != len(arr2):
return False
root1 = arr1[0]
root2 = arr1[0]
arr1 = arr1[1... |
487cc4e6bcbe699a56e2c448cd2d0ad969b75579 | TYakovchenko/GB_Less3 | /less3_HW3.py | 1,196 | 4.25 | 4 | ##3. Реализовать функцию my_func(),
# которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
#Первый вариант
def my_func(arg1, arg2, arg3):
if arg1 >= arg3 and arg2 >= arg3:
return arg1 + arg2
elif arg1 > arg2 and arg1 < arg3:
return arg1 + arg3
else:
... |
23e58c21870d678c8243a3056bc30d3e73d3fa91 | PedroMorenoTec/practica-examen | /3.2/indicedemasacorporal.py | 359 | 3.9375 | 4 | peso = float(input('Peso en kg: '))
altura = float(input('Altura en m: '))
indice = round(peso / altura**2,2)
print(indice)
if indice < 20:
print('PESO BAJO')
if 20 <= indice < 25:
print('NORMAL')
if 25 <= indice < 30:
print('SOBREPESO')
if 30 <= indice < 40:
print('OBESIDAD')
if indic... |
b128924af1b216185223f1f45d535dba6094d801 | PedroMorenoTec/practica-examen | /5.4/ejercicio1.py | 204 | 3.984375 | 4 | n = int(input('Introduce un entero positivo: '))
msg=''
for i in range(1, n+1):
msg+=str(i) + ', '
for i in range(n-1, 0, -1):
msg+=str(i) + ', '
msg = msg[:-2]
print(msg) |
f8c1e5afb9c3151430c34866c55527411ee53714 | PedroMorenoTec/practica-examen | /3.1/ejercicio2.py | 417 | 4.03125 | 4 | print('Introduzca los lados del triángulo')
x = float(input('x: '))
y = float(input('y: '))
z = float(input('z: '))
if(x+y>z and x+z>y and y+z>x and x>0 and y>0 and z>0):
if(x != y != z):
print('El tríangulo es escaleno')
elif(x == y == z):
print('El tríangulo es equilátero')
else... |
3307942491d669cc0ab88ac90a6969f4dd1a5757 | PedroMorenoTec/practica-examen | /2.2/decentimetrosakilometrosmetrosycentimetros.py | 273 | 4 | 4 | distancia = int(input('Introduzca una distancia: '))
km = distancia // (1*10**5)
distancia%=(1*10**5)
m = distancia // (1*10**2)
distancia%=(1*10**2)
cm = distancia
if km>0:
print(f'{km} km')
if m>0:
print(f'{m} m')
if cm>0:
print(f'{cm} cm') |
f448ff8716de10531614e960426e84e51d76107f | simon-suuk/Analizar | /services/graph_api.py | 2,649 | 3.53125 | 4 | import requests
class PageOrPost:
def __init__(self, page_id, page_token):
self.node_id = page_id
self.access_token = page_token
def get_edge(self, edge_name):
"""
To read an edge, you must include both the node ID and the edge name in the path.
For example, /page node... |
d0137ea42361b0a0ecaee16398bc22cc2d72d1ad | BerdeRadhika/Programs | /Python Programs/Assignment No 1/4.Display 5 times Marvellous on screen.py | 291 | 3.890625 | 4 | """4.Write a program which display 5 times Marvellous on screen.
Output :
Marvellous
Marvellous
Marvellous
Marvellous
Marvellous
"""
def Print():
i=0
for i in range (5):
print("Marvellous")
def main():
Print()
if __name__=="__main__":
main()
|
9740bf10ad88a24ee7691b27b222cff72a733351 | SamBurt/Hearts | /Deck.py | 596 | 3.734375 | 4 | from Card import Card
import random
class Deck:
suits = [
"Heart",
"Diamond",
"Spade",
"Club"
]
values = list(range(2,15))
def __init__(self):
self.cards = self.generate_deck()
def generate_deck(self):
cards = []
for suit in self.suits:
... |
940af334933c2bbe31e8b5d71647c675e10d1f2f | PranjaliKumbhar/CI-Programs | /ciANDNOTMC.py | 1,014 | 3.625 | 4 | print("Enter the ANDNOT Truth Table:")
x1=[]
x2=[]
y=[]
for i in range(0,4):
i1=input("Enter values of X1:")
x1.append(i1)
for i in range(0,4):
i2=input("Enter values of X2:")
x2.append(i2)
for i in range(0,4):
i3=input("Enter values of Y:")
y.append(i3)
print ("X1 X2 Y")
i=0
while i ... |
ce31f1b2a952762712f668d3ed590b7bdc2e599c | deyh2020/meep-geom-utils | /meep_geom_utils/src/geom2med.py | 1,485 | 3.640625 | 4 | """
:author: JPHaupt
:date: 26 Feb 2020
simple module that contains a function that takes a list of mp.GeometricObject
and Shape and returns a function of mp.Vector3 that returns the medium at that
point
"""
import meep as mp
from meep_geom_utils.src import shapes
def geom2med(geometries, default_material=mp.Medium... |
bf799eadced3aa3cb805b49329b912e9378fe9bc | abbsmile/Python-base | /BaseForm/identifyOperator.py | 1,086 | 3.96875 | 4 | # -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
# a = 20
# b = 200
# if ( a is b ):
# print "1 - a 和 b 有相同的标识"
# else:
# print "1 - a 和 b 没有相同的标识"
# print id(5)
# print id(6)
#
# print 5 is 5
# print 5 is not 5
# print id(5) is id(5)
# print id(5) is not id(5)
## ?? id 是一个有待研究的东西?????
a = [1, 2, 3]
b = [1,... |
67a04b62a354f2c0a78aa7d3fb04ad46c33e8d98 | abbsmile/Python-base | /BaseForm/variable.py | 255 | 3.953125 | 4 | # -*- coding: UTF-8 -*-
a, b, c = 1, 2, "john"
print a
print b
print c
print "**************************"
str = "Hello World"
print str
print str[0]
print str[2:5] # 这个要注意一下,肯定在5之前
print str[2:]
print str * 2
print str + " TEST"
|
a6c97190493de239f3691fd80bc798dbd7de5d39 | abbsmile/Python-base | /BaseForm/AddString.py | 1,079 | 3.6875 | 4 | # -*- coding: UTF-8 -*-
first = '上海涌洁'
second = ' 我的第二个公司'
third = first + second
print third
print 5 + 8
print '5' + '8'
print 'let\'t go'
print "let't go"
print 'c:\now'
print 'c:\\now'
# 原始字符串
print '***********************************'
fish = r'c:\now'
# 注意一下,fish = r'c:\now\' 这样是不合法的
print fish
# 多行字符串... |
d56e5bfb3687d690ffbad4ef2e5d544d6f0c8c3e | abbsmile/Python-base | /RegularExpression/pattern_aearch.py | 310 | 3.890625 | 4 | # encoding: UTF-8
import re
# 将正则表达式编译成Pattern对象
pattern = re.compile(r'hello')
match = pattern.search('hello hello world world world!')
if match:
print "match已经被匹配上了,什么情况"
print match.group()
else:
print "这个暂时它还没有被匹配上!"
|
1de7b7ff2eccba1acd3a0ade2f759afa06066c70 | Hallye/DjangoGirls | /django.py | 196 | 3.8125 | 4 | #akjds
if 3 < 2:
print("Hello Django")
def hi(name):
print("Hi " + name)
print("How are you?")
hi("Gabriela")
#bucle
girls = ["Rachel", "Rosa", "Sofia"]
for name in girls:
hi(name) |
348f1b509bb1e5928454acda482d2b06228b2567 | Mownicaraja/python-programs | /remove-dup.py | 166 | 3.53125 | 4 | from collections import OrderedDict
def dup(ss):
return "".join(OrderedDict.fromkeys(ss))
if __name__ == "__main__":
ss=str(input())
print(dup(ss))
|
b3b7bc3266df4bfd22584093f3967b5c5476fec9 | sonali-mahavar/addition-of-number | /first.py | 95 | 3.828125 | 4 | print("hello")
a=int(input("enter first no:"))
b=int(input("enter second no:"))
print(a+b)
|
0b2271242a08c6cb56c495e4d27ede2a919e2dd5 | Jhavaa/Final_Project_ML | /credit_data.py | 3,731 | 3.734375 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
############### A more detailed explanation to why we transformed the data the way we did can be found in credit_analysis.py ###############
### Prepare this dataset to be used for further analysi... |
a6d443f8388998d8fc539da675ba86969a3bf91e | ruslanabdulin1985/TheTask | /Battleships/model/game.py | 2,946 | 3.890625 | 4 | """
Module contains class Game
The module imports two Classes of this model: Player to represent players and Coordinates to let players exchange
coordinates
"""
from model.rules import Rules
from model.player import Player
from model.coordinates import Coordinates
# FIXME
from model.ship import Ship
class Game:
... |
6d621a1a63ee390fd1edebb52cb39f88fe698251 | harishkbsingh/rareEdgeDetection | /draftV3/Main.py | 1,030 | 3.59375 | 4 | import datetime
from Algorithm import Algorithm
from Util import getEdges, getKey
'''
This method simulates the algorithm for 6 months
'''
def runMonthsSimulation():
instance = Algorithm()
base = datetime.datetime(2019, 1, 1)
date_list = [base + datetime.timedelta(hours=x) for x in range((24*30*5) + 13)]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.