blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
46c297698e33dd11c58bb2d67ad11775fddfa3e1 | Jacob-Sunny/cognixia-python | /function.py | 723 | 4 | 4 | def weird_arithmetic(x,y,z): #function definition
print((x**x + y**z)//z) #code block
weird_arithmetic(5,6,7) #function call
def myFunction(greeting,name):
print(greeting + " " + name)
myFunction("Hello","Jacob")
def returnFunction(x):
return x
someNumber = returnFunction(10)
print(someNumber)
print("*... |
a1aebb502daca30d90630b996592c76fa5a3e5c8 | mwrouse/Python | /Design Exercises/dd58.py | 3,732 | 3.71875 | 4 | """
Program......: dd58.py
Author.......: Michael Rouse
Date.........: 3/7/14
Description..: Modify dd57 by adding a rolling counter for number of problems correct and attempted
"""
from tkinter import *
from random import randint
# Class for GUI
class Application(Frame):
""" GUI Application """
... |
faba524317f09830bbe0096d3a5bb5fa72887c33 | Xiaoke1982/StockPriceIndicator | /UserInterface/KNN.py | 1,346 | 4.15625 | 4 | import numpy as np
import pandas as pd
class KNNLearner(object):
"""
The class builds a KNN model object and provides a method
to make prediction on new input points.
"""
def __init__(self, k=3, verbose=False):
#initialize the k in KNN model.
self.k = k
def f... |
f3aa43fe2ca55196597029d3fbc2b120642d4ed4 | gprender/challenges | /python/is_square.py | 622 | 4.15625 | 4 | # Library-less solution to check if an integer is a perfect square.
def is_square(n):
if (n < 0):
return False # real squares only
else:
return binary_search_is_square(0,n,n)
def binary_search_is_square(min,max,n):
# base case: [min,max] are adjacent integers
if max - min == 1:
... |
00221c988d7320fdd7417a775f38c8967046de97 | julissel/Practice_with_Python | /venv/include/number_belongs_to_given_intervals.py | 267 | 4.1875 | 4 | """
There are given intervals {-10}and(-5, 3]and(8, 12)and[16, infinity).
The program returns 'True' if the number belongs to any of interval's part? and 'False' if it not.
"""
numb = int(input())
print((-10 == numb)or(-5 < numb <= 3)or(8 < numb < 12)or(numb >= 16))
|
144affbc9d46e349ee76697c0f3ef466faaa3b3f | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Island of Knowledge/isIPv4Address.py | 1,723 | 4.0625 | 4 | """
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
IPv4 addresses are repres... |
0d343da9ceffc69544e330c68dd54325fb3ecc23 | yyzhu0817/leetcode- | /链表/160.找出两个链表的交点.py | 1,226 | 3.703125 | 4 | '''
执行结果:
通过
显示详情
执行用时 :
164 ms
, 在所有 Python3 提交中击败了
84.53%
的用户
内存消耗 :
28.3 MB
, 在所有 Python3 提交中击败了
31.27%
的用户
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA, headB):
p1 ... |
5a126da44167cb3a08871d65a91f74dba1eedf13 | roboGOD/Python-Programs | /chaoticBribes.py | 2,220 | 4.03125 | 4 | #!/bin/python
'''
It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride!
There are a number of people queued up, and each person wears a sticker indicating their
initial position in the queue. Initial positions increment by 1 from 1 at the front of the line to n at the back.
Any person in t... |
2b1c22439248ac18ea315f80bb63424376c74c8d | hoodielive/python_automated_testing | /automated_software_testing/blog/app.py | 452 | 4.28125 | 4 | MENU_PROMPT = 'Enter "c" to create a blog, "l" to list a blog, "r" to read one, "p" to create a post and "q" to quit.'
blogs = dict() # mapping blog_name to blog_object
def menu():
# Show the user the available blogs
# Let the user make a choice
# Do something with that choice
# Eventually
print_b... |
71cb6300f8d026e2f002fd6f904f8cfe602f4af4 | ani03sha/Python-Language | /06_itertools/05_compress_the_strings.py | 400 | 4.03125 | 4 | # You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these
# consecutive occurrences of the character 'c' with (X,c) in the string.
from itertools import groupby
# Using list comprehensions, we are getting the length of occurrence of character c. x is the key i.e. c... |
ea0967e72eee3ca951c1a52eab1170aa52eaba96 | yglj/learngit | /PythonPractice/廖雪峰Python/14.sqlite.py | 2,439 | 3.78125 | 4 | # SQLite 一种嵌入式数据库
# 一个数据库连接称为Connection
# 通过 游标Cursor 执行sql语句
# Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。
import sqlite3 #导入驱动
'''
try:
conn = sqlite3.connect('s.db') #创建连接对象
cursor = conn.cursor() #创建游标对象
#cursor.execute('create table stu (name varchar(10),id int primary key... |
47d17b25cfc1a40c5fad46cead9740882a80dfaa | Brunocfelix/Exercicios_Guanabara_Python | /Desafio 042.py | 924 | 4.34375 | 4 | """Desafio 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo
será formado:
Equilátero: todos os lados iguais
Isósceles: dois lados iguais
Escaleno: todos os lados diferentes"""
# Desafio 035: Desenvolva um programa que leia o comprimento de três retas e diga ao usuário s... |
fb013e1ec44efb1fc590ee03e5aff0a2dbe078de | generic-user1/restaurant-selector | /output_formatting.py | 1,776 | 4.15625 | 4 |
#output formatting
#functions to print information in defined,
#human readable formats
#given a place id (from the Maps API),
#return a URL that points to that location
#on the Google Maps website.
#note that this DOES NOT require an API call;
#this is simply creating a URL that the user
#can put into their browse... |
04324d7b50ce291897aa243aaad36001d8a431ab | lizhihui16/aaa | /pbase/day15/shili/myzip.py | 1,187 | 3.78125 | 4 |
# numbers=[10086, 10000, 10010, 95588]
# names = ['中国移动', '中国电信', '中国联通']
# # def myzip(*args)
# def myzip(iter1,iter2):
# #先拿到两个对象的迭代器
# it1=iter(iter1)
# it2=iter(iter2)
# while True:
# try:
# a=next(it1)
# b=next(it2)
# yield(a,b)
# except StopIte... |
e3afacc8652b61bc007a586e4d2de7ed3165647a | rj-aj/my-coding-assignments | /Python/Python_I/PythonFundamentals/funWithFunctions.py | 1,861 | 4.46875 | 4 | """
Assignment: Fun with Functions
Create a series of functions based on the below descriptions.
Odd/Even:
Create a function called odd_even that counts from 1 to 2000.
As your loop executes have your program print the number of that iteration
and specify whether it's an odd or even number.
Your program output shou... |
7df2b180ce9ad97c5347764f5d8e5f0319a1ddaf | priyanka-cse/python | /program 1a.py | 145 | 3.609375 | 4 | a=[]
b=[]
size=int(input("enter the size"))
for i in range(size):
a.append(int(input()));
if(a[i]%2==0):
b.append(a[i])
print(b)
|
91e589d184294d6a273fcf367f0baeb9c1e18349 | ddarkclay/programming-cookbook | /Harry_Python/Multilevel Inheritance.py | 593 | 3.9375 | 4 | class Person:
def printpersondata(self,name,age):
self.name = name
self.age = age
print(f"Name is : {self.name} and Age is : {self.age}")
class Player(Person):
def printplays(self,plays):
self.plays = plays
print(f"Player Plays : {self.plays}")
class Employee(Player):
... |
7797f056b2156665874ec42dc1cd6e83c098f13d | pepelamah/MesRevisions | /TP_GE.py | 522 | 4.1875 | 4 | moy_int=0
while moy_int==0:
moy_str=input("Saisir votre note: ")
try:
moy_int=int(moy_str)
except:
print("Veuillez saisir une valeur numérique!!")
else:
if(20>=moy_int>=18):
print("Excellent!")
elif(18>moy_int>=14):
print("Très bien!!")
... |
7889281eab4f558940016a4e78cf3c30b1ff7a06 | rheehot/Algorithm-53 | /Programmers/Level2/124 나라의 숫자.py | 621 | 3.71875 | 4 | def solution(n):
answer = ''
# 몫과 나머지
quotient = 1
remainder = 1
# 나머지에따라 값 바꿔주기 위한 dictionary
country = {1: "1", 2: "2", 0: "4"}
# 몫이 0일때까지 반복
while quotient != 0:
quotient = n // 3
remainder = n % 3
# 나머지가 0일 경우에는 몫에서 1을 빼준다
if remainder == 0:
... |
f906f2d144132316f48474911e157e0389926dd0 | crizzy9/Algos | /data_structures/queue.py | 611 | 3.921875 | 4 | class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return not bool(self.items)
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
... |
2a7127f9b901619456b56e83155ca7a84936f5a4 | Max143/Python_programs | /String manipulation.py | 424 | 4.09375 | 4 | # String Manipulation
# Find the length of string
print("Find the length of string.")
Fucking_style =(input("Which style you choose to fuck Mansi ? "))
def string_length(style):
return(len(style))
print(string_length('Anal'))
def string_length(my_string):
count = 0
for letter in my_... |
b467891803f375578a7ec512b5cf7687f7e1973c | PhilippeOC/p7 | /optimized.py | 2,412 | 3.515625 | 4 | import argparse
import csv
import time
def get_data_actions(file_name: str) -> list:
""" retourne la liste des données des actions : nom, prix, profit, rentabilité """
actions = []
with open(file_name, newline='', encoding='utf-8') as csvfile:
datas = csv.reader(csvfile, delimiter=',', quotechar="... |
8121250f8a1d25babbac135460110cb9bfced48f | execion/wordlist | /py/functionality.py | 3,640 | 3.578125 | 4 | from random import randint
def verifyRepeate(word, table, cursor):
sql = "SELECT * FROM {} WHERE word=\"{}\";".format(table, word)
cursor.execute(sql)
result = cursor.fetchall()
if len(result) > 0:
return True
else:
return False
def addWord(word, meaning, table, cursor):
sql = "... |
40399459d51dfe5d9c394ac385b57be6eaf34325 | mctopherganesh/diabetes_data | /dis_helper.py | 1,462 | 3.53125 | 4 | import sqlite3
import datetime
import pandas as pd
def db_and_table_name_setter(name_of_db, name_of_table):
return name_of_db, name_of_table
def create_table_for_bs(name_of_db, name_of_table):
# function for testing and creating bs data table
conn = sqlite3.connect(name_of_db) # previously 'bs.db'
c ... |
e7d438416515a8f1f68e864b353b01c30672e592 | corey-miles/Python-Projects | /word_count_gen/word_count_gen.py | 1,569 | 3.984375 | 4 | '''
Script using a text file, reads each word into a
dictionary, then output an HTML file in a Tag Cloud
format.
** Project based on a course project **
CSS file created by dept.
'''
import os
from utils import FileParser
from web import MarkupParser
#################
## MAI... |
82315198e104b24b1612134a8400cfedadfe4e4c | elenalb/geekbrains_python | /lesson2/set.py | 519 | 3.640625 | 4 | # множества
my_set_1 = set('simple')
my_set_2 = frozenset('simple')
print(my_set_1)
print(my_set_2)
my_set_1.add(1)
print(my_set_1)
my_set_1.remove('s')
print(my_set_1)
my_set_1.pop()
print(my_set_1)
my_set_3 = {1, 3}
print(my_set_3)
my_set_3.clear()
print(my_set_3)
print(my_set_1)
print(my_set_2)
# вычитание
print... |
a275a21c9ac895db4817418a1fc330875a594388 | rvcjavaboy/eitra | /MIT python course/Assignment 1/Exercise_1_8.py | 602 | 3.84375 | 4 | #1
for i in range(1, 11):
print ("1/" + str(i) + " is " + str(1.0/i))
#2
n = int(input("Enter no. for countdown: "))
if n>0:
while n!=0:
n-=1
print(n)
else:
print("You've entered wrong or negative number")
#3
base = int(input("Enter base: "))
exp = int(input("Enter exp... |
a8473a3f04a04525e09aa06f52f5d3fda397029a | aditisinghq/IRobotics-assignments | /a2.py | 337 | 3.5 | 4 | import numpy as np
import math
def main():
p=[[2],[3],[0]]
#for rotation about x axis twice by 30 degrees
r1=np.array([[1,0,0],[0, 0.5, -0.866],[0, 8.66, 0.5]])
#for rotation about y axis by 30 degrees
r2=np.array([[0.866,0,0.5],[0,1,0],[-0.5,0,0.866]])
r=np.matmul(r2,r1)
rr=r.transpose()
res=np.matmul(rr,p)
p... |
dac765fb91cb2541d79cb9bb7e57ba9f1944c0dc | nikolaikk/First_try | /python try/surface3d_demo2.py | 2,051 | 4.15625 | 4 | '''
========================
3D surface (solid color)
========================
Demonstrates a very basic plot of a 3D surface using a solid color.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
#ax = fig.add_subplot(111, projection='3d')
# Make data... |
3a4872723eb8bbc8b256618586c427543eed20f9 | heinthu12/Python | /MyPython/Exercise/and.py | 83 | 3.53125 | 4 | x = 9
y = 3
# use and logic
print(x >= 5 and x <= 10 )
print(y >=5 and y <=10)
|
476cd1cdcbf8dc422e4dffdc7c81e66249db3493 | Aasthaengg/IBMdataset | /Python_codes/p00001/s630899474.py | 219 | 3.8125 | 4 | #coding:UTF-8
def LoT(List):
List2=sorted(List)
for i in range(3):
print(List2[len(List)-1-i])
if __name__=="__main__":
List=[]
for i in range(10):
List.append(int(input()))
LoT(List) |
405e9016b0b748ee1c757b98dd580977c1bef572 | xfhy/LearnPython | /廖雪峰老师的教程/7. 面向对象高级编程/使用__slots__.py | 1,555 | 3.796875 | 4 | # 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性
class Student(object):
pass
s = Student()
# 绑定属性
s.name = 'xfhy'
print(s.name)
# 绑定方法
def set_name(self,name):
self.name = name
from types import MethodType
s.set_name = MethodType(set_name,s) #给实例绑定一个方法
s.set_name('xfhy666')
print(s.name)... |
a9f8bdbb607ed16c977d70a78b494d74ed8adb9f | Anju-PT/pythonfilesproject | /exam/removeduplicate.py | 143 | 3.53125 | 4 | lst=[1,2,4,5,6,7,3,2,3,1,10]
s=[]
for i in lst:
if i not in s:
s.append(i)
print(s)
l=len(lst)
#output
#[1, 2, 4, 5, 6, 7, 3, 10]
|
e8878836d7646cdb4c2e1c73aa1d074812acd8a1 | github-hrithik/stringl1-py | /Q4level1.py | 160 | 3.6875 | 4 | #Count Number of vowels
st=input("Enter String-")
stf=st.upper()
ctr=0
for i in stf:
if i in ["A","E","I","O","U"]:
ctr+=1
print(ctr)
|
1fc36f89c90e0c2ba56b8f889a68a11664f1037a | yiming1012/MyLeetCode | /LeetCode/双指针(two points)/1423. 可获得的最大点数.py | 2,603 | 3.671875 | 4 | """
1423. 可获得的最大点数
几张卡牌 排成一行,每张卡牌都有一个对应的点数。点数由整数数组 cardPoints 给出。
每次行动,你可以从行的开头或者末尾拿一张卡牌,最终你必须正好拿 k 张卡牌。
你的点数就是你拿到手中的所有卡牌的点数之和。
给你一个整数数组 cardPoints 和整数 k,请你返回可以获得的最大点数。
示例 1:
输入:cardPoints = [1,2,3,4,5,6,1], k = 3
输出:12
解释:第一次行动,不管拿哪张牌,你的点数总是 1 。但是,先拿最右边的卡牌将会最大化你的可获得点数。最优策略是拿右边的三张牌,最终点数为 1 + 6 + 5 = 12 。
示例 2:
... |
fac9e42fc5d9ff5a7ea08cf78950ffa3efec1a70 | glavdev/SquareChallenge | /algorithms/hello.py | 2,322 | 3.625 | 4 | """Ознакомительная реализация
Пример поиска границ заказа
Автор: Alexandr Gorlov
"""
import cv2
def square(image) -> int:
"""Определим площадь, с помощью OpenCv.findContours"""
image = cv2.imread("./imgs/" + image)
# 0. вырежем центральную часть
#image = image[100:1700, 350:2050]
# 1. ... |
5e3277d2ded388beb5ae2c9d0cab84d03df20e7d | The-1999/Snake4d | /src/score.py | 7,058 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 25 22:01:56 2018
@author: Mauro
"""
#==============================================================================
# Score board
#==============================================================================
import datetime
import os
from tkinter import Label, Toplevel... |
44efe9184d35af42951f7e8a3914475475e7ceec | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter5/q31.py | 498 | 4.0625 | 4 | """
recursion, sum the two dimensional list
"""
def sum_one_list(data):
total = 0
if not isinstance(data, list):
return data # for one value, just return the value for the addtion in total += sum_one_list(element)
else: # for a list, go deeper into each element
for element... |
df541f0524f189bbe1d8e8910678fb494e7b2be8 | ruizhiwang11/2001-lab | /Lab1/testcaseAutoGen.py | 1,117 | 3.5 | 4 | import random
import json
TestingCharlist=['A','C','G','T']
listGen={}
tmpgen={}
testinglist={}
#Parameter you need to set
LOWER_BOUND=7
HIGHER_BOUND=10
REPEAT_TIME=5
def readInPut():
LOWER_BOUND = input ("Enter LOWER_BOUND :")
HIGHER_BOUND = input ("Enter HIGHER_BOUND :")
REPEAT_TIME = input ("Enter... |
da0f3462591f4d70d1227d57215800395d463b6e | vin-nag/Sudoku-SAT | /Model/sudoku.py | 2,105 | 3.859375 | 4 | import numpy as np
class Sudoku:
"""
A class that represents a Sudoku board
The board is stored internally as a numpy array
Zeroes preresent blank spaces
"""
def __init__(self, degree, matrix=None):
self.degree = degree
if matrix is None:
self.matrix = np.zeros((deg... |
e8340d9cbb12043870fc2e8e80e225f6e788e3a4 | alexjohnlyman/Python-Exercises | /4-8-15.py | 275 | 3.65625 | 4 | """
weekday false, vacation false true
weekday true, vacation false false
weekday false, vacation true true
"""
def sleep_in(weekday, vacation):
return vacation or not weekday
print sleep_in(False, False)
print sleep_in(True, False)
print sleep_in(False, True) |
4aec6bd05dacc556b10906d3a5692c48ec0d70a1 | shivapri/Ai | /main.py | 9,606 | 3.59375 | 4 | import numpy as np
import random
#
p=[]
for i in range(0,3,1):
c=[]
for j in range(0,3,1):
c.append('_')
p.append(c)
for i in range(0,3,1):
for j in range(0,3,1):
print(p[i][j],end=" ")
print('\n')
def checkRows(board):
for row in board:
if len(set(row)) == ... |
b720ed6db5eb0842d0652ec4fe5e64bc874c8096 | nei1d0r/python | /helloworld.py | 884 | 4 | 4 | def main():
print("Name: {name}\nAge: int{age}\nFavourite Colour: {colour}\nPet name(s): {pet}\nHobbies: {hobby}".format(name = input("What is your name? "),age = int(input("How old are you? ")),colour = input("What is your favourite colour? "),pet = input("What is/are your pet's name(s)? "),hobby = input("What are... |
77e99a341c2f4ea0bb098a698317e724b59d6847 | ckidckidckid/leetcode | /LeetCodeSolutions/140.word-break-ii.python3.py | 1,900 | 3.609375 | 4 | #
# [140] Word Break II
#
# https://leetcode.com/problems/word-break-ii/description/
#
# algorithms
# Hard (24.68%)
# Total Accepted: 115.3K
# Total Submissions: 466.6K
# Testcase Example: '"catsanddog"\n["cat","cats","and","sand","dog"]'
#
# Given a non-empty string s and a dictionary wordDict containing a list of... |
5257a3610ac3e81812272932176bed7c284160a3 | didoman/prog101tasks | /week0/normal/iterationsofnanexpand.py | 605 | 3.859375 | 4 | #iterations of nan expand
def iterations_of_nan_expand(expanded):
if len(expanded) == 0:
print(0)
return 0
elif "Not a NaN" in expanded:
counter = expanded.count("Not a")
print (counter)
return counter
else:
print("False")
return False
iterations_of... |
a39f2b66c43d1f59ff942e33741c9bc4e26a9b95 | toggled/NetTrees | /metric.py | 4,114 | 4.3125 | 4 | """
Defines classes to compute the distance between points in any general metric spaces.
"""
from abc import ABC, abstractmethod
import functools
from config import config
class Metric(ABC):
"""
An abstract base class for any arbitrary metric which delegates the distance
computation to its concr... |
15cec1129c5142f3f7a41ae119ff540df5130717 | SaudiWebDev2020/Sumiyah_Fallatah | /Weekly_Challenges/python/week5/week5day1.py | 3,255 | 4.21875 | 4 | # Node
# - Constructor
# -val
# - next
class StackNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = None
# -Constructor
# - head
class Stack:
def __init__(self):
self.head = None
temp = self.head
# Stack Push
# --... |
f6172f74dedf06addccb87890613690ddadc2b75 | sahar-murrar/python_stack | /_python/python_fundamentals/Functions Intermediate II/Task3.py | 512 | 4.1875 | 4 | students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def iterateDictionary2(key_name, students):
for student in stud... |
368b3bd63d3a7c60fa192c6f95848bc971949b46 | ArmaniGiles/P | /com/fireboxtraining/box.py | 215 | 3.5 | 4 | '''
Created on Jun 11, 2017
@author: moni
'''
def square(x):
return x * x
def sta():
if __name__ == '__main__':
print ("test: square(42) ==", square(42))
print ("this is mygame.")
print (17*17) |
5414157e6935b057f7dcaecc9ff0ec752d47f960 | bansal19/PizzaParlour | /PizzaParlour.py | 6,666 | 3.578125 | 4 | from flask import Flask, request
from Classes.Menu import Menu
from Classes.Order import Order
from Classes.MenuItem import MenuItem
from Classes.Drink import Drink
from Classes.Pizza import Pizza
import json
menu_path = "Classes/Menu.json"
app = Flask("Assignment 2")
menu = Menu(menu_path)
# Store all the orders
a... |
88f42e0e7fea00efdeb616293b9182c7b083a77b | J-Krisz/EDUBE-Labs | /PCAP/2.5.1.9 LAB: The Digit of Life.py | 868 | 4.5 | 4 | """
Some say that the Digit of Life is a digit evaluated using somebody's birthday. It's simple - you just need to sum
all the digits of the date. If the result contains more than one digit, you have to repeat the addition until you get
exactly one digit. For example:
1 January 2017 = 2017 01 01
2 + 0 + 1 + 7 ... |
6da6d2660dd06466767f0fdf0d052d9fe350bee0 | tangmingyi/offer | /4.py | 638 | 3.75 | 4 | # -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target:int, array:list)->bool:
rows = len(array)
cols = len(array[0])
for col in range(cols-1,-1,-1):
for row in range(rows):
if(array[row][col]>target):
break
... |
1b8ad2897d1c89ea821aa7a779f522af57de8fc2 | devynchew/number-guessing-game | /noGuessGame.py | 1,286 | 3.90625 | 4 | max = int(input("Enter the range: ")) # Get max number
johnsNumber = int(input(f'Think of a random number between 1 and {max} and press enter once done: ')) # Get the number the program has to guess
numberHasBeenGuessed = False
noOfQuestions = 0
candidates = list(range(1,max+1))
# breakpoint = 1 # Initialize first oldb... |
795f87bd4abdf66b13fbd17cf5ef3f68a6d3af0e | maria-zdr/softuni | /Python Fundamentals/Functions/4.Draw a Filled Square.py | 215 | 3.96875 | 4 | def print_dashes(n):
print('-' * 2 * n)
def print_middle(n):
for i in range(0, n - 2):
print('-' + '\\/' * (n - 1) + '-')
num = int(input())
print_dashes(num)
print_middle(num)
print_dashes(num)
|
30122f2f9bd8b4cc27a3643d974ad3b52113205f | hussainMansoor876/Python-Work | /Chapter 2 & 3/title 1.py | 108 | 3.53125 | 4 | name="Mansoor"
age=18
info=name+" "+str(age)
print(name)
print(age)
print(info)
print(name + " " + str(age)) |
f36b98a01be793430cfd49640364aaccddb44b1c | Bankole2000/pirple-training | /pirplePython/main.py | 1,373 | 3.703125 | 4 | """
FileName: main.py V1.0
Author: Bankole Esan
Description: Pirple.com Python Homework #1
Task: Variables for attributes of favorite Song
"""
SongTitle = "Wa Mpaleha" # Title of the song
Artist = "Lira" # Recording Artist
Genre = "R & B" # Genre or Category of the song
DurationInSeconds = 204 # Length of song in ... |
1e659720b23761566d50fc3313657a2e7759dbad | roryfortune/CP1404-Practicals | /prac_05/STATE_NAMES.py | 552 | 4.34375 | 4 | stateNames = {"QLD": "Queensland",
"ACT": "Australian Capital Territory",
"NT": "Northern Territory",
"VIC": "Victoria",
"WA": "Western Australia",
"TAS": "Tasmania",
"NSW": "New South Wales"}
states = input("Enter short state:... |
55c8d53a7d054102429a24dc9f27ca7f2bb5680c | boyshen/leetcode_Algorithm_problem | /680.验证回文字符串Ⅱ/validPalindrome.py | 2,267 | 3.609375 | 4 | # -*- encoding: utf-8 -*-
"""
@file: validPalindrome.py
@time: 2020/11/18 下午2:24
@author: shenpinggang
@contact: 1285456152@qq.com
@desc: 680. 验证回文字符串 Ⅱ
给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。
示例 1:
输入: "aba"
输出: True
示例 2:
输入: "abca"
输出: True
解释: 你可以删除c字符。
注意:
字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
来源:力扣(LeetCode)
链接:https... |
a1915e013cf9e1800bc457eb508495da4fb72917 | mengyujackson121/CodeEval | /split_the_number.py | 477 | 3.75 | 4 | import sys
import re
def split_plus_or_minus(integer_string):
if "+" in integer_string:
first, second = integer_string.split("+")
print int(first) + int(second)
else:
first, second = integer_string.split("-")
print int(first) - int(second)
f = open(sys.argv[-1],'r').readlines(... |
6f2957a258449386d7525f541ed076459bcc5175 | Squirrel-zc/Learn_share | /Try/guess_age_第一版.py | 2,205 | 3.578125 | 4 | # coding-utf-8:
import cent_screen
def guess_age(true=29,n=3,c=0): # true是正确年龄,n为可猜次数,c为已猜次数
range_begin=true-10
if range_begin<=0:
range_begin=1
range_over=true+10
if range_over<=10:
range_over=11
age_range=[range_begin,range_over]
print('我的年龄范围是:',range_be... |
981330b014f914095451db154cd064adebb5209f | AlexandreVelloso/escola-de-ferias | /2018-1/Introdução a criptografia e segurança digital/Codigos/Desafio 1/Vigenere.py | 951 | 3.609375 | 4 | import sys
def criptografa( mensagem, senha ):
mensagemCriptografada = ''
pos = 0
for c in mensagem:
mensagemCriptografada += chr( ( ord(c) + ord(senha[pos]) ) % 256 )
pos = ( pos + 1 ) % len( senha )
return mensagemCriptografada
def descriptografa( mensagem, senha ):
mensagemCrip... |
2713d49761eb192a0fbf433f5dcf5526809dd906 | trigus00/python-challenge | /Pybank/main.py | 2,198 | 3.6875 | 4 | import os
import csv
from statistics import mean
budget_data_path = os.path.join('/Users/gmendoza/Documents/GitHub/python-challenge/Pybank/main.py','budget_data.csv')
total_month = 0
total_revenue = 0
change_in_revenue_list = []
previous_revenue = 0
percent_increase = [" " ,0]
percent_decrease = [" " ,0]
... |
696ade49a388256b3c1ed043c8ce6f3f74d108a6 | idahopotato1/learn-python | /09- Python Decorators/003-decorators.py | 1,102 | 4.28125 | 4 | # functions as Arguments
print('=============================================')
def hello():
return 'Hello'
def other_fun(fun):
print('other fun')
print(fun())
other_fun(hello) # other fun , Hello
print('=============================================')
def new_decorator(func):
def wrap_func():... |
43d7c323bff218ec7ced79ddda28537e36dc05cd | kdockman96/CS0008-f2016 | /Ch3-Ex/ch3-ex11.py | 469 | 4.21875 | 4 | # Ask the user to enter the number of books purchased
books = int(input('Enter the number of books purchased: '))
# Write an IF-ELIF-ELSE statement, but an else statement \
# is not needed in this situation
if books == 0:
print('No points are awarded.')
elif books == 2:
print('5 points are awarded.')
elif book... |
d71e7905878eafacf189fce5f7df2a9e39c69e3a | EishaMazhar/Semester6-Resources | /IR/Batch15_Assignment/positional index/search.py | 2,949 | 3.6875 | 4 | import json
from nltk.stem import PorterStemmer as ps
import nltk
with open("index_without_stem.json", "r") as read_file:
index = json.load(read_file)
def intersection(a,b):
result = []
for item in a:
if item in b and not item in result:
result.append(item)
return result
def singl... |
158cce25a012104652c81075282f4e4fa1d27974 | climberhunt/wiring-x86 | /examples/fade.py | 1,814 | 4.0625 | 4 | # -*- coding: utf-8 -*-
#
# Copyright © 2014, Emutex Ltd.
# All rights reserved.
# http://www.emutex.com
#
# Author: Nicolás Pernas Maradei <nicolas.pernas.maradei@emutex.com>
#
# See license in LICENSE.txt file.
#
# This example is inspired on Arduino Fade example.
# http://arduino.cc/en/Tutorial/Fade
#
# This example... |
62c27d800f72b4521403a04c9cece0b778bd34a5 | lntutor/cp | /practice/python/time_conversion.py | 289 | 3.796875 | 4 | time = raw_input()
if 'AM' in time:
hh = (int) (time[:2])
if hh == 12:
hh = '00'
print hh + time[2:8]
else:
print time[:8]
else:
hh = (int) (time[:2])
if hh != 12:
hh += 12
print `hh` + time[2:8]
else:
print time[:8] |
83a57f785080067ca38aab040bd2c65fd7d9cc68 | kamit17/Python | /Think_Python/Chp11/Examples/primes_lessthan.py | 451 | 4.09375 | 4 | def is_prime(n):
if ( n ==1):
return False
elif (n ==2):
return True
else:
for x in range(2,n):
if(n %x ==0):
return False
return True
def primes_lessthan(n):
"""Returns a list of all prime numbers less than n."""
result = []
for i in ... |
3536a6f56204797b26c60818e7dad939d6b7f482 | saritaverma60/python-program | /recursion-factorial.py | 197 | 4.15625 | 4 | # Recursion Factorial of number
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
n=int(input("Enter the no. :"))
R=fact(n)
print("FACTORIAL of ",n," is ",R)
|
bada6cf0c7e88733ab8caa0881458d803e74c335 | Kabileshj/college-works | /Stacks and Queues/Sort Stack.py | 556 | 4.03125 | 4 | def sortedInsert(s , element):
if len(s) == 0 or element > s[-1]:
s.append(element)
return
else:
temp = s.pop()
sortedInsert(s, element)
s.append(temp)
def sortStack(s):
if len(s) != 0:
temp = s.pop()
sortStack(s)
sortedInsert(s , temp)
def printStack(s):
for i in s[::... |
74c671655defa6123b02ec3d286f5e5518f181de | qiangzuangderen/My_code | /python_learn/py_test/mypro_base/gridPassing.py | 174 | 3.75 | 4 | #coding=UTF-8
grid0 = [[1,2],[3,4],[5,6]]
grid1 = []
print(grid0)
for i in range(3):
print(grid0[i])
for j in range(2):
print(grid0[i][j])
|
ee4268323ad177d7c25992105149d646ea764124 | eloghin/Python-courses | /HackerRank/pilingup.py | 1,362 | 4 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
"""
There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical
pile of cubes. The new pile should follow these directions: if cubei is on top of cubej then sideLengthj>=sideLengthi.
When stacking the ... |
a5874e39f6d28e5a4feaa396b7f0d3827570ba17 | rachel2011/Job | /CC150/chap01/is_unique.py | 396 | 3.828125 | 4 |
def isUniqueChars(input):
# O(n) time
if len(input) > 128:
return false
charSet = [False] * 128
for char in input:
index = ord(char)
if charSet[index]:
return False
charSet[index] = True
return True
# Test
input = 'a'
print isUniqueChars(input)
input = '... |
5de5aeebb607b47b54b82d97b766423c065dcda9 | sunnyhyo/Problem-Solving-and-SW-programming | /lab12-1.py | 439 | 3.65625 | 4 | #실습1
import turtle
def play():
t.forward(2)
screen.ontimer(play, 10)
t=turtle.Turtle()
t.up()
screen=t.getscreen()
screen.ontimer(play,10)
import turtle
stop=False
def moveStop():
global stop
stop=True
def play():
t.forward(2)
if stop ==False:
screen.ontimer(play, 10)
t=turtle... |
259b05cab684c7866d4462099529706526580f24 | mwiens91/sfu_ec_2017_10_29 | /safetrain/train.py | 3,789 | 4.03125 | 4 | """Train class and related functions."""
from . import controller
from enum import Enum
class TrainState(Enum):
"""Simple enumerator which holds state of train."""
INMOTION = 1
IDLING = 2
OOS = 3
EMR = 4
class Train:
"""Represents a train on the transportation grid.
Attributes:
i... |
690e5cda620a8d2c8b5a6a1cd5657d4750a11eb0 | vit050587/Python-homework-GB | /lesson2.4.py | 1,177 | 3.8125 | 4 | # 4. Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
n_str = input("введите строку: ")
word = []
number = 1
el = 0
for el in range(n_str.count(' ') + 1):
wor... |
ba661bb30923b54847bb2ce9c967f4f8b5e54367 | Abdulrehmanvirus10/Automate_the_boring_stuff_with_Python | /tests/test_4.py | 129 | 3.78125 | 4 | def printMyName(myName):
print('My name is' + myName)
print('Who are you ?')
myName = input()
printMyName(myName)
|
77e644180f2598e302f357d888ca3363adde5f32 | woshihehao/Game | /game2.py | 1,357 | 3.5 | 4 | # -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name_, atk_, blood_, defense_):
self.name = name_
self.atk = atk_
self.blood = blood_
self.defense = defense_
def attack(self, b):
if b.defense <= self.atk:
real_damage = self.atk - b.defense
... |
29f13cfa558c53cfca4391c394fc566f08e9cfe4 | sailakshmi-mk/pythonprogram1 | /venv/co1/10. Area of circle.py | 80 | 4.03125 | 4 | r=int(input("enter a radius"))
area=3.14*r*r
print("the area of circle is",area) |
ef0f6e9bb6e2412fdc6546b14705ecea522a11bb | Tdfrantz/DJST-AI | /src/card.py | 1,536 | 3.984375 | 4 | # classes and functions for cards and decks of cards
import random
cardNumbers = ["ace",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"jack",
"queen",
"king"]
cardSuits = ["spades","hearts","diamonds","clubs"]
blackjackValues = [11,2,3,4,5,6... |
079d558de95f4650e766e308d04b68f86c1a62fc | ParisRohan/Python_Projects | /max_occurrence.py | 483 | 4.28125 | 4 | #Program to print maximum occurrence of a character in an input string along with its count
def most_occurrence(string_ip):
count={}
max_count=0
max_item=None
for i in string_ip:
if i not in count:
count[i]=1
else:
count[i]+=1
if count[i]>max_co... |
d2af354745db4ae3b8bb1846df55ecfd90623e4f | cboopen/algorithm004-04 | /Week 02/id_329/LeetCode_94_329.py | 1,881 | 4.0625 | 4 | # coding=utf-8
"""
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
"""
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
... |
93dd9ffd97af04d2212ca02ee47493d36e6a1d49 | ds-ga-1007/assignment7 | /yz1349/assignment7.py | 1,183 | 3.90625 | 4 | import sys
from interval import interval,insert
if __name__=="__main__":
while True:
try:
inputstring = raw_input("List of intervals? ")
if inputstring == "quit":
sys.exit()
inputstring = inputstring.replace(" ","")
stringlist = inputstring.s... |
992199cd12ef1cd4b2fcb3369bb26068f9b5d614 | odilonjk/matematica | /limites/exemplo_1.py | 514 | 3.578125 | 4 | # %%
from sympy import Symbol, Limit, init_printing
init_printing(use_latex=True)
x = Symbol('x')
def f(x):
return (x**3 + x**2 + x)**101
def g(x):
return (x**2 - (2 * x)) / (x + 1)
print('Considerando a função f(x)')
display(f(x))
print('\ne a função g(x)')
display(g(x))
limite_fx = Limit(f(x), x, -1)... |
fd52e8e4bd85af7a95234e8a2387bbf3fd8143a6 | seoyoungsoo/CodingTest-Python | /Programmers/Lv1/lv1_3진법뒤집기.py | 482 | 3.65625 | 4 | # 3진법 뒤집기
# 나의 풀이
THREE = 3
def solution(n):
question = []
answer = 0
decimal = n
while True:
if decimal > 0:
modular = decimal % THREE
question.append(modular)
decimal //= THREE
else:
break
sqrNum = 0
for x in range(len(questi... |
c549b371e1c1a36905f24bd9e3344ff9ff64ab4a | pemedeiros/python-CeV | /pacote-download/CursoemVideo/ex088.py | 461 | 3.515625 | 4 | from random import randint
from time import sleep
jogo = []
lista = []
tot = 1
qtd = int(input('Quantos jogos você quer fazer? '))
while tot <= qtd:
cont = 0
while True:
n = randint(1, 60)
if n not in jogo:
jogo.append(n)
cont += 1
if cont >= 6:
break... |
c7d4e0f27975b82f6a192e059d2c89775296208a | surajkumar4aug/kec | /digitsum.py | 262 | 4.09375 | 4 | num=int(input("enter number"))
even=0
odd=0
while(num!=0):
rem=int(num%10)
if(rem%2==0):
even=even+rem
else:
odd=odd+rem
num=num/10
diff=even-odd
print("difference between even and odd digit "+str(diff)) |
5b6d523703aed591d503091a0ea95eed027c5b75 | SmileAK-47/webderviver | /python_rumendaoshijian/diliuzhang/HanShu/printing_models.py | 866 | 3.609375 | 4 | '''
unprinted_designs = ['iphone cas','robot pendant','dodecahedron']
completed_models = []
while unprinted_designs:
current_dision = unprinted_designs.pop()
print("model:"+ current_dision)
completed_models.append(current_dision)
print("-----")
for a in completed_models:
print(a)
'''
def print_models... |
0ad14136fd0d4de88e3440313324c714ba6cb0b5 | cedelmaier/primeSieveProjects | /pythonPrimes/pythonPrimes.py | 4,669 | 4.1875 | 4 | #!/usr/bin/env python
import sys
import time
#Basic implementation
def eratosthenes(n):
multiples = set()
for i in range(2, n+1):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
#A different take on the basic implementation thinking about it for a little bi... |
62f280a92b94bffbc06bf3d59c42b433fd1b6bfc | lujamaharjan/IWAssignmentPython1 | /DataType/Question1.py | 423 | 4.53125 | 5 |
'''
1. Write a Python program to count the number
of characters (character frequency) in a string.
Sample String : google.com'
Expected Result :
{'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
'''
sample_string = 'google.com'
#filtering unique char
presented_char = set(sample_string)
result = dict()... |
441770cb1b866bfda831c3fe32f671899d288b6a | Danielgergely/intermediate_python | /intermediate_python/count.py | 624 | 3.84375 | 4 | import collections
import operator
def count_unique_words(filename):
with open(filename, 'r') as f:
content = f.read()
words = content.split()
lowercase_words = []
for word in words:
lowercase_words.append(word.lower())
cnt = collections.Counter(lowercase_words)... |
9931342f8bb79101fbcdcff6b2f1eef8c75dc37f | David-Smith-Zhou/PythonLearn | /main/sort/my_sort.py | 8,936 | 3.59375 | 4 | # -*- coding: utf-8 -*- f
import math
class MySort:
def __init__(self):
pass
def bubble_sort(self, src: list) -> list:
dst = src.copy()
for i in range(len(dst)):
for j in range(len(dst)):
if dst[i] < dst[j]:
tmp = dst[j]
... |
e00aaec2902b48f2b9b2c0fdca7092a4792c458b | juzh1998/CLRS_python_version | /chapter 2/insertion-sort.py | 602 | 3.8125 | 4 | """
-*- coding:utf-8 -*-
@time :2021.3.20
@IDE : pycharm
@autor :juzh
@email : juzh1998@163.com
暴力排序
"""
#生成随机list
import random
def random_int(length,a,b):
list=[]
count=0
while(count<length):
number=random.randint(a,b)
list.append(number)
count=count+1
return list
ra... |
773732ea4ad83fdb490571bfbdce62c604207c80 | thedreamer67/Simulating_Forest_Fire | /Task 1 Random Forest.py | 990 | 4.125 | 4 | # Task 1: create a random forest with stated width, height and density (num_of_trees/area)
# output: a 2D matrix of 0s and 1s to represent water and trees
def createForest(width, height, density):
from random import randint
forest = [] # Initialise empty list
trees = round(density * width * height) #Computes ... |
05a982ff7705d288fd01c1977e5566e7b61adab8 | CodingDojoDallas/python_july_2018 | /prajesh_gohel/Python/python_fundamentals/forloop_basic.py | 1,663 | 4.125 | 4 | # 1. Basic - Print all the numbers/integers from 0 to 150.
# for i in range(1, 151):
# print(i)
# 2. Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000.
# for i in range(5, 1000000, 5):
# print(i)
# 3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" ins... |
7044506b6151f966fc2d90afdfeef00205890f4e | dharanidurairaj/codevita-practice-problems | /matrix.py | 249 | 3.75 | 4 | i/p:
1
2
3
4
o/p:
0 1
2 3
r=2
c=2
b=[[0 for i in range(r)]for i in range(c)]
for i in range(0,r):
for j in range(0,c):
b[i][j]=int(input())
for i in range(0,r):
for j in range(0,c):
print(b[i][j],end=" ")
print(" ")
|
8fdcb04662fc31c53d99a995e92dc6fbf37660c8 | Neeraj-kaushik/Geeksforgeeks | /Array/Union_of_two_sorted_array.py | 391 | 3.9375 | 4 | def union(n, li, m, li2):
li3 = []
for i in range(len(li)):
if li[i] not in li3:
li3.append(li[i])
for i in range(len(li2)):
if li2[i] not in li3:
li3.append(li2[i])
li3 = sorted(li3)
print(li3)
n = int(input())
li = [int(x) for x in input().split()]
m = int... |
d24b4ae901739f5936fdf4fc73ea6139f0919880 | RyanIsCoding2021/RyanIsCoding2021 | /exercises/1.py | 925 | 3.703125 | 4 | import turtle as t
import random
s = t.Screen()
s.title("rect")
t.speed(0)
colorlist = ["black", "blue", "green", "red"]
def drawRect(width, height):
for i in range(2):
t.color(colorlist[random.randint(0, 3)])
t.fd(width)
t.lt(90)
t.fd(height)
t.lt(90)
# def ... |
b0f4efae3c3430bb2039be71df90b3980a586c7b | karkonio/first_module | /vault77/week4/test.py | 351 | 3.890625 | 4 | string = 'Alise is 21 years old'
def no_digits(string):
result = []
#result = ''.join([i for i in string if not i.isdigit()])
for char in string:
if not char.isdigit():
result.append(char)
result = ''.join(result)
return result
print(no_digits(string))
assert no_digits(s... |
366d2d58a95e33ed438bec6d990e1834ef71bceb | sklucioni/crimtechcomp | /assignments/000/sarah-lucioni/assignment.py | 1,848 | 4.0625 | 4 | def say_hello():
print("Hello, world!")
# Color: blue
# TODO: implement
def echo_me(msg):
print(msg)
# TODO: understand and remove
def string_or_not(d):
exec(d)
# TODO: understand formatting - can you eliminate the redundancy here?
def append_msg(msg):
print("Your message should have been: {}!".for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.