blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
17f7ede0cb7235991acacabf3c9c1d4e9cafd6ef | khygu0919/codefight | /Intro/stringsRearrangement.py | 674 | 3.53125 | 4 | '''
Given an array of equal-length strings, check if it is possible to rearrange the strings in such a way that after the rearrangement the strings at consecutive positions would differ by exactly one character.
'''
import itertools
def stringsRearrangement(inputArray):
a=len(inputArray[0])
b=len(inputArray)
... |
c6017724ad9e78450f3173cab545530b9594594a | karen15555/Intro-to-Python | /Lecture 1/Practical1/Problem5.py | 130 | 3.90625 | 4 | AB = 3
AC = 4
import math
BC = math.sqrt(AB ** 2 + AC ** 2)
print(AB)
print(AC)
print("The hypotenuse of the triangle ABC=", BC)
|
5c9f71c8410e0de2f672b942b0060a3849553e25 | wds360/CS7646 | /CS7646CC/stdev_code.py | 884 | 3.890625 | 4 | import math as m
# calculate the population standard deviation
def stdev_p(data):
if len(data)<2 or len(data)==[]:
raise ValueError('At least two data points needed')
n=len(data)
z=0
for y in data:
z+=y
m=z/n
s=0
for x in data:
s+=(x-m)**2
result = (s/n)**.5... |
3d1a0b343749d62dd7ea230ac997cbc2b13da507 | Hyeonwoo-Park/algo | /hyeonwoo/예전거/10768.특별한 날.py | 753 | 3.734375 | 4 | """
File: 10768.py
Title: 특별한 날
URL: https://www.acmicpc.net/problem/10768
Input #1:
1
7
Output #1:
Before
Input #2:
8
31
Output #2:
After
Input #3:
2
18
Output #3:
Special
Created At: 2020-07-18 23:39:14.642... |
9a34ef35d0faf9b58e17c2d32b2ba2774979be1a | aashishyadavally/turing | /turing/models/clustering.py | 7,411 | 3.9375 | 4 | """
This script implements clustering algorithms like K-Means Clustering Algorithm
Author:
-------
Aashish Yadavally
"""
import sys
import random
import operator
from collections import Counter
import numpy as np
def distance(x, y, distance_type):
"""
Calculates distance between two points, either Euclidean... |
a02b277eb37596e2531768109d3254dd5f6b918e | ChrisLiu95/Leetcode | /easy/Reverse_String_II.py | 666 | 4.125 | 4 | """
Given a string and an integer k, you need to reverse the first k characters for every
2k characters counting from the start of the string. If there are less than k characters left,
reverse all of them. If there are less than 2k but greater than or equal to k characters, then
reverse the first k characters and left... |
bd56a95faf98929956380b58ba4b3e4febea06a0 | Deepu2308/OpenAI-Gym | /archives/MDP.py | 1,314 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 1 04:25:51 2020
@author: dunnikrishnan
"""
import numpy as np
P = np.random.random((3,3)) #is the transition matrix
gamma = .9 #discount factor
#Environment
# State -> 0 1 2
# Reward-> 0 0 0 5
# i.e. for going r... |
a8223eb97e6b878039c6ca67f74653033a79bd30 | sanjkm/ProjectEuler | /p4/lg_pal_prod.py | 1,686 | 3.65625 | 4 | # 7/21/16
# lg_pal_prod.py
# largest palindrome product of two 3 digit numbers
def gen_digit_list (num, digit_list = []):
if num < 0:
print "Negative number cannot be palindromes"
return 0
num_digits = len (str(num))
# create list of digits
for exp in range (num_digits - 1, -... |
6e2bdc219a97b2d8e1a962baac165de26db6d140 | Jose2808/IPC2_Practica1_202004804 | /main.py | 1,229 | 3.828125 | 4 | from Cola import Cola
terminar_programa = False
ordenes = Cola()
def menuPrincipal():
print("***********************************")
print("| 1.Ingresar Orden |")
print("| 2.Entregar Orden |")
print("| 3.MostrarOrdenes |")
print("| 4.Mostrar datos del est... |
e29a19632829753af18f65cd29337e16a3b9d7df | bhoomi2611/basic-python | /10_product of 2 numbers.py | 171 | 4.34375 | 4 | #Define a method that returns the product of two numbers entered by the user.
n1=int(input("enter 1st number"))
n2=int(input("enter 2nd number"))
print("product is",n1*n2) |
28efea31bf382047997ef1a4c2354b332e3bab9c | prashantstha1717/IWPythonProject | /IWPythonProject/data_types/Q1.py | 350 | 4.34375 | 4 | # Write a Python program to count the number of characters (character frequency) in a string.
# Sample String : google.com'
# Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
sample1 = 'google.com'
out1 = {}
for char in sample1:
if char in out1:
out1[char] += 1
else:
... |
4d0178a37e4e86541576f0f88bd65044b451e16e | vippiv/python-demo | /pratise/9.py | 164 | 3.984375 | 4 | # 输出九九乘法表
print("九九乘法表")
for x in range(1, 10):
for y in range(1, x+1):
print("%d*%d=%d" % (y, x, x*y), end="\t")
print("")
|
cd02dc6aeacf50c33bcd3df4cff561f126d490c7 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc044/B/4892514.py | 163 | 3.578125 | 4 | from collections import Counter
w = input()
num = Counter(w)
ans = list(num.values())
if not any([i%2 for i in ans]):
print('Yes')
else:
print('No') |
8b0f5096b5090cc0aee4557cce5cf4b4fe867d18 | therealmikkelw/automate-the-boring-stuff | /examples/walkFolderTree_example.py | 432 | 3.78125 | 4 | import os
path = 'C:\\Users\\mwj\\Documents'
# Using walk() method to walk through a folder tree
# walk() returns three lists: folders, subfolders, filenames
for folderName, subfolders, filenames in os.walk(path):
print('The folder is ' + folderName)
print('The subfolders in ' + folderName + ' are: ' ... |
876b3f16a004419332d9f5ecf517ea2ad7fe8c5e | amyg-cc/collections | /avengers.py | 1,069 | 4.1875 | 4 | # Make a dictionary called avengers. It should contain keys for Iron Man and Hulk.
# Each attack should have an int value of the attack's power. Iron man can punch (10) and kick (100) and Hulk can smash (1000) and roll (500).
# Each avenger is represented by another dictionary, and has a name (Tony Stark and Bruce Bann... |
9705d55e05c38f532f5398c18e6767248c32d908 | jaiswalIT02/pythonprograms | /Chapter-5 Functions/function.py | 180 | 3.78125 | 4 | def printhello():
print("hello world")
printhello()
a=5
b=8
def addTwoNumbers(a,b):#a and b are parameters
sum=a+b
print(sum)
x=addTwoNumbers(1,2)
print(x)
|
860bd2cb9fd80584cec14b5fad8ebc258b423ea0 | sai-varshith/make-pull-request | /Python/27thOct.py | 226 | 4.15625 | 4 | #Function to generate and print all the binary numbers from 1 to n, given n, using the inbuilt bin() function.
def toBin(n):
for i in range(1,n+1):
print(bin(i)[2:])
# Driver program to test the above function
toBin(5)
|
e0e04def873aa53948380b4918b7fbbbd148a84f | robinmenelot/PST | /Code/code ordi/testInput.py | 355 | 3.5 | 4 | from Getch import Getch
if __name__ == '__main__':
while True:
if Getch()() == '\033':
if Getch()() == 'q':
break
else:
key = Getch()()
if key=='A':
print('UP')
if key=='B':
print('DOWN')
if key=='C':
print('RIGHT')
if key=='D':
print('LEFT')
break
if ... |
d12eb29963b91c127e8aa5e70b25b1fe9d15b87d | 962245899/t08Maira-Sandoval | /trabajo06.py | 1,062 | 3.5625 | 4 | # 10 20 30 40 50 60 70 80 90
# 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
msg="la sabiduria es un adorno en la prosperidad y un refugio en la adversidad (aristoteles)"
#indexacion
print(msg[32]) #... |
4271137e6ab278105093f10df54608bbd2d53139 | lordberric/chemical_balancer | /parse.py | 1,606 | 3.59375 | 4 | import re
from molecule import Molecule
from equation import Equation
def parse_molecule(string): #The Method that parses a molecule
if re.search(r'[a-zA-Z]', string[0]): #Adds a one coefficient if necessary
string = "1" + string
digit_search = re.search(r'^\d+', string)
coef = digit_search.group(0) #Defines the ... |
1d21fe8d4bcf3bc9b83529a5556da4cc33ed398c | andrey3OOO/python_univer | /lesson04/inclass.py | 932 | 3.828125 | 4 | import random
# Константы для строк и столбцов
ROWS = 10
COLS = 10
def main():
# Создать двумерный список.
values = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0... |
f41460c70c925f329ab3b3d146d6d37eab88e83c | Aasthaengg/IBMdataset | /Python_codes/p03331/s721892488.py | 132 | 3.71875 | 4 | n = int(input())
if n%10 == 0:
print(10)
else:
cnt = 0
while n != 0:
cnt += n%10
n //= 10
print(cnt) |
d6718375c6a75aa81b78ff089e1b5cdc08a9682c | Baz07/anagram-app | /Backend Logic/AnagramLogic_BackendModule.py | 2,614 | 4.03125 | 4 | ## Anagram Backend Logic
'''
Task1: Add Word pairs in dictionary to fetch top 10 Anagrams.
Task 2: Check whether two words are anagram or not.
'''
mydict = {}
def isAnagram(str1, str2):
str1 = str1.strip()
str2 = str2.strip()
## Task 1: Add Wordpairs to dictionary
if (str1, str2) in ... |
8d3ff58126f70108008c7f8b0593ec605fcb5fa2 | mateosceia/repositorio | /practica 2/ej1.py | 169 | 3.828125 | 4 | cadena = input("inserte una palabra ")
if cadena[0] == (cadena[0].upper()):
print ("la primera letra es mayuscula")
else:
print("la primera letra es minuscula")
|
bca9494154be0458492a3beed60347bae9f0d77c | icculp/holbertonschool-machine_learning | /supervised_learning/0x0F-word_embeddings/2-word2vec.py | 1,390 | 3.59375 | 4 | #!/usr/bin/env python3
"""
NLP - Word Embeddings
"""
import numpy as np
from gensim.models import word2vec
def word2vec_model(sentences, size=100, min_count=5, window=5,
negative=5, cbow=True, iterations=5, seed=0, workers=1):
""" creates and trains a gensim word2vec model
sentences... |
a5567b53e8b55a441da69dd27d5f312b1c419799 | andrescondo/progression_python | /arithmetic_progression.py | 4,022 | 3.984375 | 4 | #-*- coding:utf-8 -*-
# Muchas palabras no llevan tilde por que se esta desarrolando en windows en consola
# Y para usuarios que la ejecuten en consola puedan ver las palabras bien
def reason():
print('-- C A L C U L A R - L A - D I F E R E N C I A --')
d = 0
end = float(raw_input('Ingrese el ultimo termi... |
89a481066274532778c6306057ff622e77944477 | leo3065/infinifactory_py | /infinifactory/index_utils.py | 3,149 | 4.1875 | 4 | def is_valid_axis_range(axis):
"""Determines if a value is a valid axis range.
A valid index is a tuple that is one of:
- int
- slice
- list composes of ints and slices
"""
if isinstance(axis, int):
return True
elif isinstance(axis, slice):
return True
... |
71d4eedd584a98e6b8156c41fd93642bb66b2ebb | abdksyed/AutoCertify | /testing/pretests/test_data.py | 1,383 | 3.8125 | 4 | # test_data.py
import re
from collections import namedtuple
def _test_email(email):
'''
Regex for Testing Valid email address
'''
regex = r'^[a-zA-Z](\w|\.|\-)*[@](\w|\.|\-)+[.][a-zA-Z]{2,4}$'
return bool(re.search(regex, email.strip()))
def _test_name(name):
'''
Regex for Testing Valid ... |
a10d9323a7fcd1798a2ad4bccc6695523f5e30d0 | Anfany/Project-Euler-by-Python3 | /Problem001-100/044 Pentagon numbers.py | 498 | 3.734375 | 4 | #!/usr/bin/python3.5
# -*- coding: UTF-8 -*-
#Author: AnFany
# Problem044 Pentagon numbers
def an_pan(number):#判断是否为五边形数
if ((24*number+1)**0.5+1)%6==0:
return True
an_set,i,af=set(),0,1
while af!=0:
i+=1
fan=int(i*(3*i-1)/2)
an_set.add(fan)
for an in an_set:
if fa... |
087470d2b51b11b7618d29a5a7eb2af5191da699 | markencoder/CS61A | /cs61a/lecture/06/06.py | 2,679 | 4.0625 | 4 | ### DEMO: Return statements
def end(n, d):
"""Print the final digits of N in reverse order until D is found.
>>> end(34567, 5)
7
6
5
"""
while n > 0:
last, n = n % 10, n // 10
print(last)
if d == last:
return None
### FINDING pattern
def find_digit... |
18fae9eaab34097d05c6e8bd7ef71c0d594c94d2 | SamsonWorku/DATA-Project-1 | /Prime number.py | 456 | 4.25 | 4 |
num = int(input("ENTER YOUR NUMBER:"))
print ('Numbers less than ', num, 'that are prime or not prime:')
primes = []
for cur in range(2,num+1):
prime=True
for den in primes:
if not (cur % den):
print (cur,'IS NOT A PRIME NUMBER')
prime=False
break
... |
17dd9337d0a10b9e7e5d91df70353c20927b862e | ArunaBijjam/haritha | /aruna.py | 120 | 3.859375 | 4 | n=int(raw_input())
if(n>o):
if(n%2==0):
print("Even")
elif(n%2>1):
print("Odd")
else:
print("invalid")
|
be6e45cdb3675932f48e6480dd3b502a40d2bb3f | IgorPovzlo/Python | /DZ13.py | 287 | 3.765625 | 4 | print("Домашнее задание №13.Замена символов в строке:")
str1 = input("Введите строку:")
a = str1[:str1.find('h') + 1]
b = str1[str1.find('h') + 1:str1.rfind('h')]
c = str1[str1.rfind('h'):]
str1 = a + b.replace('h', 'H') + c
print(str1) |
f1ff706308fe5608ecbb711bcd181f27a4b033d6 | delobrook/comp3101finalproject | /venv/OPT.py | 6,703 | 3.546875 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode((1300,700))
pygame.display.set_caption("Optimal Page Replacement Algorithm")
#images
table=pygame.image.load('First table.PNG')
tablex=50
tabley=350
#font
font= pygame.font.Font('freesansbold.ttf',15)
fontx=100
fonty=320
titleE= pygame... |
95879fbf74ec16c9a199c665a7d79d5811b22e58 | singhsukhendra/document_classification | /src/word_embedding.py | 9,052 | 3.546875 | 4 | import numpy as np
from keras.layers.embeddings import Embedding
def cosine_similarity(u, v):
"""
Cosine similarity reflects the degree of similarity between u and v
Arguments:
u -- a word vector of shape (n,)
v -- a word vector of shape (n,)
Returns:
cosine_similarity -- the... |
27c6e4f7239e932b57c6e1a5fa4cae2d1fbbccbd | RandomY-2/Movie_Recommender_Engine | /Collaborative_Filtering/recommender.py | 1,355 | 3.796875 | 4 | # Collaborative Filtering Recommender
import pandas as pd
from scipy import sparse
corrMatrix = pd.read_csv('/dataset/item_similarity_df.csv')
def get_similar(movie_name,rating):
similar_ratings = corrMatrix[movie_name]*(rating-2.5)
similar_ratings = similar_ratings.sort_values(ascending=False)
#print(ty... |
275c7a08d825a7bed1dcac53760e12f883711eea | msoto-27/ejercicios-u3 | /Ejercicio 3/main.py | 640 | 3.703125 | 4 | from clase_menu import Menu
if __name__ == "__main__":
m = Menu()
salir = False
while not salir:
print("===== MENU DE OPCIONES =====\n"
"1) Registrar a una persona a un taller\n"
"2) Consultar datos de inscripcion de una persona\n"
"3) Mostrar dato... |
fe304e5ae7bb38c3b95caee1a1e27e26e7f6f0e7 | alacambra/arduino-xavier | /test/hello.py | 535 | 3.796875 | 4 | import sys
import pygame
pygame.init()
import PyQt4
#create the screen
window = pygame.display.set_mode((640, 480))
#draw a line - see http://www.pygame.org/docs/ref/draw.html for more
pygame.draw.line(window, (255, 255, 255), (0, 0), (30, 50))
pygame.draw.circle(window,(255, 255, 255), (50, 50), 50)
#draw it to the ... |
02a12963ccbdb01d3dbf82ba0ae128ef1ac6f194 | pvithayathil/titanic | /titantic_forest_pv.py | 1,263 | 3.5 | 4 | import numpy as np
import pandas as pd
import sklearn.linear_model as lm
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
# Import the RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
# Load Data
train = pd.read_csv('train.csv')
test = pd.read_csv('... |
8db19da1e5bafffa0cdfa4489d3f95bf9b8119f7 | romu42/aoc2020 | /day1/report_repair.py | 540 | 3.8125 | 4 | #!/usr/bin/env python3
# input is a list of numbers
# find two numbers that sum 2020, multiply these numbers for answer
def sum2020(data: list) -> int:
report = [int(x) for x in data.readlines()]
for i,num in enumerate(report):
for i2, num2 in enumerate(report):
for i3, num3 in enumerate... |
413521e26c85ebd367e4896aea5be49f4c9b195e | reidevries/codecoach | /test/50.py | 1,908 | 3.828125 | 4 | import sys
import os
def fact_iter(n):
number = 0
for I in range(n+1):
number = number * I
if I == 0:
number = 1
final = number
return final
def fact(n):
number = 1
if n != 0:
number =n*fact(n-1)
final = number
return number
def fib_iter(n):
number1 = 0
number2 = 0
temp = 0
for I in range(n... |
78854a24c23b03300fe77cc22b69b25a4720eae7 | edmondwei1987/codingdojo-python | /coin_tosses.py | 502 | 3.8125 | 4 | import random
def coin_tosses(times):
head_count=0
tail_count=0
for i in range(0,times):
head_or_tail=''
coin=random.random()
if round(coin)==0:
head_count=head_count+1
head_or_tail='head'
else:
tail_count=tail_count+1
head_or_t... |
f5c3614b8fd02c36565bd5435889be2c1b4f3186 | Hyper-Devil/learn-python3 | /sample/old/listtuple.py | 287 | 3.953125 | 4 | classmates = ['Michael', 'Bob', 'Tracy']
print(len(classmates))
classmates[0]
classmates[2]
classmates[-1]
classmates.append('Adam') #末尾
print (classmates)
classmates.insert(2, 'Jack')
print (classmates)
classmates.pop(2)
print (classmates)
classmates[1] = 'Sarah'
print (classmates) |
872db36f94f29c4ab58c9c2923b649f1cbed94d8 | cluo1989/TensorflowNotes | /basics/variable_scope.py | 1,488 | 3.515625 | 4 | # -*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
# tf.Variable, 允许重名, 会自动加 name_n
w = tf.Variable([1.0], name="w")
print(w.name, w.value)
w1 = tf.Variable([1], name="w")
print(w1.name, w1.value)
# tf.get_variable, 默认reuse=False, 不能重名
v1 = tf.get_variable("v", shape=[1]) # 未指定 initializer;
pr... |
958f1ece6220007811d970a05d772055366c1825 | ack8006/EulerProjects | /p12-HighlyDivisibleTriangularNum.py | 2,405 | 3.75 | 4 | """
The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first
ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,... |
410e0e518fbf598de6c03e7427aefe326e7a835a | ataffe/smartGarden | /test/database_test.py | 1,221 | 3.625 | 4 | #!/usr/bin/env python
import sqlite3
from datetime import datetime
from datetime import timedelta
table_command = """CREATE TABLE IF NOT EXISTS sunlight (
sunlight text NOT NULL,
record_timestamp text PRIMARY KEY,
cleanup_timestamp text); """
def create_table():
try:
conn = sqlite3.connect('gardenDataba... |
a9ba8a5537b068ff91b74e0ba91f063e4edcccd6 | mhkr007/Python_files | /Python/Letter_coding_py/demo.py | 135 | 3.71875 | 4 | from random import randint
low=int(input("enter min:"))
high=int(input("enter max"))
a=[randint(low,high) for i in range(10)]
print(a)
|
4e89413170e80fb37f8579d0409f328a8cf076dd | PRAVEEN-ARAVENDAN/Self-Learning | /Python Data Structures/Praveen_Circular_Linked_List.py | 1,679 | 4.34375 | 4 | '''
CIRCULAR LINKED LIST
l :- Linked list
a,b,c :- Nodes
n :- Node that needs to be inserted or deleted
traversal(l) :- Also displays the Linked List along with traversal
insert_after(n, a)
insert_at_last(l, n)
delete(l, n) :- n will be deleted
Note :-
A Circular Linked List is just a simple linked li... |
f13905ee3fd48735ade4d70e4ea7f7ad7efc660a | mihirm05/scratch | /misc/method_overriding.py | 337 | 4.03125 | 4 | # method overriding : same name and same number and type of
# arguments but different functioning
class A:
def show(self):
print('In A')
class B(A):
def show(self):
print('In B')
# show() of B will be invoked if it is present
# if not then the show() of A will be invoked
a = A()
a.show()
... |
c50398549e4c0f374b7a2411a46a242d797ce923 | Quadrob/RANDOM-python-projects- | /new 1.py | 82 | 3.734375 | 4 | print("hello")
name = "robert"
if (name == "robert"):
print("thats my name") |
67c5740d4d956e3e224c3cf1f1490a48c2d07743 | vladjdk/ITI1120 | /Labs/lab7-students/q1.py | 236 | 3.65625 | 4 | def indexes(word, character):
b=[]
for i in range(len(word)):
if character in word[i]:
b+=[i]
return b
def betterindexes(word, character):
return [i for i,char in enumerate(word) if char==character]
|
d59ec552044edce47110aae64f905eceb7d9ae9b | johnPractice/Algorithm-Design-Analysis | /practice/DP/can_sum_path.py | 756 | 3.671875 | 4 | def get_input():
n=int(int(input()))
result=input()
result=result.split(' ')
result=list(int(t) for t in result)
return {"canSum":n,"arr":result}
def can_sum_func(c,a,memo):
if c==0:
return []
if c<0 :
return None
for i in a:
reminder=c-i
key=str(reminder)... |
6a8b19f2bce1c284c33bd4dc89c22a7c2edc12ff | thomasperez37/cspp10 | /unit3/tperez_fizzbuzz.py | 594 | 4.09375 | 4 | end_point = int(input("Input the end point of the Fizz Buzz sequence:"))
for num in range(1,end_point+1):
len_of_num = len(str(num))
for digit in range(len_of_num):
if (str(num)[digit] == "3" or num % 3 == 0) and (str(num)[digit] == "5" or num % 5 == 0):
print("FizzBuzz,", end=" ")
... |
efc311ad78b89b3576da660a567ab833ced3c81a | liousAlready/NewDream_learning | /老师の课堂代码/day04/day04-循环语句--while.py | 4,010 | 4.03125 | 4 | '''
@File : 循环语句--while.py
@Time : 2021/4/11 09:36
@Author: luoman
'''
# import lib
'''
while 判断条件:
执行语句……
[else:
执行语句……]
'''
# 举例:要求输出一个故事五次:故事的内容是:这是一个悲伤的故事
print('这是一个悲伤的故事')
print('这是一个悲伤的故事')
print('这是一个悲伤的故事')
print('这是一个悲伤的故事')
print('这是一个悲伤的故事')
# 循环要进行使用的四个基本条件:1、起始值 2、结束值 3、循环体 4、增量(... |
d4a49099d2077605d705cdf057935886d7273208 | peter-fogg/treeviz | /tree.py | 3,096 | 3.578125 | 4 | import uuid
import sys
class Tree():
'Minimal binary tree class for testing.'
def __init__(self, value):
self.right = None
self.left = None
self.value = value
self.iden = str(uuid.uuid4().int)
def is_leaf(self):
'A leaf has no children on right or left.'
r... |
68b27b6096f256bc497b70f1ce57051f68998328 | mapetranick/python_work | /MichaelPetranick_Assignment_4_1.py | 1,091 | 4.25 | 4 | # CIS 240 Introduction to Programming
# Assignment 4.1
# Calculate the cost of installing fiber optic cable at a cost of .87 per ft for a company.
# Bulk discount .80 greater than 100 feet
# Bulk discount .70 greater than 250 feet
# Bulk discount .50 greater than 500 feet
print("Hello!")
print("What is the name of you... |
85b9c6f52a22ca05972c1fa50f0ada45a49d5dfb | VagifMammadaliyev/vagifer | /src/examples.py | 2,634 | 3.78125 | 4 | """Examples
This file contain example painters. They are not very complex
but you may get an idea of how painters are implemented.
You don't have to follow these implementation styles!
Writing a painter is actually a good time killer and it is
very addicting :)
"""
from random import randint
from painter import Bas... |
c8a3b22722f613b4171e2b42e04c218d5e2de9f3 | giangjason/StudyNotes2020 | /Data Structures/Heap/helper.py | 1,660 | 4.09375 | 4 | from binarytree import Node
from typing import List
from queue import Queue
import random
class Helper():
def generate_random_list(self, low: int, high: int, length: int) -> List[int]:
"""Generates a random list of numbers
Args:
low (int): The lowest possible value in the list
... |
5c389a7092aaab9de10fadad78e16a5dbdabed6c | szipperer/learning | /cardclass.py | 379 | 3.65625 | 4 | class Card():
def __init__(self,suit,number):
self.suit = 0
self.number = 0
self.value = 0
class Deck():
def __init__(self):
self.Cards = []
self.assign()
def assign (self):
for suit in ['heart', 'club', 'spade', 'diamond']:
for number in range(0,... |
3455030f35debc1a0f549cceffe76b80ac18e449 | edu-athensoft/stem1401python_student | /py200421_python2/day09_py200519/lambda_5_exercise.py | 540 | 3.8125 | 4 | """
list1 = [0,1]
183 days
0: outside quebec
1: stay in quebec
mystatus = {
"peter" : 0,
"marie" : 1,
"sarah": 0,
"Jack" : 1,
...
}
pick out the names who are outsite quebec for 183 days
"""
# 500 persons
mystatus = {
"peter" : 0,
"marie" : 1,
"sarah": 0,
"Jack" : 1
}
temp = list... |
9f8d64005697703bed0df9851f84bdd83a181255 | Bloom9900/python_handins | /modules/book.py | 3,003 | 4.34375 | 4 | class Paragraph():
"""A paragraph consists of a list of lines."""
def __init__(self, lines):
"""Initialize name and age attributes."""
self.lines = lines
self._reading_position = 0
def read(self):
"""Simulate reading a paragraph by printing its contents."""
... |
bd97c8c7c280a722efe40a20e802a1a006f24228 | thiagosantos1/RNN_Google_Stock | /RNN/rnn_price_stock.py | 6,007 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 21:51:01 2018
@author: thiago
"""
# Recurrent Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd.read... |
d0a7b924c4d76b89f6b8d7658d568799328c0d55 | akash19jain/Algorithms | /algorithms/Python/ExtendedEuclidean/ExtendedEuclidean.py | 415 | 3.8125 | 4 | def gcdExtended(x, y):
# Base Condition (Special Case)
if x==0:
return y,0,1
# Call the function recursively
gcd,x1,y1=gcdExtended(y%x,x)
# Update x2 and y2 using the return of recursive function
x2 = y1 - (y//x) * x1
y2 = x1
return gcd,x2,y2
# Can be modified to be taken as an ... |
ffd719509aec235088a39bfb4ab474ded60b0ad6 | Cielako/Python_exercises | /lista 3/zad7.py | 102 | 3.9375 | 4 | n = int(input("Podaj n do ciagu fibonacciego: "))
x = 0
y = 1
while y<n:
print(y)
x,y = y,x+y |
af34dcff95f859740cff60435092c6ae7161d713 | klose911/klose911.github.io | /src/python/src/pythonic/dict/dict_group.py | 919 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
#Filename: dict_group.py
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
# 在这个例子,我们按 name 的长度分组
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
# >>> {7: ['ra... |
7243cf20208defa11ba496fa4ecc625f2d3cf58f | DYNAMIC-DENOM/python | /vowel.py | 188 | 4.1875 | 4 | # vowels=['a','e','i','o','u']
letter='h'
if letter=='a'or letter=='e'or letter=='i' or letter=='o'or letter=='u':
print('this is a vowel')
else:
print('this is a consonent')
|
62948598f0fa5530edf25a5eb447cf89fcaacc0e | endy-see/AlgorithmPython | /SwordOffer/10_2-JumpFloorII.py | 532 | 3.59375 | 4 | """
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:
f(0)=1 表示一步一次性登到n>1的台阶时的一种方法
f(1)=1
f(2)=2=f(1)+f(0)
f(3)=4=f(2)+f(1)+f(0)
...
f(n)=2^(n-1)=f(n-1)+f(n-2)+...+f(2)+f(1)+f(0)
"""
# -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self, number):
# write code here
if number <... |
b8826c98092392b693b6cf4f4f5432e992879eee | adowdell18/PythonProjects | /sugar_shopping.py | 778 | 4.03125 | 4 | #Author: Angie Dowdell
#Date: February 9, 2016
weight_package_1 = eval(input("Please enter the weight of package 1 of sugar in oz: "))
price_package_1 = eval(input("Please enter the price of package 1 of sugar in dollars: "))
weight_package_2 =eval(input("Please enter the weight of 2 package of sugar in oz: "... |
2805ee814336e9e9e89c409dee7d9eb679802150 | Th3KingMak3r/Python | /F_to_C.py | 273 | 3.90625 | 4 |
Cel = input("What is the temperature you need changed in Celsius?")
Fah = (9/5) * float(Cel) + 32
conv_temp = float(Fah)
print("\nYour temperature in fahrenheit is:", Fah, "degrees.")
print("\nYour Celsius was", Cel, "and your Fahreinheit was", Fah)
|
137418bd8a36c97918fae77598ac77fb576e865b | luchovelez/Estructura | /TDD/ProgramasEstructurasBasicas/programa2_01Prueba.py | 590 | 3.5 | 4 | # Prueba del Programa 2.1: programa2_01Prueba.py
# Prueba de la implementacion de una pila en Python, asumiendo que el tope esta al final de la lista
from programa2_01 import Pila # Importar la clase Pila del modulo programa2_01
p = Pila()
print p.estaVacia()
p.incluir(4)
p.incluir('perro')
print p.inspeccionar()
p.... |
93985273a80abd92d69e36743c7a1d3adb937bdf | darsan13/python3 | /14-file-delete.py | 201 | 3.5625 | 4 | #!/bin/python3
# The above line is called as HashBang or ShBang line
import os
if os.path.exists("mynewfile.txt"):
os.remove("mynewfile.txt")
else:
print("The file is not available for delete")
|
12d9ce39cf287b4b22a6686e2ea77d41e8fde907 | gmatuska/hackerrank | /python/stacks-balanced-brackets/test_main.py | 728 | 3.90625 | 4 | from unittest import TestCase
class TestMain(TestCase):
def test_main(self):
i = '{{{}}}'
"""self.assertEqual(['{', '{', '{', '}', '}', '}'], list(i))"""
"""reversedStack = sorted(stack, reverse=True)"""
self.assertTrue(self.is_balanced(i))
def is_balanced(self,brackets):
... |
80f000eecf93c724a2267845b41b2ea605dd7ca5 | chriszhuu/Imaginary-Bus-Network | /bus system1/main.py | 5,725 | 3.828125 | 4 | from bus import Bus
from town import Town
from people import Person
townfile = open("town.txt","r")
for aline in townfile.readlines():
values = aline.split()
Town(values[1], values[3:]) # create Town objects
busfile = open("bus.txt","r")
for aline in busfile.readlines():
values = aline.split()
Bus(va... |
5f9dec778d2a53f4a87f7c3e44e2fd8e279da870 | ValS-Itescia/Calendrier_Gregorien_1 | /calendarTools.py | 1,318 | 4.1875 | 4 | # monthToString => Get month in number and return a string
# monthAdd => Return the value to add
# yearAdd => same but with the year
# lastDigit => get the last digit of year
# bissextile => Check if the year is bissextile
# dayWeek => convert the value into a string
def monthToString(... |
5c202386a25094d58c2080713e0e57e9e07bfdec | caaiofarias/Python-LabProgramming | /Lab de Programação/Juvenal Obsessivo usando Set().py | 3,995 | 3.765625 | 4 | class Vertex:#Vertice com valores
def __init__(self,nome):
self.nome = nome
self.vizinhos = set()
self.visitado = False
self.distance = [float("inf"),float("inf")]
def getVertex(self):
return self.nome
class Graph:
def __init__(self):
self.vertexes = []#l... |
a99be34821fd47569bb300e1e2bb780789bee084 | AvishDhirawat/Python_Practice | /Binary_Search.py | 654 | 4.15625 | 4 | #!/usr/bin/env python3
def binary_search(arr, start, end, element):
if(start > end):
return "Invalid Input"
mid = (start + end)//2
# print(mid, arr[mid])
if(arr[mid] == element):
return "Searched Element is at " + str(mid)
if(arr[mid] < element):
return binary_search(ar... |
18fc5951240bded85b02677adb78f28bfcb4b6d2 | NikitaAlexandrovich/lessonsProj | /Some/lesson_10.07.py | 543 | 3.703125 | 4 | # from math import *
# print(factorial(3))
# i = 1
# i +=1
#
# round(i / 5, 2)
# mas = [2, 5, 6, 8, 0, 56, 89, 10, 11, 6, 0, 0]
# num = int(input("Введите элемент для поиска в массиве: "))
# poisk = 0
# for i in range(len(mas)):
# if mas[i] == num:
# poisk += 1
#
# print(poisk)
# str_mas = ["HeLlo", "wOrl... |
0034664d5dedb384d3d7b3282821cdf391934ef0 | taimurKhann/IMDB_ANALYSIS | /transformation.py | 2,098 | 3.953125 | 4 | import pandas as pd
def avg_duration_movies_by_year(df):
""" Function to manipulate df to get average duration of movies per year.
Args:
df: dataframe containing data of movies
Returns:
final_df: final dataframe containing result
"""
df = df[ (df['titleType'].isin(['m... |
30d5ed1d88b9657e5edb28914bef4ca3b7d23aae | huy75/holbertonschool-interview | /0x08-making_change/0-making_change.py | 383 | 3.96875 | 4 | #!/usr/bin/python3
"""Making change O(n)"""
def makeChange(coins, total):
"""Clasic Bottom-Up dynamic programming"""
temp_value = 0
coins.sort(reverse=True)
if total < 0:
return 0
for coin in coins:
if total % coin <= total:
temp_value += total // coin
tot... |
e6f798268e81807dbf64c1276f968d559669ca44 | kefhifi/study_book | /study_4.py | 1,993 | 4.15625 | 4 | # input函数 和 while 循环
age = input("How old are you? ")
print(age)
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nNo........")
# 7.1.3 求模运算符
# 将两个数相除并返回余数
print(4%3)
print(12%3)
prompt = "\nTell me something, and I wil... |
8a9a527200d8616ead8fd8adb0db1b3271c1998d | daniel-reich/ubiquitous-fiesta | /mmiLWJzP3mvhjME7b_12.py | 332 | 3.625 | 4 |
s="S0"
def divisible(arg):
global s
if not arg:
if s=="S1":
s="S2"
elif s=="S2":
s="S1"
return divisible
elif arg==1:
if s=="S0":
s="S1"
elif s=="S1":
s="S0"
return divisible
a=s
s="S0"
if arg=="state":
return a
elif a=="S0":
return "accept"
retur... |
5b0f9546bd8cda208551ebd870958be26b4a9aaf | nteno555/py | /warmup/Animation_No.py | 827 | 3.546875 | 4 | from tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=500, height=400)
tk.title("Drawing")
canvas.pack()
canvas.create_line(0,0, 500, 400)
canvas.create_rectangle(0, 100, 200, 150, fill="blue")
canvas.create_oval(100, 100, 150, 150, fill="red")
canvas.create_line(500, 400, 10, 10)
canvas.create_oval... |
4131f49d676b2d403d71e104fa64518e7010ba52 | harinyoo/BAEKJOON | /StepByStep/Python/Step_07_기본 수학 1/1193.py | 201 | 3.609375 | 4 | X = int(input()) #4
sum = 2
num = 1
while X > num:
num += sum
sum += 1
if sum % 2 == 0:
print(str(1+num-X) + '/' + str(sum-1-num+X))
else:
print(str(sum-1-num+X) + '/' + str(1+num-X)) |
07cc142c48e793b4a98f3f5f216cb1f8a39f6322 | sassafras13/coding-interview | /fundamentals/dfs/dfs_v2.py | 775 | 3.765625 | 4 | # 2021-01-23
# Emma Benjaminson
# Second implementation of depth-first search
# Source: https://likegeeks.com/depth-first-search-in-python/
graph = {
'A' : ['D','C','B'],
'B' : ['E'],
'C' : ['G','F'],
'D' : ['H'],
'E' : ['I'],
'F' : ['J']
}
def dfs_non_recursive... |
ad3746d2ee3a51e79d627298db8d4d8b49624c0f | MondoGarza/Optimization-Practice | /BinarySearch.py | 6,117 | 3.796875 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def binary_search(input_array, value):
low = 0
high = len(input_array) - 1
while (low <= high):
mid = (low + high)/2
if (input_array[mid] == value):
r... |
396f1a1d2f862ecdcf70a120684f853d8c76001f | wevertonbezzera013/Python-exercises | /Python_exercises/desafio45.py | 1,200 | 3.8125 | 4 | from random import randint
print('='*25)
print('PEDRA, PAPEL E TESOURA!')
print('='*25)
itens = ('PEDRA', 'PAPEL', 'TESOURA')
escolha = randint(0, 2)
print('''Suas opções:
[0] PEDRA
[1] PAPEL
[2] TESOURA''')
resposta = int(input('Digite sua resposta: ')
print('Você escolheu {}!'.format(itens[escolha]))
print('O comp... |
5e61c7c9eb9411aed96a77db7c5e3278c60ed844 | csuzll/python_DS_Algorithm | /7、图和图的算法/shortest_path/prim.py | 1,872 | 3.765625 | 4 | # 最小生成树算法
# 使用的是贪婪的策略
from PriorityQueue import PriorityQueue
from Graph import Graph
from Vertex import Vertex
import sys
# 最小生成树
def prim(G, start):
pq = PriorityQueue(1000) # 优先级队列实例,小数优先
# 所有顶点初始化
for v in G:
v.setDistance(sys.maxsize)
v.setPredecessor(None)
start.setDistance(0)... |
8abbc11ffabf17788511db9f2cec0de8682c6a49 | cpt-nem0/The_Daily_Byte | /p8_two_sum.py | 682 | 4.09375 | 4 | """
Given an array of integers, return whether or not two numbers sum to a given target, 'k'.
Note: you may not sum a number with itself.
Ex: Given the following...
[1, 3, 8, 2], k = 10, return true (8 + 2)
[3, 9, 13, 7], k = 8, return false
[4, 2, 6, 5, 2], k = 4, return true (2 + 2)
"""
from typing import... |
b23cdacc6c5daa08aea2626e11d2b11c4ceb3f6b | liuhahi/asse | /a1.py | 6,021 | 3.9375 | 4 | """
CSSE1001 Assignment 1
Semester 2, 2020
"""
from a1_support import (
INPUT_ACTION,
INVALID,
WELCOME,
HELP,
WALL_VERTICAL,
WALL_HORIZONTAL,
GUESS_INDEX_TUPLE,
VOWELS,
CONSONANTS,
load_words,
random_index,
)
# Fill these in with your details
__author__ = "{{hongfei.shen}} ({{s4610279}})"
__ema... |
b7b40ea2dcad96470c7878f3854ce779e8edf30d | LYSHN/python-100-day | /day-102-01/2.2.4.py | 353 | 3.5625 | 4 | # 以 r 模式打开本地建立的 python-100.txt 文件,读取文件中所有内容,以列表形式返回
with open('python-100.txt', 'r', encoding='utf-8') as f:
content = f.readlines()
print(content)
for line in content:
print(line.strip('\n'))
# 输出结果
# ['Python-100\n', '坚持100天']
# Python-100
# 坚持100天 |
2ff1352c952875275f0abcba57d6116edb2e52bb | lstachon/ASD_kol_1 | /kolokwium_3/wzory_struktur/hash_dict_ints.py | 1,861 | 3.765625 | 4 | class Node:
def __init__(self , key = None , value = None):
self.key = key
self.val = value
self.next = None
import random
class Hashtable:
PRIME = 1118317
A = random.randint(1, PRIME)
B = random.randint(1, PRIME)
def __init__(self , size):
self.arr = [None] * size... |
82112852bb310a64e2593213d49a0ec9e1f6c9de | Jawwad18B/LAB-10 | /Programmin Exercise LAb 10 Q1.py | 322 | 3.5625 | 4 | print('Jawwad 18b-007-CS(A)')
print('LAB10 Programming Exercise q1')
dict = {'father':'Wayne','mother':'MRs Wayne','Me':'Rooney'}
print(dict)
dict['Maternal Grand Father'] = 'Jim'
dict['Maternal Grand Mother'] = 'Mrs Jim'
dict['Paternal Grand Father'] = 'Alex'
dict['Paternal Grand Mother'] = 'Mrs Alex'
print(di... |
d5d387701781179505971607720b0b64e9bc84a3 | makolyte/57exercises-python | /lesson27-validateInput.py | 1,574 | 3.6875 | 4 | def namesFilledIn(name):
if len(name) == 0:
return False
return True
def namesAtLeast2(name):
if len(name) < 2:
return False
return True
def validID(ID):
length = len(ID)
if length != 7:
print "ID Not the right length"
return False
if "-" not in ID:
... |
40ce0ade1dd7c90e7cb440815807380649d2f5c5 | Xynoclafe/leetcode | /medium/reverseLinkedListII.py | 1,231 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
firstNode = None
prev = None
count = 0
node = head
whil... |
28705fe4b9f97127f78fd61d67645b4d0f92cd11 | guoweifeng216/python | /python_design/pythonprogram_design/Ch8/8-3-E14.py | 1,585 | 3.59375 | 4 | from tkinter import *
class Oscars:
def __init__(self):
window = Tk()
window.title("Academy Awards")
caption = "Year (1928-2013): "
Label(window, text=caption).grid(row=0, column=0)
self._conOFentYear = StringVar()
self.entYear = Entry(window, width=4,
... |
4460743660685d8f937bf7090afd1ed0ff035e06 | saetar/pyEuler | /not_done/py_not_started/euler_329.py | 1,107 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ~ Jesse Rubin ~ project Euler ~
"""
Prime Frog
http://projecteuler.net/problem=329
Susan has a prime frog.
Her frog is jumping around over 500 squares numbered 1 to 500.
He can only jump one square to the left or to the right, with equal probability, and he cannot jump ou... |
6099f27e9c19080ab079b25e5a3dd089f2abe54f | Joseph-Macalinao/Learn | /classes_and_constructors.py | 905 | 4.46875 | 4 | '''
classes used as way to create own interpretation of complex ideas
uses Pascal naming method (first letter of each word capitalized with no spaces(NoSpacesAllCaps))
class Point:
def move(self):
print('move')
def draw(self):
print('draw')
#objects - instance of a class used differently
poi... |
ec863a019c8d16e9282265bb89f598c3f2a6cc15 | charansaim1819/Python_Patterns | /ALPHABETS/CAPITAL_ALPHABETS/Z.py | 603 | 3.875 | 4 | #Shape of capital Z:
def for_Z():
"""printing capital 'Z' using for loop"""
for row in range(7):
for col in range(7):
if row+col==6 or row%6==0:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_Z():
"""prin... |
949d4ef2e62b6c9c160965c024761330aa8ecac5 | labulakalia/note | /python_notes/一些代码/rq/rq_job.py | 183 | 3.625 | 4 | '''
运行的函数不可以和rq任务队列放在一个文件执行
'''
import time
from job_main import add
job = add.delay(2,1)
print(job.result)
time.sleep(1)
print(job.result)
|
b3d329c6f80355b626ffd89098fba5574f93f67b | markdannel/leetcode | /dp/no98.py | 1,292 | 3.9375 | 4 | # 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
# 假设一个二叉搜索树具有如下特征:
# 节点的左子树只包含小于当前节点的数。
# 节点的右子树只包含大于当前节点的数。
# 所有左子树和右子树自身必须也是二叉搜索树。
# 示例 1:
# 输入:
# 2
# / \
# 1 3
# 输出: true
# 示例 2:
# 输入:
# 5
# / \
# 1 4
# / \
# 3 6
# 输出: false
# 解释: 输入为: [5,1,4,null,null,3,6]。
# 根节点的值为 5 ,但是其右子节点值为 4 。
# Definit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.