blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
788705189f46f7b324bd0b5136c5977b2436e306 | sharan-patil/programs | /Python Files/palindrome.py | 270 | 3.96875 | 4 | from sys import argv
def fail():
print "The given word is not a palindrome!"
exit (0)
name, word = argv
i = len(word)
x = 0
i = i - 1
while x < (i / 2):
if (word[x] != word[i]):
fail()
x = x + 1
i = i - 1
print "The given word is a palindrome!"
|
17108f287870c5a8eb012ae798fb030aa0f5842b | JacobSteinfeld/tic_tac_toe | /tictactoe.py | 3,095 | 4.0625 | 4 | #goal is to play tic tac toe
#first step is to create a board
#once board create X's and O's
#figure out where players want to go
#figure out who wins or draw
#
import numpy as np
board = np.chararray((3, 3))
rows, columns = board.shape
board[:] = "v"
print("Game Start:")
print(board)
#board[0,0] = "x"
#print(board)
ga... |
3e441eb65c66ccd940f4de674d0389467b3f31f7 | mayhem215/Python | /Количество элементов, равных максимуму.py | 136 | 3.5 | 4 | m = 0
n_m = 0
n = -1
while n != 0:
n = int(input())
if n > m:
m, n_m = n, 1
elif n == m:
n_m += 1
print(n_m) |
e5056e3822d0570192376446598716e8ca7a9d2b | ZhengC1/Practice | /CrackingTheCodingInterview/Chapter8/RobotTransversal.py | 1,921 | 3.578125 | 4 | from collections import deque
import random
from pprint import pprint
class RobotTransversal():
def __init__(self):
# map_size = input("map size: ")
# self.__create_map(map_size)
# print self.bfs()
# pprint(self.map)
self.run_sim()
def run_sim(self):
for i in ra... |
2b439cfe28a94164aa680e6e91b1e1b1483de591 | Elli-Savi/Dungeon-Game | /DungeonGame.py | 12,805 | 4 | 4 | #Dungeon Game
#flaws
#when waiting for raw_input, if enter is accidentally pressed the game will break
from sys import exit
from random import randint
#global variables
rooms = []
rooms = ['Start', '0', 'Lava', '1', 'Water', '2', 'Trophy', '3', 'Cthulu', '4', 'Nothing', '5', 'Hatter', '6', 'Key', '7', 'E... |
fc9268174f952f17212cecf4ccb4441ebbde0bef | TanakitInt/Python-Year1-Archive | /In Class/Week 12/gui/botton.py | 824 | 3.953125 | 4 | # import tkinter
from tkinter import *
def init_window(master):
# initialize the window size
master.geometry('{}x{}'.format(400, 300))
# fixed size window
master.resizable(width=False, height=False)
# window title
master.title("Tkinter GUI: Button")
def init_button(master):
hello_button = ... |
85964f9b0a2acac3bfaf0cbd155954eead008266 | JeanMarieN/Amazon-Review-Analysis | /src/allpositive.py | 549 | 3.546875 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv('../data/raw/phase1_movie_reviews-train.csv')
df = pd.get_dummies(df['polarity'], drop_first=True)
train, test = train_test_split(df, test_size=0.2)
validation, test = train_test_split(test, test_size=0.5)
def predictallpos(da... |
2034573b685a301981ce49efd1da66553c1b4448 | starmaerker/Algorithmen-und-Datenstrukturen-in-Python | /Suche in Zeichenketten/sequential_search.py | 469 | 3.890625 | 4 | import random
def sequential_search(list_to_search, item):
position = 0
found = False
while position < len(list_to_search) and not found:
if list_to_search[position] == item:
found = True
else:
position += 1
return found, item, position
list_to_search = []
i... |
bced2d3c7b5412d844f3e6edef1b8dc0826e9f92 | krocriux/TICS311 | /semana_12_03/Extras/CL/SuperUserDo/SuperUserDo.py | 1,027 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 15:07:46 2018
Examples
0)
{1}
{10}
Returns: 10
Only libraries 1 to 10 must be installed, so the answer is 10.
1)
{1,101}
{10,110}
Returns: 20
2)
{1}
{1000}
Returns: 1000
3)
{1,2,3,4,5}
{6,7,8,9,10}
Returns: 10
In this test ca... |
a0b75637108bba4cba7a5be8280e9ed47b2d8a3f | tennisfar/courses | /MITx/6.00.1x Introduction to Computer Science and Programming/Material/Lecture 5 - Recursion/L5_Problem_6.py | 211 | 3.78125 | 4 | def lenIter(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
# Your code here
number = 0
for c in aStr:
number += 1
return number
print(lenIter('xxxcc'))
|
c6ff4877c4d095840443c5513227f580653175c0 | Tomdssdasd/try | /p4.py | 129 | 3.640625 | 4 | l=[]
for i in range(1,11):
import random
num=random.randint(1,11)
l.append(num)
l.sort()
l.reverse()
print(l) |
7ab6f3e6185d2d876c8d52161eb7a9a8b04715c9 | miaozaiye/PythonLearning | /miaozaiye/1207slideshow.py | 1,488 | 3.515625 | 4 | #从命令行读取2个或者更多图片文件名,然后用淡入淡出的方式来展示
'''
1. get list of filename from sys.argv[1:]
2. while not end, use fade(a,b) to show slide
3. fade(a,b), transfer a to b via n steps, and for i step, the pixel shows the value of average(a+b)
'''
import sys,pygame,PIL
from stdpackage import picture,stddraw
from stdpackage.picture imp... |
e9ca6aa9d3013fe1467cedcd7318bd91b2cd50c4 | omelkonian/ai-collection | /Sliding Blocks/slidingBlocksGenerator.py | 11,627 | 3.640625 | 4 |
"""
Generates a random grid with the given size and number of non-goal blocks
derived {steps} steps from a random goal state.
Size is given as a tuple (X,Y).
"""
from slidingBlocksUtilities import convertTupleToList, getSize,convertListToTuple,\
getValidActions, printState, getBlockSymbolsList,\
getLeftmosDo... |
99a344d1d5a6b4a1238d4a5212e3a6b39a7de5cb | 1ambda/data-analysis | /intro-to-data-science/week5/memoization.py | 650 | 3.828125 | 4 | def fib(n):
assert type(n) == int and n >= 0
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def testFib(n):
assert type(n) == int and n >= 0
for i in range(n):
print ('fib of', i, '=', fib(i))
def fastFib(n, memo):
assert type(n) == int and n >= 0
... |
9fc480dcd206444261e10d4274042742f0be4128 | jennings1716/Datastructure | /doubly_linked_list.py | 4,822 | 3.96875 | 4 | #Double Linked List
#A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer,
#together with next pointer and data which are there in singly linked list.
import time
class Node:
def __init__(self,data):
self.data=data
self.prev=None
self.next= None
if __name_... |
53ca343c61173921febd4ed4bff501e2aad5bff2 | tjohnson1988/week1 | /birthday_checker.py | 894 | 4.5625 | 5 | #Take a users input and return their name + birthday. If today is there
# birthday output “Happy Birthday!”
# use .strftime to formats dates in a specific manner
# https://www.programiz.com/python-programming/datetime
# https://www.youtube.com/watch?v=hj6Tgc4hEU0&ab_channel=CleverProgrammer
from datetime import datet... |
c5aab13827a083030540c797cc1fb37c2be86aa9 | MihailMihaylov75/algorithms | /unique_characters_in_string.py | 481 | 3.78125 | 4 | __author__ = 'Mihail Mihaylov'
# Given string determine if it is compressed of unique characters
def find_unique_characters_in_str1(string):
""""Find unique characters in string vol 1"""
return len(set(string)) == len(string)
def find_unique_characters_in_str2(string):
""""Find unique characters in stri... |
9936d2b2366f831beaecf120189b635203f2d0bc | Vincentxjh/practice0723 | /009.py | 470 | 3.78125 | 4 | #第九个练习-模拟手机充值场景
money = int(input("欢迎使用XXX充值服务,请输入您要充值的金额:"))
t = int(input("您输入的充值金额为:" + str(money) +"元,确认充值请按1,取消充值请按2: "))
if t==1:
print("充值成功,您本次充值金额为" + str(money) + "元。")
elif t==2:
print("取消成功,您本次未充值。")
else:
print("对不起,您的输入有误,请重新输入。") |
f8c8fd6a5360a32fb648401a3de2b5358f3a86d7 | jikka/pythong | /comp.py | 152 | 3.65625 | 4 | n=input("\nEnter the n value")
k=input("\nEnter the k value")
a=list(str(n))
b=0
for i in n:
for j in k:
if i==j:
b=b+1
print(b)
|
8d0c495af3bf6f44d733bfede2d845c5d6f1d6e6 | olzhas23/thinkful | /parser.py | 193 | 3.640625 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display Square of any given argument", type=int)
args=parser.parse_args()
print args.square**2
|
6f6d8094f94fc005e3b1b0bd156ec85a943c0479 | javilamarque/ITEDES | /modulo1/segmento3/apunte3 "IF - ELSE IF (ELSE)"/ejercicio3/ejercicio3.py | 255 | 4 | 4 | caracter = int(input("Ingrese un caracter para saber si es una (vocal, consonante, numero): "))
if(caracter == "a" or "e" or "i" or "o" or "u"):
opcion = "vocal"
elif(caracter.isdigit()):
opcion = "numero"
else:
opcion = "consonante"
print(opcion)
|
fd0e80daae65fe7bf5695b60fd2a161bd1ff33eb | appleface2050/Coursera-ML | /johnwittenauer/src/multiple_linear_regression.py | 1,107 | 3.890625 | 4 | # coding=utf-8
"""
http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-2/
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from util.lib import computeCost, gradient_descent
if __name__ == '__main__':
path = os.getcwd() + "\data\ex1data2.txt"
data2 = pd... |
65503ec44eaa52c4d65ca7f85b7c850d25af1324 | mpalliser/Programacion | /caminandoEnLaNiebla/Ejercicio12.py | 330 | 3.90625 | 4 | primer_numero = int (input("Introduce el primer numero "))
segundo_numero = int (input("Introduce el segundo numero "))
if primer_numero%2 ==0 and segundo_numero%2 ==0 and primer_numero <=50 and segundo_numero >99 and segundo_numero <=501 :
suma = primer_numero + segundo_numero
print (suma)
else:
print ("Er... |
d8bd41c97e3607c2fef4f633a3171d9c248cd081 | sunatthegilddotcom/hyperAFM | /GUI/Practice/thenewboston/13.shapes_graphics.py | 568 | 4.21875 | 4 | '''
SHAPES AND GRAPHICS
'''
from tkinter import *
root = Tk()
#making a canvas to draw on
canvas = Canvas(root, width=200, height=100)
canvas.pack()
#all lines by default will be black
#set parameters for the line- first parameters will tell where to begin,
#the other two will tell how big it wil be
blackLine = can... |
af588e59157b133c81fc9b8cba5737d4cda03d13 | TheNew000/python101 | /dc_Code_Challenge.py | 3,472 | 4.53125 | 5 | # 1) Declare two variables, a string and an integer
# named "fullName" and "age". Set them equal to your name and age.
full_name = "Danny Arango"
age = 31
# 2) Declare an empty array called "myArray".
# Add the variables from #1 (fullName and age) to the empty array using the push method.
# Print to the console.
... |
b6f1bf5c0a73d239c41c63553a10875b0bb50fe9 | mohammad-saber/CNN_classification_feature_extraction | /tools/visualization.py | 7,812 | 3.515625 | 4 |
# Visualization tools
import matplotlib.pyplot as plt
import numpy as np
import torch, torchvision
from torchvision import datasets
import itertools
from sklearn.metrics import confusion_matrix
import pandas as pd
def show_image_batch(data_loader, path, mean, std, class_names):
"""
Visualize training images... |
7aae923467dc9c64553c90ebfdd2425449dd943d | freddyfok/cs_with_python | /problems/leetcode/14_longest_common_prefix.py | 498 | 3.765625 | 4 | from typing import List
def longest_common_prefix(strs: List[str]) -> str:
if not strs:
return ""
if len(strs) == 1:
return strs[0]
prefix = strs[0]
prefix_len = len(prefix)
for s in strs[1:]:
while prefix != s[0:prefix_len]:
prefix = prefix[:-... |
169938151efa7004a4ba1220d56cb1c091cd9b96 | kelian33/CryptoMoney | /cryptomoney.py | 849 | 3.546875 | 4 | #!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
import requests
liste_nom=requests.get('https://www.cryptocompare.com/api/data/coinlist/')
datas=liste_nom.json()
names_money = datas['Data']
fini = False
while fini != True :
money = input("Entrez le nom d'une cryptomoney sinon tapez 'liste' ou 'exit' : ")
if... |
7424bbe296c60c382e35b013345c58af3ffa162d | nervylof/GloAcademy_python | /Урок 9/Задание 1.py | 197 | 3.984375 | 4 | while True:
num = int(input())
if num < 10:
continue
elif num > 100:
break
elif num > 10 or num < 101:
a = num
num = int(input())
print(a)
|
a86d4b218caba91487f183a9a2802738b007383c | naughtybabyfirst/algorithm | /Similarity_NLP/distance.py | 308 | 4.09375 | 4 | # -*- coding: utf-8 -*-
terms = ['Believe', 'believe', 'bargain']
def manhattan_distance(u, v, norm = False):
if u.shape != v.shape:
raise ValueError('length error..')
return abs(u - v).sum() if not norm else abs(u - v).mean()
for term in terms:
print(manhattan_distance()) |
93a35a3dc84a8a107baca4ddc39a1141367d718d | JulietaAtanasova/programming0 | /week1/conditional-statements/grader.py | 559 | 4.1875 | 4 | min_grade = 0
max_grade = 100
grade = int(input("Enter grade: "))
if min_grade <= grade <= (max_grade // 2):
print("Слаб 2")
elif (max_grade // 2 + 1) <= grade <= (max_grade // 2 + 10):
print("Среден 3")
elif (max_grade // 2 + 11) <= grade <= (max_grade // 2 + 20):
print("Добър 4")
elif (max_grade //... |
35679430edf848079e4a3c6dd339ee3c12e14c89 | jesee030/pythonProject | /Python开发技术—面向对象程序设计1/类和对象/src/step2/pointtest.py | 399 | 3.6875 | 4 | from point import Point
x1,y1 = input().split(',')
x2,y2 = input().split(',')
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
dx,dy = input().split(',')
dx = int(dx)
dy = int(dy)
p1 = Point(x1, y1)
p2 = Point(x2,y2)
print('p1点的坐标为:',p1)
print('p2点的坐标为:',p2)
p2.move_by(dx, dy)
print('移动后的坐标为:',p2)
print('p1与p2点的... |
fa93d4db389eb2aed9ee0094ad4502aaf8d9cebc | Quiver92/edX_Introduction-to-Python-Creating-Scalable-Robust-Interactive-Code | /Date_and_Time_Arithmetic/Task_2.py | 811 | 4.3125 | 4 | # [ ] Write a program to compute the date 3 weeks before your birthday
# to help you remember when to send the invitations
from datetime import datetime, timedelta
today = datetime.today()
my_birthday = datetime(today.year, 11, 17)
three_weeks_ago = timedelta(weeks = 3)
three_weeks_before_my_birhtday = my_birthday - t... |
e4fba18b052549633dde00c090ffcde1833c8631 | bailong0108/1807 | /07day/12-账号.py | 292 | 3.78125 | 4 | account = "123456"
passwd = "abc"
act = input("请输入你的账号:")
pwd = input("请输入你的密码:")
if act == account and pwd == passwd:
print("登录成功")
elif act != account:
print("账号不正确")
elif pwd != passwd:
print("密码不正确")
else:
print("重新输入")
|
3b2e91b72cb58c35cbfd4806427f39a36eaf9140 | delamorinierejh/Exercism | /python/word-count/word_count.py | 236 | 3.65625 | 4 | import re
def word_count(str):
str = str.decode('utf-8')
sentence = re.sub("[\W]|_", " ", str, re.UNICODE)
d = {}
for word in sentence.lower().split():
if word in d:
d[word] += 1
else:
d[word] = 1
return d |
97e626812bdd6c8683a3b56a1b7533372046c975 | tashakim/puzzles_python | /enqueue.py | 552 | 4.25 | 4 | # Simple python implementation of a queue
def enqueue(mylist, value) :
mylist.append(value)
return mylist
def dequeue(mylist) :
if mylist == [] :
print("list is empty")
return mylist
mylist.remove(mylist[0])
return mylist
if __name__ == "__main__":
mylist = [1,2,3]
print(enqueue(mylist, 4))
print(dequeue... |
903b95370d8c4008f59eaab498b5a404ef0458b8 | mohankumarp/Training | /Python_RF_Training/Python/LAB/variable_printing.py | 1,032 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: MohanKumarP
#
# Created: 22/12/2015
# Copyright: (c) MohanKumarP 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
... |
b780ec075d3caee0425f78e560a411842f82202e | huiyi999/leetcode_python | /Valid Parentheses.py | 2,387 | 3.921875 | 4 | '''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
'''
class Solution:
def isValid4(self, s: str)... |
a156b75c3f4d12088ac763d30edc9d82401b3ff4 | bhaumikmistry/mindDB | /software/aoc/2020/day8/run.py | 1,812 | 3.703125 | 4 | import copy
def open_file(file_path):
with open(file_path, 'r') as f:
entries = [entry.split('\n')[0] for entry in f.readlines()]
return entries
def program_2(data):
visited_list = program_1(data)
if len(visited_list) is 1:
return visited_list[0]
index = 0
old_data = copy... |
410c98c0e2b60c4f26a95c6c59f2531681c816e4 | porrametict/learningSpace | /PythonWithChulalondkorn/list_demo1.py | 614 | 4.15625 | 4 | # basic operation list
# flower = ["calla","rose","lily"]
# print(flower)
# flower = flower+["for get me not","sunflowe"]
# print(flower)
# del flower[1]
# print(flower)
# flower.remove("calla")
# print(flower)
# sorted_flower = sorted(flower)
# print(flower)
# print(sorted_flower)
# flower.sort()
# print(flower)
# fl... |
81900ff25816e47095edbcb59435c1f591800c1b | SophiaPankeyeva/python-laboratory | /laboratory1/task2.py | 905 | 3.921875 | 4 | print("Лабораторна робота №1 завдання2 \nПанкєєва Софія КМ-93 вар.№15")
while True :
print( 'введіть потрібний вам вік age= ')
r = True
while r:
try: age = int(input())
except:
print('введіть, будь ласка, числові значення ')
continue
else: r = False
if ( a... |
060d3c382971bb6ec6cf11af2021ad38af24a99d | FrancyPinedaB77/DJANGOTaller2 | /losdatos.py | 362 | 3.578125 | 4 | #!/usr/bin/env python
import json
print("un texto ")
n=1
p=3
print (n+p)
file = open("C:\\Users\\ASUS\\Desktop\\Downloads\\Taller1BigData-master\\Taller1BigData-master\\static\\js\\salida.txt","r")
d={}
for line in file:
x = line.split(",")
print(x[0],"nacio",x[2])
# print (x[0],'\n',x[1])
#print ({x... |
d1cc3e5e2f447c5e84c4fca6d67c208456c02db4 | Akazfu/Python-Rewind | /Algorithms and Data Structures/hotpotato.py | 401 | 3.5 | 4 | from datastructures import Queue
def hotpotate(namelist, num):
queue = Queue()
for name in namelist:
queue.enqueue(name)
while queue.size() > 1:
for i in range(num):
queue.enqueue(queue.dequeue())
queue.dequeue()
return queue.dequeue()
if __name__ == "__main__":... |
9ed35b984f819b153be9b34bb5c679bf9c7aa4d5 | Poli96/python | /if13.py | 443 | 4.03125 | 4 | a=int(input("Введите первое число: "))
b=int(input("Введите второе число: "))
c=int(input("Введите третье число: "))
def main(a,b,c):
if a>b and a>c:
if b>c:
print(b)
else:
print(c)
if b>a and b>c:
if a>c:
print(a)
else:
print(c)
if c>a and c>b:
... |
6ab28d84c9a13e34c8956e31d9dc93b8afeff6be | john2796/Python-Algos | /Data-Structure/Queue.py | 442 | 3.671875 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Queue:
def __init__(self):
self.size = 0
self.head = None
self.tail = None
def enqueue(self):
self
def dequeue(self):
self
def len(self):
s... |
01fb9b351bf522811f96ed7906c52c32da5966f8 | ningmengpian/algorithm | /valid_bracket_pair.py | 1,534 | 4.28125 | 4 | """
判断有效括号对
question:
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
example:
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
"""
class Solution:
def is_valid(self... |
24b4bd3a596f9d529cb529b1ad4d903535ce994b | aki202/nlp100 | /chapter1/009.py | 427 | 3.546875 | 4 | import random
#string = 'The best way to predict the future is to invent it .'
string = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
words = string.split(' ')
for index, word in enumerate(words):
if len(word) <= 4: continue
chars = list(word[1... |
4e6ca67225bbabd629abef44cf44c966c34a852c | mirabl/j | /meilleurdev/2017-session2/roller/roller.py | 815 | 3.625 | 4 | #!/usr/local/bin/python3
#
# #*******
#* Read input from STDIN
#* Use echo or print to output your result, use the /n constant at the end of each result line.
#* Use:
#* local_print (variable );
#* to display simple variables in a dedicated area.
#* ***/
import sys
from collections import *
import heapq
import ... |
96fc57c7a7b78b13b0fe248a5905c448e5d057b8 | Aasthaengg/IBMdataset | /Python_codes/p03779/s325073396.py | 177 | 3.625 | 4 | import math
X = int(input())
x = max(0, int(math.sqrt(X)) - 10)
while True:
xx = x * (x + 1) // 2
if X <= xx:
print(x)
exit()
else:
x += 1 |
b4cacd659dd0301214ab1999c8478a1c775021b2 | nianien/algorithm | /src/main/python/leetcode/editor/cn/SwappingNodesInALinkedList.py | 1,611 | 3.9375 | 4 | # 1721.swapping-nodes-in-a-linked-list
# 给你链表的头节点 head 和一个整数 k 。
#
# 交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
#
#
#
# 示例 1:
#
#
# 输入:head = [1,2,3,4,5], k = 2
# 输出:[1,4,3,2,5]
#
#
# 示例 2:
#
#
# 输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5
# 输出:[7,9,6,6,8,7,3,0,9,5]
#
#
# 示例 3:
#
#
# 输入:... |
266866adc1292b06a61277f31b2525c58c50e98a | gmidha/python-examples | /string_templates.py | 683 | 4.78125 | 5 | #!/usr/bin/env python3
# This program demonstrates the usage of template with strings.
from string import Template
def main():
str = "I am a {0}, I love coding {1}".format("coder", "python")
print(str)
print("--------------------------------")
temp = Template("I am a ${x}, I love coding ${y}")
... |
9808a485e61be9c883ade8741787d66f601acb3b | spiritdan/pypypy_v2 | /lesson19/01.py | 1,080 | 3.921875 | 4 | start_floor = input('请输入起始楼层:')
end_floor = input('请输入终止楼层:')
input('接下来请依次输入起始层每个房间的户室尾号、南北朝向及面积,按任意键继续')
start_floor_rooms = {}
floor_last_number = []
for i in range(int(start_floor),int(end_floor)+1):
for i in range(3):
last_number = input('请输入起始楼层户室的尾号:(如01,02)')
floor_last_number.append(last_n... |
861e8cb6a125eab05ac4d6a66bbb5880a19aa70c | hussein343455/Code-wars | /kyu 7/Mumbling.py | 436 | 3.890625 | 4 | # This time no story, no theory. The examples below show you how to write function accum:
# Examples:
# accum("abcd") -> "A-Bb-Ccc-Dddd"
# accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
# accum("cwAt") -> "C-Ww-Aaa-Tttt"
# The parameter of accum is a string which includes only letters from a..z and A... |
0847c2a167efc8e322d1fbe9c6ba9c596b00c594 | MarvelICY/LeetCode | /Solutions/scramble_string.py | 1,315 | 3.765625 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Scramble String] in LeetCode.
Created on: Nov 24, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return a boolean
# @ICY: dfs recurse
def isScramble(self, s1, s2):
#co... |
1b70a6ad2c0d0aa95cd89b6f1f139db0b50e5889 | MariaBet/EstudosPython | /aulas/rato.py | 417 | 3.890625 | 4 | """
Exemplo de classe e objeto.
Criado para rapidinha #7: https://youtu.be/SQXmC6PbZWk
"""
"Molde para o rato."
class Personagem:
def __init__(self, nome, cor):
self.nome = nome
self.cor = cor
def __repr__(self):
return f'Personagem("{self.nome}", "{self.cor}")'
mickey = Personagem(... |
6585f53e2ff04bc7ecd99b83d9bbab69f67d379b | Conquerk/test | /python/day02/day02zuoye/zuoye3.py | 132 | 3.59375 | 4 | x=int(input("请输入一个年份:"))
if (x%4==0)and(x%100!=0)or(x%400==0):
print("润年")
else:
print("不是润年")
|
adee40607f6e65789891bece2cbaa32519ff0ca7 | ashish3x3/competitive-programming-python | /Hackerrank/Maths/Infimium Contest/pythagorean_triplets.py | 1,365 | 3.578125 | 4 | # https://www.hackerrank.com/contests/infinitum18/challenges/pythagorean-triple
#!/bin/python
# http://www.friesian.com/pythag.htm
#from __future__ import division
#import sys, math
def solveTriplets(a):
if a % 2 == 0:
print a**2/4 - 1, a, a**2/4 + 1
else:
print a, (a**2 - 1)/2, (a**2 +... |
bdcc895fbc7657fb18f62ead89b009b61b3d2541 | Matt-Robinson-byte/DigitalCrafts-classes | /python-algorithms-challenge/seven-counter.py | 77 | 3.859375 | 4 | number = int(input("Enter number with sevens to count: "))
print(len(number)) |
d498315385d8fc5f422223714a741bef7ece7310 | willzh0u/Python | /ex29.py | 1,822 | 4.125 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
# with dogs incremented by 5, people = dogs
if peo... |
a63cfa5a79b7ce36efd02dd129d54857b1fdf7b2 | Zheny-mc/Python3_19-ivt-2 | /lb5/main.py | 1,343 | 4.03125 | 4 | def punctuation_mark(ch):
'''Определяет является ли символ знаком препинания'''
if (ch >= '!' and ch <= '/'):
return True
elif (ch >= ':' and ch <= '@'):
return True
elif (ch >= '{' and ch <= '~'):
return True
elif (ch == ' '):
return True
else:
return F... |
7972207618450968596e32659261bc9410e62be9 | ProProgrammer/udacity-cs212-coursework | /writing_hand_rank.py | 9,208 | 4 | 4 | # You may assume the following behavior of each function:
#
# straight(ranks): returns True if the hand is a straight.
# flush(hand): returns True if the hand is a flush.
# kind(n, ranks): returns the first rank that the hand has
# exactly n of. For A hand with 4 sevens
# this fun... |
f4a2f64e52ad75d07efd13cd16a9f82b2a39f5db | hassanbazari/python-practice-book | /anandology_chapter_2/2prb34_word.py | 390 | 4.21875 | 4 | # function to split data in a file into words and print in decresing order of occurences
def read_words(filename):
sorted_dict={}
import re
from collections import Counter
import operator
words = re.findall(r'\w+', open(filename, 'r').read().lower()) #list of words without punchuation
dictionary=Counter... |
6b73414d98b58649972f864e90c6f15fd77c3afe | Frijke1978/LinuxAcademy | /Python 3 Scripting for System Administrators/Adding Error Exit Status.py | 1,298 | 3.9375 | 4 | Adding Error Exit Status to reverse-file
When our reverse-file script receives a file that doesn’t exist, we show an error message, but we don’t set the exit status to 1 to be indicative of an error.
$ reverse-file -l 2 fake.txt
Error: [Errno 2] No such file or directory: 'fake.txt'
~ $ echo $?
0
Let’s use the sy... |
146b63adcd447f0ae515995b031f3543f8e49b10 | shirishdhar/HW10 | /seventeen1.py | 1,115 | 3.921875 | 4 | import sys
def random_generator():
import random
ran=random.randint(1,3)
return ran
def seventeen():
marbles=17
while True:
try:
user_in=int(raw_input('Your turn: How many marbles will you remove (1-3)? '))
if (user_in not in range(1,4)) or (marbles-user_in<0): # 1/0 used to cause an excepti... |
8a1285d448cf543a8bffdc9b834a88ed5dc3813d | utgwkk/brainfuck.py | /interpreter.py | 1,399 | 3.515625 | 4 | import sys
import re
def _generate_tree(program, ptr):
tree = []
while ptr < len(program):
if program[ptr] == '[':
leaf, nptr = _generate_tree(program, ptr + 1)
tree.append(leaf + [']'])
ptr = nptr
elif program[ptr] == ']':
return tree, ptr
... |
14d66cc839ac380257fb1f77437a6c502b16d263 | homepeople/PythonLearning | /src/像计算机科学家一样思考Python_Exercise3/Lesson005/Exercise5.5.py | 367 | 3.90625 | 4 | #coding=utf-8
#Exercise5.5
import turtle
Fred=turtle.Turtle()
#draw a branch
def draw(t,length,n):
if n==0:
return
angle=50
t.fd(length*n)
t.lt(angle)
draw(t,length,n-1)
t.rt(2*angle)
draw(t,length,n-1)
t.lt(angle)
t.bk(length*n)
if __name__ == '__main__... |
1beb1ebc3addef82905d9fcc28f4ea83685034dc | MdAbuZehadAntu/Django3 | /PythonRefresherOOP/InnerClass.py | 690 | 3.71875 | 4 | class Human:
def __init__(self, name, gender, h_color, h_type):
self.name = name
self.gender = gender
self.hand = self.Hands(h_color, h_type,self)
def show(self):
print(self.name, self.gender)
self.hand.show()
class Hands:
fingers = 5
def __init__(... |
242ccb6ad583cb09840d75281d4259e4de5db690 | juliamoraiss/python-CursoEmVideo | /Exercícios/ex050.py | 213 | 3.75 | 4 | soma = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {}º número: '.format(c)))
if n % 2 == 0:
cont += 1
soma += n
print('A soma dos {} valores pares é {}'.format(cont, soma))
|
37bbb68759df9d6256786600e7e73e84ac4b5e07 | r25ta/USP_python_1 | /semana4/primalidade.py | 302 | 4.09375 | 4 | def main():
print("Primalidade")
n = int(input("Digite um número inteiro:"))
if((n==2) or (n==3) or (n==5) or (n==7)):
print("primo")
elif((n%2==0) or (n%3==0) or (n%5==0) or (n%7==0)):
print("não primo")
else:
print("primo")
main() |
12971ba6f6a37ed9b6b94d8258366cbb48aada34 | nkchangliu/puzzles | /leetcode/longest_palindrome_subsequence.py | 484 | 3.6875 | 4 | def longest(s):
if len(s) == 0:
return 0
cache = [[1 for i in range(len(s))] for j in range(len(s))]
for i in range(len(s)-1, -1, -1):
for j in range(i+1, len(s)):
if j == i + 1 and s[i] == s[j]:
cache[i][j] = 2
elif s[i] == s[j]:
cac... |
f04514832c2d0039d0a647782c426e73b9dd04ff | shoter/PythonTex-presentation | /python/indentation.py | 130 | 3.6875 | 4 | # And this is a comment.
from random import randint
number = randint(0, 9)
if number < 5:
print("0-4")
else:
print("5-9")
|
f191e8a13c3ba4110f19e30b64654343cea4f061 | vijaykumar7686/python | /vj12.py | 125 | 3.515625 | 4 | #a
n1=int(input())
temp=n1
r=0
while(n1>0):
s=n1%10
r=r*10+s
n1=n1//10
if(temp==r):
print("yes")
else:
print("no")
|
370a32028c8d40c0c42ceb32499d02694ced079b | jevinkeffers/DC-Repos-Week-1 | /KJ_Python_101_lessons/Large/GUESS_A_NUMBER.py | 4,647 | 4.625 | 5 | # # 3. Guess a Number
# # You will implement a guess-the-number game where the player has to try guessing a secret number until they gets it right. For now, you will "hard code" the secret number to 5 (just set it to five like secret_number = 5). You will prompt the player to enter a number again and again, each time c... |
a48918d6091e6c7ae1aabc36b4573103f367d9b1 | matthewkot/pythonhillel | /lessons/lesson9.2_f.py | 1,277 | 3.6875 | 4 | import random
def create_point(min_limit,max_limit):
point = {"x": random.randint(-10, 10),
"y": random.randint(-10, 10)}
return point
def create_triangle(points_name_str, min_limit, max_limit) :
return {key: create_point(-100,100) for key in points_name_str}
triangle_ABC = create_triangle("... |
c03234c4dab7eafcecd38e146d70679c0e8ddb42 | NeonMiami271/Work_JINR | /Python_Linux/Graphics for Selynin/split.py | 117 | 3.65625 | 4 | f = open ('test.txt')
for line in f:
buf = list()
buf = line.split('_')
print(str(buf))
print(str(float(buf[3])))
|
bd9c460388507790367f0ec702710529c1984c0f | y-nagamoto/python_basic | /2-10.dictionary_method.py | 631 | 3.625 | 4 | d = {'x': 10, 'y': 20}
# help(d)
print(d.keys())
print(d.values())
"""
dict_keys(['x', 'y'])
dict_values([10, 20])
"""
d2 = {'x': 1000, 'j': 500}
print(d)
print(d2)
d.update(d2)
print(d)
print(d['x'])
print(d.get('x'))
"""
{'x': 10, 'y': 20}
{'x': 1000, 'j': 500}
{'x': 1000, 'y': 20, 'j': 500}
1000
1000
"""
r = d.ge... |
c07a38f6ae1df0f19f03738000e4a8e46db6fd67 | an33shk4tl4/PythonLearn | /iterables.py | 302 | 3.796875 | 4 | # iterating over multiple lists using zip
import pprint as pp
import os
days = ['Monday', 'tuesday', 'wednesday']
fruits = ['banana', 'orange', 'peach']
desserts = zip(days, fruits)
pp.pprint(desserts)
# raw_input('Please hit a key to proceed further')
os.system('pause')
print('End of program')
|
8e27cc0eaee85bb3fc95ce5ad3003bae801c0dcd | Larry-Volz/python-data-structures | /fs_2_valid_parentheses/valid_parentheses.py | 745 | 3.875 | 4 | def valid_parentheses(parens):
"""Are the parentheses validly balanced?
>>> valid_parentheses("()")
True
>>> valid_parentheses("()()")
True
>>> valid_parentheses("(()())")
True
>>> valid_parentheses(")()")
False
>>> valid_parentheses("())"... |
c3aff15c94eac814f5784b4d559552aeab374310 | MatejKopcik1/pytonik | /EDU18.py | 151 | 3.921875 | 4 | a = input("a = ")
b = input("b = ")
c = input("c = ")
if a < b < c:
print(a, "<", b, "<", c)
elif a < c < b:
print(a, "<", c, "<", b)
|
17a5dfb5e7894676104942ce5a82d17d9edb564c | C109156214/pythontest | /4.py | 1,033 | 3.84375 | 4 | x=int(input("X軸座標:"))
y=int(input("Y軸座標:"))
a=0
if x == 0 :
if y == 0:
print("該點位於原點")
elif y > 0:
a=y**2
print("該點位於上半平面Y軸上,離原點距離為根號",a)
else:
a=y**2
print("該點位於下半平面Y軸上,離原點距離為根號",a)
elif x > 0:
if y == 0:
a=x**2
print("該點位於右半平面X軸上,離... |
7fc3d735a01834f92f70bc3a29df6cb6f0496a30 | berazo29/network-fundamentals-py | /Server.py | 1,811 | 3.890625 | 4 | import argparse
from sys import argv
import socket
parser = argparse.ArgumentParser(description="""This is a very basic server program""")
parser.add_argument('-f', type=str, help='File to read the pairs words', default='Pairs.txt', action='store', dest='in_file')
parser.add_argument('port', type=int, help='This is t... |
49b85b54ee44e259ad3e050e7893c57f01642ffc | denis-nuzhdin/dntest3 | /test/lesson4.1.py | 993 | 4.09375 | 4 | # анограмма, угадывание слов по буквам в перемешку, глава 4
import random
WORDS = ("home",
"python",
"apple",
"google",
"led zeppelin",
"lp")
word = random.choice(WORDS)
correct = word
jumble =""
while word:
position = random.randrange(len(word))... |
95a28f2976beb68d5b66ef73be375b9a044a4007 | sakethraogandra/python1 | /1.py | 140 | 3.71875 | 4 | count=0
s=input("enter a strin :")
for i in s:
if(i =='a'or i =='e' i =='i' or i =='o' or i =='u'):
count=count+1
print(count)
|
aa19ff1b03d1acf71662ec0e3f5262cdea2e77c6 | TheGalacticCouncil/space-bridge | /HwReader/myIP.py | 416 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#https://www.w3resource.com/python-exercises/python-basic-exercise-55.php
import socket
def myIP():
ip = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127.")][:1], [[(s.connect(('1.1.1.1', 53)),
s.getsockname()[0], s.close()) for ... |
9449f24ef04c98c98ecda49a2fed060c5b84affb | debrouwere/data-analysis-in-python | /utils.py | 1,388 | 3.9375 | 4 | # encoding: utf-8
"""
Utilities for normalizing column names, which is useful
when you're using data from different data sources,
all with their own naming conventions.
"""
import re
import math
import collections
def normalize_name(name, separator='-'):
name = re.sub(r'([a-z])([A-Z])', r'\1-\2', name)
ret... |
0dcc9789953e4194c7bc04d28332e3efd2ee61cb | rk012/Python-Algorithms-and-Datastructures | /graphs/dfs.py | 659 | 3.78125 | 4 | from graphs.graph import Graph
def dfs(start, end, adj_list):
visited = [start]
stack = [start]
while len(stack) != 0:
current_node = stack.pop()
for x in adj_list[current_node]:
if x not in visited:
visited.append(x)
stack.append(x)
if ... |
3bb60b56e212391bdeec18a4995c10af14c6df6e | codecakes/algorithms | /algorithms/practice/int_sqr_range.py | 2,770 | 4.15625 | 4 | """
Problem Statement
Watson gives two integers (A and B) to Sherlock and asks if he can count the number of square integers between A and B (both inclusive).
Note: A square integer is an integer which is the square of any integer. For example, 1, 4, 9, and 16 are some of the square integers as they are squares of 1,... |
5e9e79c2f95c707b8d9b83613b914f6d8696ef97 | sasa33k/PSCourse | /_02b_exceptions.py | 4,316 | 4.0625 | 4 | """
raise an exception to interrupt program flow
handle an exception to resume control
unhandled exception will terminate the program
exception objects contain info about the exception event
"""
def convert(s):
try:
x = int(s)
print(x)
except ValueError:
print("Cannot convert (str)")
... |
d144f1959b9187a07e8df36047b1cd1323686a86 | wellqin/USTC | /leetcode/editor/cn/[537]复数乘法.py | 945 | 3.53125 | 4 | # 给定两个表示复数的字符串。
#
# 返回表示它们乘积的字符串。注意,根据定义 i2 = -1 。
#
# 示例 1:
#
#
# 输入: "1+1i", "1+1i"
# 输出: "0+2i"
# 解释: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要将它转换为 0+2i 的形式。
#
#
# 示例 2:
#
#
# 输入: "1+-1i", "1+-1i"
# 输出: "0+-2i"
# 解释: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要将它转换为 0+-2i 的形式。
#
#
# 注意:
... |
1095a84e5299bb1b4e951ea0a08590371c6ce426 | bi-nary-coder/CBSE-Class-11-Programs | /Ch 1- Data Handling/#5 Check if year is leap year.py | 355 | 4.4375 | 4 | #Question - Write a program to take year as input an check if it is a leap year or not.
# Solution=
year=int(input("Enter the year"))
if year%4 == 0:
if year%100==0:
if year%400==0:
print(f"{year} is leap year")
else:
print(f"{year} is not leap year")
else:
print(f"{year} is leap year")
else:
pr... |
814dfc1dbbedde2bd5d13df32e79b4b5c6a3bbd6 | Ebenezer-Rahul/ELO_RANKING_FOR-IPL-for-fun | /main.py | 3,848 | 3.8125 | 4 |
k = 40
baseRank = 100.0
import csv
class Team(object):
def __init__(self,name,rank):
#assert (type(name) == str and type(rank) == float)
self.name = name
self.rank = rank
def __str__(self):
return self.name
def __lt__(self,other):
return self.rank < other.rank... |
c4f4d8c4d432caff83d7a4394b56d3c83165105f | Dew2118/blackjack2 | /src/deck.py | 743 | 3.75 | 4 | from src.card import Card
import random
from src.custom_exception import DeckError
class Deck:
def __init__(self) -> None:
value = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
suit = ['S','H','D','C']
self.cards = [Card(v,s) for v in value for s in suit]
self.draw... |
bcec1ce34949131d16946eb1d1761f2271dd782d | r-arun/cse523 | /waiter/opt_sol.py | 15,111 | 3.625 | 4 | import sys
import itertools
import random
from copy import copy
GMIN = 2**32
GMAX = -GMIN
def generate_test(num):
arr = []
while len(arr) < num:
inp = random.random()
e = random.randint(0,10)
if(e > 5):
inp = inp * -1
arr.append(inp)
return arr
def median(points):
#Points is sorted
"""Given a sorted ... |
5205459cb550b7d0fdc94c9082362f6489ee9db8 | lo1cgsan/rok202021 | /2BP4/python_1/sort_wstaw.py | 830 | 3.546875 | 4 | import random
def losuj(lista, n, maks):
"""
Funkcja losuje n liczb z zakresu <0, n>
i dodaje je do listy.
"""
for i in range(n):
lista.append(random.randint(0, maks))
def sort_wstaw(lista, n):
"""
Funkcja sortuje listę liczb przy użyciu
algorytmu sortowania przez wstawianie.... |
df8a2c32664e756bdc357ba535de34d175c62a04 | xavierau/aind_soduku | /solution.py | 7,127 | 4.09375 | 4 | assignments = []
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def... |
05f832de457f92cfe61b831a2b90b248725f3c14 | nanli-7/algorithms | /merge-sort.py | 1,888 | 4.1875 | 4 | """ Merge Sort
This is a very simple sorting algorithm. Because it's also very inefficient,
Bubble Sort is not practical for real-world use and is generally only discussed
in an academic context. The basic theory behind BubbleSort is that you take an
array of integers and iterate through it; for each element at some i... |
794e2f551081b111d5c4516007d5e87aa05be37e | brajesh-rit/hardcore-programmer | /Binary Search/BS_min_diff_sorted_arr.py | 637 | 3.6875 | 4 | #Given a sorted array, find the element in the array which has minimum difference with the given number.
class Solution:
def binary_search(self, arr, low, high, x):
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > ... |
21c05e4f5d015d017b1065a892286c40451dba8e | lovejing0306/PythonInterview | /Chapter-005-generator/001_generators.py | 484 | 3.796875 | 4 | # coding=utf-8
## 生成器函数
def countdown(num):
print('Starting...')
while num>0:
yield num
num-=1
## 生成器表达式
# '()'表示一个生成器表达式,
# 不要混淆列表推导式‘[]’和生成器表达式‘()’
my_list = ['a', 'b', 'c', 'd']
gen_obj = (x for x in range(10))
if __name__ == '__main__':
val=countdown(5)
print(val)
print(val.ne... |
57ad6a5942bff9c9555d366616f01fc44b4346b2 | sanjitsbatra/Sentiment_Mining_Twitter | /sortfile.py | 194 | 3.59375 | 4 | import sys
def sort(f):
l=open(f).read().split('\n')
g=open('bigram-sorted','w')
l=sorted(l)
for i in l:
g.write('%s\n' % i)
g.close()
def main(file):
sort(file)
main(sys.argv[1])
|
6316091608d8a8c0c745f4f391919df70072b126 | abhijeet-rawat/Hackerrank-Submissions | /submissions/Write a function.py | 578 | 4.09375 | 4 | '''-----------------------------------------------------------------------
Problem Title: Write a function
Problem Link: https://www.hackerrank.com/challenges/write-a-function
Author: abhijeet_rawat
Language : Python 3
-----------------------------------------------------------------------'''
def is_leap(year):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.