blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f90156e0ff70cd910a2122df38af04c3da198e0b | nguyenhuuthinhvnpl/CS115 | /test2review.py | 3,355 | 3.875 | 4 | '''
Created on Oct 24, 2017
@author: jschm
'''
#2 types of use it or lose it - power set and knapsack sort of
#going down one path here and another path there, slightly altering the info for
#these paths
"""
CHEAT SHEET!!!!!!!!!!
-> put use it or lose it on one side (all of it)
then dictionary, memoization, circuit, u... |
c33620d3ebeb720d3a40a13334fd19094153a03e | suresh753/Guessing-Game-Challenge | /guessing_game.py | 750 | 3.875 | 4 | import random
random_number = random.randint(1,100)
guesses = []
guess = None
while (True):
guess = int( input( 'Enter your guess' ) )
if guess == random_number:
print "You're Correct and number of tries are {}".format(len( guesses ) + 1)
break
else:
if 1 <= guess <= 100 :
... |
3eedfcdeaced42bb60bbe11c86fadf0576dc4472 | longlongtjandra/driving-simulation | /AliceNBob.py | 127 | 4 | 4 | def evenodd(x):
return x%2
x=int(input("number of stones:"))
if evenodd(x)==1:
print("alice")
else:
print("Bob")
|
14282c77108b69035c9b949b182fe40c99cb4bef | raoofnaushad/GPT-3-Beginner-Workout | /gpt_3_workout.py | 2,051 | 3.84375 | 4 | # Source => https://github.com/bhattbhavesh91/gpt-3-simple-tutorial/blob/master/gpt-3-notebook.ipynb
import json
import openai
from gpt import GPT
from gpt import Example
openai.api_key = data["API_KEY"]
with open('GPT_SECRET_KEY.json') as f:
data = json.load(f)
gpt = GPT(engine="davinci",
temperatur... |
a492c6827a882a66bfedb7e12501739b31217526 | lilkeng/CodingChanllege | /leetcode/python/text_justification/solution.py | 2,277 | 3.65625 | 4 | '''
68. Text Justification QuestionEditorial Solution My Submissions
Total Accepted: 37257
Total Submissions: 222236
Difficulty: Hard
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy ap... |
90c577faf8f7a3ada1b4bd12c6e4132882f26db5 | KalinHar/Advanced-Python-SoftUni | /exams/reg-exam-pro-02.py | 1,502 | 3.5625 | 4 | def in_board(j, k):
if 0 <= j < 5 and 0 <= k < 5:
return True
board, player, shooting_targets = [], [], []
targets = 0
direction = {'left': (0, -1), 'up': (-1, 0), 'right': (0, 1), 'down': (1, 0)}
for row in range(5):
line = input().split(" ")
board.append(line)
for col in range(5):
i... |
b5e9c08a1460da1d743e4abbf86554542b267a7d | AndrejLehmann/my_pfn_2019 | /Vorlesung/src/Basic/datematch.py | 600 | 3.75 | 4 | #!/usr/bin/env python3
import re
for date in ['2014-12-13','2016-01-02']:
# extract numbers from a date string YYYY-MM-DD
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', date)
if m:
year = m.group(1)
month = m.group(2)
day = m.group(3)
print('{}.{}.{}'.format(day, month, year))
def date_parse(date):
... |
aaed9cf624f226fbbaceb5d108d8e5e3e9ee9d8a | beatriznaimaite/Exercicios-Python-Curso-Em-Video | /mundo1/exercicio015.py | 691 | 4.125 | 4 | """
Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado
e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar,
sabendo que o carro custa R$ 60 por dia e R$ 0,15 por Km rodado.
"""
# entrada de dados
km_percorrido = float(input('Digite a quantidade de quilometros... |
b6dd745cedb370a34e9aedadf3a9ddea8ce57113 | manishawsdevops/pythonmaster | /Python Basic - Part II/short_circuiting.py | 466 | 3.828125 | 4 | #Short circuiting.
#short ciruiting majorly explains like if there is an operation of and, if the first conditions is False.
#Python interpreter will not check for the second condition after and, because anyway it is going to skip the
#statement. It is the same with or condition as well.
#The process of skipping the c... |
a90249202c69237aa8ab3ce7b3cf59d1fb7a127f | TraceIvan/PythonProjects | /gcd.py | 317 | 3.765625 | 4 | #辗转相除法
print("示例:求12与32的最大公约数:")
a,b=32,12
while a%b:
a,b=b,a%b
print("12和32的最大公约数为:%d\n"%b)
print("请输入两个整数:")
x=input()
y=input()
x1=int(x)
y1=int(y)
if x1<y1:
x1,y1=y1,x1
while x1%y1:
x1,y1=y1,x1%y1
print("最大公约数为:%d\n"%y1)
|
2201d6f318b776c579d08edba287a9c177a4c93e | sathayas/AnalyticsClassSpring2019 | /textClassExamples/NameClassifier.py | 1,757 | 3.84375 | 4 | import nltk
import random
# a function to return a feature to classify whether a name is
# male or female.
# The feature and the label are returned together
def gender_feature(name):
featureDict = {'last-letter': name[-1]}
return featureDict
# reading names from the names corpus
from nltk.corpus import names
... |
3504ff1090e10cb11d8083a812faceca21835091 | wjpe/EjemplosPython-Cisco | /ej11.py | 664 | 3.96875 | 4 | numeroSecreto = 777
print(
"""
+==================================+
| Bienvenido a mi juego, muggle! |
| Introduce un número entero |
| y adivina qué número he |
| elegido para ti. |
| Entonces, |
| ¿Cuál es el número secreto? |
+============================... |
a0878140048d20558fa8917718542a0ee465c567 | TerryLun/Code-Playground | /generate_magic_squares.py | 727 | 4.125 | 4 | import copy
import magic_square
import rotate_matrix
import flip_matrix
def generate_magic_squares_three_by_three():
magic_squares = []
m = magic_square.solve(3)
magic_squares.append(copy.deepcopy(m))
for _ in range(3):
rotate_matrix.rotate_matrix(m)
magic_squares.append(copy.deepco... |
de8a427f7486828a50afafa7957614c7d20876cf | Mirage-Flare/cp1404practicals | /prac_01/shop_calculator.py | 360 | 4.09375 | 4 | """
Calculating total price from a number of items with different prices
Kyle Muccignat
"""
number_of_items = int(input("Number of items: "))
price_of_items = 0
for number in range(number_of_items):
price_of_items += float(input("Price of item: "))
if price_of_items > 100:
price_of_items *= 0.9
print("Total pri... |
dbca850457482b535afeb23462c8d5fe34e0d21f | MissPisces/python_GUI | /tkinter_05.py | 687 | 3.84375 | 4 | # 测试中文支持
import tkinter as tk
import tkinter.font as tkFont
root = tk.Tk() # must be here
screenWidth = root.winfo_screenwidth()
screenHeight = root.winfo_screenheight()
f1 = tkFont.Font(family='microsoft yahei', size=30, weight='bold')
f2 = tkFont.Font(family='microsoft yahei', size=30, slant='italic')
f3 = tkFon... |
d05f7241cc8648629f6231fc663230a5a81c0525 | zzh-python/all-project | /linkedin/des.py | 1,104 | 3.53125 | 4 | from Crypto.Cipher import DES
class MyDESCrypt:
key = chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)
iv = chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)
def __init__(self,key='',iv=''):
if len(key)> 0:
self.key = key
if len(i... |
83cbc4c2656fefb97012696601244fe43252648b | MarianaPaz/Curso-Python | /05_function.py | 366 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 18:33:49 2020
@author: CEC
"""
aclNum = int(input("What is the IPv4 ACL number?"))
if aclNum >= 1 and aclNum <= 99:
print("This is a standar IPv4 ACL.")
elif aclNum >= 100 and aclNum <= 199:
print("This is a extended IPv4 ACL.")
else:
print("T... |
8135965a95f69be9f2f18c618eb99025f76cbbcb | Alic-yuan/leetcode | /Week_08/quick_sort.py | 535 | 3.90625 | 4 | def quick_sort(nums, left, right):
if left > right:
return
pivot = pivotion(nums, left, right)
quick_sort(nums, left, pivot-1)
quick_sort(nums, pivot+1, right)
def pivotion(nums, left, right):
mark = left
p = nums[left]
for i in range(left+1, right+1):
if nums[i] < p:
... |
3f2710e318b5aaf5d0e4cffb80d5debe2d85a6ee | SoumikaNaskar/CBA | /For_TS/validate_form.py | 4,216 | 3.828125 | 4 | print(" *********** Enter the details **************** ")
f_name=input("First Name: ")
m_name=input("Middle Name (if) : ")
l_name=input("Last Name: ")
address=input("Address: ")
pincode=input("Pincode: ")
blood_group=input("Blood group: ")
age=input("Age: ")
contact_no=input("Contact Number: ")
add_contact_no=input("Ad... |
ae0350db8b030dbc3cbf32edeee384e783b8da7d | fcostanz/NTupler | /TopAnalysis/TopUtils/python/tools/Timer.py | 2,729 | 3.765625 | 4 | import time
import datetime
import os
class Timer:
__name = 'nothing'
__start = 0.0
__stop = 0.0
__secondspassed = 0.0
def __init__(self):
self.__name = 'timer'
"Return a formated date string"
def getDate():
return time.strftime("%d%m%y", time.gmtime())... |
6dc489f5b4f0d680045895d2517cc3b8af220e7e | Branden-Kang/Convert-Your-Speech-to-Text-using-Python | /sp_recognition.py | 457 | 3.59375 | 4 | # import the module
import speech_recognition as sr
# create the recognizer
r = sr.Recognizer()
# define the microphone
mic = sr.Microphone(device_index=0)
# record your speech
with mic as source:
audio = r.listen(source)
# speech recognition
result = r.recognize_google(audio)
# export the result
with open('my... |
e539fcd28af62517b34ac136f722bacebc1cd95e | abhay-ajith/amfoss-tasks | /task-2/Hackerrank/Time-Format Converter.py | 224 | 3.78125 | 4 | time = input("Enter the time")
m = time[-2:]
twm = time[:-2]
h = int(time[:2])
if m == "AM":
h = (h + 1) % 12 + 1
print("%02d" % h) + twm[2:]
elif m == "PM":
h = h % 12 + 12
print(str(h) + twm[2:])
|
45435156457b43f37fbb089fcf9e3066b113f91f | SoyeonHH/Algorithm_Python | /LeetCode/205.py | 850 | 4.15625 | 4 | '''
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, bu... |
7759ca5c95409e284f4e8fa85c3864ef9c9e0c58 | sharonsabu/pythondjango2021 | /questions/between_ranges.py | 230 | 3.859375 | 4 | #question in book
pow=int(input("enter number"))
ll=int(input("enter lowerlimit"))
ul=int(input("enter upperlimit"))
for num in range(1,ul+1):
a=num**pow
if((a>=ll)&(a<=ul)): #if a in range(ll,(ul+1)):
print(a)
|
851e3545ba323f98e9e0aaef71fe65bbf1880938 | reckful88/learning-python | /class_002.py | 448 | 4.1875 | 4 | #######定义一个班级的类,最下面的那个班级,是把学生和老师都加进去了,但别忘记定义学生和老师的姓名#######
class teacher(object):
def __init__(self,name):
self.__name = name
def run(self):
print 'hello,world'
class student(object):
def __init__(self,name):
self.__name = name
class classes(object):
def __init__(self, student, teacher):
self.__teacher = ... |
f5b6401856c88bc36c72a35d7a69f4abb4e10a4d | qinjiabo1990/Python_Project | /Assignment/Assignment_1/assignment1/trial.py | 5,340 | 4.09375 | 4 | """
def judgement(x):
while x != 1 and x != 2 and x !=3:
print('wrong')
x = input ('your answer: ')
return x
"""
"""
import partners
potential_partners = partners.Partners()
gender='1'
sexual_pref='2'
height='1'
height_pref='2'
persionality_score=22
if gender == '1':
gender_list = 'male... |
019154ddda193063b137a02d67fff0e33bb12c69 | woraseth/numer | /cubic_spline.py | 1,764 | 4.21875 | 4 |
def cubic_spline(x, y):
"""
Parameters
----------
x : list of floats
y : list of floats
Returns
-------
list of list of floats
"""
n = len(x) - 1
h = [x[i+1]-x[i] for i in range(n)]
al = [3*((y[i+1]-y[i])/h[i] - (y[i]-y[i-1])/h[i-1]) for i in range(1,n)]
al.insert(0,0)
l = [1] * (n+... |
65f5b9d14df48f63eea942560f00f6adb88184a1 | 6yeQT/_CODESIGNAL_Py3 | /Arcade/SmoothSailing/commonCharacterCount.py | 327 | 3.53125 | 4 | def commonCharacterCount(s1, s2):
count = 0
done = []
for i in range(len(s1)):
if s1[i] not in done:
count += min([s1.count(s1[i]), s2.count(s1[i])])
print(s1[i], ' ', s2[i], ' ', count)
done.append(s1[i])
return count
print(commonCharacterCount('aabcc', 'a... |
9046e21b451d2579a0cd09bd47200265124006fc | Ham5terzilla/python | /2nd Lesson/n5.py | 171 | 3.90625 | 4 | # Ввести число a/ Определить и вывести сообщение о том, чётное оно или нечётное
print(int(input()) % 2 == 0)
|
971a54ae64373be2c91eb404f5cd4e216a606093 | cyrusc008/ClassworkSpring2021 | /return.py | 193 | 3.75 | 4 | def my_function(x):
a = x + 5
if a < 0:
answer = "negative number"
else:
answer = "positive number"
return a, answer
y, z = my_function(-20)
print(y)
print(z)
|
c063ddbbda27c871c724a3992ac7518ca2f8c6f6 | rdiptan/Python-mini-projects | /Graham.py | 1,879 | 3.578125 | 4 | from tkinter import *
import math
root = Tk()
root.geometry('500x300')
root.title("Graham Formula")
price = StringVar()
eps = StringVar()
book = StringVar()
result = StringVar()
verdict = StringVar()
def Exit():
root.destroy()
def Reset():
price.set("")
eps.set("")
book.set("")
result.set("")
... |
e2c8c62ea8f8663fe3dbcc2cc7e6d38dddb57923 | bitbybitsth/automation_login | /bitbybit/assignments/dictionary_impl.py | 4,001 | 3.953125 | 4 | """
dict
--- internally implemented as hashtable and uses closed hashing a.k.a open addressing
--- Unlike other data types Dictionary holds a pair (KEY,VALUE) as a single element.
--- Dictionary is mutable
--- Key must be immutable(String, Number, Tuple) and no duplicates allowed.
--- Value cannot be of any type... |
db390cb7324b0daad27cc5265cf07427983b0234 | CrossLangNV/DGFISMA_definition_extraction | /data/preprocessing.py | 1,011 | 3.984375 | 4 | from typing import List
import nltk
def tokenize(sentences, option='nltk'):
"""For experimenting with different tokenization options:
* TODO BERT tokenizer
* TODO Spacy
* https://www.nltk.org/
Args:
sentences: list of sentence strings.
option: If option not within ava... |
ef30acf26fa0919de2e533be28cf0672e90462f9 | lvolkmann/couch-to-coder-python-exercises | /Lists/battle_ship.py | 4,173 | 4.09375 | 4 | """
Fill in the methods below to get this battleship program working
HINT: You may want to use exceptions when checking for bounds of the board
"""
import random
def display_board_hits(board, hit):
for row in range(len(board)):
for col in range(len(board[0])):
if hit[row][col]:
... |
f91dbbcfab56832d07cde1a4ba534de573cacdbf | anacarolina1002/infosatc-lp-avaliativo-04 | /atividade1.py | 662 | 4.03125 | 4 | #Crie uma função que receba uma palavra por parâmetro e permita inverter a ordem
#dessa palavra. Exemplo: ATOR = ROTA
#Só nessa atividade tem vários commits pq usei ela pra me ajudar no próximo exercício
#pra ver como ficavam as palavras ao contrário pra usar lá
#e tbm pq uma hora commitei tudo junto e fiz bagunça
def ... |
ff6f7434ebf01986756140e545975af380e4b707 | AmandaRH07/AulaEntra21_AmandaHass | /Prof01/Aula11/Exercicios/exercicio1.py | 1,098 | 4.3125 | 4 | """Exercício 1
(não usar o continue ou o break)
Crie um programa que mostre um menu com as seguites opções:
1) Soma
2) Subtração
3) Multiplicação
S) Para sair!
Para número 1: Peça 2 números e mostre a soma deles
Para número 2: Peça 2 númeors e mostre a subtração deles
Para númeor 3: Peça 2 números e mostre a multip... |
79c58ae9e76a5a245ff38e64232741056aed8ac1 | niranjan2822/Interview1 | /Convert Key-Value list Dictionary to List of Lists.py | 1,903 | 4.625 | 5 | # Convert Key-Value list Dictionary to List of Lists --we need to perform the flattening a key value pair of dictionary
# to a list and convert to lists of list.
'''
Input: {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]}
Output : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]]
'''
# Method #1 : Using loop + items... |
35d7388dbfcef88a1c1121183efc833529f613be | ssmmchoi/python1 | /workspace/chap01_Basic/lecture/step03_string.py | 3,068 | 4.125 | 4 | '''
문자열 처리
- 문자열(string) : 문자들의 순서(index)의 집합
- indexing / slicing 가능
- 문자열 = 상수이면, 수정 불가
'''
# 1. 문자열 처리
# 1) 문자열 유형
lineStr = "this is one line string" # 한 줄 문자열
print(lineStr)
multiStr = '''this
is multi line
string'''
print(multiStr)
multiStr2 = 'this\nis multi line\nstring'
print(multiStr2)
# sql문 : 부서번호
d... |
cc696b95ca3298f976203b66e6004fea86f155c4 | chosaihim/jungle_codingTest_study | /FEB/14th/용-즐거운막대기.py | 1,476 | 3.6875 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42860
name = "JAZ"
# name = 'BBABA'
# name = 'BBBAAB'
# name = 'BBAABB'
from collections import deque
def ordering(name):
name_list = list(name)
for i in range(len(name_list)):
name_list[i] = ord(name_list[i])
return name_list
# A : 65 / Z :9... |
1664308287f58b836f3e8d0fb03b33bca6802f8f | spaceack/codewars | /Title_Case(6kyu).py | 2,109 | 3.9375 | 4 | def title_case(title, minor_words = ''):
new_list = []
new_string = ''
title_l = title.split()
minor_words_l = minor_words.split()
minor_words_l_lower = [x.lower() for x in minor_words_l]
title_l_num = len(title_l)
minor_words_l_num = len(minor_words_l)
# first word upper()
if titl... |
601bdbaef312b2cbbff6a06b59084b1ff4905739 | htmlprogrammist/kege-2021 | /tasks_12/task_12_18590.py | 119 | 3.703125 | 4 | s = '1' * 45 + '2' * 45
while '111' in s:
s = s.replace('111', '2', 1)
s = s.replace('222', '1', 1)
print(s)
|
b753d5b99cee599954623d3575d175177627eeca | coderzhuying/Algorithm | /tencent.py | 451 | 3.59375 | 4 | def minDistance(s):
stack = []
for i in range(len(s)):
if not stack:
stack.append(s[i])
else:
if stack[-1] == '0' and s[i] == '1':
stack.pop()
elif stack[-1] == '1' and s[i] == '0':
stack.pop()
else:
... |
8d083b8fbe3fdf2bf14b87085270e1bc43811379 | rsshalini/practice_programs | /06_30_2018/trailingzero.py | 799 | 4.40625 | 4 | #!usr/bin/python
#counts the number of trailing zero for n factorial
import math
def count_trailing_zero_n_fact(n):
n_factorial = str(math.factorial(n))
reversed_factorial = reversed(n_factorial)
trailing_zero_count = 0
if n_factorial.endswith('0'):
for digit in reversed_factorial:
... |
85f3584646304718c6344956055b173af6779cda | zzzpp1/python | /python/停车场/ParkingLot.py | 7,696 | 3.6875 | 4 | from Car import Car
'''
需求1构造一个停车场,停车场可以停车和取车,停车成功后得到停车票。 用户取车的时候也需要提供停车票,停车票有效,才可以成功取到车。
'''
class ParkingLot(Car):
def __init__(self, capacity=2,park_name ='park'):
# todo: 构造停车场所需的字段
self.capacity = capacity #停车场最大停车数
self.name = park_name #停车场名字
self.c... |
e149658194f5abdd88bbc334b9d9471bceecc475 | heyberto/Tutorial-python | /Tutorial1.8.py | 322 | 4.09375 | 4 | #NESTED LOOPS
filas = int(input('Cuantas filas quieres que haya?: '))
columnas = int(input('Cuantas columnas quieres que haya?: '))
simbolo = input('Dime el simbolo que quieres utilizar: ')
for y in range (filas):
for z in range(columnas):
print(simbolo, end='')
print... |
9d96ba56e9d1e1e8ce90d67bd28ac80a8283afd4 | shuoshuren/PythonPrimary | /18文件/xc_05_python2中文.py | 156 | 3.921875 | 4 | # *-* coding:utf8 *-*
# 引号前面的u告诉解释器这是一个utf8编码格式的字符串
str = u"hello世界"
print(str)
for c in str:
print(c) |
965f6e11c68697adc306c833c4cc83c5b27c0556 | baolibin/leetcode | /程序员面试金典/面试题 16.08. 整数的英语表示.py | 1,991 | 3.890625 | 4 | '''
面试题 16.08. 整数的英语表示
给定一个整数,打印该整数的英文描述。
示例 1:
输入: 123
输出: "One Hundred Twenty Three"
示例 2:
输入: 12345
输出: "Twelve Thousand Three Hundred Forty Five"
示例 3:
输入: 1234567
输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million F... |
e7f58d129578b666e9e9d80c3d3be576be9fe62f | rishabjn/Iris-Classifier | /decision_tree_iris.py | 956 | 3.5 | 4 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
iris_data = pd.read_csv("iris.csv") #Reading data u... |
9c3cc6a74751fdda23ffb9465bc806398a6b119e | razvannica/Numerical-Calculus | /Homework4/main.py | 4,472 | 3.78125 | 4 | """
Author: Răzvan NICA
Study Year: 3
Group: English
"""
import numpy
import copy
import time
def read_file(path, to_check):
size = 0
input_list = []
matrix = []
with open(path) as file:
k = 0
for num, lines in enumerate(file, 1):
if num < size + 3 and k != 0:
... |
60c413063b2a41e58661dad0a2cc0710577222ed | toshitaka18/schoo | /PycharmProjects/SampleProject/fizz.py | 416 | 3.9375 | 4 | #fizzbuzz問題を再現、正しいくつまでカウントするか引数で指定
def fizzbuzz(max_num):
for i in range(1,max_num ):
if i % 15 == 0:
print('fizzbuzz')
elif i % 3 == 0:
print('fizz')
elif i % 5 == 0:
print('buzz')
else:
print(i)
max_num = int(input('数値を入力してください'))
p... |
f0e18d92da8d7174326b09ad95de8683e9f5d9b2 | spandanasalian/Python | /stringbalace.py | 341 | 3.953125 | 4 | def stringBalanceCheck(s1,s2):
flag=True
for char in s1:
if char in s2:
continue
else:
flag=False
return flag
s1="th"
s2="Python"
flag=stringBalanceCheck(s1, s2)
print("S1 and s2 are balance",flag)
s1="tha"
s2="Python"
flag=stringBalanceCheck(s1, s2)
print("s1 and s... |
225483d70b95e91d25b3919ced0009bd5e6076cf | GSantos23/Crash_Course | /Chapter2/Exercises/ex2_8.py | 432 | 4.28125 | 4 | # Exercise 2.8
# Number Eight: Write addition, subtraction, multiplication, and division operations that each result in the number 8.
# Be sure to enclose your operations in print statements to see the results. You should create four lines that look
# like this:
# print(5 + 3)
#
# Your output should simply be f... |
89dd42eabc01f3d1865bad4210c6c2b6dd35d99c | fotavio16/PycharmProjects | /pythonjogos/cap8_jogo.py | 1,815 | 3.984375 | 4 | '''
Bagels
'''
from random import randint, shuffle
def abertura():
print("Estou pensando em um número de 3 dígitos. Tente adivinhar o que é.")
print("Aqui estão algumas dicas:")
print("Quando digo: Isso significa:")
print("Pico: Um dígito está correto, mas na posição errada.")
print("Fermi:... |
deca947ece09c0a927ec07667da83b3df2867cc4 | AndersonHJB/Student_homework | /早期代码/作业二/yunshi_1.py | 7,710 | 3.875 | 4 | import random
# 输入性别或退出
while True:
gender = input('请输入您的性别(F/M),输入(exit)退出:\r\n')
if gender.upper() == 'F' or gender.upper() == 'M':
gender = gender.upper()
break
elif gender.upper() == 'EXIT':
print('\r\n\r\n感谢使用,再见!')
exit()
else:
print('您的输入有误,请重新输入\r\n')
# 输入年龄并判断年龄层
while True:
ag... |
edf80b41083f3aa09b624e0ec1652ec926e5940b | Nahid-Hassan/fullstack-software-development | /code-lab/Python3 - More Variables and Printing.py | 842 | 4.03125 | 4 | import math
# Format string
my_name = "Md. Nahid Hassan"
my_age = 23 # years
my_height = 63 # inches
my_weight = 50 # kg
my_eyes = "Black"
my_teeth = "White"
my_hair = "Black"
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print(f"Actually that's... |
fc331fca9451adecc56bdf7a05d0555f27e2f436 | jacquerie/leetcode | /leetcode/0419_battleships_in_a_board.py | 805 | 3.671875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def countBattleships(self, board):
result = 0
if not board or not board[0]:
return result
for i in range(len(board)):
for j in range(len(board[0])):
result += (
1
if (
... |
960740cd83825717259d8b3eabcd023d4d8d8623 | juansalvatore/algoritmos-1 | /ejercicios/11-objetos/11.9.py | 2,671 | 3.53125 | 4 | # Ejercicio 11.9. Implementar el método duplicar(elemento) de ListaEnlazada, que recibe un
# elemento y duplica todas las apariciones del mismo. Ejemplo:
# L = 1 -> 5 -> 8 -> 8 -> 2 -> 8
# L.duplicar(8) => L = 1 -> 5 -> 8 -> 8 -> 8 -> 8 -> 2 -> 8 -> 8
class _Nodo:
def __init__(self, dato):
self.dato = da... |
473932cb0c233bd3fad1c2caec11f5560bb512dd | lpelczar/Todo-MVC | /view.py | 2,457 | 3.703125 | 4 | STARTING_INDEX = 1
class MenuView:
"""
View which shows the menu of the program
"""
@staticmethod
def display(options):
"""
:param options: dict -> dictionary with number keys and option names values for menu
"""
print('Todo App. What do you want to do?')
fo... |
caba494777dde6864b51d251f99da508a5ffe415 | fabnonsoo/Matplotlib | /SubPlots/sub_plot1.py | 1,495 | 3.796875 | 4 | # SubPlots are used to work with plots in a object oriented matter...
# SubPlots are used to replace 'gcf' & 'gca' when plotting/working w/multiple figures & axis...
# By default, SubPlots creates a figure & specifies a certain number of rows & columns of axis....
# NB: 'sharex=True' removes the x-axis values for the 1... |
6e9ed828b4ddf7c3d3958ac6d5d311b1395356e1 | VAEH/TiempoLibre | /Funcionesv1.py | 1,114 | 4.03125 | 4 | ##Realiza el mismo ejercicio pasado, respecto a la evaluación de unos valores
#Pero la verdad toma los posibles valores dentro de una matriz
"""
Escriba un programa que solicite repetidamente a un usuario números enteros hasta
que el usuario ingrese 'hecho'. Una vez que se ingresa 'hecho', imprima el número
más grande ... |
7dc0a2aeb566afeb7a2a102720d1f3aa1fc150ba | faizanzafar40/Intro-to-Programming-in-Python | /2. Practice Programs/31. customer_class.py | 1,216 | 4.15625 | 4 | '''
Write a Amazon Customer class which can do basic customer operations
when using with statement - no need to close the file
put file.close() in finally block else it wil stay in memory
readlines() returns a list of lines
.append() makes a nested list
.extend() enlarges the original list
.append() and extend() retu... |
a7c7a823f35f718155e3fb2ebe0a0a3e3e613e88 | shikha1997/Interview-Preparation-codes | /Day5/delgivennode.py | 979 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.next = None
self.data = data
class LL:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = s... |
58f9901d848b8aea90babb768f8f62def31e9e92 | Steps-devmyself/shiyanlouSratches | /py.checkio/面向对象高级编程.py | 1,774 | 3.671875 | 4 |
'''使用__slots__限制实例的属性'''
'''使用@property,把方法变成属性只读,@函数名.setter可写,有setter必须有property'''
class Stundet():
#__slots__ = ('name','gender','score')
def __init__(self,name,gender,_score):
self.name=name
self.gender=gender
self._score=_score
@property
def get_score(self):
re... |
54fd1b6b2c41a3c546d02b729bd1ea61b565c806 | wszeborowskimateusz/cryptography-exam | /extended_euclides.py | 878 | 3.59375 | 4 | from polynomials import x, pol_div
def euclides(a, b):
x, x_prim, y, y_prim = 1, 0, 0, 1
while b != 0:
q = a // b
r = b
b = a%b
a = r
t = x_prim
x_prim = x - q*x_prim
x = t
t = y_prim
y_prim = y - q*y_prim
y = t
return (a, x, y... |
4e5bc6ca079d011944ab67d8ce76e3538d77760c | MachFour/info1110-2019 | /week9/nahian/person.py | 1,808 | 4.4375 | 4 | class Person:
"""
The person class simulates the attributes and actions of a person.
"""
species = "Homo Sapiens"
"""
This is a class variable. Notice that the self key word is missing.
This attribute is shared by all persons and is non-unique.
"""
def __init__(self, name, age):
... |
d47680c4174b1b5c68109cbf60816726dedcc199 | Steven-Kha/CPSC-386-Pong-no-walls | /top_paddle.py | 2,157 | 3.609375 | 4 | # By Steven Kha 2018
import pygame
pygame.init()
from pygame.sprite import Sprite
class Top_Paddle(Sprite):
def __init__(self, ai_settings, screen):
"""Create the Top_Paddle and set its starting position."""
super(Top_Paddle, self).__init__()
self.screen = screen
self.ai_settings ... |
c0fa4cbdedd8fe271d67fde576eaf46966e87fed | parthpatel361999/Hunting | /rule3MAST.py | 2,805 | 4.34375 | 4 | import random as rnd
import time
from common import Agent, Target, manhattanDistance, numActions
'''
This is Basic Agent 3 for the stationary target. We initialize all cells with their respective probabilities
in the first for loop and select the first cell that we want to explore. After exploring that first... |
7ee17bb6e4c1830549ebcd329087b0857e6fb0d9 | fedoseev-sv/Course_GeekBrains_Python | /lesson_6/hw_6_2.py | 1,501 | 4.28125 | 4 | """Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
Использовать формулу:... |
23fa2e27dc96b3e2dff8995646836f97e56a0ec2 | mikochou/leetcode_record | /LongestConsecutiveSequence.py | 803 | 3.53125 | 4 | # 建一个哈希表,存储每个num的最大序列,如果本身包含在一个序列里就删除
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic, maxl = set(nums), 0
for n in set(nums):
cur, r = 1, n + 1
while r in dic:
cur += 1
dic.remove(r)
r += 1
l = n - 1
... |
f28bf735e0b72024d62ea3a95538e69cb1346deb | Anirudh-27/Nodal-Analysis | /Data_Clustering.py | 1,976 | 3.515625 | 4 |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('musae_facebook_target.csv')
X = dataset.iloc[:, [2,3]].values
#Encoding categorical data in X
from sklearn.compose import ColumnTransformer
from sklearn.preproce... |
96635ab4bbf8985257cc486d8ca54283da1b9498 | ezekie97/Connect5-AI-Project | /Connect_5/src/board.py | 12,394 | 4.21875 | 4 | __author__ = 'Bill'
class Board:
"""
Class for the Connect 5 Game Board. The Board is always a 7 long by
9 high. A board always remembers the last move made.
"""
# Class Constants
BLANK_SPACE = "_" # Blank Space
PLAYER_ONE = "R" # Red Chip
PLAYER_TWO = "B" # Black Chip
BOARD_HE... |
9bcafcc6ebc7d95f6cb5d7b3fa76b42068ee7270 | himominul/DS_and_Algorithm | /Stack/stackFuncation.py | 481 | 4.03125 | 4 |
def create_stack():
stack = []
return stack
def is_Empty(stack):
return len(stack) == 0
def push (stack,item):
stack.append(item)
print('item Pushed',item)
def pop(stack):
if is_Empty(stack):
return ' Stack Is Empty'
return stack.pop()
stack = create_stack()
push(stack,str(1)... |
b366523cf0f5d16db0bae2767da2494eeaecb0a6 | theLoFix/30DOP | /Day23/Day23_Excercise01.py | 371 | 4 | 4 | # Write a generator that generates prime numbers in a specified range.
def gen_primes(limit):
for dividend in range(2, limit + 1):
for divisor in range(2, dividend):
if dividend % divisor == 0:
break
else:
yield dividend
primes = gen_primes(101)
print(next(... |
5dd2b1c33214e41d08e4af2ffa0879c06d999695 | ArthurKhakimov/python_hw | /hw11.py | 222 | 3.828125 | 4 | #!/usr/bin/env python3
def letters_range(start, stop, step=1):
abc=list(map(chr, range(97, 123)))
return abc[abc.index(start):abc.index(stop):step]
if __name__ == "__main__":
print(letters_range('p', 'g',-2))
|
454147f473920ae07a60c680e4e4e8f576101293 | nsbradford/CS525-DeepNeuralNetworks | /HW5_3LayerNN/homework5_nsbradford.py | 14,887 | 3.90625 | 4 | """
homework5_nsbradford.py
Nicholas S. Bradford
Wed 03/17/2017
In this problem you will train a 3-layer neural network to classify images of
hand-written digits from the MNIST dataset. Similarly to Homework 4,
the input to the network will be a 28 x 28-pixel image
(converted... |
ae2d220de68581c10fedf5547d9bad379463a47b | ejdeposit/nb_capstone | /src/readingGroups.py | 29,172 | 3.625 | 4 |
# ----------------------------------------------------------------------------------------------------------------------------------
# $match
# -------------------------------------------------------------------------------------------------------------------------... |
46d1ba7031ec4fd659e659edeb655627e1bdae0d | EwertonRod/EstudoPython | /1Exercicio_Estrutura de decisão.py | 395 | 4.03125 | 4 | """
Faça um programa que peça dois números e imprima o maior deles.
"""
print("\t\tImprime o Maior numero\n")
num1 = int (input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
maiornum1 = num1 > num2
if maiornum1 == True :
print("o numero {} e maior".format(num1))
else:
... |
1184014aebe713f125b72e9d875a997166cbe519 | jbalderasgit/pruebas_pyhon | /schoolar_age.py | 290 | 4 | 4 | edad= int (input("Dame tu edad: "))
if edad <6:
print("Kinder")
elif edad >=6 and edad<12:
print("Primaria")
elif edad >=13 and edad<15:
print("Secundaria")
elif edad >=15 and edad<18:
print("Bachillerato")
else :
print("Universidad") |
6a945a517039e112648afc92f2d1733c1d84591c | liuzh825/myAlgorithm | /Algorithm/如何把一个有序整数数组放到二叉树中/ep_01.py | 1,308 | 3.859375 | 4 |
'''
思路:递归思想
取数组中间的数字作为根节点,将数组分成左右两部分,左右两部分递归处理
'''
class BiTNode():
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
def arraytotree(arr, start, end):
root = None
if end >= start:
root = BiTNode()
mid = int((start+end+1)/2)
root... |
27fc408ec20342ac52337d59574e3a5174d503fc | wangjiliang1983/test | /crashcourse/ex06_08_pets.py | 276 | 3.671875 | 4 | kitty = {'catigory': 'yingduan', 'host': 'Frank',}
doggy = {'catigory': 'muyang', 'host': 'Xin',}
piggy = {'catigory': 'yezhu', 'host': 'Ling',}
pets = [kitty, doggy, piggy]
for animal in pets:
print(animal['catigory'].title() + " belongs to " + animal['host'].title())
|
b4a65662a827bf68673e13272fd61b1185160736 | abhinav0000004/Criminal-Database-Management-System | /form.py | 2,663 | 3.546875 | 4 | import tkinter as tk
from tkinter import ttk
from criminal import insert_rec
win = tk.Tk()
# Application Name
win.title("Python GUI App")
win.geometry("400x400")
# Label
headd = ttk.Label(win, text = "ENTER THE DETAILS OF CRIMINAL",font='Helvetica 17 bold underline').place(x=0,y=0)
id = ttk.Label... |
e3983a3e29767d37f0a050193ae050c86e27a71a | scottshepard/advent-of-code | /2020/day22.py | 2,373 | 3.578125 | 4 | from utils import read_input
class Game:
def __init__(self, p1, p2, mode='normal'):
self.p1 = p1.copy()
self.p2 = p2.copy()
self.round = 0
self.mode = mode
self.configurations = []
self.solved = False
def __next__(self):
if (self.p1, self.p2) in self.c... |
b649624f582358d5751847d09edd4bb19c914f5a | Official-BlackHat13/100_days_of_python | /day_1_5/day_4_1.py | 183 | 3.890625 | 4 | import random
random_seed = int(input('enter a number: '))
random.seed(random_seed)
random_int = random.randint(0, 1)
if random_int == 0:
print('heads')
else:
print('tails')
|
39aca1a68dd4c5935b355c687d12754acc8b0a3a | AlexCC1943/challenge_computing_Endava | /ordenamiento_y_busqueda/heapSort.py | 1,027 | 3.640625 | 4 | def heapIfy(lis2, pos):
# si el nodo tiene dos hijos
if 2 * pos + 2 <= len(lis2)-1:
if lis2[2 * pos + 1] <= lis2[2 * pos + 2]:
min = 2 * pos + 1
else:
min = 2 * pos + 2
if lis2[pos] > lis2[min]:
aux = lis2[pos]
lis2[pos] = lis2[min]
... |
49508a6c49dc58fa28b87fd111c2308f52c8331f | romulogm/EstudosPython | /cursoUSP/calc.py | 411 | 4.03125 | 4 |
def num_fat(i):
result = 1
while i >= 1:
result = result * i
i = i - 1
return result
def numerobinomial(num1,num2):
return num_fat(num1) // num_fat(num2) * (num_fat(num1-num2))
num1 = int(input("Digite o valor do primeiro número binomial: "))
num2 = int(input("Digite o valor do se... |
26832affa8741ff6449de067f6d7794c562c44f8 | Fluffhead88/blackjack | /blackjack_1.py | 4,112 | 3.71875 | 4 |
import random
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
def get_value(self):
if self.value == 'J':
return 10
if self.value == 'Q':
return 10
if self.value == 'K':
return 10
if self.valu... |
35d874672650a3242dbad04c0e4d0d2dbb0d9cd4 | SartJ/Notes | /Data Pre-Processing Test/DPP_Handling_Imputting.py | 1,719 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 8 14:05:03 2021
@author: sartaj
"""
import pandas as pd
import numpy as np
# import sklearn
volunteer = pd.read_csv('volunteer_opportunities.csv')
#.head(n) used to return first n rows of a dataFrame to check
print(volunteer.head(3))
#To check the shape (no_rows or s... |
037be673b8224f5f0e6d1cf07712df1afb486974 | loraxiss/MITx6.00.1x | /BattleShip.py | 3,137 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# Import function to generate a random integer
from random import randint
# Create the playing board
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
"""
input: board is a list of equal sized lists of single characters to be printed
for use ... |
cd8a54cec4efedc475e8e400f45cda6d6a33ede9 | MahaAmin/Learn-Python-By-Games | /jokes.py | 931 | 3.859375 | 4 | # Some Silly Jokes
print('What do you get when you cross a snowman with a vampire?')
input()
print('Frostbite!')
print()
print("What do dentists call an astronaut's cavity?")
input()
print("A black hole!")
input()
print('Knock knock.')
input()
print("Who's there?")
input()
print('Interrupting cow.', end='')
print('Int... |
f8d80e8a35574c1efa0ed7ac4243f2368f864176 | VioletMyth/CTCI | /Zero matrix 1.8.py | 861 | 3.765625 | 4 | def zeroMatrix(matrix):
positions = {"x": [], "y": []}
i,j = 0,0
while i < len(matrix):
if 0 in matrix[i]:
positions["x"].append(i)
while j < len(matrix[i]):
if matrix[i][j] == 0 and j not in positions["y"]:
positions["y"].append(j)
... |
cc593514b7713d629d1a37e94df6400d45a74a80 | orlyrevalo/Personal.Project.2 | /Project2.7.4.py | 677 | 4.1875 | 4 | '''While Loop'''
# Using break to Exit a Loop
print("Using break to Exit a Loop")
prompt = "\nPlease enter the name of the city you have visited"
prompt += "\n(Enter 'quit' when you are finished.)"
city = input(prompt)
while True:
if city == 'quit':
break
else:
print("I'd love to go to... |
1417487717918201ac31142a9e2cb58c0b873865 | jiangyoudang/python3 | /algorithm/leetcode/wildcard.py | 1,617 | 3.5 | 4 | class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
#'solution 1
#dp, time cost N^2
# def isMatch(self, s, p):
# s_len = len(s)
# p_len = len(p)
# dp = [[False for i in range(s_len+1)] for j in range(p_len+1)]
# dp[0][0] ... |
81222c382d345adbf7b84417fdf94f3dc3dbdd40 | I201821180B/Machine-Learning-Lab | /Assignment_9_ANN/ANN_faceRecognition.py | 6,864 | 3.671875 | 4 | #!/usr/bin/env python
import numpy as np
import cv2
import random
import os
import matplotlib.pyplot as plt
from math import exp
# Initialize a network
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random.uniform(0.1,1.0) for i in range(n_inputs + 1)]} for i in... |
22c1713ccc10d8c450c12ff437ba321730a6e6de | yuanbitnu/Study_Python | /Python_Study_oldboy/day34_进程_进程间数据共享_进程锁_进程池/多进程创建.py | 1,172 | 3.640625 | 4 | ## 方式一:使用multiprocessing模块创建
# import multiprocessing
# def fun(arg):
# process = multiprocessing.current_process() # 获取执行本方法的进程
# process.name = '进程%s'%arg # 为进程重新设置名称
# print(arg,arg+10,process.name)
# if __name__ == "__main__":
# for i in range(1,11):
# print(i)
# process = multip... |
439d014f2226a208d3e55b44b1ad0e083ac60b7d | leifdenby/markdown-toc-tree | /mdtoctree/__main__.py | 1,576 | 3.578125 | 4 | import tree_text
import operator
import sys
class Node:
def __init__(self, parent, value):
self.children = []
self.parent = parent
self.value = value
@property
def depth(self):
if not self.parent is None:
return 1 + self.parent.depth
else:
re... |
c268b2c6f0917df8bf832d787d3ab902c3d05485 | actecautomacao/automatiza | /arquivofunc/principal.py | 477 | 3.609375 | 4 |
from registrousuario import connect1
while True:
operacao = int(input('Informe senha padrão (223) para processeguir: '))
try:
if operacao != 223:
print('Usuario Invalido!')
elif operacao == 223:
print('Inicio do processo!! ')
print(operacao)
... |
8170f1b9d557f81beeca52b8fdc3c567592ac4a3 | shivam221098/data-structures | /program.py | 9,031 | 4.5 | 4 | # PROGRAM(WORKING ON LIST):
# starting with list
# Initialising a list
name = []
# inserting values in a list using insert function
print('Inserting values in a list using insert function :- ')
name.insert(0, 'Rida')
name.insert(0, 'Ali')
print(name, '\n')
# inserting values in a list using append function
print('in... |
cc2eed4379c074e76f43483e1e653f084ebb5839 | syurskyi/Algorithms_and_Data_Structure | /Data Structures & Algorithms - Python/Section 6 Data Structures Stacks & Queues/src/47.SOLUTION-Queue-Constructor.py | 514 | 3.953125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self, value):
new_node = Node(value)
self.first = new_node
self.last = new_node
self.length = 1
def print_queue(self):
temp = self.first
... |
1be96f710c6fe646c8702bca76d04880b7f6993f | mapozhidaeva/other | /Test_yourself_before_exam/Guess_definition.py | 2,012 | 3.875 | 4 | import random
def file_reading(filename):
with open(filename, 'r') as f:
return f.read().split('\n')
terminology = file_reading('Terminology.tsv')
definitions = file_reading('Definitions.tsv')
#for i in range(len(definitions)):
# print (i + 1, definitions[i])
the_dictionary = dict(zip(terminology, ... |
5afe9ee03178b30f52f1575f1959ec75ca3aca99 | Sancus/pyinvoice | /worked.py | 3,658 | 3.609375 | 4 | #!/usr/bin/env python3
import argparse
import calendar
import collections
import datetime
import jsondate3 as json
import os
import sys
def main():
pfile = 'project.json'
parser = argparse.ArgumentParser(
description="""
worked start -s Feb 24 2017
worked 8 -s Feb 24 2017 comment
worked 8 comm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.