blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3b959c8b140a34401ffb7b0ca80be2115b7d5d03 | brianchiang-tw/CodingInterviews | /21_Sort by Parity/by_module_and_element swap.py | 550 | 3.5625 | 4 | from typing import List
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
i, j = 0, 0
while i < len(nums):
if nums[i] % 2 == 1:
nums[i], nums[j] = nums[j], nums[i]
j += 1
i += 1
return nums
# n : the leng... |
52760e84dbbe500efdc1f6ec9c844452010238d6 | victorazzam/stash | /Challenges/ZeroDays 2018/Reversing/1 Cryptex/cryptex.py | 452 | 3.609375 | 4 | #!/usr/bin/env python
password_guess= raw_input("Enter Password: ")
if len(password_guess) != 14:
print "Wrong Length"
exit()
verify_code = [113, 220, 168, 206, 164, 220, 180, 236, 250, 73, 196, 228, 220, 244]
user_code = []
for char in password_guess:
user_code.append( (((ord(char) << 2) | (ord(char) >> 5))... |
13de4f848523a86a86d24ac9c2b986c0b4f9cd7c | Desperaaado/ex4 | /ex4/ex4a.py | 739 | 3.9375 | 4 | from sys import argv
from sys import exit
lenth = len(argv)
def print_sentense(who='I', do='eat', what='apple'):
print(f'Today {who} {do} {what}!!')
if '-h' in argv or '--help' in argv:
print("""
HELP:
This program can show you a sentense on the basis of
three word which you ... |
5bd011bb00cf377fc1f763aa73356d09df1597bd | EmanuelYano/python3 | /URI - Lista 3/1217.py | 353 | 3.671875 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
mKg = mBrl = 0
i = 1
n = int(input())
while i <= n:
val = float(input())
frutas = input()
nFru = 1
for crtr in frutas:
if crtr == ' ':
nFru += 1
print("day %d: %d kg"%(i,nFru))
mKg += nFru
mBrl += val
i += 1
mKg /= n
mBrl /= n
print("%.2f kg by day"%(mKg))
print... |
7dbe9a52e02ba87f59876b03a79404bfe7888c26 | eryeer/pythonStudy | /card_system/cards_tool.py | 2,857 | 4 | 4 | # 记录所有的名片字典
card_list = []
def show_menu():
"""show menu"""
print("*" * 50)
print("欢迎使用名片管理系统 V 1.0")
print("")
print("1. 新增名片")
print("2. 显示全部")
print("3. 搜索名片")
print("")
print("0. 退出系统")
print("*" * 50)
def new_card():
"""new card"""
print("-" * 50)
print("新增名片... |
c8e224c420bcd860291e7346ffcddc01d5a66cb2 | RookieLinLucy666/Codewar | /Where my anagrams at?.py | 325 | 4 | 4 | def anagrams(word, words):
sort_word = "".join(sorted(word))
result = []
for sub_words in words:
if sort_word == "".join(sorted(sub_words)):
result.append(sub_words)
else:
continue
return result
print(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'race... |
eb1a937c0651bf59052b16a59e43f78d5f6a578a | kyleburton/sandbox | /examples/python/exceptions/ex.py | 401 | 3.765625 | 4 | #!/usr/bin/env python
import sys
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError as e:
#import pdb; pdb.set_trace()
print "Oops! invalid number, try again. %s" % (e.message)
print "Oops! invalid number, try again. %s" % (sys.exc_info()[0])
try:
raise... |
acafa1621ed2e0bf893eff4dc69bc326b10997b0 | linctothepast/The-Game | /a_scenario/approaching_an_acorn_pile/approaching_acorn_pile.py | 5,368 | 4 | 4 | import random
# Function for the actual thing.
def approaching_acorn_pile():
print("APROACHING AN ACORN PILE")
print("---------------------------")
loop = True
while loop:
choice = input("""You're walking through the Forest of Kloa,
and you come across a small pile of acorns (they seem to be ... |
a7fbd15da45dac1e382f471ebe03acb6830ebd26 | IrisLiQinyi/mis3690 | /hello.py | 237 | 3.96875 | 4 | print('hello, world')
name = input()
name
print(name)
name = input('Enter your name: ')
print ('Hello, ', name)
message ='I did something cool today!'
print (message)
n=100
print (n)
a=123
print (a)
a = 'ABC'
b=a
a='XYZ'
print(b)
|
bed18ae9c1fa6f6e919367127ca2fffff37a199c | viciouspetal/knn-ml-cit | /common_utils.py | 4,088 | 4.09375 | 4 | import pandas as pd
import numpy as np
def load_data(path, columns):
"""
For a given path to file it loads a dataset with given headers.
:param path: paths to dataset
:param columns: columns specified for a given dataset
:return: dataset with headers loaded in a pandas dataframe
"""
df = p... |
5ec9665ecf9a15fd38a1a45c23188ba68fe8fa25 | Me-Pri/Python-programs | /multiple_inheritance.py | 462 | 4.0625 | 4 | class add:
def operate1(self):
self.sum=self.a+self.b
return self.sum;
class subtract:
def operate2(self):
self.diff=self.a-self.b
return self.diff;
class multiply(add,subtract):
def input(self):
self.a=int(input("Enter the first no: "))
self.b=int(input("Enter the second no: "))
def operate... |
1ba008e2c977fd4fc1f521d26401bf3ce672ab2a | msullivancm/CursoEmVideoPython | /Mundo2-ExerciciosEstruturasDeRepeticao/ex057.py | 204 | 3.75 | 4 | c = 1
while c != 0:
sexo = str(input('Informe seu sexo: [M/F]:')).upper()
if sexo != 'M' and sexo != 'F':
c = 1
print('Digite M ou F somente.')
else:
c = 0
print('fim') |
4392ca6533302eb1edf55d6fd0eac912e322dd12 | hemangbehl/Data-Structures-Algorithms_practice | /leetcode_session2/queue_builtin.py | 234 | 3.953125 | 4 | from queue import Queue
a = Queue()
print (a)
print("size", a.qsize())
a.put(1)
a.put(2)
a.put(3)
print(a)
a.get() #removes and returns an item
print ("size", a.qsize())
#print queue
for i in range(a.qsize()):
print (a.get())
|
b7893d4fcfb8902ea43e42fcdf1195c9494ebf67 | JoseJunior23/Iniciando-Python | /cursoemvideo/aula10.py | 180 | 4.03125 | 4 | nome = str(input('Qual o seu nome: '))
if nome == 'Junior':
print('É um belo nome!')
else:
print('seu nome não contem Junior que pena!')
print('Bom dia, {}'.format(nome)) |
a2f92a11505a09b14f14b79e4879da2c0ba2e406 | akrizma12/pythonProjects | /H3/trace_me.py | 2,080 | 3.953125 | 4 | # The Python program trace_me.py is posted next to this handout on Canvas.
# Download it and add to your project for this assignment. Set breakpoints on the two print("set...") statements in this program.
# Run your program in the PyCharm debugger and enter 5 for the first input, then the values 1.0, -2.0, 3.0, -4.0, 5... |
c2fdab62f985323ffbe6340f333ca6da1fa6b407 | ninepillars/trunk | /example/pythonexample/bookexample/lession_1/lession_1_3.py | 1,337 | 3.5625 | 4 | # coding: utf-8
'''
Created on 2011-11-28
@author: Lv9
'''
a = 1;
b = 2;
product = "game";
productType = "pirate memory";
age = 5;
suffix = ".png";
s = "Lv9 is a cool kid"
hasLv9 = True;#Python的布尔值分别为True和False
if a < b:
print("Computer says yes");
else:
print("Computer says no");
... |
b029886a76caba4d52b55a5262aa1afbb7f57477 | gitForKrish/PythonInPractice | /TeachingPython/math03.py | 611 | 3.828125 | 4 | '''
5. Write all possible 2-digits numbers that can be formed by using the digits 2, 3 and 4.
Repetition of digits is not allowed. Also find their sum.
output: 23,24,32,34,42,43 - >
'''
def find_numbers(digits, decimal_place):
generated_numbers = []
for (index, value) in enumerate(digits): # 2,3,4
... |
c8fefc38670bd237ea1eeeecc5469087add08b9e | deepashreeKedia/Solutions | /secret_number | 698 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 15:50:57 2018
@author: deep
"""
# Paste your code into this box
print("Please think of a number between 0 and 100!")
low = 0
high = 100
while True:
guess = (low + high) // 2
print("Is your secret number {}?".format(guess))
ans = i... |
24840bf0b8d4fc375a84e0e04a88258639f304c6 | ShanjinurIslam/HackerRank | /min_max_sum.py | 500 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
min_val = 2e10
max_val = -1
total = 0
for each in arr:
if min_val > each:
min_val = each
if max_val < each:
max_val = each... |
46342767b1a5a5b8c396e2084582cb025ecfe83e | pink-sheep/duplicates | /main.py | 1,574 | 3.875 | 4 | ##########################################################
################# Plagiarism detection ###################
##########################################################
#### Main - user interation
# manages the plagiarism detection program, introduces
# human-computer interaction
import os, preprocessing, nea... |
1f67d7dd406c4eb85cc8be9f20c8010c6b20f47e | buyuxing/leetcode-cn | /python/679. 24点游戏.py | 4,023 | 3.5 | 4 | '''
https://leetcode-cn.com/problems/24-game/description/
679. 24点游戏
你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 *,/,+,-,(,) 的运算得到 24。
示例 1:
输入: [4, 1, 8, 7]
输出: True
解释: (8-4) * (7-1) = 24
示例 2:
输入: [1, 2, 1, 2]
输出: False
注意:
除法运算符 / 表示实数除法,而不是整数除法。例如 4 / (1 - 2/3) = 12 。
每个运算符对两个数进行运算。特别是我们不能用 - 作为一元运算符。例如,[1, 1, 1, 1] 作为输入时,... |
70968c67e7a72dab62fb7d4c42bc983eb4db9430 | neeraj-badam/python | /Lab Internal/12.Dijkstra.py | 1,291 | 3.703125 | 4 | # Dijkstra's
import heapq as heap
import sys
class Pair:
def __init__(self,first,second) -> None:
self.first = first
self.second = second
def __lt__(self,next):
return self.first < next.first
def dijkstra(g,source,destination):
n = len(g)
dis = [sys.maxsize]*(n+1)
... |
4275646ad3d54cf408852112c09698d69c51ce66 | litvaOo/algorithms_and_structures | /Lab02.py | 1,147 | 3.65625 | 4 | class HashTable:
def __init__(self, size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hash(key)
if self.slots[hashvalue] is None:
self.slots[hashvalue] = key
self.dat... |
a90e149f7147f8b4a3844d84e5fe768ea51f5e91 | dhumindesai/Problem-Solving | /educative/two_heaps/MedianOfAStream.py | 1,352 | 3.984375 | 4 | from heapq import *
class MedianOfAStream:
max_heap = []
min_heap = []
def insert_num(self, num):
if not self.max_heap or -self.max_heap[0] > num:
heappush(self.max_heap, -num)
else:
heappush(self.min_heap, num)
# if min_heap has more elements than max_heap... |
9c28d69b00f31d5394112a31340e6c44b2de6faf | varshajoshi36/practice | /leetcode/python/easy/symmetricTree.py | 1,217 | 4.4375 | 4 | """
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
"""
# Definition for a binary ... |
03e81f455a5d2bab66078ff4c210da966c8958de | dinoivusic/Python-Challenges | /day35.py | 222 | 3.609375 | 4 | def overlap(arr,num):
count = 0
for i in range(len(arr)):
if arr[i][0] == num or arr[i][1] == num:
count+=1
if num > arr[i][0] and num < arr[i][1]:
count+=1
return count
|
73b01e4dd8b166684ab37d4a43213f367d294656 | ArunkumarSennimalai/-Python-Assignment2 | /Assingment2/37.py | 1,588 | 3.5625 | 4 | import json
def biggestDict(dict1,dict2,dict3):
biggestDict = dict2
if cmp(dict1,dict2):
biggestDict = dict1
if cmp(dict3,biggestDict):
biggestDict = dict3
return biggestDict
def addToDict(tempdict,key,val):
tempdict[key] = val #dict2['l'] = 12
def addDictToAnothe... |
3a2738c0e3f007f9e2ad33bc5c55d91ca129842b | 89chrisp/python-course-project | /adventure/one.py | 3,999 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Room one
"""
import gameItem
import game
descr = """-------------------------------------------------------------------------------
Room no. 1
You find yourself in a room without windows.
There is a table in the room and the walls are decorated with some paintings.
... |
f7001ee78ebdfc5de4913ed025a95bad63de0593 | candyer/leetcode | /2020 December LeetCoding Challenge/26_numDecodings.py | 1,634 | 3.765625 | 4 | # https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3581/
# Decode Ways
# A message containing letters from A-Z is being encoded to numbers using the following mapping:
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Given a non-empty string containing only di... |
07d19e6dee75c1325cf33829f7f5e561066903e0 | Vejusatko/Pyladies_beginners_course | /02/task07_house.py | 355 | 3.640625 | 4 | from turtle import forward, left, right, exitonclick
from math import sqrt
#house variables
x = 100
diagonal = sqrt(2*(x**2))
#let's draw
forward(x)
left(135)
forward(diagonal)
right(135)
forward(x)
left(120)
forward(x)
left(120)
forward(x)
left(30)
forward(x)
left(135)
forward(diagonal)
right(135... |
c0051c43975ff7d55df1fa1b4a205ad73c2dec91 | ramsayleung/leetcode | /600/valid_parenthesis_string.py | 1,614 | 4.28125 | 4 | """
source: https://leetcode.com/problems/valid-parenthesis-string/
author: Ramsay Leung
date: 2020-02-17
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis '('... |
e5f2b0b03acefae21ed2009fcffb80a95731f628 | thomasngn673/Python-with-ATBS | /conwaysGameOfLife.py | 3,092 | 4.1875 | 4 | # Conway's Game of Life Rules
# 1. If a living square has 2-3 living neighbors, it continues to live
# 2. If a dead square has exactly 3 living neighbors, it comes to live
import random, time, copy
width = 12
height = 4
# creates a list of x values that each have own individual list of y values
# creates a list of l... |
c8cf540c6abccfc7c23e41cb6a86fb6685fd0ff8 | GGolfz/100DaysOfPythonPro | /Day002/Ex2-2.py | 122 | 4.125 | 4 | height = float(input("Enter you height: "))
weight = float(input("Enter you weight: "))
print(int(weight/(height*height))) |
f2b3b851cbc8170d6eb2a60b8996560b9c6ab9c0 | ijuarezb/InterviewBit | /06_TreesDataStructure/kth_smallest_element_ina_tree.py | 2,168 | 3.890625 | 4 | #!/usr/bin/env python3
import sys
from BST import TreeNode
from BST import insertNode
from BST import inOrderTraversal
# Kth Smallest Element In Tree
# https://www.interviewbit.com/problems/kth-smallest-element-in-tree/
#
# Given a binary search tree, write a function to find the kth smallest element in the tree.
#
# ... |
6b478f510d43c3eabcd26a623817002ba7033770 | vjs7898/pythonProject1 | /binarysearch.py | 476 | 3.6875 | 4 | pos = -1
def search(list,n):
l = 0
u = len(list) - 1
for i in range(l,u+1):
mid = (l + u)//2
if(list[mid]==n):
globals()['pos'] = mid
return True
else:
if(list[mid] < n):
l = mid + 1
else:
u = mid - 1
... |
95e57df785f2d508856e71be2143818a54621a5a | quitaiskiluisf/TI4F-2021-LogicaProgramacao | /atividades/avaliacao-02/a02_03.py | 647 | 4.125 | 4 | # Apresentação
print('Programa para calcular estatísticas dos números e um vetor')
print()
# Solicita os 18 valores
valores = list()
for i in range(18):
valores.append(float(input('Informe um número: ')))
# Calcula a média dos valores (somatório de todos os
# valores dividido pela quantidade de valores existentes... |
10d81e4d4f9fdc9af33a2735b01bae7e7ea0d1fb | vickyrr24/guvi | /countstr.py | 78 | 3.640625 | 4 | st=input()
count=0
for i in st:
if(i!=" "):
count+=1
print(count)
|
04d959ec43ecf8efef397ff38e1d2147fa777f45 | sediame/mad-libs | /mad-libs.py | 519 | 3.625 | 4 | import re
with open('data/template.txt') as f:
mylist = list(f)
text = mylist[0]
print('Enter an adjective:')
new1 = input()
print('Enter a noun:')
new2 = input()
print('Enter a verb:')
new3 = input()
print('Enter a noun:')
new4 = input()
text = re.sub("ADJECTIVE", new1, text, count=1)
text = re.sub("NOUN", ... |
c3c75d6f1644af5a1aff889442da7bd0a596bf37 | MarioFried/Project03 | /Dicionario.py | 252 | 4.3125 | 4 | """
Pequeno Exemplo de Funcionamento da Estrutura Dicionario em Python
"""
Database={}
Database['Cliente']={1:'Mario',2:'Ana'}
Database['Leads']={1:'Manu',2:'David',3:'Marcelo'}
print(Database['Cliente'][1])
print(Database['Leads'][3])
print(Database) |
4e5ea9dd3da0ab0360df0126ea35ff3ea4992981 | SourabhKul/Adversarial-attacks-NN | /mnist-example-cnn.py | 2,757 | 3.765625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# read in data
mnist = input_data.read_data_sets("", one_hot=True)
# define number of hidden layers and nodes per hidden layer
# define number of classes and batch size to avoid ram overload
n_classes = 10
batch_size = 128
# x is da... |
f61fdc9801d3f28d22549709ffab4c6740b7e9c3 | Srikesh89/PythonBootcamp | /Python Scripts/MilestoneProject2.py | 8,215 | 3.765625 | 4 | '''Blackjack Game: Player vs Dealer'''
import random
SUITS = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
RANKS = ('Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
VALUES = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7,
'Eight':8, 'Nin... |
8e4c026eba08f044cb29bd848bb85950e70d7fc9 | minhyeong-joe/coding-interview | /Array/ReverseInPlace.py | 465 | 4.21875 | 4 | '''
Given a list, reverse the order without using extra arrays.
'''
def reverse(arr):
left = 0
right = len(arr)-1
print(left, right)
while left < right:
arr[left] = arr[left] + arr[right]
arr[right] = arr[left] - arr[right]
arr[left] = arr[left] - arr[right]
left += 1
... |
6f8152facd772df3b6efdb19e022b82a36d379dc | pczubows/img-crypt | /img_crypt/imgcrypt.py | 11,294 | 3.71875 | 4 | """Img Crypt
Script for testing different image encryption methods. It implements
traditional stream ciphers and an algorithm designed for image encryption
based on chaotic map lattices.
Chosen image is being encrypted and decrypted. When procedure finishes script
displays image before and after encryption, along wit... |
edec7c17e0f732fd22fa3ce5f14402d9fbe24985 | eulersformula/Lintcode-LeetCode | /Product_of_Array_Exclude_Itself.py | 1,076 | 3.65625 | 4 | # Lintcode 50//Easy
# Description
# Given an integers array A.
# Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]B[i]=A[0]∗...∗A[i−1]∗A[i+1]∗...∗A[n−1], calculate B WITHOUT divide operation.Out put B
# Example
# Example 1:
# Input:
# A = [1,2,3]
# Output:
# [6,3,2]
# Explanation:
# B[0] = A[1] * A[2] = ... |
1e7257295f1e7746e142863197627c0402cb8852 | hazardg/CP1404-Practicals-GeraldoGenesius | /Practical 1/menu.py | 337 | 4.0625 | 4 | name = str(input("Enter name: "))
menu = """(H)ello
(G)oodbye
(Q)uit"""
print(menu)
choose_menu = str(input(">>> "))
while choose_menu != 'Q':
if choose_menu == 'H':
print("Hello ", name)
elif choose_menu == 'G':
print("Goodbye ", name)
print(menu)
choose_menu = str... |
e5ee8c64a2f764ce6484cf37a33e7a1ad2728182 | bfonta/OutliersGAN | /src/letters.py | 3,584 | 3.5625 | 4 | from matplotlib import pyplot as plt
import numpy as np
class Letters():
def __init__(self, hsize, vsize):
"""
Creates the frame where a single letter will be drawn
"""
self.frame = np.zeros(shape=(hsize*vsize), dtype=float)
self.hsize = hsize
self.vsize = vsize
... |
7c94dfab1a10ebaa927b1da32dba7ba0e7e5abdd | juliafealves/advanced-algorithms-basic | /list-02/p3.py | 898 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# Author: Júlia Fernandes Alves. <juliafealves@gmail.com>
# Handle: juliafealves
# Problem: B. Queries about less or equal elements
def binary_search(array, number, length):
i, j = 0, length
while i <= j:
middle = (i + j) / 2
if array[middle] > number:
if ... |
4375db9c019e58b6947c4c6080b579ecf0ed9b1c | navinraman1996/Connected-Devices-Python_workspace | /apps/labs/common/SensorData.py | 2,985 | 3.71875 | 4 | '''
Created on Jan 24, 2019
@author: Navin Raman
'''
from datetime import datetime
import os
class SensorData(object):
'''
this class contains sensor data's and attributes
'''
timestamp = None
name = 'not set'
curVal = 0;
avgVal ... |
a81c59c1187145afc32852bf7d5db6c860953b89 | ZukhriddinMirzajanov/Data-structures | /bstree.py | 3,332 | 3.765625 | 4 | import queue
class BSTree:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
def insert(self, root_node, node_value):
if root_node.data is None:
root_node.data = node_value
elif node_value <= root_node.dat... |
6eae1f12227c23a47e0045c5a2b40ab7d70308bc | Toranian/hackerspace-control-panel | /src/file_finder.py | 5,734 | 3.625 | 4 | from pathlib import Path
from sys import platform
import os, re, time
class FindFile:
"""Returns a selected file."""
def __init__(self):
# Helpful variables and home directory
self.home_dir = str(Path.home())
self.working_dir = self.home_dir
os.chdir(self.working_dir)
s... |
895dfb4c61759a34a3e5bd1b5f706e1f2d4afae4 | leticiafelix/python-exercicios | /08 - Repetições (while)/desafio071.py | 980 | 4.15625 | 4 | #faça um programa que simula o funcionamento de um caixa eletrônico
#no inicio pergunte ao usuario qual o valor a ser sacado (inteiro)
#o programa informa quantas cédulas de cada valor serão entregues
#considere que o caixa possui cédulas de 20, 50, 10 e 1 real
print('--------------------------------')
print(' ... |
cd2fc25b9b32d762b298e702edf4beecb474aad5 | treesakul/LR-1-parser-generator | /Parser.py | 1,571 | 3.671875 | 4 | def parser(table, string):
stack = ['$',0]
input_string = string+'$'
input_index = 0
table = {0: {'c': ('s', 1), 'd': ('s', 2), 'S': ('s', 3), 'C': ('s', 4), "S'": ('', 'accept')}, 1: {'c': ('s', 1), 'd': ('s', 2), 'C': ('s', 5)}, 2: {'d': ('r', ('C', ('d',))), 'c': ('r', ('C', ('d',)))}, 3: {'$': ('r',... |
4f61f3c44329b8b0294f074b88138a3fe6323b4d | poonampatil26/StudentAddressExceptionTask | /result.py | 10,576 | 4.125 | 4 | from ProjectTaskStudent import *
class InvalidInput(Exception):
def __init__(self,msg):
self.msg=msg
def len_pincode(pincode):
count=0
while pincode>0:
count+=1
pincode=pincode//10
return count
def add_pincode_check(pin):
if len_pincode(pin)>6 or len_pincode(pin)<6:
... |
211cb57a1bd7157355a378fa8cc330e49e0b298e | sforrester23/Veterinary_Class_Project | /Pet_Class.py | 332 | 3.84375 | 4 | # Define a Pet class
class Pet():
def __init__(self, name, owner, breed, animal='Dog'):
self.name = name
self.owner = owner
self.breed = breed
self.animal = animal
def get_pet_info(self):
return '{} is a {} {} owned by {}.'.format(self.name, self.breed, self.animal, self... |
bdd0227f6cac5ef35ebfe81ad7c0d0fdf02f476f | filozyu/leetcode-journey | /src/string/group_anagrams.py | 1,661 | 3.75 | 4 | from collections import defaultdict, Counter
def groupAnagrams(strs):
"""
Hacking (slow)
Time: O(nk), n: length of strs; k: max length of words;
Space: O(nk), same as strs
"""
res_dict = defaultdict(list)
for word in strs:
key = frozenset(Counter(word).items())
res_dict[key... |
4afd4b26dac5707bc319d251608cb13cee76b57b | suyalmukesh/python | /warmup/CeasarCipher.py | 1,042 | 3.59375 | 4 | class CeasarCipher:
def __init__(self,shift):
encoder = [None] * 26
decoder = [None] * 26
for k in range(26):
encoder[k] = chr((k+shift)%26 + ord('A'))
decoder[k] = chr((k-shift))%26 + ord('A')
self._forward = ''.join(encoder)
self._backward = ''.... |
44a0963016dfbfa13263a78eb03d5df256cf166e | sandi0805/vba_challenge | /Minis/house_of_pies_bonus Sandra Hall.py | 698 | 3.8125 | 4 | pie_purchases = [0,0,0,0,0,0,0,0,0,0]
print("Welcome to the House of Pies! Here are our pies:")
pies = ["Pecan", "Apple Crisp", "Bean", "Banoffee", "Black Bun", "Blueberry", "Buko", "Burek", "Tamale", "Steak"]
print(pies)
pie_cart = []
x = input("Which pie would you like to try? Choose 0-9. ")
print(f"Great! W... |
e22612d5f4536b688b0c04d0633c97e5e4431db1 | zingzheng/LeetCode_py | /242Valid Anagram.py | 591 | 3.859375 | 4 | ##Valid Anagram
##Given two strings s and t,write a function to determine if t is an anagram of s.
##
##2015年8月23日 19:17:58 AC
##zss
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic={}
for c in s:
... |
12af2884232a70d1cbe2a1b938d64e42d74d8378 | Andrew940/robot-europa | /catkin_ws/src/local_mapper/nodes/numpy_extra.py | 870 | 3.921875 | 4 | #!/usr/bin/env python3
"""
Extra functions that should probably have been features of numpy.
"""
import numpy as np
def shift_2d_replace(data, dx, dy, constant=False):
"""
Shifts the array in two dimensions while setting rolled values to constant
:param data: The 2d numpy array to be shifted
:param d... |
96a1eb2b4d5a3d855366915d7e1732471a29a6e1 | sancharibasak/tusk | /List1.py | 1,153 | 3.53125 | 4 | #list of states in India
#Mutable Objects - Lists:
listA = [2.3, 4, 67, 12.8, "Python", True]
for i in range(len(listA)):
print(listA[i], end=' ')
print()
for i in range(-1, -len(listA)-1, -1):
print(listA[i], end=' ')
print()
tupA = tuple(listA)
print(tupA)
#List Comprehension:
listB = [x for x in range(10... |
6c76f871c1bb8bcb4903865c00ba3e6e313a569f | JessiMcKissick/RPyG | /Learn it/step_7.py | 4,365 | 3.71875 | 4 | import os # Allows you to utilize OS functions.
import random # Allows you to utilize math randomization and the likes.
import time # Allows access to time. This will mostly be used for delays.
import platform # We'll use this to find the current devices platform.
version = "0.0"
lb = "----------------------------... |
3e0f29145531b9b66f4be2c011c6ea098114b0f5 | wayneshun/LPTHW | /spider/列表.py | 403 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 04 00:09:32 2014
@author: shunxu
"""
def swap(lst,a,b):
c = lst[a]
lst[a] = lst[b]
lst[b] = c
def shift_left(lst):
tmp = lst[0]
for i in range(len(lst)-1):
lst[i] = lst[i+1]
lst[-1] = tmp
x = [10,20,30]
shift_left(x)
... |
8df8c2eeb973eccca47bfa41f1c7c628f60079e6 | aerosayan/Learning-Machine-Learning | /src/01_soup_sale.py | 1,446 | 4.125 | 4 | # LANG : Python 2.7
# FILE : 01_soup_sale.py
# AUTH : Sayan Bhattacharjee
# EMAIL: aero.sayan@gmail.com
# DATE : 2/JULY/2018
# INFO : How does hot soup sale change in winter based on temperature?
# : Here, we do linear regression with ordinary least squares
import numpy as np
import matplotlib.pyplot as plt
n = ... |
cf7ae57d863e390eb9f4170c0d27cb26c87d38de | saurabhkawli/PythonHackerRankCodes | /TestSmartNumber.py | 612 | 3.921875 | 4 | import math
num = 1
val = int(math.sqrt(num))
print("num: ",num," Val: ",val)
print("Num/val",num/val)
print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG")
num = 2
val = int(math.sqrt(num))
print("num: ",num," Val: ",val)
print("Num/val",num/val)
print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG... |
3801624e79f5e49f1a36f382afc8237a485aa126 | Osmel1999/holbertonschool-higher_level_programming | /0x0B-python-input_output/10-class_to_json.py | 388 | 3.625 | 4 | #!/usr/bin/python3
"""Module 10-class_to_json.
Returns the dictionary description with
simple data structure (list, dictionary,
string, integer and boolean)
for JSON serialization of an object.
"""
def class_to_json(obj):
"""Creates a dict description of obj.
Args:
- obj: object to serialize
Retur... |
f742a6010866badbb9f77203c6f6b4e69cd6c56f | Prabhjyot2/workshop-python | /L3/p4.py | 196 | 3.765625 | 4 | # wapp to generate
num = int(input("enter the number "))
if num < 0:
print("b +ve")
else:
n = 0
for i in range(1 , num+1):
for j in range(1, i+1):
print(n, end="")
n = n + 1
print()
|
66620ac288f4f441fd7d34ef92a70c7a62248fbc | DavidGrice/CSC-241-Doubly-Link-List-Hanoi | /Delimiter_Check.py | 1,645 | 4.5625 | 5 | # for sys.argv, the command-line arguments
import sys
from Stack import Stack
# def delimiter_check(filename):
# Sets a constructor equal to the stack
# Has a set to check against the delimiters and creates a variable
# to open the file
# From here it goes through the file and if the characters match
# then ... |
228daf2ad0aa547a911030c45b6dacedff295ede | bliack-swan/my_github | /fast_sort.py | 792 | 3.953125 | 4 | def the_biggest_el ( arg ) :
if len ( arg ) <= 1 :
return arg [ 0 ] if len ( arg ) != 0 else None
elif len ( arg ) == 2 :
return arg [ 0 ] if arg [ 0 ] > arg [ 1 ] else arg [ 1 ]
else :
max_value = the_biggest_el ( arg [ 1 : ] )
return arg [ 0 ] if arg [ 0 ] > max_valu... |
5ea80dafde3893cf542d99360decf7c36969dc8f | sunnyhyo/big_data | /Python/064 oop.py | 595 | 4.3125 | 4 | student = {'name': '홍길동', 'year': 2,'class':3, 'student_id':35}
print( '{}, {}학년 {}반 {}번'.format(student['name'], student['year'], student['class'], student['student_id']))
class student(object):
def __init__(self,name, year, class_num, student_id):
self.name=name
self.year=year
self.cla... |
906fb5e0f1fcc8267e63f178e984bdbde5d55509 | JackRyannn/LeetCode | /24.py | 929 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
first = head
if not first:
... |
55dbef2eeb6d1fab43281a44f8c99366b3bbafca | yagnyasridhar/Python | /Training/Flask/EmployeeManagement/DBLoadJob.py | 3,711 | 3.828125 | 4 | import sqlite3
from sqlite3 import Error
import Employee
def sql_connection():
try:
con = sqlite3.connect('Employee.db')
return con
except Error:
print(Error)
def sql_table(con):
try:
cursorObj = con.cursor()
cursorObj.execute("CREATE TABLE employees(i... |
4f6c06632daaa4851676644db6036a32fd594c04 | julian59189/ThePythonMegaCourse | /script3.py | 582 | 4.0625 | 4 | import random, string
vowels='aeiouy'
consonants='bcdfghjklmnpqrstvwxz'
letters=vowels+consonants
letter_input_1=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ")
letter_input_2=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter... |
726e0ec2151c342a3325ee4614793eae278cd2fe | LucyHsu/training1 | /perfect_number.py | 494 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
def perfect_number_check(test_num):
listtwo = [ i for i in range(1,(test_num/2)+1) if test_num % i ==0 ]
# print repr(test_num) + ' is perfect number' if sum(listtwo) == test_num else 'false'
return True if sum(listtwo) == test_num else False
if __name__ == ... |
0c1ecd4b63dfb926fb4583d8be6944d49eba2d47 | swizzard/selector | /selector.py | 8,426 | 3.59375 | 4 | """
Mimic `select`-type behavior over a set of generators
"""
from itertools import cycle
from operator import itemgetter
class Selector(object):
"""
'Select' inputs from a collection of generators. Generators are paused or
stopped based on user-defined conditions.
"""
def __init__(self, stop_cond... |
130049813722047d8668c04715d845d858001c84 | claudiodornelles/CursoEmVideo-Python | /Exercicios/ex039 - Alistamento militar.py | 1,384 | 4.0625 | 4 | """
Faça um programa que leia a idade de nascimento de um jovem e informe, de acordo com sua idade:
- Se ele ainda deve se alistar ao serviço militar.
- Se é a hora de se alistar.
- Se já passou do tempo do alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
"""
from datetime im... |
2e7ee81d95dc1e7318a5a4147f50b47979266c6e | jhonatanmaia/python | /study/curso-em-video/exercises/075.py | 401 | 4 | 4 | x=(int(input('Digite um valor: ')),int(input('Digite um valor: ')),
int(input('Digite um valor: ')),int(input('Digite um valor: ')))
print(f'O valor 9 apareceu {x.count(9)} vezes')
if 3 in x:
print(f'O valor 3 aparece primeiro no índice {x.index(3)}')
else:
print('O número 3 não foi digitado')
print('Os valo... |
4efdbc64538470bcc25e2d0a0e47e72959fdc078 | lein-hub/python_basic | /programmers/find_prime_number.py | 554 | 3.734375 | 4 | # def solution(n):
# def isPrime(n):
# if n != 2 and n % 2 == 0:
# return False
# for a in range(2, n//2+1):
# if n % a != 0:
# continue
# else:
# return False
# return True
# answer = 0
# for i in range(2, n+1):
#... |
5019cb29f92406085636e737439008774e6e593f | DRomanova-A/Base_project_python | /основы программирования python (ВШЭ)/solutions/week-2/task_2_17_seq_len_even.py | 660 | 4.40625 | 4 | '''
Количество четных элементов последовательности
Определите количество четных элементов в последовательности,
завершающейся числом 0.
Формат ввода: Вводится последовательность целых чисел,
оканчивающаяся числом 0 (само число 0 в последовательность не входит,
а служит как признак ее окончания).
'''
n = int(input())
... |
809aa2234fa08e6291c09b46fc858f9bd8bb99c9 | SpringSnowB/All-file | /m1/d4/esercise08.py | 149 | 3.703125 | 4 | """
几 + 几 =几
"""
import random
number1, number2 = random.randint(1,10),random.randint(1,10)
print("%d+%d=%d"%(number1,number2,number1+number2)) |
1e7d00285e3386c5cf2bae84386bb04294a06b69 | lijubjohn/python-stuff | /algorithms/linkedlist/remove_nth_node_frm_end.py | 453 | 4.09375 | 4 | # '''
# Given a linked list, remove the n-th node from the end of list and return its head.
# Example:
# Given linked list: 1->2->3->4->5, and n = 2.
# After removing the second node from the end, the linked list becomes 1->2->3->5.
# '''
#
#
# class ListNode:
# def __init__(self, val=0, next=None):
# s... |
135d327f5aeb122c5c61838c1bcd42170afcc3af | mandalaalex1/MetricsConverionTool | /MetricsConversionTool.py | 1,906 | 4.15625 | 4 | print("Options:")
print("[P] Print Options")
print("[C] Convert from Celsius")
print("[F] Convert from Fahrenheit")
print("[M] Convert from Miles")
print("[KM] Convert from Kilometers")
print("[In] Convert from Inches")
print("[CM] Convert from Centimeters")
print("[Q] Quit")
while True:
Option1 = input("Option: ")... |
9a6bcdbc9ef9307f229326ec584d77fe001c1de2 | dbconfession78/holbertonschool-webstack_basics | /0x01-python_basics/10-simple_delete.py | 309 | 3.84375 | 4 | #!/usr/bin/python3
"""
Module 10-simple_delete
"""
def simple_delete(my_dict, key=""):
"""
Description - deletes a key in a dictionary
:param my_dict: dict to delete from
:param key: key of dict element to delete
"""
if my_dict:
my_dict.pop(key, None)
return my_dict
|
a553136bc8047e1d45f6cab4c34e290b9874d31f | apple-han/Learning_python | /python/python_automation/string_encoding.py | 725 | 4.125 | 4 | python2 编码问题
def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf-8')
else:
value = unicode_or_str
return value
def to_str(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.encode('utf-8')
else:
... |
2df60ffb99ecac399ac959168224e58f96372bb2 | attacker2001/Algorithmic-practice | /Codewars/Find the odd int.py | 672 | 4.25 | 4 | # coding=UTF-8
'''
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
test.describe("Example")
test.assert_equals(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5)
即找出列表中 出现次数为奇数的元素
'''
def find_it(seq):
for i in seq:
... |
f23ada6de8dde7f22d00f1648c97da02c0da22f2 | mahamadousylla/GPS-via-MapQuest | /ducktyping.py | 4,189 | 3.796875 | 4 | #Mahamadou Sylla
class Steps:
def lookup(self, json_object):
'''
takes in a json object and
finds out directions about
a particular trip
'''
directions = [ ] #empty list
for dictionary in json_object['route']['legs']: #we are at the dictionary under [route][l... |
1dbc81627b5d9f096a94946072d51f09ef7b9d5d | phuonghoangpham/phamhoangphuong-fundamental-c4e20 | /Session02/sum_function.py | 78 | 3.546875 | 4 | numb=int(input("enter a number = "))
total = sum(range(numb+1))
print(total) |
754651adfa862bf68453fc90b5f8abdddd2c4930 | op-secure/ML-Python-Scikit-Notes | /5_numpy_bool-array.py | 242 | 3.859375 | 4 | # Boolean arrays
# - Handle indexing with boolean logic
import numpy as np
a = np.arange(10).reshape(5,2) + 1
# Create a boolean array
ba = a > 5
print(ba)
# Filter by a boolean array
# Example 1
print(a[ba])
# Example 2
print(a[a < 5])
|
b1763841a3ce3cec9230ba460fcf4b76b33f03df | MollyKate-G/file_managment_MG | /shop_list.py | 1,358 | 4.21875 | 4 | def shopping_list():
print("Shopping List!\n")
choice = " "
while choice.upper() != 'Q':
choice = input("""--------------------------\n\nChoose an option:
(P)rint shopping list
(A)dd item to shopping list
(C)lear shopping list
(Q)uit
""")
if choic... |
d6e86fd486f908e5e0561cdfde9a11e375673453 | xaviergoby/Python-Data-Structure | /Excersise/EvenOrOddWithoutUsingModDiv.py | 1,107 | 4.5 | 4 | __author__ = 'Sanjay'
# The below program is to check whether the given number is odd or even
# The logic is acheived by Bit wise operator
# normally people will use Modulo or division operator to find its even or odd.
numList = range(0, 10, 2) # [0,2,4,6,8]
def commonLogicPlusMyOwnImplementation(n):
# used bit... |
b0012d11daa4dfd8e1e146a3c2fe637cd3455aee | ahartikainen/avroc | /avroc/util.py | 749 | 3.84375 | 4 | from typing import Dict, Union, List, Any
import random
import re
# SchemaType is a type which describes Avro schemas.
SchemaType = Union[
str, # Primitives
List[Any], # Unions
Dict[str, Any], # Complex types
]
def rand_str(length: int) -> str:
"""Generate a random string of given length."""
... |
f7a09db70f8cf4429535df53db401e9a570d5ff9 | AbandonBlue/Coding-Every-Day | /NLP_Useful_Function/functions.py | 2,686 | 3.703125 | 4 | def stem(word):
"""
Find stem like (a little different)
ex:
pattern = r"^.*(?:ing|ly|ed|iout|ies|ive|es|s|ment)$"
re.findall(pattern, 'processing')
"""
word = word.lower() # lower first
for suffix in ['ing', 'ly', 'ed', 'ious', 'ies', 'ive', 'ed', 's', 'ment']:
if w... |
dc4ad722af7e7f3fbe1fbe6ff54f4ef97db57f61 | tarekalmowafy/Compatetive_Programming | /hackerrank/domains/python/sets/set_intersection.py | 140 | 3.75 | 4 | input()
english=set([x for x in input().split() ])
input()
french=set([x for x in input().split()])
print(len(english.intersection(french))) |
67ed09aeabb92bda5b975c6dcc7991f4130a980a | danalrds/FP | /Other/A2.py | 4,911 | 3.9375 | 4 | def printmenu():
print("0.Read numbers")
print("1.Strictly increasing numbers")
print("3.All consecutive number pairs have the greatest common divisor 1")
print("5.Consist of a single number")
print("4.Only prime numbers")
print("7.The difference between the absolute value of consecutive numbers... |
fbedc5db38e482a5f7606c5b03bdd0b6e527c4df | TLS97/sudoku-solver | /utilities.py | 3,203 | 3.59375 | 4 | import cell
knight = False
king = False
def empty_cell(b):
for i in range(9):
for j in range(9):
if b[i][j].num == 0:
return i, j
return False
def print_board(b):
print("\nBoard: ")
for i in range(9):
if (i == 3) or (i == 6):
print("- - - - - ... |
7a744bde105d59e43a4b6555c9dc758d345959be | fabiiogomes/exerciciospy | /exercicios/015.py | 325 | 3.640625 | 4 | #Progama que ler a quantidade de dia e km de um carro alugado
#e mostra o preço a pagar sabendo que: 1dia = R$60 e 1km = R$0,15
quantkm = float(input('Quantos Km rodados? '))
quantdia = int(input('Quantos dias alugados? '))
preço = (quantkm * 0.15) + (quantdia * 60)
print('O total a pagar é de R${:.2f}'.format(preço)... |
b0b800cc68991927eef966829e076bfd115dc74f | PedroAM/Euler-project | /PE_7.py | 547 | 3.6875 | 4 | import time
def isPrime(n):
if n==1:
return False
if n==2 or n==3 or n==5 or n==7:
return True
if n%2 ==0 or n%3==0 or n%5==0 or n%7==0:
return False
for i in xrange(3,int(n**0.5+1),2):
if n % i ==0:
return False
i +=1
retur... |
d5d4df79ab090a4f1a898c47dc65fdd428ac2cd1 | PandaWhoCodes/udhaar.site | /db_utils.py | 2,411 | 3.71875 | 4 | """
functions for interaction with the database.
"""
from db_secrets import DB_NAME, USER_NAME, PASSWORD, HOST
import pymysql
def create_connection():
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or Noneinsert... |
df104b81674fb0a06ea94c1fe587814f7b4e6cc3 | ricardo64/Over-100-Exercises-Python-and-Algorithms | /src/examples_in_my_book/general_problems/numbers/convert_from_decimal.py | 523 | 4.15625 | 4 | #!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_from_decimal(number, base):
''' convert any decimal number to another base. '''
multiplier, result = 1, 0
while number > 0:
result += number%base*multiplier
multiplier *= 10
number = number//base
re... |
21cc164694d6a079b4cb221c0703e23ed25ed995 | ApplauseWow/IT_new_technique_assignment | /practice1/practice1-1.py | 836 | 3.765625 | 4 | # -*-coding:utf-8-*-
# created by HolyKwok 201610414206
# practice1-1
# detect the quality of the air
def air_detection(air_data):
# a function for air detection
if air_daata >= 250 : # severe pollution
print(u'严重污染')
elif air_data >= 150: # heavy pollution
print(u'重度污染')
elif air... |
6e7641c80563678626da5aaa8c75971829d0d30b | AmitAps/python | /pythontute/string1.py | 55 | 3.6875 | 4 |
s = input("Name: ")
print(f"Hello, {s.capitalize()}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.