blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
866df365ca6ec790f67224b2208e90eca5eeb811 | vaamarnath/amarnath.github.io | /content/2011/10/multiple.py | 665 | 4.125 | 4 | #!/usr/bin/python
import sys
def checkMultiple(number) :
digits = {"0":0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":0, "7":0, "8":0, "9":0}
while number != 0 :
digit = number % 10
number = number / 10
digits[str(digit)] += 1
distinct = 0
for i in range(0, 10) :
if digi... |
96961f632167a62d1a4dfd8b6928b0a21f86cfc2 | dengking/TheAlgorithms-Python | /recursion/Euclidean_algorithm.py | 962 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/6 11:21
# @File : Euclidean_algorithm
def recursive_gcd(a, b):
"""
gcd(a, b) = gcd(b, a mode b)
:param a:
:param b:
:return:
"""
if b == 0:
return a
remainder = a % b
if remainder == 0:
return b
return recursive_gc... |
3a29452ad6baf1d89fc522842a7657ea54bc2e16 | ViswanathanMukundan/AutoSummarizer_Python | /Summarizer.py | 1,810 | 3.90625 | 4 | '''PY PROGRAM TO GENERATE A SUMMARY FOR A GIVEN PIECE OF TEXT'''
'''FURTHER TASKS:
1. REPLACE MORE CASES LIKE i.e., AND e.g. IN ORDER TO AVOID CONFUSIONS WHILE TOKENIZING.
2. FIND A WAY TO GET THE TEXT FROM PARSING THE SOURCE CODE OF A WEBSITE.
3. MODULARIZE THE CODE.
4. EXPAND STOPWORD LIST.
5. CONVERT THE SUM... |
2cac53c06247c2326e847d77a9c3f402e5ec59c0 | Aarif123456/prisonerDilemmaSimulator | /pavlov.py | 987 | 3.65625 | 4 | # COMP-3710 Final project Prisoner Dilemma simulator
# the pavlov bot cooperates on the first move and defect if the players had two different previous move
# this strategy is also called win-stay-lose-shift
from botBase import baseBot
class pavlovBot(baseBot):
def __init__(self):
# bot inherits from base cla... |
080025aa8dea5b5a00709e17964d026f03c60d0e | MKRNaqeebi/CodePractice | /Past/amma/4442.py | 1,716 | 3.984375 | 4 | import collections
def solution(S):
"""
Calculate smallest sub-array length from an array in which all integer exists from the original array
Sample Input ==> Sample Output
[7, 3, 7, 3, 1, 3, 4, 1] ==> 5
[2, 1, 1, 3, 2, 1, 1, 3] ==> 3
[7, 5, 2, 7, 2, 7, 4, 7] ... |
c50e993970f4bc347da833816541caa978c68642 | BobcatsII/brush_leetcode | /tree/N叉树的层序遍历.py | 930 | 3.703125 | 4 | ##dfs
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
res = []
def dfs(root, depth):
if not root: return
if len(res) <= depth:
res.append([])
res[depth].append(root.val)
for ch in root.children:
d... |
6ec390b3fd5f838db120c42991b17d59ef289ce0 | BobcatsII/brush_leetcode | /stack_and_queue/有效的括号.py | 1,297 | 3.78125 | 4 | # 详细写法
from collection import deque
class Stack:
def __init__(self):
self.items = deque()
def push(self, val):
return self.items.append(val)
def pop(self):
return self.items.pop()
def empty(self):
return len(self.items) == 0
def top(self):
return se... |
7655aca2a56f81d9b23a40f4e83e4b18389c2355 | BobcatsII/brush_leetcode | /array_linkedlist/合并两个有序数组.py | 1,312 | 3.546875 | 4 | # 方法一
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
if 0 == n:
pass
elif 0 == m:
nums1[:n] = nums2[:n]
else:
a, b = m-1, n-1
k = m+n-1
while (a >= 0) and (b >= 0):
if nu... |
95623ba15a7de048ac4527d053acbe8a3eeb6ccc | artem1205/shipengine-python | /shipengine/util/__init__.py | 481 | 3.640625 | 4 | """Testing a string manipulation helper function."""
from .sdk_assertions import * # noqa
def snake_to_camel(snake_case_string: str) -> str:
"""
Takes in a `snake_case` string and returns a `camelCase` string.
:params str snake_case_string: The snake_case string to be converted
into camelCase.
:... |
68be2823bda994f4bdebb5c508bf80e9a0ad4a44 | jasper-lu/LNYF-Matching | /matching.py | 4,383 | 3.625 | 4 | from dancer import Dancer, Dancers
from dance import Dance
import random
# Our matching algorithm is basically just the hospital resident matching algorithm.
# https://en.wikipedia.org/wiki/Stable_marriage_problem
# Classes are named as such to reflect that.
class Player:
def __init__(self, name):
self.n... |
e1289e9769ad313bc415a66d5e5600e5007fec90 | dhansolo/R-P-S | /main.py | 684 | 4.21875 | 4 | from random import randint
player = raw_input('rock (r), paper (p), or scissors (s)? ')
while player != 'r' and player != 'p' and player != 's':
player = raw_input('Must choose rock (r), paper (p), or scissors (s) ')
# end='' tells print to print an extra space instead of a line in python 3 and above
computer =... |
8ade0d93f3f875e777b57d39c90326247da41860 | Wallart/gluon-tacotron2 | /initializer/custom_xavier.py | 2,164 | 3.59375 | 4 | from mxnet import nd
from mxnet.initializer import Xavier, register
import math
def calculate_gain(nonlinearity, param=None):
r"""Return the recommended gain value for the given nonlinearity function.
The values are as follows:
================= ====================================================
n... |
7cee4713aa67c45851d8ac66e6900c25c95ccef1 | UCMHSProgramming16-17/final-project-shefalidahiya | /day05/ifstatement2.py | 366 | 4.375 | 4 | # Create a program that prints whether a name
# is long
name = "Shefali"
# See if the length of the name counts as long
if len(name) > 8:
# If the name is long, say so
print("That's a long name")
# If the name is moderate
elif len(name) < 8:
print("That's a moderate name")
# If the name is short
else l... |
c0e649a267a181a377f4f3651c6467908cd6789c | UCMHSProgramming16-17/final-project-shefalidahiya | /day14/rps.py | 3,138 | 4.46875 | 4 | # import random module
import random
# run function while count is less than/equal to 3
while count >= 3:
# set count to zero at start
count = 0
# set number of computer wins to 0
computer = 0
# set number of human wins to 0
human = 0
# allow user to choose rock, paper, or scissors
a =... |
97650c893ca11f33314f88708d54257d5f6ccbf6 | Mini-Pingu/studious-giggle | /past_apps/app6.py | 235 | 3.8125 | 4 | # values = [item * 2 for item in range(5) if item > 2]
# print(values)
try:
age = int(input("Age: "))
x = 10 / age
except (ValueError, ZeroDivisionError):
print("You entered the wrong type value.")
else:
print("hihi")
|
b362396efd75e55fea862695e2592ab8e50a1f59 | tommy85/test | /python/test8.py | 806 | 4.09375 | 4 | #!/usr/local/bin/python
import exceptions
#print dir(exceptions)
#raise ZeroDivisionError("zero exception")
class CustomException(Exception):
str = "caonima"
def hehe(self):
print self.str
while True:
try:
x = input('first number:')
y = input('second number:')
r... |
524f63f9f4d75d2da2259550b912a473a4673b96 | elu267/python-challenge | /PyPoll/main.py | 4,503 | 3.828125 | 4 | # Read the csv file
import os
import csv
# getting the csv file (data set)
csvFile = os.path.join('election_data.csv')
# creating a variable to store the entire dataset
csvDataset = []
# creating a variable to store the candidate names
csvDataset_Candidate = []
# creating a variable to store the voter IDs
csvDataset_... |
9a9ce98f6276d68c81f501b3815f71ec11dce377 | danebulat/py-image-manip-demo | /imgmanip/manipulator.py | 6,824 | 3.75 | 4 | """ manipulator.py
Implements the ImageManipulator class which caches a loaded image in
memory. The class operations process this image, and the image can be
saved to a new file by called ImageManipulator.save_image().
"""
import os
import copy
from PIL import Image, ImageEnhance, ImageFilter
# --------------------... |
808727432b9d4db61b4c6b6dfc497ce9302e0a76 | core-harshit/core-harshit | /Coding/alternatesorting.py | 715 | 3.921875 | 4 | def alternatingSort(a):
b=[]
c=0
if len(a)%2==0:
for c in range(len(a)//2):
b.append(a[c])
b.append(a[-c-1])
if len(b)!=len(set(b)):
return False
else:
if b==sorted(b):
return True
else:
retu... |
1a9dea57415668bf56fd5e0b0193952a1af49e27 | freaking2012/coding_recipes | /Python/LearnBasics/HashPattern2.py | 365 | 4.3125 | 4 | '''
This program takes input a even number n. Then it prints n line in the following pattern
For n = 8
##
####
######
########
########
######
####
##
'''
n=input("Enter number of lines in patter (should be even): ")
for i in range(1,n/2+1):
print (' ' * (n/2-i)) + ('##' * i)
for i in range(1,n/2+1):
... |
f55cc1e9874d4173e4ee8f3e6b0451753a048c70 | Jan-Zeiseweis/pycriteo | /pycriteo/util.py | 1,742 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
class CurrencyConverter(object):
"""
Converts currencies (ISO 4217 format).
Arguments:
from_currency -- currency to convert from (i.e 'EUR')
to_currency -- currency to convert to (i.e 'USD')
Example:
C... |
f1ee0a14505213b22191a31d3e9ce1c3446828ea | smoloney/CS415 | /project1/project.py | 7,674 | 4.03125 | 4 | #Authors: Sean Moloney and Jon Killinger
#Class : CS 415
#Assignment: Project 1
#In order to run this program, compile it wil python2 project.py
# all the computations for HW 1 shall be done using binary arithmetic
# only the user input and the final output will be in decimal.
# the two functions dec2bin and ... |
4ca634a62c46930073c67fbb01bea13796de8edb | leoP0/OS1 | /Small Python/mypython.py | 1,376 | 4.1875 | 4 | #Python Exploration
#CS344
#Edgar Perez
#TO RUN IT JUST DO: 'python mypython.py' (whitout the ' ')
#Modules
import random
import string
import os
import io
#function that generates random lowercase leters given a range
def random_char(y):
return ''.join(random.choice(string.ascii_lowercase) for x in range(y))
#cre... |
12c8fb82cfd7dba46e3f27b5b61e061c6b78c927 | starlightromero/flower-garden | /Flower.py | 843 | 4.09375 | 4 | """Import Turtle Graphics and Plant."""
import turtle as jerry
from Plant import Plant
class Flower(Plant):
"""Class to make a flower which inherits from Plant."""
def __init__(self, x, y, size, color):
"""Initialize Flower and parent Plant."""
super().__init__(x, y, size, color)
self... |
affb49e789f1a8a2222310b5912ab01119618677 | cyancirrus/datastructures | /datastructures/MinHeap.py | 1,240 | 3.890625 | 4 | class min_heap:
def __init__(self,array:list):
self.array = array
self.heap_size = len(self.array)
self.length = len(self.array)
def left(self,i):
return 2*i+1
def right(self,i):
return 2*i+2
def parent(self,i):
return int((i-1)/2)
def build_min_heap(self):
for i in range(int((self.length-1)/2),-1,-1... |
493e7bcfcd6648b9aca1bd25d3c7bb5ec4d79090 | IllinoisWCS/python-start | /intermediate.py | 5,431 | 4.65625 | 5 | import csv
import sys
class Intermediate:
'''
This exercise should get you warmed up on how the data structure `dictionary` can be used
Dictionaries, or hashmaps, allow for a way to associate a 'key' with a 'value'. Imagine it like an index of a textbook. You know what topic you want to look for (the key)... |
5548df9c3f3e31ffce2cdb3e0f6fda197bf7ab72 | tazdaboss/python_basic | /datatype_learn/number_operation.py | 226 | 4.1875 | 4 | num1=int(input("enter num1:\t"))
num2=int(input("enter num2:\t"))
print("add",num1+num2)
print("subtract",num1*num2)
print("divide",num1/num2)
print("remainder",num1%num2)
print("quotient",num1//num2)
print("power",num1**num2) |
a599c583af200aa0365d49cc22f0903842c12ccc | kclaka/HackerRank | /HackerRank/Mutations.py | 303 | 3.609375 | 4 | '''
Created on Dec 29, 2018
@author: K3NN!
url : https://www.hackerrank.com/challenges/python-mutations/problem
'''
def mutate_string(string, position, character):
string = string[:position] + character + string[position+1:]
return string
if __name__ == '__main__':
pass
|
b87c87815df4281b6c6046136515cda3896b8ea7 | CanonMukai/Qiskit-2048 | /display.py | 6,988 | 3.75 | 4 |
import numpy as np
import sys
import copy
ROW = 4
COLUMN = 4
def Display(board):
print ("\n - - - - - - - - -")
n = len(board)
for i in range(n):
for j in range(n):
if board[i][j] == '*':
num = ' '
else:
num = board[i][j]
if j ==... |
4873da408f7e0eef3c60e2a734d018d5d81b15ba | TheConstructRIT/Machine-Swipe-System | /tests/Model/UserTest.py | 1,062 | 3.703125 | 4 | """
Zachary Cook
Unit tests for the User module.
"""
import unittest
from Model import User
"""
Test the User class.
"""
class TestUserClass(unittest.TestCase):
"""
Tests the constructor.
"""
def test_constructor(self):
User.User("000000000",100)
"""
Tests the getId method.
"""
def test_getId(self):
C... |
10b80bbf124cc3b1bcd8a0b2c9a2424fcbc1e786 | aarozhentsev/HH-tasks | /hh 2_1.py | 1,340 | 3.53125 | 4 | def DigitAndX(s,var):
i = 0
while i<len(s)-1:
if s[i].isdigit():
if s[i+1]==var:
s = s.replace(s[i]+s[i+1],s[i]+'*'+s[i+1])
if s[i].isdigit() or s[i]==var:
if s[i+1]=='(':
s = s.replace(s[i]+s[i+1],s[i]+'*'+s[i+1])
i+=1
return ... |
8c3835e2d19f46231c6982724c4680e54228c7d7 | SanjayMarreddi/Open-CV | /Object_Detection/4.Contour_Object_Detection.py | 3,283 | 4.15625 | 4 | # Once We have segmented out the key areas of an image, the next step is typically to identify the individual objects.
# One powerful way is to use OpenCV's implementation of contours. The goal of contours is to take a binary image and create a tightly fitting closed perimeter around all individual objects in the scen... |
b6f5c5dc5b1c4703650b0e12ba82517d237c92ea | SanjayMarreddi/Open-CV | /Object_Detection/1.Simple_Thresholding.py | 2,452 | 4.375 | 4 | # Now we are focused on extracting features and objects from images. An object is the focus of our processing. It's the thing that we actually want to get, to do further work. In order to get the object out of an image, we need to go through a process called segmentation.
# Segmentation can be done through a variety ... |
ada6baf778bbc2c8092e91aba6bdda306d217a99 | SanjayMarreddi/Open-CV | /Object_Detection/6.Canny_Edge_Detection.py | 1,626 | 4.03125 | 4 | # Often we need to pre-process images in order to improve our final result, and in the case of extracting contours from individual objects in an image it is often handy to first detect and accentuate the edges within an image.
# Canny Edges is one type of edge detection algorithm that works quite well to help create b... |
a2277f1bd4c2522d4199a1c960a4bff9751cbc62 | MOOC-Learner-Project/MOOC-Learner-Visualized | /config/config.py | 2,305 | 3.53125 | 4 | #!/usr/bin/env python
'''
This is the parser of YAML configuration file.
Parse the YAML config file and store all configuration variables as constants.
'''
import yaml
import getpass
class ConfigParser(object):
'''
Handles parsing and processing the config YAML file and
act as an interface for other modu... |
1e13d93a10f306025b94c070c9f972ab48e87093 | Mpumelelo-Change/Project_Euler | /sum_sqr_diff.py | 292 | 3.671875 | 4 | def sqr_of_sum(num):
tot = 0
for i in range(1, num + 1) :
tot += i
return (tot**2)
def sum_of_sqr(num):
tot = 0
for i in range(1, num + 1) :
tot += i**2
return (tot)
spec = 100
print(sqr_of_sum(spec) - sum_of_sqr(spec))
|
f8c5b89b5c26a8fb389d24d3e2dbd56194b03c9a | gatij/python_fun_projects | /flower.py | 511 | 3.859375 | 4 | import turtle
def DrawFlower():
window=turtle.Screen()
window.bgcolor("white")
some_turtle=turtle.Turtle()
some_turtle.shape("arrow")
some_turtle.speed(1000000000)
some_turtle.color("blue")
for j in range(0,36):
DrawTriangle(some_turtle,2)
DrawTriangle(some_turtle,3)
some_turtle.right(10)
#s... |
7e9ec36b9950de705ceddea727d9597998ed75f4 | namitasurana96/dataEngineering | /Set2.py | 71 | 3.765625 | 4 | set = {"a", "b", "c", "d", "a", "e", "d", "f"}
for x in set:
print(x) |
2e3dfc66b1a26f06c86ab484ca405430c6cb1d72 | namitasurana96/dataEngineering | /Array4.py | 77 | 3.6875 | 4 | vowels = ['a', 'e', 'i', 'o', 'a', 'u', 'a']
vowels.remove("a")
print(vowels) |
869c397c85225c688fe51d389a56e09da8987a45 | Mohan110594/Design-4 | /Design_Twitter.py | 3,664 | 4.125 | 4 | // Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
from collections import OrderedDict
#created a class tweet which contains tweetid and created time.
class Tweet:
def __init__(self,tweetid,createdAt):
self.tweetid=tweetid
self.createdAt=createdAt
... |
bd1997c9427f2f364e60fccc86e04d39c628f979 | walidA1/programmingnew | /Pe5_1/functie met if.py | 227 | 3.515625 | 4 | def lang_genoeg(lengte):
if lengte >= 120:
print('Je bent lang genoeg voor de attractie!')
else:
print('Je bent te klein!')
lengte = input('Hoelang ben jij in centimeters?')
(lang_genoeg(int(lengte)))
|
0fbfdc83757f9153365c06b1f9e86950d8d46e99 | walidA1/programmingnew | /Final assignment bagagekluizen/functions.py | 3,868 | 3.828125 | 4 | def printmenu():
print('1: Ik wil weten hoeveel kluizen nog vrij zijn')
print('2: Ik wil een nieuwe kluis')
print('3: ik wil even iets uit mijn kluis halen')
print('4: ik geef mijn kluis terug\n')
select()
def select():
selected_number = 0
while selected_number > 4 or selected_number < 1:
... |
dddf7daa3fd9569dbeb61fdba7f39f070aa4be39 | Ironkey/ex-python-automatic | /Chapter 01-02/Hello World.py | 597 | 4.21875 | 4 | # This program says hello and asks for my name.
print('Hello wolrd!')
print ('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The Length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be... |
aac96403d55aedefb8f4c550b3aa2681e8359db2 | willcl-ark/boltstore | /database.py | 2,545 | 3.71875 | 4 | import sqlite3
from utilities import sha256_of_hex_to_hex
# data types #
# INTEGER: A signed integer up to 8 bytes depending on the magnitude of the value.
# REAL: An 8-byte floating point value.
# TEXT: A text string, typically UTF-8 encoded (depending on the database encoding).
# BLOB: A blob of data (binary large... |
4c69bf913b87c5c3373368d83464ecd9e49e9184 | mennonite/Python-Automation | /Chapter 8 -- Reading and Writing Files/Practice Projects/madlibs_Regex.py | 920 | 4.25 | 4 | #! python3
# madlibs_Regex.py - opens and reads a text file and lets the user input their own words (solved using REGEX)
import re
# open text file
madlibFile = open('.\\Chapter 8 -- Reading and Writing Files\\Practice Projects\\test.txt')
# save the content of the file into a variable
content = madlibFile.read()
m... |
94e4db9080e79ac124178be55ab9cf86896e2153 | Y1B0/Artificial-Intelligence-for-Robotics | /expansion grid.py | 3,340 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 13 11:36:16 2017
@author: huyibo
"""
# ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid pa... |
319b50bba1445e6aeb1d7282c61a8a5c583b80b5 | vadim-kravtsov/skyCam | /libs/guiLibs.py | 3,693 | 3.65625 | 4 | #! /usr/bin/env python2
from os import path
import pygame
class TextLabel(object):
def __init__(self, screen, xStart, yStart):
self.font = pygame.font.SysFont(u'ubuntumono', 22)
self.xStart = xStart
self.yStart = yStart
self.fontColor = (119,153,51)#pygame.Color("green")
s... |
797c941cf15e8010a432aa770feb313e93d4f124 | pantherman594/countermachine | /countermachine_copy_macros.py | 8,636 | 3.78125 | 4 | #counter machine
#The low level code is a list of instructions.
#Each instruction is a string.
#The strings have the following format:
#I<let> (where <let> denotes any lower-case letter)
#D<let>
#B<let><n> where <n> denotes an integer constant--note that this is written
#without spaces
#B<n>
#H#
#The function below in... |
2cc34c8802dcc2d6973903960182889adbfb31f2 | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que24.py | 188 | 3.671875 | 4 | def cumulative_list(lists):
list_var=[]
length=len(lists)
list_var=[sum(lists[0:x+1]) for x in range (0,length)]
return list_var
lists = [10,20,30,40,50]
print(cumulative_list(lists)) |
ad60442beb74e0d4e6b1048a86425641b2760577 | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que4.py | 158 | 4.1875 | 4 | num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
print("Quotient is :" ,num2/num1)
print("REmainder is :" ,num2%num1)
|
ebb53ab79760bfa0d6d0c33cb5a08a0423922f9b | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que20.py | 294 | 3.96875 | 4 | str1 = str(input("Enter the first string"))
str2 = str(input("Enter the second string"))
count1 = 0
count2 = 0
for ch in str1:
count1 = count1+1
for ch in str2:
count2 = count2+1
if(count1>count2):
print(str1)
elif(count2>count1):
print(str2)
else:
print("Both string are of same length")
|
9301ec25d5d7cd6e0e80a64d05b799cd987cb5dc | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que16.py | 178 | 4.09375 | 4 | str1 = str(input("Enter the string"))
new_str=''
for ch in str1:
if ch == 'a':
new_str += '$'
else:
new_str += ch
print(new_str)
#str1=str1.replace('a','$')
#print(str1) |
bea1ddcc6371381ee84f4588c24bb97c290ece8b | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que22.py | 217 | 3.921875 | 4 | str1 = str(input("Enter the string"))
count = 0
count2 = 0
for ch in str1:
if ch.isdigit():
count = count+1
else:
count2=count2+1
print("The number of digit is", count)
print("THe number of alphabet is", count2) |
7ff9e2b37bded88fbd494d9679821004d05025f3 | dcandrade/python_para_zumbis | /palindromo.py | 189 | 3.96875 | 4 | #verifica se a palavra lida é palídromo, supondo que não tem acentos
palavra = input("Digite a palavra:").lower()
print("E palidrome" if palavra==palavra[::-1] else "Nao e palindrome")
|
3959cf84ecea19519ef31a462a07a6127e44d0b0 | rohitprofessional/test | /StringPractice/SP02.py | 649 | 4.0625 | 4 | # ---------Write a program to count vowels and consonants in a string.----------
S = input("Enter a STRING: ")
print("You entered the string:",S)
print("Length of the string you entered:",len(S))
vow = 0
con = 0
space = 0
for i in range(len(S)):
if (S[i]==" "):
space = space + 1
print("T... |
cb5a0fa4c5e15ece58b25f8a0fedb9fb56f26c5f | rohitprofessional/test | /f_string.py | 386 | 4.4375 | 4 | letter = "Hey my name is {1} and I am from {0}"
country = "India"
name = "Rohit"
print(letter.format(country, name))
print(f"Hey my name is {name} and I am from {country}")
print(f"We use f-strings like this: Hey my name is {{name}} and I am from {{country}}")
price = 49.09999
txt = f"For only {price:.2f} doll... |
db834ca3d26f8d0901498cc48d2219ea940b38f3 | rohitprofessional/test | /CLASS AND OBJECTS/Introduction to oops/class_attributes.py | 669 | 4.09375 | 4 | # How to create a class:
class Item:
def calculate_total_price(self, x, y):
return x * y
# How to create an instance of a class
item1 = Item()
# Assign attributes:
item1.name = "Phone"
item1.price = 100
item1.quantity = 5
# Calling methods from instances of a class:
print(item1.calculate_to... |
3b5e88fd60e1fcc969536b9a995d53b4ab14e563 | rohitprofessional/test | /OUTPUT PROG/output_07.py | 119 | 3.53125 | 4 | x = 'one'
y = 'two'
counter = 0
while counter < len(x):
print(x[counter],y[counter])
counter = counter + 1 |
f9d5c0e1ab4ec959bb7988e185c83b2ba49a23a5 | rohitprofessional/test | /PRACTICE/stop_watch.py | 534 | 4.125 | 4 | #---------------STOP WATCH--------
import time
time_limit = int(input("Enter the stopwatch time.: "))
# hours = int(time_limit/3600)
# minutes = int(time_limit/60) % 60
# seconds = (time_limit) % 60
# print(hours,minutes,seconds)
for x in range(time_limit,0,-1):
seconds = (x) % 60
minutes = i... |
3677635246e0838d7d9ce919e40713bcd2c2a2b0 | rohitprofessional/test | /StringPractice/SP05.py | 442 | 3.859375 | 4 | n = '@pyThOnlobb!Y34'
numeric = 0
lower = 0
upper = 0
special = 0
for i in range(len(n)):
if n[i].isnumeric():
numeric = numeric + 1
elif n[i].islower():
lower = lower+1
elif n[i].isupper():
upper = upper+1
else:
special = special + 1
# printing result
... |
608257fd5528026be5797f7ca712d9328ca7382b | rohitprofessional/test | /CHAPTER 01/localVSglobal_variable.py | 1,353 | 4.5 | 4 | # It is not advisable to update or change the global variable value within in a local block of code. As it can lead to complexity
# in the program. But python provides a global keyword to do so if you want to.
# Although it is also not advisable to use global variable into a local function. It is a maintainable progr... |
e49eb95627c1f9262aad83447236cc085a6f5afd | rohitprofessional/test | /CHAPTER 07/intro to for loops.py | 1,151 | 4.375 | 4 | # -------------------- FOR LOOP UNDERSTANDING -------------------------------
'''So here we range is a function w/c helps compiler to run the for loop.
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defa... |
ba5c344d4431c6f434b1bd7f2f9bcff98f9ef1ba | chaitanyakush/PythonLearning | /Date Detection.py | 980 | 4 | 4 | import re
def dateValidate(date):
# 31/02/2020
dateRegex = re.compile(r'(\d\d)/([0-1]\d)/([1-2]\d\d\d)')
mo = dateRegex.search(date).groups()
day = int(mo[0])
month = int(mo[1])
year = int(mo[2])
if month in (4, 6, 9, 11) and day > 30:
print("Wrong date")
return False
... |
6af71e11738ca1f1a56d20c477462ebc0e48602d | seohae2/python_algorithm_day | /알고리즘구현/04_BFS/bfs.py | 1,233 | 3.75 | 4 | # BFS
from collections import deque
def bfs(graph, start, visited):
# 큐 구현을 위해 deque 라이브러리 사용
queue = deque([start])
# 현재 노드를 방문 처리
visited[start] = True
while queue:
v = queue.popleft()
print(v, end=' ')
for value in graph[v]:
if not visited[value]:
... |
8d49d90011858c4fba6724068786e20d7f9254e6 | seohae2/python_algorithm_day | /코딩인터뷰/chapter11_해시_테이블/03_중복문자_없는_가장긴_부분문자열/exam2.py | 656 | 3.65625 | 4 | """
중복 문자가 없는 가장 긴 부분 문자열 (substring)의 길이를 리턴하라.
입력
"abcabcbb"
출력
3
= 정답은 "abc"로 길이는 3이다.
"""
def lengthOfLongesSubstring(self, s: str) -> int:
used = {}
max_length = start = 0
for index, char in enumerate(s):
# 이미 등장했던 문자라면 'start' 위치 갱신
if char in used and start <= used[char]:
... |
a57a4b323d90a1390bacf3cd59393f4846099bb2 | seohae2/python_algorithm_day | /코딩인터뷰/chapter07_배열/D0120/04_세수의_합/exam/9-2.py | 2,111 | 3.5625 | 4 | from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
results = []
# 정렬
nums.sort()
for i in range(len(nums) - 2):
# 중복된 값 건너뛰기
if i > 0 and nums[i] == nums[i - 1]:
continue
# 간격을 좁혀가며 ... |
c55faee6657fbb7d1a938f6f07b8e64896c0c680 | seohae2/python_algorithm_day | /01_파이썬_첫걸음/18_함수.py | 2,718 | 3.71875 | 4 | # coding=utf-8
# 결과값이 있는 함
def add(a, b):
return a + b
# 결과값이 없는 함수
def voidAdd(a, b):
print("%d, %d의 합은 %d입니다." % (a, b, a+b))
a = 3
b = 4
c = add(a, b)
print(c)
print(add(3, 4)) # 3, 4는 인수
print(voidAdd(1,2))
a1 = add(3, 4)
print(a1)
a2 = voidAdd(3, 4)
print(a2) # None
# 매개변수 지정하여 호출
result = add(a=3, b... |
8e104c272b50a9ea7c1b16b200b2a4b42a6a0914 | seohae2/python_algorithm_day | /이것이코딩테스트다/01_기본_개념/02_리스트_자료형.py | 3,218 | 3.796875 | 4 | # 리스트 자료형
# 여러개의 데이터를 연속적으로 담아 처리하기위해 사용하는 자료형
# 파이썬은 배열 을 사용할때 리스트를 사용한다. (리스트를 배열 또는 테이블이라고도 한다.)
# 인덱스는 0 부터 시작한다
# 직접 데이터를 넣어 초기화
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
# 네번째 원소 출력
print(a[3])
# 크키가 N이고, 모든 값이 0인 1차원 리스트 초기화
n = 10
a = [0] * n
print(a) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a = [1, 2, 3, 4, 5, 6, ... |
44c04f70f03915db09630c870952a87f87f9afab | seohae2/python_algorithm_day | /이것이코딩테스트다/00_알고리즘_구현/09_계수정렬.py | 650 | 3.515625 | 4 | # 모든 원소의 값이 0보다 크거나 같다고 가정한다
array = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2]
# 모든 범위를 포함하는 리스트 선언 (모든 값은 0으로 초기화)
count = [0] * (max(array) + 1) # max(array)=9, 0 부터 이므로 + 1 처리
print(count) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(len(array)):
# array[i] : value 를 인덱스로 지정한다
count[array[i]] += 1... |
b83e800b14ee1bcaff0c3d5a3e6da8b0cd787bc1 | seohae2/python_algorithm_day | /코딩인터뷰/chapter06_문자열조작/D0119/05_그룹_애너그램/seohae.py | 674 | 3.875 | 4 | # https://leetcode.com/problems/group-anagrams/
# 리스트 순서대로 단어 꺼내기
# 꺼낸 단어를 알파벳 순으로 정렬하기 (이렇게되면 같은 알파벳의 단어는 동일한 값으로 비교 가능하다)
test_list = ["eat", "tea", "tan", "ate", "nat", "bat"]
test_dict = {}
for text in test_list:
alpha_list = list(text)
alpha_list.sort()
print(alpha_list)
sort_text = "".join(al... |
06bcfa5043b7daed8c40ecb3d513a0bfd5ddb2d8 | seohae2/python_algorithm_day | /코딩인터뷰/1_기본_문법/4_딕셔너리_모듈.py | 1,313 | 3.71875 | 4 | """
defaultdict 객체 : 존재하지 않는 키를 조회할 경우, 에러 메시지를 출력하는 대신 디폴트 값을 기준으로 해당 키에 대한 딕셔너리 아이템을 생성한다.
"""
import collections
a = collections.defaultdict(int)
a['A'] = 5
a['B'] = 4
print(a) # defaultdict(<class 'int'>, {'A': 5, 'B': 4})
a['C'] += 1 # 존재하지않는 key 사용
print(a) # defaultdict(<class 'int'>, {'A': 5, 'B': 4, 'C': 1}... |
f4131a488c76f6bc1938b6a214b91125cf3ff0bd | seohae2/python_algorithm_day | /코딩인터뷰/chapter08_연결리스트 [다시하기]/01_두_정렬_리스트의_병합/seohae.py | 1,198 | 3.671875 | 4 | # 정렬되어있는 두 연결 리스트를 합쳐라
# 입력 1->2->4, 1->3->4
# 출력 1->1->2->3->4->4
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 리스트 변환
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
while l1 is not None:
prev = l1.val
while l2 is not No... |
849a3fe2b8dc3cf6d78c3f738bb8835b77b2bc11 | seohae2/python_algorithm_day | /02_파이썬_300제/M071~M080_튜플.py | 1,338 | 3.578125 | 4 | # 071. 튜플을 만들어라
my_variable = ()
print(type(my_variable))
# 072. 요소 3개인 튜플을 만드세요
movies = ("닥터 스트레인지", "스플릿", "럭키")
print(movies)
# 073. 숫자 1이 저장된 튜플을 생성하세요
my_tuple = (1)
print(type(my_tuple)) # <class 'int'> (튜플이 아닌 정수형으로 인식한다)
my_tuple = (1, )
print(type(my_tuple)) # <class 'tuple'> 쉼표를 함께 입력하자.
# 074. 에러 발생의 ... |
5cdca923cabb019f8b64f8e4098cc02179a030ba | seohae2/python_algorithm_day | /알고리즘구현/05_연결리스트/node.py | 1,056 | 3.59375 | 4 | # 연결리스트
class Node:
def __init__(self, data):
self.data = data
self.next = None
def add(self, node):
# 다음 노드가 None 이라면,
if self.next is None:
self.next = node
# 다음 노드가 None이 아니라면,
else:
n = self.next
# 마지막 노드를 찾을때까지 반복문 실행
while True:
#... |
57bb333497c4da8133ea63bcba7a06eaceef7a3f | seohae2/python_algorithm_day | /01_파이썬_첫걸음/16_while문.py | 1,258 | 3.6875 | 4 | # coding=utf-8
# while문 사용
treeHit = 0
while treeHit < 10:
treeHit = treeHit +1
print("나무를 %d번 찍었습니다." % treeHit)
if treeHit == 10:
print("나무 넘어갑니다.")
# while문 빠져나가기 (break)
coffee = 10
money = 300
while money:
print("돈을 받았으니 커피를 줍니다.")
coffee = coffee -1
print("남은 커피의 양은 %d개입니다." % c... |
176d1ff7a48509e3095cdfc3372d1460efbf9609 | CurtisNewbie/Learning-Notes | /PyTutorial/w3schools/examples/PythonVariables.py | 702 | 4.0625 | 4 | x, y, z = "X", "Y", "Z"
print(x, y, z)
x = y = z = "XYZ"
print(x, y, z)
x = y + "ABC"
print("XYZ + ABC =", x)
print("XYZ + ABC = " + x)
# this will cause exception
# print("1 + 1 = " + 2)
"""
Traceback (most recent call last):
File "PythonVariables.py", line 12, in <module>
print("1 + 1 = " + 2)
TypeError: can... |
6cde4e6620a5d5e13d310615cb7b6527bff6da89 | iotarepeat/sms-spam-detector | /main.py | 594 | 3.515625 | 4 | import pickle
from train import messageFunction
def predict(message):
message = messageFunction(message)
with open('probab.pickle', 'rb') as f:
probablity = pickle.load(f)
with open('word_count.pickle', 'rb') as f:
word_counter = pickle.load(f)
for word in message:
for label, cou... |
c726cb7f310a7f4bccc8dc03e93f1def136d89a9 | JohnHuiWB/leetcode | /22. Generate Parentheses/22.py | 555 | 3.609375 | 4 | class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def gen(cur, l, r):
if not l and not r:
out.append(cur)
return
if r and r > l:
gen(cur + ')', l, r - 1)
... |
62a5040efaa5a7702cc952e0e8399f2cfc8aeac0 | luifrancgom/mintic_retos_2021 | /004_reto4_luis_francisco.py | 7,968 | 3.9375 | 4 | # Aplicar la estrategia divide y venceras
# Primero se requiere obtener información del número de zonas
# Ingresar el número de zonas
zonas = int(input())
# Segundo se requiere guardar los datos en una matriz
# de la variable materia orgánica
matriz_materia_organica = []
for i in range(0, zonas, 1):
# En esta par... |
2062912d0fdc908793112866c857b605a457d998 | luifrancgom/mintic_retos_2021 | /002_reto2_luis_francisco.py | 2,043 | 3.59375 | 4 | # no incluir mensajes en los inputs
# tambien se incluye int dado que las muestras deben
# ser números enteros
muestras = int(input())
# indicadores de la variable de conteo
# muestras
i = 0
# categorias
n_sumamente_apto = 0
n_moderadamente_apto = 0
n_marginalmente_apto = 0
n_no_apto = 0
# suma variables
suma_materia_... |
ca96436efca7c0b171625683d122951b8ba4b833 | YashMeh/HCI-Project | /image_operations.py | 739 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 28 19:25:56 2018
@author: yash
"""
import numpy as np
import cv2
#Usually people perform analysis on grayscale image
#then export the result on coloured image
img=cv2.imread('tejas.jpg',cv2.IMREAD_COLOR)
###Referencing a particular pixel
px=img[... |
37940d1160cc5a78595a58676589eca91d3d7fdc | AlanaMina/CodeInPlace2020 | /Assignment1/TripleKarel.py | 1,268 | 4.28125 | 4 | from karel.stanfordkarel import *
"""
File: TripleKarel.py
--------------------
When you finish writing this file, TripleKarel should be
able to paint the exterior of three buildings in a given
world, as described in the Assignment 1 handout. You
should make sure that your program works for all of the
Triple sample w... |
3da0242e36ee059b8471559ae4491a435b90e234 | AlanaMina/CodeInPlace2020 | /Assignment5/word_guess.py | 2,881 | 4.1875 | 4 | """
File: word_guess.py
-------------------
Fill in this comment.
"""
import random
LEXICON_FILE = "Lexicon.txt" # File to read word list from
INITIAL_GUESSES = 8 # Initial number of guesses player starts with
def play_game(secret_word):
"""
Add your code (remember to delete the "pass" below)
"""
... |
fbd5d7800af041a8e69102609f84bba5d8b6c63f | AlanaMina/CodeInPlace2020 | /Assignment5/credit_card_total.py | 1,036 | 3.984375 | 4 | """
File: credit_card_total.py
--------------------------
This program totals up a credit card bill based on
how much was spent at each store on the bill.
"""
INPUT_FILE = 'bill1.txt'
def main():
"""
Add your code (remember to delete the "pass" below)
"""
dict = {}
name = ""
num = ""
wit... |
46f4a78818e9ff35199700107f193ce49587569c | SpiralBL0CK/Programming-solutions-from-codeforces | /asu_3_cup.py | 230 | 3.53125 | 4 | x = int(raw_input())
y = int(raw_input())
command = raw_input()
for i in command:
if i == 'U':
y = y + 1
if i == 'D':
y = y -1
if i == 'L':
x = x-1
if i == 'R':
x = x+1
print(x,y)
|
6033405dc1913c086c43a57b8ed06e70a481a8c1 | mrahmed0116/Practise1 | /sortbasedonvalues.py | 429 | 4.28125 | 4 | '''
Sort dictionary based on keys
'''
dict1= {'x':4,'y':3,'z':2,'a':1,'b':1, 'c':0}
s1 = sorted(dict1.keys())
print(s1)
output={}
for s in s1:
for i in dict1:
if i == s:
output[i] = dict1[i]
print(output)
'''
Sort dictionary based on values
'''
s2 = sorted(dict1.values())
print(s2)
output1={}... |
6946898e4785bc0dca8b2f0e4284a9bd51b4b24d | ckid/LeetCode | /AddTwo.py | 1,405 | 3.921875 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
@staticmethod
def addTwoNumbers( l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
datareturn = ListNode(0)
cur... |
0857fa157a39ff743884d00466b885fadb02e17d | cduhaney1/ubiquitous-fiesta | /prompt_user.py | 154 | 3.953125 | 4 | print("hello")
user_input = int(input("Give me a number! "))
result = int (user_input) * int(user_input)
print (result)
name = input ('What is your name') |
bb91dc84c3520303d5ccc1dfc29615d6a85a3dd9 | cduhaney1/ubiquitous-fiesta | /Hello.py | 70 | 3.625 | 4 | user_name = input('What is your name?')
print('hello, %s' %user_name)
|
cf7a0769baca60bd80d8fe5c6e1af2eb07c1273c | li-MacBook-Pro/li | /static/Mac/play/调用/累加/累加.py | 401 | 3.890625 | 4 | def sum_numbers(num):
if num == 1:
return 1
temp = sum_numbers(num - 1)
return num + temp
print(sum_numbers(3))
def sum_numbers(num):
if num == 3:
return 3
temp = sum_numbers(num + 1)
return num + temp
print(sum_numbers(1))
def my_sum(i):
if i < 0:
raise ValueError
elif i <= 1:
re... |
51adf901afcf2ff68f2b82d4c28c19e8074bd715 | li-MacBook-Pro/li | /static/Mac/play/调用/器/迭代器.py | 1,016 | 4.09375 | 4 | # 可迭代对象
# 可通过for…in 进行遍历的数据类型包括 list,tuple, dict, set, str;以及生成器generator,及带yield的生成器函数
# 这些可直接作用于for循环的对象统称为可迭代对象:Iterable
# from collections import Iterable
# print(isinstance('abc',Iterable))
# print(isinstance((x for x in range(10)),Iterable))
# print(isinstance(100,Iterable))
# 迭代器
# Iterator,无限大数据流,内部定义__next__... |
347c26e4de6383598ea3a21ca20ff027713b3e8f | li-MacBook-Pro/li | /static/Mac/play/调用/二分树/小偷偷钱.py | 1,101 | 3.828125 | 4 | #定义一个二叉房子类,包括当前节点、左节点和右节点
class House():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
#定义一个函数,返回根节点最后的偷值和不偷值较大那个
def rob(root):
a = helper(root)
print(max(a[0], a[1]))
#定义一个辅助函数,递归算出根节点偷值和不偷值
def helper(root):
if(root == None):
return... |
5612738c34956713a04a55923765d1718fdcd934 | li-MacBook-Pro/li | /static/Mac/play/调用/长方体/changfangxing.py | 2,251 | 3.8125 | 4 | #第一种
import random
class cube:
def define(self):
global x,y,z
x=self.x = random.randint(1,5)
y=self.y = random.randint(1,5)
z=self.z = random.randint(1,5)
return x,y,z
def Cuboid_Area(self):
global Area
Area=(2*(self.x * self.y + self.x * self.z + self.y *... |
e93fdc9cee0fa4388f92877ceaee733624c3900a | tveebot/organizer | /tveebot_organizer/matcher.py | 1,919 | 3.75 | 4 | import re
from tveebot_organizer.dataclasses import Episode, TVShow
class Matcher:
"""
The Matcher is one of the sub-components of the *Organizer*. An organizer is associated with a
single matcher. The matcher is used to match an episode name, using some pre-defined format,
to an episode object.
... |
46a808d1c32ca99e7672ed19389480728ee21b6b | CooperNederhood/spring2018_project | /data_processing/model0.py | 1,663 | 3.734375 | 4 | from keras import layers
from keras import models
'''
From Chapter 5, create a simple CNN model from scratch
'''
model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(128, 128, 3)))
model.add(layers.MaxPooling2D( (2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
... |
662afa79e92cac1dab547c962292fa42efca4e57 | MrCordero/testgithub2 | /ejercicio_7.py | 410 | 4 | 4 | #Contador de numeros
cont_num = 0
#Contador de vueltas
cont_vueltas = 0
#Acumulador de numeros
acu_num = 0
while(True):
num = int(input("Ingrese numero : "))
#Suma
acu_num += num
cont_vueltas = cont_vueltas + 1}
prom = acu_num / cont_vueltas
if(cont_vueltas == -1):
break
p... |
712b6de931dcfe6fcdce13e16c4edf5e16b7fc94 | KontextuellEnergivisualisering/Priority-Calculations | /Algorithms.py | 1,521 | 3.6875 | 4 | import time
# Calculates the minimum power in the combined list with old data ('points') and new data ('lastHourData')
def min(points, lastHourData):
min = -1
# Check if points are from database
if not isinstance(points[0][1], int):
# If points come from database, loop through every point until a p... |
a2942eea4bbccc41c49f0a87b00324f23b93fb40 | pisa-engine/pisa | /script/bp/generate_config.py | 1,394 | 3.703125 | 4 | #!/usr/bin/env python
import argparse
import sys
def generate_recursive(lvl, first, last, out):
if last - first < 2:
return
left_range = (first, first + (last - first) // 2)
right_range = (left_range[1], last)
print(lvl, 20, left_range[0], left_range[1],
right_range[0], right_range[1... |
7b16f62b068e3f5de037781f496881846d025fa3 | XiaoyuZhou1106/CSC108-Introduction-to-Computer-Programming | /a3/tweets.py | 14,057 | 3.953125 | 4 | """Assignment 3: Tweet Analysis"""
from typing import List, Dict, TextIO, Tuple
HASH_SYMBOL = '#'
MENTION_SYMBOL = '@'
URL_START = 'http'
# Order of data in the file
FILE_DATE_INDEX = 0
FILE_LOCATION_INDEX = 1
FILE_SOURCE_INDEX = 2
FILE_FAVOURITE_INDEX = 3
FILE_RETWEET_INDEX = 4
# Order of data in a tweet tuple
TWE... |
a2c11f8cdd280ce12b1d56ad3745fff0b19f456c | osamaawadallah/AlgorithmicToolbox | /week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.py | 1,028 | 3.875 | 4 | # python3
from random import randrange
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.