blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5d3707ba313e522dde805ab03bc7840a75019834 | Stunion235/TicTacToe | /Final project-TicTacToe with OOP.py | 8,439 | 3.90625 | 4 | #Tic Tac Toe
#Note: I worked alone for this project.
#ADDED USER-FRIENDLY IMPROVEMENTS:
# 1. Defined a getHint() function that is called if the user types 'hint' for a move.
# 2. Implemented a __repr__() for the TicTacToe class if the user wants to print it.
# 3. Created a printInstructions() function to print the ins... |
d3fa8bf44b2ce96fbe50cde8042a4c636c797ee7 | Smithdyl/Ch.04_Conditionals | /4.3_Quiz_Master.py | 2,458 | 3.765625 | 4 | '''
QUIZ MASTER PROJECT
-------------------
The criteria for the project are on the website. Make sure you test this quiz with
two of your student colleagues before you run it by your instructor.
'''
print("Chapter 4 Quiz")
print()
input("Type anything to begin: ")
print()
total_correct=0
total_possible=0
print("Ques... |
9af1710d3635a66317269d22089af4361db1a9a3 | qeedquan/challenges | /codegolf/draw-the-olympic-games-logo.py | 1,646 | 3.78125 | 4 | """
Challenge
Draw the Olympic Games logo...
Olympic Games logo
...as character (e.g. ASCII) art!
Sample Output
* * * * * * * * *
* * * * * *
* * * * * *
* * * * *... |
7eb8f95401dc62fc9c6e646679c4dfa1bbd0ab67 | Kellyfang/Get-Out | /GET OUT/GET OUT.py | 5,063 | 3.5625 | 4 |
#Almighty Tech
#Get out
from gamelib import*
game=Game(800,600,"GET OUT")
bk=Image("images\\bk.jpg",game)
bk.resizeTo(800,600)
logo=Image("images\\GET OUT!!!.png",game)
comp=Image("images\\ALMIGHTY TECH.png",game)
comp.moveTo(400,400)
bk2=Image("images\\haunted house.png",game)
bk2.resizeTo(800,600)
... |
85783d7a0e5ac551bc8f9dce451984edcfab7735 | malek19-meet/yl1201718 | /lab3.py | 421 | 3.71875 | 4 | class Animal(object):
def __init__(self,sound,name,age,favourite_color):
self.sound = sound
self.name = name
self.age = age
self.favourite_color = favourite_color
def eat(self,food):
print("YUMMY!! " + self.name + "is eating " + food)
def description(self):
print(self.name + "is" + self.age + "years old... |
77edf42547803bcc7c2afb2dfb19205e07156a3a | Jeff-Clapper/Coding_Dojo | /Pre-Boot/the_missing_assignment.py | 371 | 4.28125 | 4 | vowels = ['a','e','i','o','u','y']
non_vowel = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
name = input('Write what you will: ')
name = name.lower()
name = str(name)
vowel = 0
cons = 0
for letter in name:
if letter in vowels:
vowel += 1
elif letter in non_vo... |
304280ed754939a66008139fc761e21fe6530867 | khushboo1510/leetcode-solutions | /30-Day LeetCoding Challenge/November/Medium/47. Permutations II.py | 711 | 3.578125 | 4 | # https://leetcode.com/problems/permutations-ii/submissions/
# Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
self.result = []
self.n = len(nu... |
edc886f356ccc6be90228f2a96eae81fb19d045d | NiallS4/CA117 | /lab_9.1/geometry_091.py | 1,333 | 4 | 4 | from math import sqrt
class Shape(object):
def __init__(self, points):
self.points = points
def sides(self):
l = []
for i in range(1, len(self.points)):
l.append(sqrt((self.points[i-1].x - self.points[i].x)**2 +
(self.points[i-1].y - self.points[i].y)**2))
l.append(sqrt((self.points[len(self.points... |
30189b7c155fcb74858d29ac4d71974dde347b39 | jerrywardlow/Euler | /4palindromes.py | 581 | 4.21875 | 4 | def is_palindrome(target):
'''Returns a Boolean ofwhether a number is a palindrome or not'''
return str(target) == str(target)[::-1]
def largest_palindrome_product(a, b):
'''Prints the largest palindromic number with factors in the specified
range, 'a' being the low end and 'b' being the high.'''
... |
affc93b2fa24b27e79d01072333c5f47bceef55d | drunckoder/ThesisWork | /sources/NoiseGenerator.py | 550 | 3.5625 | 4 | import numpy as np
def put_pixel(target: np.array, x: int, y: int, color: tuple = (0., 0., 0.)):
for i in range(3):
target[i][y][x] = color[i]
def noise_image(target: np.array, noise_level: float, size: int = 32):
for y in range(size):
for x in range(size):
if np.random.rand() < ... |
26594d0a5c1f3ee5eb7d347af05c3fa325d75dcb | Kundan-pseudo/myprofile | /discount.py | 174 | 3.625 | 4 | a=input("Enter the Amount")
if (a<1000):
print a-a/10.0
elif 1000<=a<2000:
print a-(a*20.0)/100.0
elif 2000<=a<3000:
print a-(a*30.0)/100.0
else :
print a-(a*50.0)/100.0
|
417fbfe14d0557bf4037ff2c86397aa6e049b1e2 | MikaMahaputra/Binus | /Assignment/Ascii count.py | 367 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 22:52:12 2019
@author: user
"""
def countletter(str_input):
a= []
b= []
for i in str_input:
if i not in a:
a.append(i)
b.append(1)
else:
x=findinlist(i,a)
b[x]+=1
for i in r... |
c05e82e0d20d66f2fa2aa40931756a6abcab8491 | davidmurphy5456/eulerprojects | /euler project 26.py | 646 | 3.53125 | 4 | def maxlength():
lim = 1000
maxlength=0
max_d= 1
for i in range(1, lim):
q = []
val = 1
len_recur = 0
while val not in q:
if not val: #if val is 0, empty, false
break
len_recur += 1
q.append(val)
... |
ea1d5e3feafc9763d03bdbef578d7379b5ec193c | perryc85/word_hyphen | /Word_Hy-phen-a-tion.py | 3,609 | 4.125 | 4 | # target word
word = input('Enter word: ').strip()
# each index is a space in the target word.
# Each val is the score of that space.
scores = [0] * len(word)
scores.pop() # minus one
DOT = "."
def stripped_patterns(pattern):
stripped_pattern = ''
for char in pattern:
# strip out all ... |
7859f07d78594e9f86faeff05170949e29f459a2 | lawy623/Algorithm_Interview_Prep | /Algo/Leetcode/043MulString.py | 541 | 3.59375 | 4 | class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
return str(self._multiply(num1, num2))
def _multiply(self, num1, num2):
n1 = len(num1)
n2 = len(num2)
if n2 == 0:
retur... |
a9fb1b96b8b03c4b44fed9e0c5af89f50b5a78e8 | daehyun1023/Algorithm | /python/programmers/level2/오픈채팅방.py | 577 | 3.53125 | 4 | def solution(records):
answer=[]
id_name = {}
for record in records:
record = record.split(' ')
if record[0] == 'Enter':
id_name[record[1]] = record[2]
answer.append(record[1] + "님이 들어왔습니다.")
elif record[0] == 'Change':
id_name[record[1]] = record... |
783c5577ef69d6a3231431f8535aa6a7af428939 | ArthurIpolitov/GammaCourses | /012_map_zip/012_itertools.py | 2,580 | 3.890625 | 4 | # ! ---- # ---- # ---- # ---- # ---- # ----
'''
ITERTOOLS
'''
# ! ---- # ---- # ---- # ---- # ---- # ----
# ! ·
# ! ·
# ! ---- # ---- # ---- # ---- # ---- # ----
import itertools
import itertools as itl
# ! ---- # ---- # ---- # ---- # ---- # ----
# ! ·
# ! ·
# ! ---- # ---- # ---- # ---- # ---- # ----
'''EXAMPLE COUNTE... |
281f1e0bc4dd6e6fa9dd129f2372aba4d68ec829 | lvang0123/LeastCommonMultiple_TeamPurple | /main.py | 2,308 | 4.09375 | 4 | #Python Team Project - Least Common Multiple
#This program will prompt the user for two number inputs. The program will then try to find the least common multiple for those two numbers.
#May 1, 2018 - Ben, Dan, Kyle, Lisa, and Lia all worked on this program together during class time.
#Welcoming the user
print("Welco... |
497b1af3acaeb540c1148d67370e9f70f456e739 | FiyinIsrael/chunk | /chunk.py | 2,050 | 3.90625 | 4 | import os
from pydub import AudioSegment
from pydub.silence import split_on_silence
# a function that splits the audio file into chunks
# and applies speech recognition
def silence_based_conversion(path, seconds_waiting=1):
# open the audio file stored in
# the local system as a wav file.
extens... |
30372d850ad2e490892f199ed4ac020cd016b411 | sahilsuri008/python_practice | /01_acloud_guru/age.py | 129 | 4.09375 | 4 | #!/usr/bin/python
name=raw_input("Enter your name: ")
age=input("Enter your age: ")
print ("%s is %s years old." % (name,age))
|
9b097aaba27fdd9dcb23693e5e8f58a67fe16114 | chisoftltd/PythonTuples | /PythonTuples.py | 1,561 | 4.25 | 4 | thistuple = ("ben", "joy", "emma", "joy", "emma")
print(thistuple)
print(len(thistuple))
thistuple2 = ("ben",)
print(type(thistuple2))
thistuple2 = ("ben")
print(type(thistuple2))
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3... |
ddf4ceec417c9c35369d71d20f60ec7c42457c7c | adaltospjr/SI-2-semestre | /Dicionario/exercicio.py | 1,303 | 4.125 | 4 | '''
Exercício 1
A - o maior número da lista
B - o menor número da lista
C - a quantidade de números pares contidos na lista
D - a média dos números contidos na lista
E - todos os números menores do que a média calculada no item anterior
'''
'''
par = 0
lista = []
numero = 0
for a in range(3):
numer... |
378372e1019c8c8c3757601329b04d1043088ed4 | apolonis/PythonExamples | /guesTheNumberGame/app.py | 430 | 3.953125 | 4 | # gues the random number from 0-10, u've got 3 try's
import random
secretNumber = random.randint(0,10)
guessCount = 0
guessLimit = 3
print('Guess the number from 0 - 10')
while guessCount < guessLimit:
guess = int(input('Guess: '))
guessCount += 1
if guess == secretNumber:
print('Congratulations! U... |
6d084b1a4eb9bdfe737e38cefd43e627710d27e7 | nehni/pdsnd_github | /bikeshare_2.py | 9,120 | 4.28125 | 4 | """ This is a script to analyse the data of a bikeshare company
This work was created by nehni as part of the udacity programming for data science nanodegree
"""
import time
import pandas as pd
import numpy as np
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
... |
f27cd30f9a76a0b6f2496569e399a752af3d8a63 | eric100lin/Learn | /algorithm/Array/242.py | 799 | 3.890625 | 4 | '''
242. Valid Anagram
https://leetcode.com/problems/valid-anagram/
Given two strings s and t,
write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
'''
from typing import *
import colle... |
11ffbd2aaf6b50aa344d95d9c316829f4dfd03c1 | himani007/pygame_one | /one.py3 | 812 | 3.515625 | 4 |
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("Hola Gameos")
x = 250
y = 450
width = 40
height = 60
vel = 5
#mainloop:
run = True
while run:
pygame.time.delay(100)#this is miniseconds!
#checking events.....
for event in pygame.event.get():
if event.type ==py... |
628c2fb943e46b912711a8b8dd655b8438324d5a | morteneiby/HelloWorld | /app.py | 720 | 3.875 | 4 | #name = input("Instast dir navn? ")
#if len(name) < 3:
# print("Navn skal have mindst 3 karakterer")
#elif len(name) > 50:
# print("Navn kan max have 50 karakterer")
#else:
# print("Navn er ok")
weight = input("Din vægt? ")
x = input("(P)und eller (K)ilo ")
kilo = int(weight) / 2
pund = int(weight) * 2
if x =... |
41946ef911ec01f4a22831d83944ae1aff3b04c6 | GeekJamesO/Python_MakeChange | /MakeChange.py | 1,039 | 3.59375 | 4 |
# It is assumed that the MoneyArray is ordered from highest value to the lowest value floats.
def MakeChange(DesiredChange, MoneyArray):
if MoneyArray == None:
raise Exception ("Money array must not be null")
if len(MoneyArray) == 0:
raise Exception ("Money array must be populated")
rtnCh... |
b3212c3c1b14e3c8b8ed4022148679a290e01417 | catherine7st/SoftUni-Python_Fundamentals | /problems_from_exams/(from-exams)numbers.py | 278 | 3.75 | 4 | list_numbers = list(map(int, input().split()))
average = sum(list_numbers) / len(list_numbers)
new_list = [num for num in list_numbers if num > average]
new_list.sort(reverse=True)
if len(new_list) == 0:
print("No")
else:
new_list = new_list[:5]
print(*new_list)
|
db7da2842425e47c2b40399c595d33d4f8dfe350 | Gendo90/HackerRank | /Strings/alternatingCharacters.py | 402 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the alternatingCharacters function below.
def alternatingCharacters(s):
count = 0
curr = s[0]
for item in s:
#flips the value
if(item==curr):
if(item=="A"):
curr="B"
e... |
7a4a5af4588761d31aa655eab7b24a795c5894a7 | jennarunge/exercises | /chapter-8/ex_8_1.py | 1,122 | 4.40625 | 4 | # Programming Exercise 8-1
#
# Program to extract initials from a person's name.
# This program prompts a user for his or her full name,
# Splits the name into a list of parts and extracts the first character from each,
# and displays the characters in upper case, followed by periods.
# Define the main function... |
6a285d785366cb9f33b1a9d8426f50daf99ed295 | siliconchris1973/PyPiBotter | /OuterWorld/MotorController.py | 6,003 | 3.5 | 4 | #!/usr/bin/env python3
#
# drive the motors of the robot
#
# Author: pibotter@gmx.de
# Version: 0.0.1
# Date: 1st Aug. 2016
#
#
# This class is based on the CamJam EduKit 3 - Robotics / Worksheet 7 – PWM driving
# The original code alongside documentation on the hardware setup can be found on github
#
import RP... |
a21b7c8f3ec3efcea733d05754f3879b39592d79 | BillJung1024/p2_201611104 | /w5Main4.py | 404 | 4.21875 | 4 | def bmi():
height=input("height: ")
weight=input("weight: ")
print "%.1f"%height, "%.1f" % weight
bmi=weight/(height*height)
print "%.1f" %bmi
if bmi <=18.5:
print 'underweight'
elif bmi>=18.5 and bmi<=23:
print 'normalweight'
elif bmi>=23 and bmi<=25:
... |
f6a09619d980ee0af57cbbe4bc5846141095e71b | LSSTC-DSFP/LSSTC-DSFP-Sessions | /Sessions/Session15/Day1/oop/camping/two_classes/camping.py | 1,637 | 3.59375 | 4 | import operator
class Camper:
max_name_len = 0
template = '{name:>{name_len}} paid ${paid:7.2f}'
def __init__(self, name, paid=0.0):
self.name = name
self.paid = float(paid)
if len(name) > Camper.max_name_len:
Camper.max_name_len = len(name)
def pay(self, amount):... |
aa0673fb0b69b10be7702378b08be9d3f3fd0f21 | isibord/DecisionTree | /Code/MostCommonModel.py | 449 | 3.609375 | 4 | import collections
class MostCommonModel(object):
"""A model that predicts the most common label from the training data."""
def __init__(self):
pass
def fit(self, x, y):
count = collections.Counter()
for label in y:
count[label] += 1
self.prediction = count.m... |
00e05ee9d056ae35e5ef836d79f3413bded0d54f | jgerstein/intro-programming-19-20 | /day10/errorchecking.py | 319 | 4.21875 | 4 | num = ""
# while we haven't chosen a number, repeat
while num == "":
try:
# try to do something
num = int(input("Pick a number >>> "))
except ValueError:
# do something
print("Do you not know what a number is?")
# this print statement represents the rest of the turn
print(num) |
74146cf0a6faee74d08da808b22c420adb046a41 | shakthisachintha/FOSSALGO | /longest_common_subsequence/lcs.py | 954 | 3.8125 | 4 | # Recursive Algorithm For LCS
def recLcs(string1,string2):
stringx=string1+'\0'
stringy=string2+'\0'
return(lcsUtil(stringx,stringy))
def lcsUtil(stringx,stringy,i=0,j=0):
if(stringx[i]=='\0' or stringy[j]=='\0'):
return 0
if(stringx[i]==stringy[j]):
return 1+lcsUtil(stringx,s... |
cd7510bbe34b4cf2256780ee705734be88f3a437 | sageskr/LeetCodeExercise | /problems/Q3.py | 662 | 3.5625 | 4 | #!/bin/env python
# coding: utf8
# author: Kairong
# create time: 2019-04-10
# 3. Longest Substring Without Repeating Characters
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max=0
lens = len(s)
for _j in xrang... |
533cc79c4516259434101ebc84e6341775261c42 | RazvanBerbece/MultiLayerPerceptronFNN | /functions/activation/sigmoid.py | 339 | 3.640625 | 4 | import numpy as np
# Sigmoid function with added derivative functionality through param if true
def sigmoid(x, derivative):
if derivative == True:
"""
Return derivative of function sigmoid(x)
"""
return sigmoid(x, derivative=False) * (1 - sigmoid(x, derivative=False))
return 1... |
0510071f44025842a84e0482d4f57e499e217582 | MrDrDAVID/Python-practice-book | /employee.py | 361 | 3.734375 | 4 | class Employee() :
'''Class that represents an employee'''
def __init__(self, f_name, l_name, salary) :
'''Employee instance holds first and last name and salary'''
self.f_name = f_name
self.l_name = l_name
self.salary = salary
def give_raise(self, raise_amount=500... |
4545f3fa5d837f74009766dff1e81b5f627b5a94 | aadilkhhan/Conditional-Expressions | /09_pr_04.py | 160 | 4 | 4 | a = input("Enter your username : ")
if (len(a) >= 10):
print("not have less 10 character.")
else:
print("It has less than 10 character.")
|
12461edaa2a19105f65275c381dc27b8478056ee | BBackJK/2020tech | /python/200520/13_randomChallenge.py | 1,101 | 3.53125 | 4 | # 교재 p.157 8번 문제
from random import randint
status = True
result = 0
while status:
num = randint(1, 100)
print("첫 값은 %d 입니다." %num)
s = input("산술 연산의 종류를 입력하세요. >> ")
if s != '+' and s != '-' and s != '*' and s !='/':
print("산술연산이 잘못됐습니다.")
status = False
else:
inputNu... |
b9f7904f3527e6295978a01f6cab8b1cc14811a2 | JairMendoza/Python | /curso 2/ej4.py | 436 | 4 | 4 | print ("Vamos a sacar la suma, resta, multiplicacion y divicion de dos numeros.")
numero1=int(input("Ingrese el primer numero a operar: "))
numero2=int(input("Ingrese el segudo numero a operar: "))
suma= numero1+numero2
resta= numero1-numero2
multiplicacion= numero1*numero2
divicion= numero1/numero2
print(f"La s... |
9fc6d41b019af0a5063c4b0db459093878d4c39a | StepDan23/MADE_algorithms | /hw_11/a.py | 1,265 | 3.546875 | 4 | from collections import deque
def make_step(x, y, n_max):
steps = [(x + 1, y + 2), (x + 2, y + 1),
(x + 2, y - 1), (x + 1, y - 2),
(x - 1, y - 2), (x - 2, y - 1),
(x - 2, y + 1), (x - 1, y + 2)]
correct_steps = [(a, b) for (a, b) in steps
if 0 < a <=... |
9600e263a027c48a61b8463a37630680dd89783c | Dakhi00/Competitve-Programming | /Qwerty keyboard.py | 404 | 4.15625 | 4 | #Qwerty Keyboard
dict1={'W':'Q','E':'W','R':'E','T':'R','Y':'T','U':'Y','I':'U','O':'I','P':'O','[':'P','S':'A','D':'S','F':'D','G':'F','H':'G','J':'H','K':'J','L':'K',';':'L','X':'Z','C':'X','V':'C','B':'V','N':'B','M':'N',',':'M','.':',','/':'.'}
print('Enter string')
string=input()
Final=""
for i in string:
... |
69cb21596e2561712b590c79accce8cfdc9bab0c | VSVDEv/python_starter | /filesandstreams/files.py | 10,045 | 3.796875 | 4 | """Пример открытия файла для чтения"""
def read_file(fname):
"""Функция для чтения файла fname
и вывода его содержимого на экран
"""
# Открытие файла для чтения
file = open(fname, 'r')
# Вывод названия файла
print('File ' + fname + ':')
# Чтение содержимого файла построчно
for l... |
851cc1b8f4b760e5ab78fe622d4fafd95528a847 | danielalvesleandro/520-Python-Fundamentals | /aula_2/exercicio_3.py | 578 | 4.09375 | 4 | # EXERCICIO 3:
# Dar prompt solicitando a idade do usuário
# validando e removendo caracteres inválidos
# da impressão
idade = input('Digite sua idade: ')
string_vazia = ''
caracteres_validos = '0123456789'
for letra in idade:
if letra in caracteres_validos:
string_vazia += letra
print(string_vazia)
... |
7c8ec68f97c2c5476ac2c688c4c0266dc2bd0f73 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/listcomp_no_side_effect.py | 518 | 4.1875 | 4 | #!/usr/bin/env python
# declare a list of numbers
numbers = list(range(1, 7))
number = 0
while True:
number = int(input("Please enter a number between 1 and 6: "))
if 1 <= number <= 6:
break
# Note that the variable used in list comprehension has the same name as that of a local variable
# However, ... |
1b8c6fb3196514f4c194cebe92e683bde899e49f | wadephillips/PrettyPandas | /prettypandas/formatters.py | 2,559 | 3.703125 | 4 | from numbers import Number, Integral
from functools import partial
import locale
import warnings
from babel import Locale, numbers
LOCALE, ENCODING = locale.getlocale()
LOCALE_OBJ = Locale(LOCALE or "en_US")
def format_number(v, number_format, prefix='', suffix=''):
"""Format a number to a string."""
if is... |
421366445f62c136a632ab6f66bd1da41d09daf2 | DemoshenkovGG/pythonintask | /PMIa/2014/Demoshenkov_G_G/6.py | 710 | 3.734375 | 4 |
import random
a="Ворчун"
b="Чихун"
c="Умник"
d="Соня"
e="Простак"
f="Весельчак"
g="Тихоня"
h="хочу зачёт"
gnom=random.randint(1,8)
print("Программа случайным образом отображает имя одного из семи гномов,друзей Белосжнежки(а иногда и желание автора программы(примерно с шансом 1/8))")
if gnom==1:
print(a)
... |
24ed6298823ea0d54fdad337b55bc6b06f4af2cf | arpita-ak/APS-2020 | /Hackerrank solutions/Easy- Beautiful Triplets.py | 594 | 3.734375 | 4 | """
Beautiful Triplets:https://www.hackerrank.com/challenges/beautiful-triplets/problem
"""
import math
import os
import random
import re
import sys
def beautifulTriplets(d, arr):
sarr = set(arr)
return len([c for c in arr if c + d in sarr and c + 2 * d in sarr])
if __name__ == '__main__':
... |
a227f96b8d9722d4943136bda29f8e78ea76abe0 | muyicui/pylearn | /Py Data Analysis/3.1/3.1.3.py | 597 | 3.890625 | 4 | x = '我是一个字符串'
y = "我也是一个字符串"
z = """我还是一个字符串"""
#字符串str用单引号(' ')或双引号(" ")括起来
#使用反斜杠(\)转义特殊字符。
s = 'Yes,he doesn\'t'
#如果你不想让反斜杠发生转义,
#可以在字符串前面添加一个r,表示原始字符串
print('C:\some\name')
print('C:\\some\\name')
print(r'C:\some\name')
#反斜杠可以作为续行符,表示下一行是上一行的延续。
s = "abcd\
efg"
print(s)
#还可以使用"""..."""或者'''...'''跨越多行
s = "... |
6c762444ab047e55101ffd18fd7c92241771dba3 | neiderolivo/metodos-2020 | /neiderolivo/caida_libre.py | 263 | 3.75 | 4 | print('caida libre')
yo=float(input('ingese el valor de la altura inicial:'))
g=float(input('ingrese el valor de la gravedad:'))
t=float(input('ingrese el valor del tiempo:'))
y=yo-0.5*g*t**2
print('el valor de la altura a la cual se encontara el objeto es:',y)
|
ad7f713b1be312995b1d85d507d6f26838498267 | shiyanshirani/w3s-150-questions | /12_calendar_month_year.py | 180 | 3.734375 | 4 | import calendar
month = int(input("Month = "))
year = int(input("Year = "))
print(calendar.month(year, month, l=0,w=0)) # play with l and w for gap
print(calendar.month(1999, 10)) |
f90ea9c65b69e4c6a510c579bce21d707c016c9e | laperss/nmea_navsat_driver | /scripts/positioner.py | 5,662 | 3.546875 | 4 | #! /usr/bin/python
""" Class Positioner for converting between local and global reference frames.
Author: Linnea Persson, laperss@kth.se
This module contains a class used for converting between global (GPS)
coordinates and a user defined local coordinate system. The local
coordinate system is defined by:
1) Origi... |
0e6daae2a9372f33d43ca8b30845f1875e1dbc63 | RahulTechTutorials/PythonPrograms | /Recursion/DeepCopyList.py | 1,638 | 4.375 | 4 | import copy
def deepcopy(megalist, result=[]):
if megalist == []:
pass
else:
if type(megalist[0]) != list:
result.append(megalist[0])
else:
result.append([])
deepcopy(megalist[0],result[-1])
deepcopy(megalist[1:], result)
return result
de... |
cef9e22b1136b08c6917252bf628e6b9f8278d46 | harryd13/Arrays-in-python | /python_arrays/quicksort.py | 503 | 3.78125 | 4 | def partition(arr, l,r):
i = l-1
j = l
while j < r:
if (arr[j] < arr[r-1]):
i += 1
arr[i], arr[j] = arr[j], arr[i]
else:
pass
j+=1
arr[i+1], arr[r-1] = arr[r-1], arr[i+1]
return i+1
arr = [1,3,4,6,7,2]
print(partition(arr... |
fa4e4b254c3fd216e5f86636ad615d59822d84af | devopsvj/PythonAndMe | /oops/constructors.py | 276 | 3.640625 | 4 | class student():
def __init__(self,v1,v2):
self.rollno=v1
self.name=v2
def display(self):
print "Roll No : ",self.rollno
print "Name : ",self.name
obj1=student(100,"Vibaashini")
obj2=student(101,"Sundar")
obj1.display()
obj2.display()
|
2ec9a5f16dd64baef383e7cf5bda25255bdf4c5b | ali-3fr/C.K | /2_1/average_1_N.py | 272 | 4.0625 | 4 | # -*- coding: utf-8 -*-
def average(N):
sum=0
for i in range(0,N+1):
sum+=i
return sum/N
N = input(u'Введите натуральное число N:')
print 'среднее значение целых чисел i=1,2,…,N : '+ str(average(N))
|
ab56827d3c72488066cc20bc422f150b520ae975 | elodeepxj/PythonFirstDemo | /numpyEX/NumpyEx3.py | 836 | 3.765625 | 4 | # -*- coding:utf-8 -*-
#数组的分割
import numpy as np
# x = np.arange(3)
# y = x+3
# z = y+3
# a = np.array([x,y,z])
a = np.arange(9).reshape(3,3)
print a
print "-----------水平分割-----------"
ha = np.hsplit(a,3)#水平分割,对数组a进行水平分割,分割成3份
print ha
sha = np.split(a,3,axis=1) #效果等同水平分割
print sha
print "-----------垂直分割-----------"... |
9dcd1a62e23d6982d476d8ca7227a1e82a9e4cce | Jacobb200/ComputerScience3 | /dog.py | 1,422 | 3.890625 | 4 | """Assignment4 04 Jacob B."""
class dog:
# Class Constants
POPULATION = 0
DEFAULT_AGE = -1
def __init__(self, names="No Name", age=-1, breed="No breed"):
"""Initializes instance variables"""
self._name = names
self._age = age
self._breed = breed
dog.POPULATION ... |
d5c22a994eec6417eb6e9bb72df26bf2642aa8ed | antonmeosh/Learning | /Glava_6_ Slovari.py | 756 | 3.640625 | 4 | alien_0 = {
'color': 'green',
'points': 5,
'x_position': 0,
'y_position': 25,
}
new_points = alien_0['points']
#print(f"You just earned {new_points} points!")
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}. ")
#
alien_0['speed'] = '... |
d1752fcf13bbe040f1cc41ffd9a29715d78803b3 | yjiao1213/python-leetcode-offer | /剑指offer66题_pyhton实现/25_MergeSortedLists.py | 1,034 | 3.8125 | 4 | # -*- coding:utf-8 -*-
'''
合并两个排序链表
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def MergeSortedList(self, head1, head2):
if not head1 and not head2:
return None
if not head1:
return head... |
e190caff29304175cd6d6fefef26263ad3bf7ba6 | erikaklein/algoritmo---programas-em-Python | /4Funções.py | 923 | 4.09375 | 4 | def LerNumero():
a=int(input("Digite um número inteiro: "))
return(a)
def soma (a,b,c):
return (a+b+c)
def media (a,b,c):
return(soma(a,b,c)/3)
def maior (a,b,c):
if a>b and a>c:
M=a
elif b>a and b>c:
M=b
elif c>a and c>b:
M=c
return (M)
def... |
11fab6f03f9716d955b16e22c3f3d46a2f657a76 | ColdSpike/Leetcode | /widest-vertical-area-between-two-points-containing-no-points.py | 974 | 3.828125 | 4 | '''
Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
N... |
8ba0e1e08298feaa7e9ebc6f893be1d0491405c6 | hopaz/LeetCode | /Easy 303. Range Sum Query - Immutable.py | 1,117 | 3.71875 | 4 | from typing import List
class NumArray:
def __init__(self, nums: List[int]):
if len(nums) == 0:
# ["NumArray","sumRange","sumRange","sumRange"]
# [[[]]]
self.nums = None
elif len(nums) == 1:
# ["NumArray","sumRange"]
# [[[-1]],[0,0]]
... |
62cd24165dc792b85298787d406e9d26465d532a | kvraiden/GUVI | /camel.py | 149 | 3.546875 | 4 | import camelcase
x = camelcase.CamelCase()
a = "hello there general kenobi, this is a test to check camelcase is working or not."
print(x.hump(a)) |
53aa4d4d2ef8cd323e48f1aab335aaceee9935d9 | captain-yun/algorithm-playground | /programmers/citations.py | 1,176 | 3.5 | 4 | from functools import reduce
# def solution(citations):
# answer = 0
# citations.sort()
# n = len(citations)
# # size
# # 1. 우선 정렬한다
# # 2. 정렬된 원소 중 하나씩 타겟으로 하여 다음을 반복한다.
# # 2-1. target = 1 ~ 10000
#
# # size.sort()
# h = 0
# for h in range(n):
# if len(list(filter(... |
f1723938bd43c84bdc86c3a0185a67bb372a649b | bithu30/myRepo | /Machine Learning A-Z/Part 1 - Data Preprocessing/data_pre_proc.py | 902 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing data
df = pd.read_csv('Data.csv')
X = df.iloc[:,:-1].values
y = df.iloc[:,3].values
#print(X)
#Taking Care of missing data, done using Imputer class
#from sklearn.preprocessing
from sklearn.preprocessing import Imputer
imputer = Imputer... |
c2ed019cd1fc5f0a2d3918018f34f9cc6b6ad882 | ishika161/githubcampus_geekcoders | /Problem Statement 1.py | 1,205 | 3.703125 | 4 | N=int(input())
P=list()
for i in range(N):
name=input()
P.append(name)
noOfEvents=int(input())
M=list()
#User will input integer for particular query evaluation ie 1 for SERVE, 2 for FRIEND X Y, 3 for VIP X
def finalQueue(N,P,M,X):
if(M==1):
print(SERVE(P))
elif(M==2):
pri... |
cb70acb1cdac54678e6342abba3d3467f87734ee | haveano/codeacademy-python_v1 | /11_Introduction to Classes/02_Classes/09_Inheritance.py | 1,741 | 4.875 | 5 | """
Inheritance
One of the benefits of classes is that we can create more complicated classes that inherit variables or methods from their parent classes. This saves us time and helps us build more complicated objects, since these child classes can also include additional variables or methods.
We define a "child" clas... |
7c37487910f4d3b331e99b88c5125c718ae8d2a6 | mingxoxo/Algorithm | /baekjoon/5639.py | 1,309 | 3.6875 | 4 | # 이진 검색 트리
# 22.10.25
# https://www.acmicpc.net/problem/5639
# https://www.acmicpc.net/board/view/81443
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def binary_search(preorder):
root = preorder[0]
left, right = 1, len(preorder) - 1
result = 1
while left <= right:
mid =... |
e0bc1e698dcb426382ff8de43df882fb5085a9de | TehWeifu/CoffeeMachine | /Problems/snake_case/task.py | 180 | 4.34375 | 4 | string = input()
result = ""
for char in string:
if char == char.upper():
result += '_'
result += char.lower()
else:
result += char
print(result)
|
b1c97bcb5e5d11fae25bb2d3698d1a53d25cc627 | jeongnara/Programming-Python- | /module, pakage/baseball.py | 340 | 3.71875 | 4 | answer = make_answer()
#무한반복
while True:
# 숫자 묻자
guess = input("뭘까?")
# strike, ball 판정하자
strike, ball = check(guess, answer)
# 출력하자
print(f'{guess}\tstrike: {strike}, ball: {ball}')
# 정답 == 숫자, 끝내자
if answer == guess:
print('정답입니다.')
break |
73222049b0a598259bab10633bb2cf8bdacc4fab | dekapaan/python-add-two-numbers | /main.py | 1,070 | 3.90625 | 4 | from tkinter import *
root = Tk()
root.title("Adding Two Numbers")
lb1 = Label(root, text="Please enter first number")
lb1.grid(column=1, row=1)
entry1 = Entry(root)
entry1.grid(column=2, row=1)
lb2 = Label(root, text="Please enter second number")
lb2.grid(column=1, row=2)
entry2 = Entry(root)
entry2.grid(column=2, ro... |
43ffef6e59099c8417a6176a467d8080d750c9c3 | GuileStr/proyectos-py | /Animadoras.py | 467 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 10:08:28 2020
@author: palar
"""
an_letters="aefhilnorsxAEFHILNORSX"
word = input("Te aiuro a echar porras: ")
times = int(input("¿Cuantas veces lo quieres gritar? "))
var=0
while var<len(word):
char= word[var]
if char in an_letters:
print("Give me an... |
6b80a53c8b0e01da63c4cc0428e03317929c826a | jocoder22/PythonDataScience | /DataFrameManipulation/AppendSeries.py | 2,145 | 3.640625 | 4 | ############ appending series
import pandas as pd
def print2(*args):
for arg in args:
print(arg, end='\n\n')
sp = {"sep":"\n\n", "end":"\n\n"}
# Load 'sales-jan-2015.csv' into a DataFrame: jan
jan = pd.read_csv('sales-jan-2015.csv', parse_dates=True, index_col='Date')
# Load 'sales-feb-2015.csv' into... |
1d0e7850dcae154598f35ca4682960070b86db34 | hyo-eun-kim/algorithm-study | /ch09/saeyoon/ch9_6_saeyoon.py | 3,562 | 4.0625 | 4 | """
## 9-6. 원형 큐 디자인
원형 큐를 디자인하라.
MyCircularQueue(k): Constructor, set the size of the queue to be k.
Front: Get the front item from the queue. If the queue is empty, return -1.
Rear: Get the last item from the queue. If the queue is empty, return -1.
enQueue(value): Insert an element into the circular queue. Return ... |
1921981eb5629096e6dfb4ee69a5d2f49b39ff84 | deayqf/Online-Compiler | /python.py | 901 | 3.796875 | 4 | class Node:
def __init__( self ):
self.val = None
self.next = None
def setVal( self, val ):
self.val = val
def initNext( self ):
self.next = Node()
def moveToNext( self ):
return self.next
def hasNext( self ):
if self.next:
return True
... |
11bd930b3ada385f5efc2abc415cbddcfab444a8 | OanaApostol/ITOD | /tests/string_operations_unittests/test_lowercase.py | 1,040 | 4.1875 | 4 | """This module aims to test the lowercase method."""
import unittest
class Lower(unittest.TestCase):
def test_lower_existence(self):
self.Lower = Lower("aaaa")
def test_lowercase_null_values(self):
with self.assertRaises(TypeError):
Lower(None)
def test_lowercase_empty_val... |
36b41286f939161e14c89631e7aaae8a9cee3312 | XiaoLing941212/Summer-Leet-Code | /7.16 - BF(985), DFS(988), Recursive(894)/894. All Possible Full Binary Trees.py | 1,415 | 3.9375 | 4 | '''
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
Each node of each tree in the answer must have node.val = 0.
You may return the final list of trees in... |
9a2201ff64e1814d8f57e3e3debc0031d33cfe9d | andrewyen64/letsbrewcode-python | /4-Bool-ifElse-Ternary/notes.py | 905 | 3.921875 | 4 | # Write a function that returns true if number passed in is even
def is_even(num):
return num % 2 == 0
def is_qualified(age, state):
return age >= 18 and state == 'CA'
print(is_even(99))
print(is_even(100))
print(is_qualified(17, 'CA'))
# ===========================
# if condition:
# stmt1
# stmt2
... |
d8a4adad128a23afbd4c207c50e2058ce99ad259 | melodist/CodingPractice | /src/LeetCode/Koko Eating Bananas.py | 1,113 | 3.6875 | 4 | """
https://leetcode.com/problems/koko-eating-bananas
Using binary search
"""
#1. My Solution (591ms)
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def calculcateSpeed(piles, speed):
hours = 0
for k in piles:
q, r = divmod(k, speed)
... |
a903a6283fc7b0b91ece85c6f68ebe66170c140f | sugia/leetcode | /Repeated Substring Pattern.py | 1,103 | 4 | 4 | '''
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the... |
3b5f907997c5f2b2283eead4e73b102db22d99a8 | darksacred/Python_L2 | /L_2_2.py | 141 | 3.515625 | 4 | el = input("Введите значения: ").split()
for i in range(0, len(el)-1, 2):
el[i], el[i+1] = el[i+1], el[i]
print(el)
|
2e14630ea49373e6e312b0108292a3417b477055 | mickeyouyou/Path_Plan | /A_Star/A_Star.py | 8,459 | 3.859375 | 4 | """
A* 寻路算法
"""
class Array2D:
def __init__(self, w, h, mapdata=[]):
self.w = w
self.h = h
if mapdata:
self.data = mapdata
else:
self.data = [[0 for y in range(h)] for x in range(w)] # CAUTION!!! data列表包含w个子列表,每个子列表含h个元素
def showArray2D(self):
... |
208f59eebfc58d1bf697d015c903138945effb8c | Dhadhazi/PD17-OOPQuiz | /quiz_brain.py | 842 | 3.59375 | 4 | class QuizBrain:
def __init__(self, question_list):
self.question_number = 0
self.question_list = question_list
self.score = 0
def still_has_questions(self):
return len(self.question_list) > self.question_number
def next_question(self):
question = self.question_list... |
c9faf8712ce7b092a5741c709f7b4a9beefc9b33 | vikash-india/DeveloperNotes2Myself | /languages/python/src/concepts/P002_HelloWorld.py | 526 | 4.15625 | 4 | # Description: "Hello World" Program in Python
print("Hello World!")
print('Hello Again! But in single quotes')
print("You can't enter double quotes inside double quoted string but can use ' like this.")
print('Similarly you can enter " inside single quoted string.')
print('Or you can escape single quotes like t... |
a10443761947bcd8faa475a81fc643b44f0e9881 | marquesarthur/programming_problems | /leetcode/btree/tilt.py | 1,135 | 3.859375 | 4 | from leetcode.btree.binary_tree import BTree
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tilt_sum(self, root):
if not root:
return 0, 0
... |
c944defe9f6d6fec58fe7e78dce406a8887e93fd | jiaoqiyuan/Tests | /Python/python-practice/chapter8-func/greeter.py | 682 | 4.09375 | 4 | def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
f_name = input("First nam... |
4b76b782d0f955ab9d99c3c8cab5306584c60560 | rocker2019/python_homework | /Second/grammar.py | 1,271 | 4.1875 | 4 | print('Basic Grammar')
# ################# 常量与变量 #################
'''
均存在内存中,常量是不可变的变量
命名规则
常量:一般采用大写字母,单词间下划线相连,如 PI | APP_URL
变量;只能是字母、数字和下划线的组合,但不能以数字开头,不能使用python关键字作为变量名
'''
# ################# 变量命名方法 #################
'''
驼峰式写法:firstName
下划线连接式写法:first_name
'''
# ################# 数字类型 #########... |
61a095644b32444109ac2e37987cf399b5ea90be | zhukaijun0629/Programming_Daily-Practice | /2020-09-28_Sorting_a_list_with_3 unique_numbers.py | 665 | 4.1875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Google:
Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
"""
def sortNums(nums):
mid = 2
left = 0
right = len(nums)-1
i=... |
56baa0ac18495aa9b6b384396632fe04e9fe1508 | dogsoft0937/SEOULIT_PYTHON_LEARN | /day1/score.py | 190 | 3.53125 | 4 | score=70
if score>80:
print("Good")
elif score>60:
print("So Good")
elif score > 40:
print("20 Good")
elif score > 20:
print("10 Good")
else:
print("Very Good") |
10b14c7d97a05932fb34e9dff6ed0fa0ca65b571 | Eric2D/generator | /row_omitter/omitter.py | 2,286 | 3.9375 | 4 | # Searches unique content and deletes the row containing it
import io
import os
import sys
def counter(count):
try:
count = input('How many phrases would you like to omit?\n\n')
return count
except SyntaxError:
print 'Please use a number.\n\n'
return
except NameError:
print 'Please use a number.\n\n'
r... |
c5fbdf222fe2149f0105e867d7b1493db8c2dcce | GitDeus/1_Lab_Python | /4. Строки/4.2___Lab_Python.py | 325 | 3.921875 | 4 | #Дана строка. Вывести первый, последний и средний (если он есть)) символы.
#2
def get_string(string):
print('first', string[0])
if len(string) % 2:
print('mid',string[len(string)//2])
print('last',string[len(string)-1])
get_string('denis') |
cbb0cc893e383894f07c74fb036f0c3f0e3aceba | GatzZ/Leetcode | /229. Majority Element II.py | 1,286 | 3.578125 | 4 | # coding=utf-8
# Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
# The algorithm should run in linear time and in O(1) space.
# 如何找到所有出现次数严格大于总数1 / k的数? 提示: 保存(k – 1)个数!!!!
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
... |
46ec3286ed9b8a4122deb7c0dc333a216d947038 | SemHiel/PythonExtra | /pythonturtle/test3.py | 354 | 3.609375 | 4 | import turtle
sem = turtle.Turtle()
sem.getscreen().bgcolor("#994444")
sem.speed(100)
sem.penup()
sem.goto((-200,100))
sem.pendown()
def star(turtle, size):
if size <= 10:
return
else:
turtle.begin_fill()
for i in range(5):
turtle.forward(size)
star(turtle, size/3)
turtle.left(216)
turtle.end_fill... |
13a39b28e715ea5aacd0d6e8c9aa7f25f66282e6 | anggieladorador/ejerciciospy | /saludo.py | 129 | 3.796875 | 4 | #ejercicio 1 python
#Ingrese su nombre: Perico
#Hola, Perico
print("ingrese su nombre")
name = input()
print("hola "+name) |
3a3372214b0fa776c3c7b90515873d6b86f6c4f7 | Axiom-Cloud-Inc/interview | /tree/tree_answers.py | 3,658 | 3.59375 | 4 | import json
class Node:
def __init__(self, name):
self.name = name
self._parent = None
self._children = set()
self.value = None
def __repr__(self):
return f'{self.id} = {self.value}'
def __iter__(self):
yield self
for child in self.children:
... |
1add1ffa3e654f4afe56ba90df8256a651bf162a | cartoonqq/CoPython3 | /p_print.py | 1,284 | 3.625 | 4 |
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
import pymysql
'''
# 用户输入数字
num1 = input('输入第一个数字:')
num2 = input('输入第二个数字:')
# 求和
sum = float(num1) + float(num2)
# 显示计算结果
print('数字 {0} 和 {1} 相加结果为: {2}'.format(num1, num2, sum))
print(100+200)
'''
n = 123
f = 456.789
s1 = 'Hello, world'
s2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.