blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
06e0599e504edf6aaccdc7f1ba0ac57884ade929 | pengLP/LeetCode | /python/chuji/chiji_list/leetCode_141.py | 1,212 | 3.921875 | 4 | """
环形链表
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if(head == None):
return False
i... |
045a1da9c417c6c6c9ab585ad2af8f3e1b2d7ad7 | keremh/codewars | /Python/7KYU/sum_digits.py | 258 | 3.828125 | 4 | def sumDigits(number):
number = abs(number)
n = 0
while number:
n += number % 10
number //= 10
return n
"""
test.assert_equals(sumDigits(10), 1)
test.assert_equals(sumDigits(99), 18)
test.assert_equals(sumDigits(-32), 5)
"""
|
d641e7077401b04ab5d5ac4502ba363d71f6def3 | keremh/codewars | /Python/8KYU/reverse_array.py | 222 | 4.21875 | 4 | """
Get the number n to return the reversed sequence from n to 1.
Example : n=5 >> [5,4,3,2,1]
"""
def reverse_seq(n):
n_array = []
i = 0
for i in range(n, 0, -1):
n_array.append(i)
return n_array
|
29686d25a1edc3648f9540d7c573ee809d6dd1ce | RidaBushra/Assignment-2-AI-Q2-PIAIC | /PIAIC 151780_Assignment 2.py | 3,300 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Numpy_Assignment_2::
# ## Question:1
# ### Convert a 1D array to a 2D array with 2 rows?
# #### Desired output::
# array([[0, 1, 2, 3, 4],
# [5, 6, 7, 8, 9]])
# In[2]:
import numpy as np
y=np.arange(0,10)
z=y.reshape((2,5))
print(z.tolist())
# ## Question:2
#... |
8b5ae99551bb9f9b2f45e21b11d5a016f7542a02 | teazj/keychain-bruteforce | /mkwordlist.py | 899 | 3.6875 | 4 | #!/usr/bin/env python2
# This program generates various kinds of typos in the given password.
#
# Useful for generating wordlists in case you mistyped your password twice when setting it.
#
# SUBSTS = {'s': 'ad', 'h': 'jg', ...}
# PWD = 'my secret original password'
from substs import SUBSTS, PWD
def mogrify(pwd):
... |
30f5f199767c214c57a1560f864ac141e3219fcd | zs930831/Practice | /Demo/test.py | 895 | 3.90625 | 4 | # print("my wife's name is {}".format('wxs'))
# print('my salary is {:.2f},{:.3f}'.format(3.1213213,4.3213))
#import numpy as np
#自己当作成一位数组
# List=[[1,2,3],[4,5,6],[7,8,9]]
#
# print([np.column_stack([i for i in l])for l in List])
# print([np.column_stack([i for i in l]).mean(axis=1)for l in List])
# print(np.column_st... |
3d2b350ad664a12c0c411900dd919f3a55e15984 | zs930831/Practice | /Ml/Numpy/demo1.py | 618 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
# a=np.arange(1,10,1).reshape(3,3)#左闭右开
# print(a)
# print(a.ndim)#矩阵的维度
# zero=np.zeros((3,4))#传入元组格式,就是(3,4)
# print(zero)
# one=np.ones((3,4),dtype=int)#传入元组格式,就是(3,4)
# print(one)
# random=np.random.random((2,3))#-1到1的随机
# print(random)
#print(np.linspac... |
e383b8320ba9b788bbdd999033210397f1fda6aa | zs930831/Practice | /Demo/generator.py | 798 | 3.875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#如果直接对文件对象调用 read() 方法,会导致不可预测的内存占用。
#好的方法是利用固定长度的缓冲区来不断读取文件内容。通过 yield,我们不再需要编写读文件的迭代类,就可以轻松实现文件读取:
def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield bl... |
7ae9d4a8beefa7b28aa19ce7e9a460ad42fe6f64 | zs930831/Practice | /Ml/SklearnDemo/cv_1.py | 937 | 3.6875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
from sklearn.model_selection import cross_val_score
import matplotlib.pypl... |
c10f523deaca3b606d195f0c80b8dc16188b913e | userddssilva/Exemplos-introducao-a-programacao | /listas.py | 2,775 | 4.6875 | 5 | """
## Listas em python 3
As listas em python são objetos heterogênios iteráveis, isso significa que podem
armazenar em tempo de execução dados de valores e tipos diferentes.
- Exemplo:
```python
>>> lista = ["NOME 1", 12, "QUIN. B", 1.90]
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9]
... |
3819550104a3779f06f0a380d9d3593be5510ee1 | aishwaryac21/extra-python-program | /remove duplicates and print the length.py | 184 | 3.703125 | 4 | from collections import OrderedDict
def remove_duplicate(str1):
return "".join(OrderedDict.fromkeys(str1))
n=input()
a=remove_duplicate(n)
print(len(a))
#i/p:ABCDEFAB
#o/p:6
|
d6589c38418640722df8c424da186d7ba0c76945 | sujithg9/Python_ZTM | /Section 3/data_types.py | 1,589 | 4.09375 | 4 | ### Data Types
'''
Data Type is a value in Python. Program stores information in these datatypes and modifies the values in them by actions (create, store, read, modify, remove).
Fundamental datatype (core to the language)
int
float
str
boot
list
set
tuple
dict
Custom datatypes (Create our own datatype)
Class
Sp... |
b51ea3673b3366bc2bc8646a49888b13c2dca444 | sanneabhilash/python_learning | /Concepts_with_examples/inbuild_methods_on_lists.py | 350 | 4.25 | 4 | my_list = [2, 1, 3, 6, 5, 4]
print(my_list)
my_list.append(7)
my_list.append(8)
my_list.append("HelloWorld")
print(my_list)
my_list.remove("HelloWorld") # sorting of mixed list throws error, so removing string
my_list.sort() # The original object is modified
print(my_list) # sort by default ascending
my_list.sort... |
db7b4af913e90310e154910ef8e11eb52269890b | sanneabhilash/python_learning | /Concepts_with_examples/listOperations.py | 2,139 | 4.40625 | 4 | # List is an ordered sequence of items. List is mutable
# List once created can be modified.
my_list = ["apples", "bananas", "oranges", "kiwis"]
print("--------------")
print(my_list)
print("--------------")
# accessing list using index
print(my_list[0])
print(my_list[3])
# slicing list
print(my_list[1:4])
print(my_... |
4124b28cb4f44037a2ba0a99529aa74ee63b8db0 | sanneabhilash/python_learning | /Concepts_with_examples/Operators/bitwise.py | 431 | 4.03125 | 4 | # Bitwise Operator & | ^
print('Bitwise AND operator')
print(0 & 0)
print(0 & 1)
print(1 & 0)
print(1 & 1)
print('Bitwise OR operator')
print(0 | 0)
print(0 | 1)
print(1 | 0)
print(1 | 1)
print('Bitwise ExOR operator')
print(0 ^ 0)
print(0 ^ 1)
print(1 ^ 0)
print(1 ^ 1)
print('<< Binary Left Shift')
a = 240
print(a... |
01677a7c933fa163221e27a8bea963a35b8888be | oddsorevans/eveCalc | /main.py | 2,991 | 4.34375 | 4 | # get current day and find distance from give holiday (christmas) in this case
from datetime import date
import json
#made a global to be used in functions
holidayList = []
#finds the distance between 2 dates. Prints distance for testing
def dateDistance(date, holiday):
distance = abs(date - holiday).days
pr... |
c0f8d7f63f2c9c59a88912926719d20b3232777d | samgel/GellStorm | /sqlite/sqliteUtility.py | 1,310 | 3.875 | 4 | import sqlite3
import pandas as pd
from sqlite3 import Error
class sqliteUtility():
def __init__(self):
pass
def create_connection(self, db_file):
""" create a database connection to a SQLite database """
self.conn = sqlite3.connect(db_file)
return self.conn
... |
bb7b259e0b97ce4ca0cf44954ced60135c0a5b5e | bondxue/Monte-Hall-Problem-Model | /main.py | 2,910 | 3.640625 | 4 | '''
6.2.1
Purpose: This program is to test Monty Hall game using multi-processing
Author: Mengheng
Date: 11/23/2018
'''
from game import Game
from player import Player
from timer import Timer
import multiprocessing
# doWork function can be any function with any argument
def doWork(input, output):
while (True):
... |
89017f71e86f7d55b6b5755d4fb9bccd8978cc1f | saileshchauhan/PythonMySQL | /Indexes/Main.py | 1,085 | 3.703125 | 4 | '''
@Author: Sailesh Chauhan
@Date: 25-06-2021
@Last Modified time: 25-06-2021
@Title : To Perform Indexes related operation to create,show and drop indexes.
'''
from MySQL_Indexes import IndexFunction
class Main:
func=IndexFunction()
switcher={
'1':func.read_index,
'2':func.show_tables,
'3':fun... |
846dda5697c3e4ff32ae5ba74c455b32bd5d379c | tmckay/music-scales | /music_scales/utils.py | 536 | 4.09375 | 4 | """Misc utility functions"""
def to_ordinal(number: int):
"""Convert a number to an ordinal version of it"""
ordinals = {
11: '11th',
12: '12th',
13: '13th',
}
if number in ordinals:
return ordinals[number]
number_as_str = str(number)
if number_as_str[-1] in ('1'... |
e2638ddaf621804f647dac1d88ae50e1574e20f3 | kitmehta77/PycharmProjects | /HTCS5604/introductionToPython/TestCalculator.py | 634 | 3.515625 | 4 | import unittest
import HTCS5604.introductionToPython.calculation as g
class TestCalculator(unittest.TestCase):
def test_add(self):
result = g.add(5,6)
self.assertEqual(11,result)
def test_subtract(self):
result = g.subtract(8,2)
self.assertEqual(6,result)
def test_multiply... |
384b7614b5a269e28baf4cfe148ee619f729ca40 | kitmehta77/PycharmProjects | /HTCS5604/guessANumber/game.py | 561 | 3.875 | 4 | from random import randint
# 1. random a integer
myNumber = randint(1, 99)
# 2. ask player input a number
num = input("Please input your number: ")
# 3. if the number equal to generate number
if num == myNumber:
print("You win")
# 4. give another chance to player, if their guess is wrong
num = input("Please inp... |
355cf960a9b37718a94ee0f6dbe8eb5a1cc3219d | pdeitel/PythonFundamentalsLiveLessons | /examples/ch09/snippets_py/09_05.py | 1,764 | 4.03125 | 4 | # Section 9.5 snippets
# JSON Data Format
# Python Standard Library Module `json`
accounts_dict = {'accounts': [
{'account': 100, 'name': 'Jones', 'balance': 24.98},
{'account': 200, 'name': 'Doe', 'balance': 345.67}]}
# Serializing an Object to JSON
import json
with open('accounts.json', 'w') as accounts:... |
f741aefbf7db7999cd841a79eb5344b564765c44 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch05/snippets_py/05_02.py | 2,085 | 4.09375 | 4 | # Section 5.2 snippets
# Creating a List
c = [-45, 6, 0, 72, 1543]
c
# Accessing Elements of a List
c[0]
c[4]
# Determining a List’s Length
len(c)
# Accessing Elements from the End of the List with Negative Indices
c[-1]
c[-5]
# Indices Must Be Integers or Integer Expressions
a = 1
b = 2
c[a + b]
# Lists Ar... |
70fec296d60c640fc3f7886ee624a2ca90a16799 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch02/snippets_py/02_06.py | 1,577 | 4.15625 | 4 | # Section 2.6 snippets
name = input("What's your name? ")
name
print(name)
name = input("What's your name? ")
name
print(name)
# Function input Always Returns a String
value1 = input('Enter first number: ')
value2 = input('Enter second number: ')
value1 + value2
# Getting an Integer from the User
value = input... |
112a4768b8e9a7ddd7c88d7169c475c65c42b459 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch06/snippets_py/06.02.07selfcheck.py | 1,316 | 3.546875 | 4 | # Section 6.2.1 Self Check snippets
# Exercise 2
import random
numbers = [random.randrange(1, 6) for i in range(50)]
from collections import Counter
counter = Counter(numbers)
for value, count in sorted(counter.items()):
print(f'{value:<4}{count}')
######################################################... |
3c46927084fded1c76ae62b1096e9eeab24e9533 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch09/snippets_py/09_12.02.py | 1,301 | 3.65625 | 4 | # Section 9.12.2 snippets
# Datasets
# Working with Locally Stored CSV Files
import pandas as pd
df = pd.read_csv('accounts.csv',
names=['account', 'name', 'balance'])
df
df.to_csv('accounts_from_dataframe.csv', index=False)
#####################################################################... |
92a0ad01e24dbddfc64b17e8265295cd5557d6c2 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch05/snippets_py/.ipynb_checkpoints/05_17-checkpoint.py | 3,132 | 3.65625 | 4 | # Section 5.17 snippets
# 5.17.1 Sample Graphs for 600, 60,000 and 6,000,000 Die Rolls
# 5.17.2 Visualizing Die-Roll Frequencies and Percentages
# Launching IPython for Interactive Matplotlib Development
# Importing the Libraries
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as... |
7211c56625ec95f77e1e3a680d771da42d1be208 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch06/snippets_py/06.02.03.py | 1,843 | 4 | 4 | # Section 6.2.3 snippets
# 6.2.3 Basic Dictionary Operations
roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X': 100}
roman_numerals
# Accessing the Value Associated with a Key
roman_numerals['V']
# Updating the Value of an Existing Key–Value Pair
roman_numerals['X'] = 10
roman_numerals
# Adding a New Key–V... |
b0aeac9d3de02c5d9bac6bfd8f4f3cc121214e1a | prashanthr11/cs50x | /pset6/mario/less/mario.py | 514 | 3.75 | 4 | from cs50 import get_int
from sys import exit
while True:
x = get_int('Height: ') # Get Input
if x > 0 and x < 9: # Condition
cnt = x - 1 # Spaces
for i in range(x):
for j in range(cnt):
print(' ', end='') # Print Spaces
# print('\n'... |
3802fcc84e9e0b2b08ef8a603cc9f3b38fdfbcbc | SR-11-2021-10/Backend-SR | /db/models.py | 1,894 | 3.671875 | 4 | # DB models used by the ORM
"""
DB models used by the ORM
Currently, we are not going to use relations in the DB
SQLAlchemy handles this in a simple and easy way. Please read the next reference
https://fastapi.tiangolo.com/tutorial/sql-databases/?h=sql#create-the-database-models
"""
from sqlalche... |
530b7e8783876ba98938ccbecad2a45f103df870 | raghavbansal27/Uber-Routes-via-ML | /uber.py | 758 | 3.5625 | 4 | """Import required modules and load data file"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
uber = pd.read_csv('Travel_Times.csv')
print(uber.shape)
"""Create train-test split"""
X = uber[['Mean Travel Time (Seconds)']]
y = ube... |
b3d0e07a1e3a6ccf587653cb2fd404395891ab47 | gverebl6/pythonmaster | /CodigoSemana7/matplotlib/heatmap1.py | 170 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
A=np.random.random( (10,10) )
print(A*50)
plt.figure()
plt.gray()
plt.imshow(A,interpolation='nearest')
plt.show()
|
a4319a253106813a414339f9a32935448ace209d | princemathew1997/random-python | /Day 2/rev.py | 129 | 4.0625 | 4 | a=int(input("Enter a number"))
rev=0
while a>0:
b=a%10
rev=rev*10+b
a=a//10
print("Reverse of the number is",rev)
|
87460a6da10eabca460b1b3edb75f921a5aadb3d | princemathew1997/random-python | /Day 7/d7-6.py | 64 | 3.625 | 4 | #print odd numbers in tuple
x=(tuple(range(201,400,2)))
print(x) |
51ce23a1586e6827a62ae8d92d5f8b7ba2ec3eab | princemathew1997/random-python | /Day 9/d9-5.py | 99 | 3.5 | 4 | k=[('x','y','z'),('m','c','1'),('1','5','3')]
for x,y,z in k:
print(y,x,z)
print("\n")
|
1311062e13ae0064909347bcf03f1e14f0503585 | princemathew1997/random-python | /Day 12/hw4.py | 188 | 3.90625 | 4 | for i in range(1,151):
if i % 3==0 and i %5==0:
print("Fizz Buzz")
elif i % 3== 0:
print("Fizz")
elif i % 5==0:
print("Buzz")
else:
print(i) |
e1bf0328a520d13022200f6ed901410865d7f0aa | princemathew1997/random-python | /Day 10/d10-3.py | 93 | 3.6875 | 4 | #list unpacking using multiple values
L = [1,2,3,4,5,6]
a,b,*c = L
print(a)
print(b)
print(c) |
ee93dd039cd9039b91318f042753168956533d53 | princemathew1997/random-python | /Day 12/d12-5.py | 91 | 3.953125 | 4 | # enumerate using tuple unpacking
L = ['a','b','c']
for i,l in enumerate(L):
print(i,l) |
e6efecc8e0521bfbe6519713f8d0b19410b43c76 | keshavmusunuri/Isolation_Game_Agent | /my_custom_player.py | 3,733 | 3.71875 | 4 |
from sample_players import DataPlayer
import random
class CustomPlayer(DataPlayer):
""" Implement customized agent to play knight's Isolation """
def get_action(self, state):
""" Employ an adversarial search technique to choose an action
available in the current state calls self.queue.put(ACT... |
63b7736616683f7daac46ab5eab7dbd2b1ad37c8 | alex-klim/python_tasks | /sierpinski/sierpinski.py | 1,574 | 3.734375 | 4 | import turtle
import random
import math
def triangle_height(length):
height = math.sqrt((length ** 2) - ((length/2) ** 2))
print(height)
if(height > 0):
return height
def iter_sierpinski(length,depth):
if depth==0:
for i in range(0,3):
trtl.forward(length)
trtl.... |
434d00d8f1e5fde604d5df6c0433a9f45a5e289e | SamirMaoude/The-Beninese-Collegiate-Programming-Contest | /e.py | 629 | 3.546875 | 4 | import sys
def rotate(g, x):
rotation=[]
for i in range(x):
a=[]
for j in range(x):
a.append(g[j][i]) # Transformation de colonne en ligne
rotation.append(a[::-1]) # inversion
return g == rotation # 1 si vrai 0 si faux
sys.stdin=open("matrix.in", "r")
n... |
ed252183196ab562334ace658bbb4fb17f05eb11 | mdrijwan123/Python-Programs | /Link List/Identify intersection link node.py | 2,015 | 3.578125 | 4 | def intersetPoint(head_a, head_b):
# code here
h1 = head_a
h2 = head_b
d = {h1: 1}
while h1 is not None:
h1 = h1.next
d[h1] = 1
while h2 is not None:
try:
a = d[h2]
except:
b = 1
else:
ans = h2
break
... |
ec012273ecbee18e292704f349b584b5f14426e6 | mdrijwan123/Python-Programs | /Arrays/Check Panagram.py | 353 | 3.578125 | 4 | def checkPanagram(s):
h = [0] * 256
for i in s:
h[ord(i.upper())] += 1
for j in range(65, 91):
if h[j] == 0:
return 0
return 1
if __name__ == '__main__':
t = int(input())
for i in range(t):
s = str(input())
if checkPanagram(s):
print(1)
... |
deb0a9f3bcb0f85a4cf9e0e4e0cbfa56ff1bb768 | mdrijwan123/Python-Programs | /Hashing/Group Anagram together.py | 257 | 3.6875 | 4 | from collections import defaultdict
def main():
arr = ['tac', 'toe', 'cat', 'eto']
h = defaultdict(list)
for i in range(len(arr)):
h["".join(sorted(arr[i]))].append(arr[i])
for j in h.keys():
print(*h[j], end=" ")
main()
|
67b7fc86f541ab2b89a6ea7cdc376645f714260e | mdrijwan123/Python-Programs | /Dictionary/Ordered Dictionary.py | 180 | 3.609375 | 4 | from collections import OrderedDict
h = OrderedDict()
h[1] = 'one'
h[0] = 'zeros'
k = {}
k['a'] = 'A'
k['b'] = 'B'
k['c'] = 'C'
k['d'] = 'D'
print(k)
print(h)
h.pop(0)
print(h) |
41b622fbf78313ceae733158126aee3431a1b2bc | lili1147/Sub_Code | /Code_/test.py | 531 | 3.640625 | 4 | # 随机数据生成器
# from random import randrange, choice
# # generateor
# from string import ascii_lowercase as lc
# from time import ctime
# tlds = ['edu', 'com', 'net', 'cn']
# for i in range(5, 11):
# maxint = randrange(2**32)
# time_str = ctime(maxint)
# name_len = randrange(4, 8)
# name_str = ''.join(choi... |
052416dc211f624280debfc7b81bda3645c5eb09 | lokesh-pathak/Python-Programs | /ex40.py | 1,133 | 4.03125 | 4 | # An anagram is a type of word play,
# the result of rearranging the letters of a word
# or phrase to produce a new word
# or phrase, using all the original letters exactly once;
# e.g., orchestra = carthorse, A
# decimal point = I am a dot in place.
# Write a Python program that, when started
# 1) randomly picks a wor... |
4a9dddf948d68d000c1da8065c0d4762eba63a8c | lokesh-pathak/Python-Programs | /ex21.py | 516 | 4.21875 | 4 | # Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it.
# Represent the frequency listing as a Python dictionary.
# Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
def char_freq(str):
frequency = {}
for n in str:
key = frequency.ke... |
0bdc8ceb19ab6e4f6f305bc33ca8682917661dff | lokesh-pathak/Python-Programs | /ex41.py | 1,135 | 4.21875 | 4 | # In a game of Lingo, there is a hidden word, five characters long.
# The object of the game is to find this word by guessing,
# and in return receive two kinds of clues:
# 1) the characters that are fully correct, with respect to identity as well as to position, and
# 2) the characters that are indeed present in the w... |
8eafb237ab16ac14decc606b7ee80e4e82119196 | lokesh-pathak/Python-Programs | /ex33.py | 918 | 4.84375 | 5 | # According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards.
# ("Semordnilap" is itself "palindromes" spelled backwards.)
# Write a semordnilap recogniser that accepts a file name
# (pointing to a list of words) from the user and finds and prints
# all pairs of words tha... |
97d90fb94f6427ae1c13eba623ea4e9ce7665670 | lokesh-pathak/Python-Programs | /ex1.py | 269 | 4.28125 | 4 | # Define a function max() that takes two numbers as arguments and returns the largest of them.
# Use the if-then-else construct available in Python.
def max(num1, num2):
if num1 > num2:
return num1
else:
return num2
#test
print max(3, 5)
print max(10, 6)
|
3016528cd228734ebf8172389e5dcc5407183b36 | virgilnr/Py-SimpleCommand | /QnAFtr.py | 612 | 3.8125 | 4 | nama = input('siapa namanya bro?? ')
umur = input('umurmu berapa bro?? ')
cita = input('kamu mau jadi apa?? ')
hobi = input('kalau waktu luang seringnya ngapain?? ')
Y = print('Sangat tampan')
N = print('Benar - Benar tampan')
Question = input('Apakah Virgi ganteng (Y/N)? ')
if Question==Y:
print('Sangat Gant... |
ac12de50365598a59b8689554be5056048072347 | sagnikdatta2017/Macpy | /Macpy.py | 164 | 3.859375 | 4 | import os
import sys
def func(x , y):
z = x+y
return z
x = int(input("Enter Value of x"))
y = int(input("Enter Value of y"))
res= func(x,y)
print(res) |
f7e5d3d7975f397fec17e4e7f0a7894d797ccae0 | dongdong-e/TIL | /python_190527/write.txt.py | 538 | 3.59375 | 4 | # write file
# 1. open()
f = open('mulcam.txt', 'w') # 'w': write, 'r': read, 'a': append
for i in range(10):
f.write(f"Hello Mulcam {i}\r\n")
f.close()
# 2. with open()
with open('mulcam.txt', 'w') as f:
f.write('Hello, Mulcam!\n')
# 2-1. writelines
with open('mulcam.txt', 'w') as f:
f.writelines(['1\n',... |
b9a5a9963edfe72b2bcc2d0687c5f945366f3673 | Jap3is/TTT | /TicTacToe/ticTacToeUsingDict.py | 4,258 | 3.515625 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
import sys
import re
class TicTacToeUsingDict( object ):
__gameCount = 0
def __init__( self, showResultOnly=False ):
self.list = {
"1": "1", "2": "2", "3": "3",
"4": "4", "5": "5", "6": "6",
"7": "7",... |
0e3807f9aceed4182440cc81f94051ebfa676449 | GanLay20/The-Python-Workbook-1 | /pyworkbookex015.py | 208 | 3.953125 | 4 | feet = int(input("Enter feet to be converted\n>>> "))
inches = feet * 12
print("Total inches:", inches)
yards = (feet / 36) * 12
print("Total yards:", yards)
miles = feet / 5280
print("Total miles", miles) |
0f0533ca86ac0ae61985f60de3123e8dc85d5e6c | GanLay20/The-Python-Workbook-1 | /pyworkbookex071.py | 295 | 4.03125 | 4 | print(" ~~~~~~~Newton's Method~~~~~~~\n[][][]Square Root Guess-Imater[][][]\n")
n = float(input("Enter A Positive Number:\n>>> "))
x = float(input("Enter You Estimate:\n>>> "))
final = (0.5*(x+(n/x)))
print (final)
for i in range(0,10):
final = (0.5*(final+(n/final)))
print (final) |
a0ea041eeb131dd28038413c9389d99f0290dc32 | GanLay20/The-Python-Workbook-1 | /pyworkbookex024.py | 353 | 4.125 | 4 | print("The Seconds Calculator\n")
days = int(input("Enter the amount of Days:\n>>> "))
hours = int(input("Enter the amount of Hours:\n>>> "))
minutes = int(input("Enter the amount of Minutes:\n>>> "))
day_s = days * 86400
hour_s = hours * 3600
minute_s = minutes * 60
seconds = day_s + hour_s + minute_s
print("The ... |
f4a61563068fa1a16ef68ff5817ff56d76fd7fa0 | GanLay20/The-Python-Workbook-1 | /pyworkbookex046.py | 926 | 4.375 | 4 | print("The Seasons\n")
month = input("Enter the month:\n>>> ")
day = int(input("Enter the day:\n>>> "))
if month == "january" or month == "febuary":
season = "Winter"
elif month == "march":
if day <= 20:
season = "Winter"
else:
season = "Spring"
elif month == "april" or month == "may":
... |
0d043a4d307c675be436b57aacf85851d5d55463 | GanLay20/The-Python-Workbook-1 | /pyworkbookex082.py | 560 | 4.125 | 4 | def main():
print(" Taxi Taxi\n~~~Trip Calculator~~~")
km = float(input("Enter distance travelled in KM:\n>>> "))
taxi_fare(km)
def taxi_fare(km):
'''Calculate a taxi fare'''
distance = 7.1428571428571 # 1km ÷ 140 m (7.14...... km)
set_fee = 4.00
fee = .25 # per 140 m
fa... |
d242694b3d8ac4b4a5ed9c01c00269ee4c6dca2d | GanLay20/The-Python-Workbook-1 | /pyworkbookex003.py | 226 | 4.125 | 4 | print("The area calculator")
lenth = float(input("Enter The Lenth In Feet >>> "))
width = float(input("Enter The Width In Feet >>> "))
print(lenth)
print(width)
area = lenth * width
print("The Area Is: ", area, " Square Feet") |
87e9c3980f14dde7910ba0314d7dd24427849ba2 | GanLay20/The-Python-Workbook-1 | /pyworkbookex014.py | 381 | 4.3125 | 4 | print("Enter you height in FEET followed by INCHES")
feet_height = int(input("Feet:\n>>> "))
inch_height = int(input("Inches:\n>>> "))
print("Your height is", feet_height, "feet", inch_height, "inches\n")
# 1 inch = 2.54cm // 1 foot = 30.48
feet_cm = feet_height * 30.48
inch_cm = inch_height * 2.54
total_height = f... |
f7ce7a2b80cea0e04204a84727743e2b9217a293 | GanLay20/The-Python-Workbook-1 | /pyworkbookex066.py | 1,570 | 4.34375 | 4 | print("~~~~Grade Point Average Calculator~~~~\n")
grade_letter = ()
float_grade = 0
average_count = 0
while grade_letter != "":
grade_letter = input("Enter A Grade Letter:\n>>> ")
average_count += 1
if grade_letter == "a+" or grade_letter == "A+":
float_grade = 4.10 + float_grade
elif grade... |
0e2655f5c91f4ffaf5644430f0e6de8e3c98e23b | GanLay20/The-Python-Workbook-1 | /pyworkbookex036.py | 373 | 4.28125 | 4 | print("Vowel or Consonant")
letter = input("Enter a letter:\n>>> ")
if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":
print("The letter", letter.title(), "is a Vowel.")
elif letter == "y":
print("The letter", letter.title(), "is sometimes a Vowel or Consonant.")
else:
p... |
825b35f48e9095380a784f59204de9a8acad9341 | GanLay20/The-Python-Workbook-1 | /pyworkbookex012.py | 887 | 4.03125 | 4 | import math
start = input("Starting point:\n>>> ")
# Schreiber / 48.809961 / -87.267758
t1 = float(input("Enter longitude of " + start + ":\n>>> "))
g1 = float(input("Enter latitude of " + start + ":\n>>> "))
print(start, "'s longitude is:\n", t1, "\n", start, "'s latitude is:\n", g1)
end = input("End point:\n>>> ... |
8b4ff8160fb8f665a3235fedef2b77a5ca3a68ce | GanLay20/The-Python-Workbook-1 | /pyworkbookex043.py | 687 | 4.09375 | 4 | print("The Faces of Money\n")
money = int(input("Enter The Dollar Amount:\n>>> $"))
if money == 1:
print("The one dollar banknote features George Washington.")
elif money == 2:
print("The two dollar banknote features Thomas Jefferson.")
elif money == 5:
print("The five dollar banknote features Abraham... |
af2e6ddea575ea304623b4f39d8935f1f0e697a0 | GanLay20/The-Python-Workbook-1 | /pyworkbookex055.py | 522 | 4.5 | 4 | print("The 7 Categories Of Radiation\n")
hz = float(input("Enter The Radiation Frequency In Hz:\n>>> "))
type = ""
if hz <= 3 * 10 **9:
type = "Radio Waves"
elif hz <= 3 * 10 **12:
type = "Microwaves"
elif hz <= 4.3 * 10 **14:
type = "Infrared Light"
elif hz <= 7.5 * 10 **14:
type = "Visible Light"
el... |
4febcdf887dd80cdf0f5a9eddb86bfc1d786057d | GSIL-Monitor/python | /core/04_闭包.py | 472 | 3.875 | 4 | # coding=utf-8
"""
闭包: 在函数内部继续定义函数,并且内部函数用到了外部函数的变量,最终返回内部函数结果,那么这个内部函数及用到的变量称为闭包
优点: 调用函数时可以减少参数的传递
缺点: 由于闭包引用了外部函数的局部变量,导致局部变量没有及时释放,占用内存
"""
def outer(a, b):
def inner(x):
return a * x + b
return inner
o = outer(3, 5)
print(o(2)) # 11
|
7572554f77ef575c5648f253dca86e8cdb60626f | claudio1624/Python | /ejemplo.py | 214 | 3.625 | 4 | import os, sys
a = int(input("Primer Numero :"))
b = int(input("Segundo numero:"))
c = int(input("tercer Nemero:"))
d = int(input("Cuarto numero:"))
suma = a+b+c+d
resultado='la sumatoria es'
print(resultado, suma) |
f745f71c64726bf0a0c4159f73b24abc9da11d06 | wmacevoy/ai-wmacevoy | /baghchal/agent.py | 973 | 4.09375 | 4 | from game import Game
from move import Move
class Agent:
'''
Agents are the 'AI' part, they propose
a Move object as the best next move in the
game for their side.
'''
def __init__(self, game : Game, side : int):
self._game = game
self._side = side
@property
def state(s... |
ec841668a2193f3cbb7b544121e9086591f1fb3e | aspuru-guzik-group/selfies | /selfies/utils/matching_utils.py | 3,405 | 3.703125 | 4 | import heapq
import itertools
from collections import deque
from typing import List, Optional
def find_perfect_matching(graph: List[List[int]]) -> Optional[List[int]]:
"""Finds a perfect matching for an undirected graph (without self-loops).
:param graph: an adjacency list representing the input graph.
:... |
7ecfb220e0e6a378c12ba968650c7045ad596529 | simeonborko/syllabiky | /src/syllabiky/syllabiky.py | 14,402 | 3.859375 | 4 | #!/usr/bin/python3.5
"""
Recognize syllables in words, adjusted to Slovak language rules and heuristics.
Author: Simeon Borko, simeon.borko@gmail.com
Date: Sep 01, 2017
Usage:
split_phrase('phrase to be processed') -> returns string where words syllables are delimited by hyphen (-)
split_word('wordtobesplit') -> ... |
c9eb17e6fdd59b77ae8fa518fc65755c557f0764 | hongsally/nonprofit_project | /code/numberguesser.py | 169 | 4 | 4 | guess = int(input("Guess a number: "))
number = 21
if guess == number:
print("You got it")
elif guess >= 22:
print("Guess lower")
else:
print("Guess higher") |
3135a41a21a97878dd462647b9fb5ebbc931eb7c | nomac35/100daysofPython | /Days28-30 - regular expressions/practice1.py | 2,136 | 4.09375 | 4 | text = 'Awesome, I am doing 100 days python'
#starts with Awesome?
print(text.startswith('Awesome'))
#ends with python?
print(text.endswith('python'))
#replace 100 wth 200
print(text.replace('100', '200'))
import re
####regex#####
text = 'Awesome, I am doing the #100DaysOfCode challenge'
print(re.search(r'I am', text... |
efb498d2b3696c3274287d01e9eb7841c4db0833 | nomac35/100daysofPython | /Days19-21 - Iterations/bite11.py | 569 | 4.0625 | 4 | # Write a function called friends_teams that takes a list of friends, a team_size (type int, default=2) and order_does_matter (type bool, default False).
#
# Return all possible teams. Hint: if order matters (order_does_matter=True), the number of teams would be greater.
#
# See the tests for more details. Enjoy :)
imp... |
6a86006ba62182d839293b70d056443804d0a7ac | nomac35/100daysofPython | /Days46-48 - BeautifulSoup/wundergroud.py | 894 | 3.515625 | 4 | import requests
import bs4
import collections
Weather = collections.namedtuple('Weather', 'location temp value')
def main():
zipcode = input("What is your zip code?")
#zipcode = 91601
url = f'https://www.wunderground.com/weather/{zipcode}'
data = get_html(url)
parse_html(data)
def get_html(url):
... |
85f148eeef23f54d8ad36048d774baa188d9afd9 | hhsieh/Python_R_SmallCode | /comb_replace.py | 526 | 4 | 4 | ## Given a string S, print all possible size N replacement combinations of the string in lexicographic sorted order.
from itertools import combinations_with_replacement
def comb_replace():
A = map(str, raw_input().split())
S = "".join(sorted(A[0]))
N = int(A[1])
L = list(combinations_with_replacement(... |
123a72dee8b7f8c819a18acea4f3db365cdf9792 | taichi2781/machineLearning | /test.py | 215 | 4.15625 | 4 | print("こんにちは")
print("10+8=",10+8)
print("10-8=",10-8)
print("10*8=",10*8)
print("九九")
for x in range(0,9):
for y in range(0,9):
print('{0}'.format('%2d'%((x+1)*(y+1))), end="")
print('')
|
6aa0a12265b6293e6657f59579cb0d579e42f90a | tomerfry/Advent-of-Code-2015 | /13/script.py | 1,868 | 3.671875 | 4 | #! /usr/bin/python3
import itertools
import re
INPUT_PATTERN = '(?P<first_name>.+?) would (?P<operator>.+?) (?P<cost>.+?) happiness units by sitting next to (?P<second_name>.+?)\.'
OPERATORS = {'lose': -1, 'gain': 1}
SITTER_NAME = 'a'
def main():
print('Advent of Code 2015')
with open('input.txt',... |
48fae2975c91efbe47376348f6bf0482a44aee41 | tomerfry/Advent-of-Code-2015 | /3/main.py | 1,353 | 3.796875 | 4 | #! /usr/bin/python
movement = {
'^': lambda pos_x, pos_y: (pos_x, pos_y + 1),
'>': lambda pos_x, pos_y: (pos_x + 1, pos_y),
'v': lambda pos_x, pos_y: (pos_x, pos_y - 1),
'<': lambda pos_x, pos_y: (pos_x - 1, pos_y),
}
def main():
with open('input.txt', 'r') as input_file:
instru... |
d44e18267ab0940984bc6f3433ac40cdeae316d8 | tomerfry/Advent-of-Code-2015 | /11/script.py | 1,501 | 3.984375 | 4 | #! /usr/bin/python3
import string
import re
GIVEN_INPUT = 'vzbxkghb'
SECOND_GIVEN_INPUT = 'vzbxxyzz'
ALPHABET = string.ascii_lowercase
CHR_OFFSET = ord('a')
NON_OVERLAPPING_PAIRS_PATTERN = '(.)\\1.*(.)\\2'
def main():
print('Advent of Code 2015')
num = alphabse_2_dec(SECOND_GIVEN_INPUT)
wh... |
276158e1754954c9cb1017c535d83bdaaff28867 | Iboatwright/mod9homework | /sum_of_numbers.py | 1,750 | 4.53125 | 5 | # sum_of_numbers.py
# Exercise selected: Chapter 10 program 3
# Name of program: Sum of Numbers
# Description of program: This program opens a file named numbers.dat
# that contains a list of integers and calculates the sum of all the
# integers. The numbers.dat file is assumed to be a string of positive
# integ... |
aaca9a7935e445741c837b0ef45be58cd104fd0a | insancs/data-manipulation-with-pandas | /handling_missing_value.py | 2,817 | 3.515625 | 4 | import pandas as pd
df_cov = pd.read_csv("E:/DQLab/Dataset/missval_public_data_covid19.csv")
print(df_cov)
print(df_cov.info())
# Cetak jumlah missing value tiap kolom
print("\nJumlah missing value :\n", df_cov.isna().sum())
# [1] Treatment Missing Value : Hapus kolom
print("\n[1] Hapus Kolom")
# Cetak ukuran awal d... |
660e322a33a09e4d934f7c8a690fae4a1264f5c6 | forakert05711/TurtleLetters | /turtleletters.py | 2,600 | 3.765625 | 4 | import turtle
def turtleLetter(letter,tur):
if letter=="box":
tur.setheading(0)
tur.forward(40)
tur.right(90)
tur.forward(60)
tur.right(90)
tur.forward(40)
tur.right(90)
tur.forward(60)
elif letter == "A":
tur.setheading(0)
tur.pu... |
ef0f9308f77b1217233b182675ec9a26d46baed5 | hvardhan20/lidar_filter | /filters/tm_filter.py | 2,298 | 3.53125 | 4 | import numpy as np
from range_filter import RangeFilter
def median(a):
"""
Helper function to calculate the median of a given list
Parameters
----------
a : array-like
Sequence of values whose median has to be calculated
"""
le = len(a)
mid = le // 2
a... |
4dc7216b95455e4072aa897bf4cfa4cbf6deac6d | hadreanK/The-Pi-Brewing-System | /Archive/UI_Module_AK.py | 1,227 | 3.640625 | 4 | #http://thinkingtkinter.sourceforge.net/all_programs.html
from tkinter import *
class Brasseur:
def __init__(self, parent):
# Instance variables
self.temps = [0.0, 0.0, 0.0] #TA, TB, int
self.myParent = parent
self.myContainer1 = Frame(pa... |
a06ebb4a426ceef2ca070ab882e92ec851202cb5 | jom9/autumn | /RulesEngine/Hand.py | 411 | 3.71875 | 4 |
class Hand():
def __init__(self):
self.cards = []
self.revealedCards = []
def showHand(self):
print("Current Hand is:")
for card in self.cards:
print(card[0].cardName, end=' ')
print('')
def addCard(self,card):
self.cards.append(card)
re... |
8e58735ddf10bd19f1c31c2dfa9a18988b708292 | BAFurtado/Python4ABMIpea2019 | /while_break_continue.py | 802 | 4.03125 | 4 |
def got_it(number):
while number > 0:
print('Got it!')
number -= 1
def while_true():
while True:
ipt = input('Do you wanna stop?')
if ipt == 'YES!':
break
def for_only_odd(n):
for i in range(n):
n -= 1
if n % 13 == 0:
print(n)
... |
0d9b719cfb941b2d016a7aaa1c610252422f9dd9 | BAFurtado/Python4ABMIpea2019 | /practical_pandas.py | 2,100 | 3.515625 | 4 | # Chama a biblioteca
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Cria uma DataFrame, utilizando-se de um dicioário.
# Keys são column names
# Values, em listas, são os valores
data = pd.DataFrame({'col_a': [0, 1, 2, 3, 4, 5, 6, 7],
'col_b': [7, 6, 4, 2, 1, 1, 1, 0],
... |
c3aac5c6496d132f85f75e105955e9c75e332329 | BAFurtado/Python4ABMIpea2019 | /temperature_converter.py | 216 | 4 | 4 | """ Função para converter entre Celsius e Fahreneith
"""
def to_celsius(f):
return (f - 32) / 9 * 5
def to_f(c):
return (c * 9 / 5) + 32
if __name__ == '__main__':
c = 10
print(to_celsius(c))
|
d6a4ee396926531ca232760b942022ba640e8362 | BAFurtado/Python4ABMIpea2019 | /class_da_turma.py | 964 | 4.40625 | 4 | """ Exemplo de uma class construída coletivamente
"""
class Turma:
def __init__(self, name='Python4ABMIpea'):
self.name = name
self.students = list()
def add_student(self, name):
self.students.append(name)
def remove_student(self, name):
self.students.remove(name)
de... |
8eb5042a8f90ba520e2288942b744582d68b235f | BAFurtado/Python4ABMIpea2019 | /hello.py | 61 | 3.6875 | 4 | x = int(input('Entre um número: '))
print('O número é', x) |
97cc05e61e4d058451e453e0d0a7be9a61dc6242 | gup-abhi/dictionary | /DIctonary.py | 1,169 | 4.0625 | 4 | # importing all from tkinter
from tkinter import *
# importing messagebox from tkinter
from tkinter import messagebox
# importing PyDictionary from PyDictionary
from PyDictionary import PyDictionary
# importing time module
import time
# creating function for finding meaning for specific word given by the user
def f... |
9ad67c528d7806670bb15b37909696166c20167d | MagiRui/python3-spider-learn | /urllib-using/urllib_one_testing.py | 2,387 | 3.75 | 4 | #!/usr/bin/env python
#coding:utf8
#author:MagiRui
import urllib.request
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))
print("######post request######");
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({"word":"hello"}), encoding="utf... |
80c9e293f963cee51d7652218cb162dd722c0415 | pylixm/learn_codes | /python/day01.py | 1,020 | 3.890625 | 4 | """
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def remove_duplicates(self, nums: list) -> int:
... |
d2d03e19d534ba30d68af66df984c76fc91d63a4 | AnabelSalomone/HelloPython | /optional_params.py | 559 | 3.875 | 4 | # Optional Parameters
# Second parameter becomes optional
def func(word, freq=3):
print(word*freq)
call = func('hello')
# hellohellohello
class car(object):
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display(self, showAll=True... |
e7f9280fa4afb71beb5498d729f8cd0a876ed659 | comingboy0701/algorithm-learning | /book/流畅的python-fluent_python/第一章/test2.6.py | 254 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# ## 序列的增量赋值
# ### 可变序列
l = [1,2,3]
print(l, id(l))
l *=2
print(l, id(l))
l +=[1]
print(l, id(l))
# ### 不可变序列
l = (1,2,3)
print(l, id(l))
l *=2
print(l, id(l))
import dis
dis.dis('s[a] += b')
|
9446e6a88f1c01f3de9fa9d9f1b781d09baace39 | Alejandroacho/Pong | /models.py | 6,242 | 3.890625 | 4 | import pygame
from settings import *
class Player():
def __init__(self, player_number):
self.player_number = player_number
self.color = WHITE
self.x = self.initial_x()
self.y = self.initial_y()
self.width = PLAYER_WIDTH
self.height = PLAYER_HEIGHT
self.dimens... |
f923f36b3f734a53584758466d3acba9699eb852 | sd17spring/python-modules | /controller/mouse_controller.py | 617 | 3.5 | 4 | """The Brick Breaker controller."""
from pygame.locals import *
class Controller(object):
"""Controls Brick Breaker using the mouse."""
def __init__(self, model):
"""Construct a PyGameMouseController object.
model: the Brick Breaker game state
"""
self.model = model
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.